Files
sionrui/frontend/app/web-gold/src/api/agent.js
2026-02-22 21:36:47 +08:00

85 lines
2.1 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* AI 智能体 API
*/
import request from '@/api/http'
import { fetchEventSource } from '@microsoft/fetch-event-source'
import tokenManager from '@gold/utils/token-manager'
import { API_BASE } from '@gold/config/api'
const BASE_URL = `${API_BASE.APP_TIK}`
/**
* 获取启用的智能体列表
*/
export function getAgentList() {
return request({
url: `${BASE_URL}/agent/list`,
method: 'get'
})
}
/**
* 流式对话SSE
* @param {Object} options - 请求配置
* @param {number} options.agentId - 智能体ID
* @param {string} options.content - 用户输入内容
* @param {string} [options.conversationId] - 会话ID可选首次对话不传
* @param {AbortController} [options.ctrl] - 取消控制器
* @param {Function} options.onMessage - 消息回调
* @param {Function} [options.onError] - 错误回调
* @param {Function} [options.onClose] - 关闭回调
*/
export async function sendChatStream(options) {
const {
agentId,
content,
conversationId,
ctrl,
onMessage,
onError,
onClose
} = options || {}
const token = tokenManager.getAccessToken()
return fetchEventSource(`${BASE_URL}/dify/chat/stream`, {
method: 'post',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`,
'tenant-id': import.meta.env?.VITE_TENANT_ID
},
openWhenHidden: true,
body: JSON.stringify({
agentId,
content,
conversationId
}),
onmessage: (event) => {
if (typeof onMessage === 'function') {
try {
const data = JSON.parse(event.data)
// 解析 CommonResult 包装
const result = data.code === 0 ? data.data : data
onMessage(result)
} catch (e) {
console.error('解析 SSE 数据失败:', e)
}
}
},
onerror: (err) => {
if (typeof onError === 'function') {
onError(err)
}
throw err // 不重试
},
onclose: () => {
if (typeof onClose === 'function') {
onClose()
}
},
signal: ctrl ? ctrl.signal : undefined
})
}