80 lines
1.8 KiB
TypeScript
80 lines
1.8 KiB
TypeScript
|
|
import request from '@/utils/request'
|
||
|
|
|
||
|
|
// 对话
|
||
|
|
export interface AgentParamsType {
|
||
|
|
message: string // 消息
|
||
|
|
threadId: string // 对话ID
|
||
|
|
checkpointId?: string // 检查点ID
|
||
|
|
imageUrlList?: string[] // 图片URL列表
|
||
|
|
configParams: Record<string, any> // 其他配置参数
|
||
|
|
token: string
|
||
|
|
}
|
||
|
|
export const fetchAgentReply = (data: AgentParamsType): Promise<AgentResponse> => {
|
||
|
|
return request({
|
||
|
|
url: '/api/ai-design/chat',
|
||
|
|
method: 'post',
|
||
|
|
data,
|
||
|
|
meta: { responseAll: true }
|
||
|
|
})
|
||
|
|
}
|
||
|
|
|
||
|
|
// 流式对话
|
||
|
|
export const fetchAgentReplyStream = async (
|
||
|
|
data: AgentParamsType,
|
||
|
|
onMessage: (chunk: string) => void,
|
||
|
|
onEnd: () => void
|
||
|
|
) => {
|
||
|
|
try {
|
||
|
|
const params = new URLSearchParams({
|
||
|
|
message: data.message,
|
||
|
|
threadId: data.threadId,
|
||
|
|
token: data.token,
|
||
|
|
configParams: JSON.stringify(data.configParams)
|
||
|
|
})
|
||
|
|
|
||
|
|
const response = await fetch(`/api/ai-design/chat?${params.toString()}`, {
|
||
|
|
method: 'GET'
|
||
|
|
})
|
||
|
|
|
||
|
|
if (!response.ok) {
|
||
|
|
throw new Error(`HTTP error! status: ${response.status}`)
|
||
|
|
}
|
||
|
|
|
||
|
|
const reader = response.body?.getReader()
|
||
|
|
if (!reader) {
|
||
|
|
throw new Error('Response body is not readable')
|
||
|
|
}
|
||
|
|
|
||
|
|
const decoder = new TextDecoder()
|
||
|
|
let buffer = ''
|
||
|
|
|
||
|
|
while (true) {
|
||
|
|
const { done, value } = await reader.read()
|
||
|
|
if (done) break
|
||
|
|
|
||
|
|
buffer += decoder.decode(value, { stream: true })
|
||
|
|
const lines = buffer.split('\n')
|
||
|
|
buffer = lines.pop() || '' // 保留不完整的行
|
||
|
|
|
||
|
|
for (const line of lines) {
|
||
|
|
console.log('line---', line)
|
||
|
|
|
||
|
|
const trimmedLine = line.trim()
|
||
|
|
if (trimmedLine.startsWith('data: ')) {
|
||
|
|
const chunk = trimmedLine.slice(6)
|
||
|
|
if (chunk === '[DONE]') {
|
||
|
|
onEnd()
|
||
|
|
return
|
||
|
|
} else {
|
||
|
|
onMessage(chunk)
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
onEnd()
|
||
|
|
} catch (error) {
|
||
|
|
console.error('Stream error:', error)
|
||
|
|
onEnd()
|
||
|
|
}
|
||
|
|
}
|