Initial commit

This commit is contained in:
饺子大魔王
2025-04-11 08:14:27 +08:00
commit 626af60456
1540 changed files with 110511 additions and 0 deletions
+440
View File
@@ -0,0 +1,440 @@
import { API_PREFIX } from '@/config'
import Toast from '@/app/components/base/toast'
import type { AnnotationReply, MessageEnd, MessageReplace, ThoughtItem } from '@/app/components/chat/type-mars'
import type { VisionFile } from '@/types/app'
const TIME_OUT = 100000
const ContentType = {
json: 'application/json',
stream: 'text/event-stream',
form: 'application/x-www-form-urlencoded; charset=UTF-8',
download: 'application/octet-stream', // for download
}
const baseOptions = {
method: 'GET',
mode: 'cors',
credentials: 'include', // always send cookies、HTTP Basic authentication.
headers: new Headers({
'Content-Type': ContentType.json,
}),
redirect: 'follow',
}
export type WorkflowStartedResponse = {
task_id: string
workflow_run_id: string
event: string
data: {
id: string
workflow_id: string
sequence_number: number
created_at: number
}
}
export type WorkflowFinishedResponse = {
task_id: string
workflow_run_id: string
event: string
data: {
id: string
workflow_id: string
status: string
outputs: any
error: string
elapsed_time: number
total_tokens: number
total_steps: number
created_at: number
finished_at: number
}
}
export type NodeStartedResponse = {
task_id: string
workflow_run_id: string
event: string
data: {
id: string
node_id: string
node_type: string
index: number
predecessor_node_id?: string
inputs: any
created_at: number
extras?: any
}
}
export type NodeFinishedResponse = {
task_id: string
workflow_run_id: string
event: string
data: {
id: string
node_id: string
node_type: string
index: number
predecessor_node_id?: string
inputs: any
process_data: any
outputs: any
status: string
error: string
elapsed_time: number
execution_metadata: {
total_tokens: number
total_price: number
currency: string
}
created_at: number
}
}
export type IOnDataMoreInfo = {
conversationId?: string
taskId?: string
messageId: string
errorMessage?: string
errorCode?: string
}
export type IOnData = (message: string, isFirstMessage: boolean, moreInfo: IOnDataMoreInfo) => void
export type IOnThought = (though: ThoughtItem) => void
export type IOnFile = (file: VisionFile) => void
export type IOnMessageEnd = (messageEnd: MessageEnd) => void
export type IOnMessageReplace = (messageReplace: MessageReplace) => void
export type IOnAnnotationReply = (messageReplace: AnnotationReply) => void
export type IOnCompleted = (hasError?: boolean) => void
export type IOnError = (msg: string, code?: string) => void
export type IOnWorkflowStarted = (workflowStarted: WorkflowStartedResponse) => void
export type IOnWorkflowFinished = (workflowFinished: WorkflowFinishedResponse) => void
export type IOnNodeStarted = (nodeStarted: NodeStartedResponse) => void
export type IOnNodeFinished = (nodeFinished: NodeFinishedResponse) => void
type IOtherOptions = {
isPublicAPI?: boolean
bodyStringify?: boolean
needAllResponseContent?: boolean
deleteContentType?: boolean
onData?: IOnData // for stream
onThought?: IOnThought
onFile?: IOnFile
onMessageEnd?: IOnMessageEnd
onMessageReplace?: IOnMessageReplace
onError?: IOnError
onCompleted?: IOnCompleted // for stream
getAbortController?: (abortController: AbortController) => void
onWorkflowStarted?: IOnWorkflowStarted
onWorkflowFinished?: IOnWorkflowFinished
onNodeStarted?: IOnNodeStarted
onNodeFinished?: IOnNodeFinished
}
function unicodeToChar(text: string) {
return text.replace(/\\u[0-9a-f]{4}/g, (_match, p1) => {
return String.fromCharCode(parseInt(p1, 16))
})
}
const handleStream = (
response: Response,
onData: IOnData,
onCompleted?: IOnCompleted,
onThought?: IOnThought,
onMessageEnd?: IOnMessageEnd,
onMessageReplace?: IOnMessageReplace,
onFile?: IOnFile,
onWorkflowStarted?: IOnWorkflowStarted,
onWorkflowFinished?: IOnWorkflowFinished,
onNodeStarted?: IOnNodeStarted,
onNodeFinished?: IOnNodeFinished,
) => {
if (!response.ok)
throw new Error('Network response was not ok')
const reader = response.body?.getReader()
const decoder = new TextDecoder('utf-8')
let buffer = ''
let bufferObj: Record<string, any>
let isFirstMessage = true
function read() {
let hasError = false
reader?.read().then((result: any) => {
if (result.done) {
onCompleted && onCompleted()
return
}
buffer += decoder.decode(result.value, { stream: true })
const lines = buffer.split('\n')
try {
lines.forEach((message) => {
if (message.startsWith('data: ')) { // check if it starts with data:
try {
bufferObj = JSON.parse(message.substring(6)) as Record<string, any>// remove data: and parse as json
}
catch (e) {
// mute handle message cut off
onData('', isFirstMessage, {
conversationId: bufferObj?.conversation_id,
messageId: bufferObj?.message_id,
})
return
}
if (bufferObj.status === 400 || !bufferObj.event) {
onData('', false, {
conversationId: undefined,
messageId: '',
errorMessage: bufferObj?.message,
errorCode: bufferObj?.code,
})
hasError = true
onCompleted?.(true)
return
}
if (bufferObj.event === 'message' || bufferObj.event === 'agent_message') {
// can not use format here. Because message is splited.
onData(unicodeToChar(bufferObj.answer), isFirstMessage, {
conversationId: bufferObj.conversation_id,
taskId: bufferObj.task_id,
messageId: bufferObj.id,
})
isFirstMessage = false
}
else if (bufferObj.event === 'agent_thought') {
onThought?.(bufferObj as ThoughtItem)
}
else if (bufferObj.event === 'message_file') {
onFile?.(bufferObj as VisionFile)
}
else if (bufferObj.event === 'message_end') {
onMessageEnd?.(bufferObj as MessageEnd)
}
else if (bufferObj.event === 'message_replace') {
onMessageReplace?.(bufferObj as MessageReplace)
}
else if (bufferObj.event === 'workflow_started') {
onWorkflowStarted?.(bufferObj as WorkflowStartedResponse)
}
else if (bufferObj.event === 'workflow_finished') {
onWorkflowFinished?.(bufferObj as WorkflowFinishedResponse)
}
else if (bufferObj.event === 'node_started') {
onNodeStarted?.(bufferObj as NodeStartedResponse)
}
else if (bufferObj.event === 'node_finished') {
onNodeFinished?.(bufferObj as NodeFinishedResponse)
}
}
})
buffer = lines[lines.length - 1]
}
catch (e) {
onData('', false, {
conversationId: undefined,
messageId: '',
errorMessage: `${e}`,
})
hasError = true
onCompleted?.(true)
return
}
if (!hasError)
read()
})
}
read()
}
const baseFetch = (url: string, fetchOptions: any, { needAllResponseContent }: IOtherOptions) => {
const options = Object.assign({}, baseOptions, fetchOptions)
const urlPrefix = API_PREFIX
let urlWithPrefix = `${urlPrefix}${url.startsWith('/') ? url : `/${url}`}`
const { method, params, body } = options
// handle query
if (method === 'GET' && params) {
const paramsArray: string[] = []
Object.keys(params).forEach(key =>
paramsArray.push(`${key}=${encodeURIComponent(params[key])}`),
)
if (urlWithPrefix.search(/\?/) === -1)
urlWithPrefix += `?${paramsArray.join('&')}`
else
urlWithPrefix += `&${paramsArray.join('&')}`
delete options.params
}
if (body)
options.body = JSON.stringify(body)
// Handle timeout
return Promise.race([
new Promise((resolve, reject) => {
setTimeout(() => {
reject(new Error('request timeout'))
}, TIME_OUT)
}),
new Promise((resolve, reject) => {
globalThis.fetch(urlWithPrefix, options)
.then((res: any) => {
const resClone = res.clone()
// Error handler
if (!/^(2|3)\d{2}$/.test(res.status)) {
try {
switch (res.status) {
case 401: {
Toast.notify({ type: 'error', message: 'Invalid token' })
return
}
case 500: {
Toast.notify({ type: 'error', message: 'Server error' })
return
}
default:
// eslint-disable-next-line no-new
new Promise(() => {
const bodyJson = res.json()
bodyJson.then((data: any) => {
Toast.notify({ type: 'error', message: data.message })
})
})
}
}
catch (e) {
Toast.notify({ type: 'error', message: `${e}` })
}
return Promise.reject(resClone)
}
// handle delete api. Delete api not return content.
if (res.status === 204) {
resolve({ result: 'success' })
return
}
// return data
const data = options.headers.get('Content-type') === ContentType.download ? res.blob() : res.json()
resolve(needAllResponseContent ? resClone : data)
})
.catch((err) => {
Toast.notify({ type: 'error', message: err })
reject(err)
})
}),
])
}
export const upload = (fetchOptions: any, url?: string): Promise<any> => {
const urlPrefix = API_PREFIX
const urlWithPrefix = url ? `${urlPrefix}/${url}` : `${urlPrefix}/file-upload`
const defaultOptions = {
method: 'POST',
url: `${urlWithPrefix}`,
data: {},
}
const options = {
...defaultOptions,
...fetchOptions,
}
return new Promise((resolve, reject) => {
const xhr = options.xhr
xhr.open(options.method, options.url)
for (const key in options.headers)
xhr.setRequestHeader(key, options.headers[key])
xhr.withCredentials = true
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200)
resolve(JSON.parse(xhr.response))
else
reject(xhr)
}
}
xhr.upload.onprogress = options.onprogress
xhr.send(options.data)
})
}
export const ssePost = (
url: string,
fetchOptions: any,
{
onData,
onCompleted,
onThought,
onFile,
onMessageEnd,
onMessageReplace,
onWorkflowStarted,
onWorkflowFinished,
onNodeStarted,
onNodeFinished,
onError,
}: IOtherOptions,
) => {
const options = Object.assign({}, baseOptions, {
method: 'POST',
}, fetchOptions)
const urlPrefix = API_PREFIX
const urlWithPrefix = `${urlPrefix}${url.startsWith('/') ? url : `/${url}`}`
const { body } = options
if (body)
options.body = JSON.stringify(body)
globalThis.fetch(urlWithPrefix, options)
.then((res: any) => {
if (!/^(2|3)\d{2}$/.test(res.status)) {
// eslint-disable-next-line no-new
new Promise(() => {
res.json().then((data: any) => {
Toast.notify({ type: 'error', message: data.message || 'Server Error' })
})
})
onError?.('Server Error')
return
}
return handleStream(res, (str: string, isFirstMessage: boolean, moreInfo: IOnDataMoreInfo) => {
if (moreInfo.errorMessage) {
Toast.notify({ type: 'error', message: moreInfo.errorMessage })
return
}
onData?.(str, isFirstMessage, moreInfo)
}, () => {
onCompleted?.()
}, onThought, onMessageEnd, onMessageReplace, onFile, onWorkflowStarted, onWorkflowFinished, onNodeStarted, onNodeFinished)
}).catch((e) => {
Toast.notify({ type: 'error', message: e })
onError?.(e)
})
}
export const request = (url: string, options = {}, otherOptions?: IOtherOptions) => {
return baseFetch(url, options, otherOptions || {})
}
export const get = (url: string, options = {}, otherOptions?: IOtherOptions) => {
return request(url, Object.assign({}, options, { method: 'GET' }), otherOptions)
}
export const post = (url: string, options = {}, otherOptions?: IOtherOptions) => {
return request(url, Object.assign({}, options, { method: 'POST' }), otherOptions)
}
export const put = (url: string, options = {}, otherOptions?: IOtherOptions) => {
return request(url, Object.assign({}, options, { method: 'PUT' }), otherOptions)
}
export const del = (url: string, options = {}, otherOptions?: IOtherOptions) => {
return request(url, Object.assign({}, options, { method: 'DELETE' }), otherOptions)
}
+339
View File
@@ -0,0 +1,339 @@
import type { Fetcher } from 'swr'
import { del, get, post, put } from './base'
import type {
AccountIntegrate,
ApiBasedExtension,
CodeBasedExtension,
CommonResponse,
DataSourceNotion,
FileUploadConfigResponse,
ICurrentWorkspace,
IWorkspace,
InitValidateStatusResponse,
InvitationResponse,
LangGeniusVersionResponse,
Member,
ModerateResponse,
OauthResponse,
PluginProvider,
Provider,
ProviderAnthropicToken,
ProviderAzureToken,
SetupStatusResponse,
UserProfileOriginResponse,
} from '@/models/common'
import type {
UpdateOpenAIKeyResponse,
ValidateOpenAIKeyResponse,
} from '@/models/app'
import type {
DefaultModelResponse,
Model,
ModelItem,
ModelLoadBalancingConfig,
ModelParameterRule,
ModelProvider,
ModelTypeEnum,
} from '@/app/components/header/account-setting/model-provider-page/declarations'
import type { RETRIEVE_METHOD } from '@/types/app'
import type { SystemFeatures } from '@/types/feature'
type LoginSuccess = {
result: 'success'
data: { access_token: string; refresh_token: string }
}
type LoginFail = {
result: 'fail'
data: string
code: string
message: string
}
type LoginResponse = LoginSuccess | LoginFail
export const login: Fetcher<LoginResponse, { url: string; body: Record<string, any> }> = ({ url, body }) => {
return post(url, { body }) as Promise<LoginResponse>
}
export const fetchNewToken: Fetcher<CommonResponse & { data: { access_token: string; refresh_token: string } }, { body: Record<string, any> }> = ({ body }) => {
return post('/refresh-token', { body }) as Promise<CommonResponse & { data: { access_token: string; refresh_token: string } }>
}
export const setup: Fetcher<CommonResponse, { body: Record<string, any> }> = ({ body }) => {
return post<CommonResponse>('/setup', { body })
}
export const initValidate: Fetcher<CommonResponse, { body: Record<string, any> }> = ({ body }) => {
return post<CommonResponse>('/init', { body })
}
export const fetchInitValidateStatus = () => {
return get<InitValidateStatusResponse>('/init')
}
export const fetchSetupStatus = () => {
return get<SetupStatusResponse>('/setup')
}
export const fetchUserProfile: Fetcher<UserProfileOriginResponse, { url: string; params: Record<string, any> }> = ({ url, params }) => {
return get<UserProfileOriginResponse>(url, params, { needAllResponseContent: true })
}
export const updateUserProfile: Fetcher<CommonResponse, { url: string; body: Record<string, any> }> = ({ url, body }) => {
return post<CommonResponse>(url, { body })
}
export const logout: Fetcher<CommonResponse, { url: string; params: Record<string, any> }> = ({ url, params }) => {
return get<CommonResponse>(url, params)
}
export const fetchLanggeniusVersion: Fetcher<LangGeniusVersionResponse, { url: string; params: Record<string, any> }> = ({ url, params }) => {
return get<LangGeniusVersionResponse>(url, { params })
}
export const oauth: Fetcher<OauthResponse, { url: string; params: Record<string, any> }> = ({ url, params }) => {
return get<OauthResponse>(url, { params })
}
export const oneMoreStep: Fetcher<CommonResponse, { url: string; body: Record<string, any> }> = ({ url, body }) => {
return post<CommonResponse>(url, { body })
}
export const fetchMembers: Fetcher<{ accounts: Member[] | null }, { url: string; params: Record<string, any> }> = ({ url, params }) => {
return get<{ accounts: Member[] | null }>(url, { params })
}
export const fetchProviders: Fetcher<Provider[] | null, { url: string; params: Record<string, any> }> = ({ url, params }) => {
return get<Provider[] | null>(url, { params })
}
export const validateProviderKey: Fetcher<ValidateOpenAIKeyResponse, { url: string; body: { token: string } }> = ({ url, body }) => {
return post<ValidateOpenAIKeyResponse>(url, { body })
}
export const updateProviderAIKey: Fetcher<UpdateOpenAIKeyResponse, { url: string; body: { token: string | ProviderAzureToken | ProviderAnthropicToken } }> = ({ url, body }) => {
return post<UpdateOpenAIKeyResponse>(url, { body })
}
export const fetchAccountIntegrates: Fetcher<{ data: AccountIntegrate[] | null }, { url: string; params: Record<string, any> }> = ({ url, params }) => {
return get<{ data: AccountIntegrate[] | null }>(url, { params })
}
export const inviteMember: Fetcher<InvitationResponse, { url: string; body: Record<string, any> }> = ({ url, body }) => {
return post<InvitationResponse>(url, { body })
}
export const updateMemberRole: Fetcher<CommonResponse, { url: string; body: Record<string, any> }> = ({ url, body }) => {
return put<CommonResponse>(url, { body })
}
export const deleteMemberOrCancelInvitation: Fetcher<CommonResponse, { url: string }> = ({ url }) => {
return del<CommonResponse>(url)
}
export const fetchFilePreview: Fetcher<{ content: string }, { fileID: string }> = ({ fileID }) => {
return get<{ content: string }>(`/files/${fileID}/preview`)
}
export const fetchCurrentWorkspace: Fetcher<ICurrentWorkspace, { url: string; params: Record<string, any> }> = ({ url, params }) => {
return get<ICurrentWorkspace>(url, { params })
}
export const updateCurrentWorkspace: Fetcher<ICurrentWorkspace, { url: string; body: Record<string, any> }> = ({ url, body }) => {
return post<ICurrentWorkspace>(url, { body })
}
export const fetchWorkspaces: Fetcher<{ workspaces: IWorkspace[] }, { url: string; params: Record<string, any> }> = ({ url, params }) => {
return get<{ workspaces: IWorkspace[] }>(url, { params })
}
export const switchWorkspace: Fetcher<CommonResponse & { new_tenant: IWorkspace }, { url: string; body: Record<string, any> }> = ({ url, body }) => {
return post<CommonResponse & { new_tenant: IWorkspace }>(url, { body })
}
export const fetchDataSource: Fetcher<{ data: DataSourceNotion[] }, { url: string }> = ({ url }) => {
return get<{ data: DataSourceNotion[] }>(url)
}
export const syncDataSourceNotion: Fetcher<CommonResponse, { url: string }> = ({ url }) => {
return get<CommonResponse>(url)
}
export const fetchPluginProviders: Fetcher<PluginProvider[] | null, string> = (url) => {
return get<PluginProvider[] | null>(url)
}
export const validatePluginProviderKey: Fetcher<ValidateOpenAIKeyResponse, { url: string; body: { credentials: any } }> = ({ url, body }) => {
return post<ValidateOpenAIKeyResponse>(url, { body })
}
export const updatePluginProviderAIKey: Fetcher<UpdateOpenAIKeyResponse, { url: string; body: { credentials: any } }> = ({ url, body }) => {
return post<UpdateOpenAIKeyResponse>(url, { body })
}
export const invitationCheck: Fetcher<CommonResponse & { is_valid: boolean; data: { workspace_name: string; email: string; workspace_id: string } }, { url: string; params: { workspace_id?: string; email?: string; token: string } }> = ({ url, params }) => {
return get<CommonResponse & { is_valid: boolean; data: { workspace_name: string; email: string; workspace_id: string } }>(url, { params })
}
export const activateMember: Fetcher<LoginResponse, { url: string; body: any }> = ({ url, body }) => {
return post<LoginResponse>(url, { body })
}
export const fetchModelProviders: Fetcher<{ data: ModelProvider[] }, string> = (url) => {
return get<{ data: ModelProvider[] }>(url)
}
export type ModelProviderCredentials = {
credentials?: Record<string, string | undefined | boolean>
load_balancing: ModelLoadBalancingConfig
}
export const fetchModelProviderCredentials: Fetcher<ModelProviderCredentials, string> = (url) => {
return get<ModelProviderCredentials>(url)
}
export const fetchModelLoadBalancingConfig: Fetcher<{
credentials?: Record<string, string | undefined | boolean>
load_balancing: ModelLoadBalancingConfig
}, string> = (url) => {
return get<{
credentials?: Record<string, string | undefined | boolean>
load_balancing: ModelLoadBalancingConfig
}>(url)
}
export const fetchModelProviderModelList: Fetcher<{ data: ModelItem[] }, string> = (url) => {
return get<{ data: ModelItem[] }>(url)
}
export const fetchModelList: Fetcher<{ data: Model[] }, string> = (url) => {
return get<{ data: Model[] }>(url)
}
export const validateModelProvider: Fetcher<ValidateOpenAIKeyResponse, { url: string; body: any }> = ({ url, body }) => {
return post<ValidateOpenAIKeyResponse>(url, { body })
}
export const validateModelLoadBalancingCredentials: Fetcher<ValidateOpenAIKeyResponse, { url: string; body: any }> = ({ url, body }) => {
return post<ValidateOpenAIKeyResponse>(url, { body })
}
export const setModelProvider: Fetcher<CommonResponse, { url: string; body: any }> = ({ url, body }) => {
return post<CommonResponse>(url, { body })
}
export const deleteModelProvider: Fetcher<CommonResponse, { url: string; body?: any }> = ({ url, body }) => {
return del<CommonResponse>(url, { body })
}
export const changeModelProviderPriority: Fetcher<CommonResponse, { url: string; body: any }> = ({ url, body }) => {
return post<CommonResponse>(url, { body })
}
export const setModelProviderModel: Fetcher<CommonResponse, { url: string; body: any }> = ({ url, body }) => {
return post<CommonResponse>(url, { body })
}
export const deleteModelProviderModel: Fetcher<CommonResponse, { url: string }> = ({ url }) => {
return del<CommonResponse>(url)
}
export const getPayUrl: Fetcher<{ url: string }, string> = (url) => {
return get<{ url: string }>(url)
}
export const fetchDefaultModal: Fetcher<{ data: DefaultModelResponse }, string> = (url) => {
return get<{ data: DefaultModelResponse }>(url)
}
export const updateDefaultModel: Fetcher<CommonResponse, { url: string; body: any }> = ({ url, body }) => {
return post<CommonResponse>(url, { body })
}
export const fetchModelParameterRules: Fetcher<{ data: ModelParameterRule[] }, string> = (url) => {
return get<{ data: ModelParameterRule[] }>(url)
}
export const fetchFileUploadConfig: Fetcher<FileUploadConfigResponse, { url: string }> = ({ url }) => {
return get<FileUploadConfigResponse>(url)
}
export const fetchNotionConnection: Fetcher<{ data: string }, string> = (url) => {
return get(url) as Promise<{ data: string }>
}
export const fetchDataSourceNotionBinding: Fetcher<{ result: string }, string> = (url) => {
return get(url) as Promise<{ result: string }>
}
export const fetchApiBasedExtensionList: Fetcher<ApiBasedExtension[], string> = (url) => {
return get(url) as Promise<ApiBasedExtension[]>
}
export const fetchApiBasedExtensionDetail: Fetcher<ApiBasedExtension, string> = (url) => {
return get(url) as Promise<ApiBasedExtension>
}
export const addApiBasedExtension: Fetcher<ApiBasedExtension, { url: string; body: ApiBasedExtension }> = ({ url, body }) => {
return post(url, { body }) as Promise<ApiBasedExtension>
}
export const updateApiBasedExtension: Fetcher<ApiBasedExtension, { url: string; body: ApiBasedExtension }> = ({ url, body }) => {
return post(url, { body }) as Promise<ApiBasedExtension>
}
export const deleteApiBasedExtension: Fetcher<{ result: string }, string> = (url) => {
return del(url) as Promise<{ result: string }>
}
export const fetchCodeBasedExtensionList: Fetcher<CodeBasedExtension, string> = (url) => {
return get(url) as Promise<CodeBasedExtension>
}
export const moderate = (url: string, body: { app_id: string; text: string }) => {
return post(url, { body }) as Promise<ModerateResponse>
}
type RetrievalMethodsRes = {
retrieval_method: RETRIEVE_METHOD[]
}
export const fetchSupportRetrievalMethods: Fetcher<RetrievalMethodsRes, string> = (url) => {
return get<RetrievalMethodsRes>(url)
}
export const getSystemFeatures = () => {
return get<SystemFeatures>('/system-features')
}
export const sendForgotPasswordEmail: Fetcher<CommonResponse & { data: string }, { url: string; body: { email: string } }> = ({ url, body }) =>
post<CommonResponse & { data: string }>(url, { body })
export const verifyForgotPasswordToken: Fetcher<CommonResponse & { is_valid: boolean; email: string }, { url: string; body: { token: string } }> = ({ url, body }) => {
return post(url, { body }) as Promise<CommonResponse & { is_valid: boolean; email: string }>
}
export const changePasswordWithToken: Fetcher<CommonResponse, { url: string; body: { token: string; new_password: string; password_confirm: string } }> = ({ url, body }) =>
post<CommonResponse>(url, { body })
export const uploadRemoteFileInfo = (url: string, isPublic?: boolean) => {
return post<{ id: string; name: string; size: number; mime_type: string; url: string }>('/remote-files/upload', { body: { url } }, { isPublicAPI: isPublic })
}
export const sendEMailLoginCode = (email: string, language = 'en-US') =>
post<CommonResponse & { data: string }>('/email-code-login', { body: { email, language } })
export const emailLoginWithCode = (data: { email: string; code: string; token: string }) =>
post<LoginResponse>('/email-code-login/validity', { body: data })
export const sendResetPasswordCode = (email: string, language = 'en-US') =>
post<CommonResponse & { data: string; message?: string; code?: string }>('/forgot-password', { body: { email, language } })
export const verifyResetPasswordCode = (body: { email: string; code: string; token: string }) =>
post<CommonResponse & { is_valid: boolean }>('/forgot-password/validity', { body })
export const sendDeleteAccountCode = () =>
get<CommonResponse & { data: string }>('/account/delete/verify')
export const verifyDeleteAccountCode = (body: { code: string; token: string }) =>
post<CommonResponse & { is_valid: boolean }>('/account/delete', { body })
export const submitDeleteAccountFeedback = (body: { feedback: string; email: string }) =>
post<CommonResponse>('/account/delete/feedback', { body })
+100
View File
@@ -0,0 +1,100 @@
import type { IOnCompleted, IOnData, IOnError, IOnFile, IOnMessageEnd, IOnMessageReplace, IOnNodeFinished, IOnNodeStarted, IOnThought, IOnWorkflowFinished, IOnWorkflowStarted } from './base'
import { get, post, ssePost, del, upload } from './base'
import type { FeedbackType } from '@/app/components/chat/type'
export const sendChatMessage = async (
body: Record<string, any>,
{
onData,
onCompleted,
onThought,
onFile,
onError,
getAbortController,
onMessageEnd,
onMessageReplace,
onWorkflowStarted,
onNodeStarted,
onNodeFinished,
onWorkflowFinished,
}: {
onData: IOnData
onCompleted: IOnCompleted
onFile: IOnFile
onThought: IOnThought
onMessageEnd: IOnMessageEnd
onMessageReplace: IOnMessageReplace
onError: IOnError
getAbortController?: (abortController: AbortController) => void
onWorkflowStarted: IOnWorkflowStarted
onNodeStarted: IOnNodeStarted
onNodeFinished: IOnNodeFinished
onWorkflowFinished: IOnWorkflowFinished
},
) => {
return ssePost('chat-messages', {
body: {
...body,
response_mode: 'streaming',
},
}, { onData, onCompleted, onThought, onFile, onError, getAbortController, onMessageEnd, onMessageReplace, onNodeStarted, onWorkflowStarted, onWorkflowFinished, onNodeFinished })
}
export const fetchConversations = async (limit = 100, last_id = null) => {
return get('conversations', { params: { limit, last_id } })
}
export const fetchChatList = async (conversationId: string, limit = 20, last_id = null) => {
return get('messages', {
params: { conversation_id: conversationId, limit, last_id }
})
}
// init value. wait for server update
export const fetchAppParams = async () => {
return get('parameters')
}
export const updateFeedback = async ({ url, body }: { url: string; body: FeedbackType }) => {
return post(url, { body })
}
export const generationConversationName = async (id: string) => {
return post(`conversations/${id}/name`, { body: { auto_generate: true } })
}
export const uploadRemoteFileInfo = (url: string) => {
return post('/file-upload/remote', { body: { url } })
}
// TODO mars
export const fetchSuggestedQuestions = async (messageId: string) => {
return get(`/messages/${messageId}/suggested`)
}
export const stopChatMessageResponding = async (taskId: string) => {
return post(`/chat-messages/${taskId}/stop`,)
}
export const renameConversation = async (conversationId: string, name: string) => {
return post(`conversations/${conversationId}/name`, { body: { name } })
}
export const delConversation = async (id: string) => {
return del(`conversations/${id}`)
}
export const fetchAppInfo = async () => { return get('info') }
export const fetchAppMeta = async () => { return get('meta') }
export const audioToText = (formData: any): Promise<{ text: string }> => {
return upload({
xhr: new XMLHttpRequest(),
data: formData,
}, '/audio-to-text')
}
export const pinConversation = async (conversationId: string) => {
return get('messages1', { params: { conversation_id: conversationId, limit: 20, last_id: '' } })
}
export const unpinConversation = async (conversationId: string) => {
return get('messages3', { params: { conversation_id: conversationId, limit: 20, last_id: '' } })
}
export const getUrl = async (conversationId: string) => {
return get('messages5', { params: { conversation_id: conversationId, limit: 20, last_id: '' } })
}
+17
View File
@@ -0,0 +1,17 @@
{
"headers": [
{
"source": "/api/(.*)",
"headers": [
{
"key": "Cache-Control",
"value": "no-store, max-age=0"
},
{
"key": "Pragma",
"value": "no-cache"
}
]
}
]
}