base.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  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. onMessageEnd?.(bufferObj as MessageEnd)
  126. }
  127. else if (bufferObj.event === 'message_replace') {
  128. onMessageReplace?.(bufferObj as MessageReplace)
  129. }
  130. }
  131. })
  132. buffer = lines[lines.length - 1]
  133. }
  134. catch (e) {
  135. onData('', false, {
  136. conversationId: undefined,
  137. messageId: '',
  138. errorMessage: `${e}`,
  139. })
  140. hasError = true
  141. onCompleted?.(true)
  142. return
  143. }
  144. if (!hasError)
  145. read()
  146. })
  147. }
  148. read()
  149. }
  150. const baseFetch = <T>(
  151. url: string,
  152. fetchOptions: FetchOptionType,
  153. {
  154. isPublicAPI = false,
  155. bodyStringify = true,
  156. needAllResponseContent,
  157. deleteContentType,
  158. }: IOtherOptions,
  159. ): Promise<T> => {
  160. const options: typeof baseOptions & FetchOptionType = Object.assign({}, baseOptions, fetchOptions)
  161. if (isPublicAPI) {
  162. const sharedToken = globalThis.location.pathname.split('/').slice(-1)[0]
  163. const accessToken = localStorage.getItem('token') || JSON.stringify({ [sharedToken]: '' })
  164. let accessTokenJson = { [sharedToken]: '' }
  165. try {
  166. accessTokenJson = JSON.parse(accessToken)
  167. }
  168. catch (e) {
  169. }
  170. options.headers.set('Authorization', `Bearer ${accessTokenJson[sharedToken]}`)
  171. }
  172. else {
  173. const accessToken = localStorage.getItem('console_token') || ''
  174. options.headers.set('Authorization', `Bearer ${accessToken}`)
  175. }
  176. if (deleteContentType) {
  177. options.headers.delete('Content-Type')
  178. }
  179. else {
  180. const contentType = options.headers.get('Content-Type')
  181. if (!contentType)
  182. options.headers.set('Content-Type', ContentType.json)
  183. }
  184. const urlPrefix = isPublicAPI ? PUBLIC_API_PREFIX : API_PREFIX
  185. let urlWithPrefix = `${urlPrefix}${url.startsWith('/') ? url : `/${url}`}`
  186. const { method, params, body } = options
  187. // handle query
  188. if (method === 'GET' && params) {
  189. const paramsArray: string[] = []
  190. Object.keys(params).forEach(key =>
  191. paramsArray.push(`${key}=${encodeURIComponent(params[key])}`),
  192. )
  193. if (urlWithPrefix.search(/\?/) === -1)
  194. urlWithPrefix += `?${paramsArray.join('&')}`
  195. else
  196. urlWithPrefix += `&${paramsArray.join('&')}`
  197. delete options.params
  198. }
  199. if (body && bodyStringify)
  200. options.body = JSON.stringify(body)
  201. // Handle timeout
  202. return Promise.race([
  203. new Promise((resolve, reject) => {
  204. setTimeout(() => {
  205. reject(new Error('request timeout'))
  206. }, TIME_OUT)
  207. }),
  208. new Promise((resolve, reject) => {
  209. globalThis.fetch(urlWithPrefix, options as RequestInit)
  210. .then((res) => {
  211. const resClone = res.clone()
  212. // Error handler
  213. if (!/^(2|3)\d{2}$/.test(String(res.status))) {
  214. const bodyJson = res.json()
  215. switch (res.status) {
  216. case 401: {
  217. if (isPublicAPI) {
  218. return bodyJson.then((data: ResponseError) => {
  219. Toast.notify({ type: 'error', message: data.message })
  220. return Promise.reject(data)
  221. })
  222. }
  223. const loginUrl = `${globalThis.location.origin}/signin`
  224. bodyJson.then((data: ResponseError) => {
  225. if (data.code === 'not_setup' && IS_CE_EDITION)
  226. globalThis.location.href = `${globalThis.location.origin}/install`
  227. else if (location.pathname !== '/signin' || !IS_CE_EDITION)
  228. globalThis.location.href = loginUrl
  229. else
  230. Toast.notify({ type: 'error', message: data.message })
  231. }).catch(() => {
  232. // Handle any other errors
  233. globalThis.location.href = loginUrl
  234. })
  235. break
  236. }
  237. case 403:
  238. bodyJson.then((data: ResponseError) => {
  239. Toast.notify({ type: 'error', message: data.message })
  240. if (data.code === 'already_setup')
  241. globalThis.location.href = `${globalThis.location.origin}/signin`
  242. })
  243. break
  244. // fall through
  245. default:
  246. bodyJson.then((data: ResponseError) => {
  247. Toast.notify({ type: 'error', message: data.message })
  248. })
  249. }
  250. return Promise.reject(resClone)
  251. }
  252. // handle delete api. Delete api not return content.
  253. if (res.status === 204) {
  254. resolve({ result: 'success' })
  255. return
  256. }
  257. // return data
  258. const data: Promise<T> = options.headers.get('Content-type') === ContentType.download ? res.blob() : res.json()
  259. resolve(needAllResponseContent ? resClone : data)
  260. })
  261. .catch((err) => {
  262. Toast.notify({ type: 'error', message: err })
  263. reject(err)
  264. })
  265. }),
  266. ]) as Promise<T>
  267. }
  268. export const upload = (options: any, isPublicAPI?: boolean, url?: string): Promise<any> => {
  269. const urlPrefix = isPublicAPI ? PUBLIC_API_PREFIX : API_PREFIX
  270. let token = ''
  271. if (isPublicAPI) {
  272. const sharedToken = globalThis.location.pathname.split('/').slice(-1)[0]
  273. const accessToken = localStorage.getItem('token') || JSON.stringify({ [sharedToken]: '' })
  274. let accessTokenJson = { [sharedToken]: '' }
  275. try {
  276. accessTokenJson = JSON.parse(accessToken)
  277. }
  278. catch (e) {
  279. }
  280. token = accessTokenJson[sharedToken]
  281. }
  282. else {
  283. const accessToken = localStorage.getItem('console_token') || ''
  284. token = accessToken
  285. }
  286. const defaultOptions = {
  287. method: 'POST',
  288. url: url ? `${urlPrefix}${url}` : `${urlPrefix}/files/upload`,
  289. headers: {
  290. Authorization: `Bearer ${token}`,
  291. },
  292. data: {},
  293. }
  294. options = {
  295. ...defaultOptions,
  296. ...options,
  297. headers: { ...defaultOptions.headers, ...options.headers },
  298. }
  299. return new Promise((resolve, reject) => {
  300. const xhr = options.xhr
  301. xhr.open(options.method, options.url)
  302. for (const key in options.headers)
  303. xhr.setRequestHeader(key, options.headers[key])
  304. xhr.withCredentials = true
  305. xhr.responseType = 'json'
  306. xhr.onreadystatechange = function () {
  307. if (xhr.readyState === 4) {
  308. if (xhr.status === 201)
  309. resolve(xhr.response)
  310. else
  311. reject(xhr)
  312. }
  313. }
  314. xhr.upload.onprogress = options.onprogress
  315. xhr.send(options.data)
  316. })
  317. }
  318. export const ssePost = (url: string, fetchOptions: FetchOptionType, { isPublicAPI = false, onData, onCompleted, onThought, onMessageEnd, onMessageReplace, onError, getAbortController }: IOtherOptions) => {
  319. const abortController = new AbortController()
  320. const options = Object.assign({}, baseOptions, {
  321. method: 'POST',
  322. signal: abortController.signal,
  323. }, fetchOptions)
  324. const contentType = options.headers.get('Content-Type')
  325. if (!contentType)
  326. options.headers.set('Content-Type', ContentType.json)
  327. getAbortController?.(abortController)
  328. const urlPrefix = isPublicAPI ? PUBLIC_API_PREFIX : API_PREFIX
  329. const urlWithPrefix = `${urlPrefix}${url.startsWith('/') ? url : `/${url}`}`
  330. const { body } = options
  331. if (body)
  332. options.body = JSON.stringify(body)
  333. globalThis.fetch(urlWithPrefix, options as RequestInit)
  334. .then((res) => {
  335. if (!/^(2|3)\d{2}$/.test(String(res.status))) {
  336. res.json().then((data: any) => {
  337. Toast.notify({ type: 'error', message: data.message || 'Server Error' })
  338. })
  339. onError?.('Server Error')
  340. return
  341. }
  342. return handleStream(res, (str: string, isFirstMessage: boolean, moreInfo: IOnDataMoreInfo) => {
  343. if (moreInfo.errorMessage) {
  344. onError?.(moreInfo.errorMessage, moreInfo.errorCode)
  345. if (moreInfo.errorMessage !== 'AbortError: The user aborted a request.')
  346. Toast.notify({ type: 'error', message: moreInfo.errorMessage })
  347. return
  348. }
  349. onData?.(str, isFirstMessage, moreInfo)
  350. }, onCompleted, onThought, onMessageEnd, onMessageReplace)
  351. }).catch((e) => {
  352. if (e.toString() !== 'AbortError: The user aborted a request.')
  353. Toast.notify({ type: 'error', message: e })
  354. onError?.(e)
  355. })
  356. }
  357. // base request
  358. export const request = <T>(url: string, options = {}, otherOptions?: IOtherOptions) => {
  359. return baseFetch<T>(url, options, otherOptions || {})
  360. }
  361. // request methods
  362. export const get = <T>(url: string, options = {}, otherOptions?: IOtherOptions) => {
  363. return request<T>(url, Object.assign({}, options, { method: 'GET' }), otherOptions)
  364. }
  365. // For public API
  366. export const getPublic = <T>(url: string, options = {}, otherOptions?: IOtherOptions) => {
  367. return get<T>(url, options, { ...otherOptions, isPublicAPI: true })
  368. }
  369. export const post = <T>(url: string, options = {}, otherOptions?: IOtherOptions) => {
  370. return request<T>(url, Object.assign({}, options, { method: 'POST' }), otherOptions)
  371. }
  372. export const postPublic = <T>(url: string, options = {}, otherOptions?: IOtherOptions) => {
  373. return post<T>(url, options, { ...otherOptions, isPublicAPI: true })
  374. }
  375. export const put = <T>(url: string, options = {}, otherOptions?: IOtherOptions) => {
  376. return request<T>(url, Object.assign({}, options, { method: 'PUT' }), otherOptions)
  377. }
  378. export const putPublic = <T>(url: string, options = {}, otherOptions?: IOtherOptions) => {
  379. return put<T>(url, options, { ...otherOptions, isPublicAPI: true })
  380. }
  381. export const del = <T>(url: string, options = {}, otherOptions?: IOtherOptions) => {
  382. return request<T>(url, Object.assign({}, options, { method: 'DELETE' }), otherOptions)
  383. }
  384. export const delPublic = <T>(url: string, options = {}, otherOptions?: IOtherOptions) => {
  385. return del<T>(url, options, { ...otherOptions, isPublicAPI: true })
  386. }
  387. export const patch = <T>(url: string, options = {}, otherOptions?: IOtherOptions) => {
  388. return request<T>(url, Object.assign({}, options, { method: 'PATCH' }), otherOptions)
  389. }
  390. export const patchPublic = <T>(url: string, options = {}, otherOptions?: IOtherOptions) => {
  391. return patch<T>(url, options, { ...otherOptions, isPublicAPI: true })
  392. }