base.ts 13 KB

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