base.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. import { API_PREFIX, IS_CE_EDITION, PUBLIC_API_PREFIX } from '@/config'
  2. import Toast from '@/app/components/base/toast'
  3. import type { AnnotationReply, MessageEnd, MessageReplace, ThoughtItem } from '@/app/components/app/chat/type'
  4. const TIME_OUT = 100000
  5. const ContentType = {
  6. json: 'application/json',
  7. stream: 'text/event-stream',
  8. form: 'application/x-www-form-urlencoded; charset=UTF-8',
  9. download: 'application/octet-stream', // for download
  10. upload: 'multipart/form-data', // for upload
  11. }
  12. const baseOptions = {
  13. method: 'GET',
  14. mode: 'cors',
  15. credentials: 'include', // always send cookies、HTTP Basic authentication.
  16. headers: new Headers({
  17. 'Content-Type': ContentType.json,
  18. }),
  19. redirect: 'follow',
  20. }
  21. export type IOnDataMoreInfo = {
  22. conversationId?: string
  23. taskId?: string
  24. messageId: string
  25. errorMessage?: string
  26. errorCode?: string
  27. }
  28. export type IOnData = (message: string, isFirstMessage: boolean, moreInfo: IOnDataMoreInfo) => void
  29. export type IOnThought = (though: ThoughtItem) => void
  30. export type IOnMessageEnd = (messageEnd: MessageEnd) => void
  31. export type IOnMessageReplace = (messageReplace: MessageReplace) => void
  32. export type IOnAnnotationReply = (messageReplace: AnnotationReply) => void
  33. export type IOnCompleted = (hasError?: boolean) => void
  34. export type IOnError = (msg: string, code?: string) => void
  35. type IOtherOptions = {
  36. isPublicAPI?: boolean
  37. bodyStringify?: boolean
  38. needAllResponseContent?: boolean
  39. deleteContentType?: boolean
  40. onData?: IOnData // for stream
  41. onThought?: IOnThought
  42. onMessageEnd?: IOnMessageEnd
  43. onMessageReplace?: IOnMessageReplace
  44. onError?: IOnError
  45. onCompleted?: IOnCompleted // for stream
  46. getAbortController?: (abortController: AbortController) => void
  47. }
  48. type ResponseError = {
  49. code: string
  50. message: string
  51. status: number
  52. }
  53. type FetchOptionType = Omit<RequestInit, 'body'> & {
  54. params?: Record<string, any>
  55. body?: BodyInit | Record<string, any> | null
  56. }
  57. function unicodeToChar(text: string) {
  58. if (!text)
  59. return ''
  60. return text.replace(/\\u[0-9a-f]{4}/g, (_match, p1) => {
  61. return String.fromCharCode(parseInt(p1, 16))
  62. })
  63. }
  64. export function format(text: string) {
  65. let res = text.trim()
  66. if (res.startsWith('\n'))
  67. res = res.replace('\n', '')
  68. return res.replaceAll('\n', '<br/>').replaceAll('```', '')
  69. }
  70. const handleStream = (response: Response, onData: IOnData, onCompleted?: IOnCompleted, onThought?: IOnThought, onMessageEnd?: IOnMessageEnd, onMessageReplace?: IOnMessageReplace) => {
  71. if (!response.ok)
  72. throw new Error('Network response was not ok')
  73. const reader = response.body?.getReader()
  74. const decoder = new TextDecoder('utf-8')
  75. let buffer = ''
  76. let bufferObj: Record<string, any>
  77. let isFirstMessage = true
  78. function read() {
  79. let hasError = false
  80. reader?.read().then((result: any) => {
  81. if (result.done) {
  82. onCompleted && onCompleted()
  83. return
  84. }
  85. buffer += decoder.decode(result.value, { stream: true })
  86. const lines = buffer.split('\n')
  87. try {
  88. lines.forEach((message) => {
  89. if (message.startsWith('data: ')) { // check if it starts with data:
  90. try {
  91. bufferObj = JSON.parse(message.substring(6)) as Record<string, any>// remove data: and parse as json
  92. }
  93. catch (e) {
  94. // mute handle message cut off
  95. onData('', isFirstMessage, {
  96. conversationId: bufferObj?.conversation_id,
  97. messageId: bufferObj?.id,
  98. })
  99. return
  100. }
  101. if (bufferObj.status === 400 || !bufferObj.event) {
  102. onData('', false, {
  103. conversationId: undefined,
  104. messageId: '',
  105. errorMessage: bufferObj?.message,
  106. errorCode: bufferObj?.code,
  107. })
  108. hasError = true
  109. onCompleted?.(true)
  110. return
  111. }
  112. if (bufferObj.event === 'message') {
  113. // can not use format here. Because message is splited.
  114. onData(unicodeToChar(bufferObj.answer), isFirstMessage, {
  115. conversationId: bufferObj.conversation_id,
  116. taskId: bufferObj.task_id,
  117. messageId: bufferObj.id,
  118. })
  119. isFirstMessage = false
  120. }
  121. else if (bufferObj.event === 'agent_thought') {
  122. onThought?.(bufferObj as ThoughtItem)
  123. }
  124. else if (bufferObj.event === 'message_end') {
  125. console.log(bufferObj)
  126. onMessageEnd?.(bufferObj as MessageEnd)
  127. }
  128. else if (bufferObj.event === 'message_replace') {
  129. onMessageReplace?.(bufferObj as MessageReplace)
  130. }
  131. }
  132. })
  133. buffer = lines[lines.length - 1]
  134. }
  135. catch (e) {
  136. onData('', false, {
  137. conversationId: undefined,
  138. messageId: '',
  139. errorMessage: `${e}`,
  140. })
  141. hasError = true
  142. onCompleted?.(true)
  143. return
  144. }
  145. if (!hasError)
  146. read()
  147. })
  148. }
  149. read()
  150. }
  151. const baseFetch = <T>(
  152. url: string,
  153. fetchOptions: FetchOptionType,
  154. {
  155. isPublicAPI = false,
  156. bodyStringify = true,
  157. needAllResponseContent,
  158. deleteContentType,
  159. }: IOtherOptions,
  160. ): Promise<T> => {
  161. const options: typeof baseOptions & FetchOptionType = Object.assign({}, baseOptions, fetchOptions)
  162. if (isPublicAPI) {
  163. const sharedToken = globalThis.location.pathname.split('/').slice(-1)[0]
  164. const accessToken = localStorage.getItem('token') || JSON.stringify({ [sharedToken]: '' })
  165. let accessTokenJson = { [sharedToken]: '' }
  166. try {
  167. accessTokenJson = JSON.parse(accessToken)
  168. }
  169. catch (e) {
  170. }
  171. options.headers.set('Authorization', `Bearer ${accessTokenJson[sharedToken]}`)
  172. }
  173. else {
  174. const accessToken = localStorage.getItem('console_token') || ''
  175. options.headers.set('Authorization', `Bearer ${accessToken}`)
  176. }
  177. if (deleteContentType) {
  178. options.headers.delete('Content-Type')
  179. }
  180. else {
  181. const contentType = options.headers.get('Content-Type')
  182. if (!contentType)
  183. options.headers.set('Content-Type', ContentType.json)
  184. }
  185. const urlPrefix = isPublicAPI ? PUBLIC_API_PREFIX : API_PREFIX
  186. let urlWithPrefix = `${urlPrefix}${url.startsWith('/') ? url : `/${url}`}`
  187. const { method, params, body } = options
  188. // handle query
  189. if (method === 'GET' && params) {
  190. const paramsArray: string[] = []
  191. Object.keys(params).forEach(key =>
  192. paramsArray.push(`${key}=${encodeURIComponent(params[key])}`),
  193. )
  194. if (urlWithPrefix.search(/\?/) === -1)
  195. urlWithPrefix += `?${paramsArray.join('&')}`
  196. else
  197. urlWithPrefix += `&${paramsArray.join('&')}`
  198. delete options.params
  199. }
  200. if (body && bodyStringify)
  201. options.body = JSON.stringify(body)
  202. // Handle timeout
  203. return Promise.race([
  204. new Promise((resolve, reject) => {
  205. setTimeout(() => {
  206. reject(new Error('request timeout'))
  207. }, TIME_OUT)
  208. }),
  209. new Promise((resolve, reject) => {
  210. globalThis.fetch(urlWithPrefix, options as RequestInit)
  211. .then((res) => {
  212. const resClone = res.clone()
  213. // Error handler
  214. if (!/^(2|3)\d{2}$/.test(String(res.status))) {
  215. const bodyJson = res.json()
  216. switch (res.status) {
  217. case 401: {
  218. if (isPublicAPI) {
  219. return bodyJson.then((data: ResponseError) => {
  220. Toast.notify({ type: 'error', message: data.message })
  221. return Promise.reject(data)
  222. })
  223. }
  224. const loginUrl = `${globalThis.location.origin}/signin`
  225. bodyJson.then((data: ResponseError) => {
  226. if (data.code === 'not_setup' && IS_CE_EDITION)
  227. globalThis.location.href = `${globalThis.location.origin}/install`
  228. else if (location.pathname !== '/signin' || !IS_CE_EDITION)
  229. globalThis.location.href = loginUrl
  230. else
  231. Toast.notify({ type: 'error', message: data.message })
  232. }).catch(() => {
  233. // Handle any other errors
  234. globalThis.location.href = loginUrl
  235. })
  236. break
  237. }
  238. case 403:
  239. bodyJson.then((data: ResponseError) => {
  240. Toast.notify({ type: 'error', message: data.message })
  241. if (data.code === 'already_setup')
  242. globalThis.location.href = `${globalThis.location.origin}/signin`
  243. })
  244. break
  245. // fall through
  246. default:
  247. bodyJson.then((data: ResponseError) => {
  248. Toast.notify({ type: 'error', message: data.message })
  249. })
  250. }
  251. return Promise.reject(resClone)
  252. }
  253. // handle delete api. Delete api not return content.
  254. if (res.status === 204) {
  255. resolve({ result: 'success' })
  256. return
  257. }
  258. // return data
  259. const data: Promise<T> = options.headers.get('Content-type') === ContentType.download ? res.blob() : res.json()
  260. resolve(needAllResponseContent ? resClone : data)
  261. })
  262. .catch((err) => {
  263. Toast.notify({ type: 'error', message: err })
  264. reject(err)
  265. })
  266. }),
  267. ]) as Promise<T>
  268. }
  269. export const upload = (options: any, isPublicAPI?: boolean, url?: string): Promise<any> => {
  270. const urlPrefix = isPublicAPI ? PUBLIC_API_PREFIX : API_PREFIX
  271. let token = ''
  272. if (isPublicAPI) {
  273. const sharedToken = globalThis.location.pathname.split('/').slice(-1)[0]
  274. const accessToken = localStorage.getItem('token') || JSON.stringify({ [sharedToken]: '' })
  275. let accessTokenJson = { [sharedToken]: '' }
  276. try {
  277. accessTokenJson = JSON.parse(accessToken)
  278. }
  279. catch (e) {
  280. }
  281. token = accessTokenJson[sharedToken]
  282. }
  283. else {
  284. const accessToken = localStorage.getItem('console_token') || ''
  285. token = accessToken
  286. }
  287. const defaultOptions = {
  288. method: 'POST',
  289. url: url ? `${urlPrefix}${url}` : `${urlPrefix}/files/upload`,
  290. headers: {
  291. Authorization: `Bearer ${token}`,
  292. },
  293. data: {},
  294. }
  295. options = {
  296. ...defaultOptions,
  297. ...options,
  298. headers: { ...defaultOptions.headers, ...options.headers },
  299. }
  300. return new Promise((resolve, reject) => {
  301. const xhr = options.xhr
  302. xhr.open(options.method, options.url)
  303. for (const key in options.headers)
  304. xhr.setRequestHeader(key, options.headers[key])
  305. xhr.withCredentials = true
  306. xhr.responseType = 'json'
  307. xhr.onreadystatechange = function () {
  308. if (xhr.readyState === 4) {
  309. if (xhr.status === 201)
  310. resolve(xhr.response)
  311. else
  312. reject(xhr)
  313. }
  314. }
  315. xhr.upload.onprogress = options.onprogress
  316. xhr.send(options.data)
  317. })
  318. }
  319. export const ssePost = (url: string, fetchOptions: FetchOptionType, { isPublicAPI = false, onData, onCompleted, onThought, onMessageEnd, onMessageReplace, onError, getAbortController }: IOtherOptions) => {
  320. const abortController = new AbortController()
  321. const options = Object.assign({}, baseOptions, {
  322. method: 'POST',
  323. signal: abortController.signal,
  324. }, fetchOptions)
  325. const contentType = options.headers.get('Content-Type')
  326. if (!contentType)
  327. options.headers.set('Content-Type', ContentType.json)
  328. getAbortController?.(abortController)
  329. const urlPrefix = isPublicAPI ? PUBLIC_API_PREFIX : API_PREFIX
  330. const urlWithPrefix = `${urlPrefix}${url.startsWith('/') ? url : `/${url}`}`
  331. const { body } = options
  332. if (body)
  333. options.body = JSON.stringify(body)
  334. globalThis.fetch(urlWithPrefix, options as RequestInit)
  335. .then((res) => {
  336. if (!/^(2|3)\d{2}$/.test(String(res.status))) {
  337. res.json().then((data: any) => {
  338. Toast.notify({ type: 'error', message: data.message || 'Server Error' })
  339. })
  340. onError?.('Server Error')
  341. return
  342. }
  343. return handleStream(res, (str: string, isFirstMessage: boolean, moreInfo: IOnDataMoreInfo) => {
  344. if (moreInfo.errorMessage) {
  345. onError?.(moreInfo.errorMessage, moreInfo.errorCode)
  346. if (moreInfo.errorMessage !== 'AbortError: The user aborted a request.')
  347. Toast.notify({ type: 'error', message: moreInfo.errorMessage })
  348. return
  349. }
  350. onData?.(str, isFirstMessage, moreInfo)
  351. }, onCompleted, onThought, onMessageEnd, onMessageReplace)
  352. }).catch((e) => {
  353. if (e.toString() !== 'AbortError: The user aborted a request.')
  354. Toast.notify({ type: 'error', message: e })
  355. onError?.(e)
  356. })
  357. }
  358. // base request
  359. export const request = <T>(url: string, options = {}, otherOptions?: IOtherOptions) => {
  360. return baseFetch<T>(url, options, otherOptions || {})
  361. }
  362. // request methods
  363. export const get = <T>(url: string, options = {}, otherOptions?: IOtherOptions) => {
  364. return request<T>(url, Object.assign({}, options, { method: 'GET' }), otherOptions)
  365. }
  366. // For public API
  367. export const getPublic = <T>(url: string, options = {}, otherOptions?: IOtherOptions) => {
  368. return get<T>(url, options, { ...otherOptions, isPublicAPI: true })
  369. }
  370. export const post = <T>(url: string, options = {}, otherOptions?: IOtherOptions) => {
  371. return request<T>(url, Object.assign({}, options, { method: 'POST' }), otherOptions)
  372. }
  373. export const postPublic = <T>(url: string, options = {}, otherOptions?: IOtherOptions) => {
  374. return post<T>(url, options, { ...otherOptions, isPublicAPI: true })
  375. }
  376. export const put = <T>(url: string, options = {}, otherOptions?: IOtherOptions) => {
  377. return request<T>(url, Object.assign({}, options, { method: 'PUT' }), otherOptions)
  378. }
  379. export const putPublic = <T>(url: string, options = {}, otherOptions?: IOtherOptions) => {
  380. return put<T>(url, options, { ...otherOptions, isPublicAPI: true })
  381. }
  382. export const del = <T>(url: string, options = {}, otherOptions?: IOtherOptions) => {
  383. return request<T>(url, Object.assign({}, options, { method: 'DELETE' }), otherOptions)
  384. }
  385. export const delPublic = <T>(url: string, options = {}, otherOptions?: IOtherOptions) => {
  386. return del<T>(url, options, { ...otherOptions, isPublicAPI: true })
  387. }
  388. export const patch = <T>(url: string, options = {}, otherOptions?: IOtherOptions) => {
  389. return request<T>(url, Object.assign({}, options, { method: 'PATCH' }), otherOptions)
  390. }
  391. export const patchPublic = <T>(url: string, options = {}, otherOptions?: IOtherOptions) => {
  392. return patch<T>(url, options, { ...otherOptions, isPublicAPI: true })
  393. }