base.ts 13 KB

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