add AIAgent
This commit is contained in:
@@ -0,0 +1,398 @@
|
||||
import { computed, onUnmounted, shallowRef, toValue, watch, type MaybeRefOrGetter } from "vue";
|
||||
import { useUserStore } from "timi-web-api/store";
|
||||
import {
|
||||
chat,
|
||||
ensureChatResponse,
|
||||
GaoAiHttpError,
|
||||
GaoAiStreamError,
|
||||
parseSseData,
|
||||
readSseStream,
|
||||
type GaoAiStreamEvent
|
||||
} from "@/api/GaoAiAPI";
|
||||
|
||||
export type AiMessageRole = "user" | "assistant";
|
||||
|
||||
export interface AiCitation {
|
||||
source?: string;
|
||||
dataDomain?: string;
|
||||
timeRange?: string;
|
||||
caliber?: string;
|
||||
generatedAt?: string;
|
||||
}
|
||||
|
||||
export interface AiChatMessage {
|
||||
id: number;
|
||||
role: AiMessageRole;
|
||||
content: string;
|
||||
citationList: AiCitation[];
|
||||
createdAt: number;
|
||||
statusText?: string;
|
||||
duration?: number;
|
||||
}
|
||||
|
||||
export interface UseAiChatOptions {
|
||||
sessionKey: MaybeRefOrGetter<string>;
|
||||
storeId?: MaybeRefOrGetter<string | undefined>;
|
||||
scrollToBottom?: () => Promise<void>;
|
||||
}
|
||||
|
||||
const conversationExpiredText = "AI 会话不存在或已过期";
|
||||
|
||||
/** 管理门店智能助手的会话、流式消息和取消操作。 */
|
||||
export function useAiChat(options: UseAiChatOptions) {
|
||||
const userStore = useUserStore();
|
||||
const messages = shallowRef<AiChatMessage[]>([]);
|
||||
const conversationId = shallowRef("");
|
||||
const isGenerating = shallowRef(false);
|
||||
const activeToolStatus = shallowRef("");
|
||||
const lastError = shallowRef("");
|
||||
const lastQuestion = shallowRef("");
|
||||
const canRetry = computed(() => !!lastError.value && !!lastQuestion.value && !isGenerating.value);
|
||||
let activeController: AbortController | undefined;
|
||||
let messageSequence = 0;
|
||||
|
||||
async function sendMessage(message: string): Promise<void> {
|
||||
const normalizedMessage = message.trim();
|
||||
if (!normalizedMessage || isGenerating.value) {
|
||||
return;
|
||||
}
|
||||
|
||||
const userMessage: AiChatMessage = {
|
||||
id: nextMessageId(),
|
||||
role: "user",
|
||||
content: normalizedMessage,
|
||||
citationList: [],
|
||||
createdAt: Date.now()
|
||||
};
|
||||
const assistantMessage: AiChatMessage = {
|
||||
id: nextMessageId(),
|
||||
role: "assistant",
|
||||
content: "",
|
||||
citationList: [],
|
||||
createdAt: Date.now()
|
||||
};
|
||||
messages.value = [...messages.value, userMessage, assistantMessage];
|
||||
lastQuestion.value = normalizedMessage;
|
||||
lastError.value = "";
|
||||
isGenerating.value = true;
|
||||
activeToolStatus.value = "";
|
||||
const controller = new AbortController();
|
||||
activeController = controller;
|
||||
let hasRetriedExpiredConversation = false;
|
||||
|
||||
try {
|
||||
while (true) {
|
||||
resetAssistantMessage(assistantMessage.id);
|
||||
try {
|
||||
await readChatStream(normalizedMessage, assistantMessage.id, controller);
|
||||
break;
|
||||
} catch (error) {
|
||||
if (
|
||||
!hasRetriedExpiredConversation
|
||||
&& !!conversationId.value
|
||||
&& isExpiredConversationError(error)
|
||||
) {
|
||||
hasRetriedExpiredConversation = true;
|
||||
conversationId.value = "";
|
||||
continue;
|
||||
}
|
||||
handleChatError(error, assistantMessage.id, controller.signal.aborted);
|
||||
break;
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
if (activeController === controller) {
|
||||
activeController = undefined;
|
||||
}
|
||||
isGenerating.value = false;
|
||||
activeToolStatus.value = "";
|
||||
await scrollToBottom();
|
||||
}
|
||||
}
|
||||
|
||||
function stopGeneration(): void {
|
||||
if (!isGenerating.value) {
|
||||
return;
|
||||
}
|
||||
activeController?.abort();
|
||||
activeToolStatus.value = "";
|
||||
const assistantMessage = [...messages.value].reverse().find(item => item.role === "assistant");
|
||||
if (assistantMessage) {
|
||||
updateMessage(assistantMessage.id, { statusText: "已停止生成,可重新提问" });
|
||||
}
|
||||
}
|
||||
|
||||
function resetConversation(): void {
|
||||
activeController?.abort();
|
||||
activeController = undefined;
|
||||
messages.value = [];
|
||||
conversationId.value = "";
|
||||
isGenerating.value = false;
|
||||
activeToolStatus.value = "";
|
||||
lastError.value = "";
|
||||
lastQuestion.value = "";
|
||||
}
|
||||
|
||||
async function retryLastMessage(): Promise<void> {
|
||||
if (canRetry.value) {
|
||||
await sendMessage(lastQuestion.value);
|
||||
}
|
||||
}
|
||||
|
||||
async function readChatStream(message: string, assistantId: number, controller: AbortController): Promise<void> {
|
||||
const storeId = options.storeId ? toValue(options.storeId) : undefined;
|
||||
const request = {
|
||||
message,
|
||||
...(conversationId.value ? { conversationId: conversationId.value } : {}),
|
||||
...(storeId ? { storeId } : {})
|
||||
};
|
||||
const response = await chat(request, userStore.token, controller.signal);
|
||||
await ensureChatResponse(response);
|
||||
let hasDoneEvent = false;
|
||||
await readSseStream(response, async (event) => {
|
||||
hasDoneEvent = await handleStreamEvent(event, assistantId, hasDoneEvent);
|
||||
await options.scrollToBottom?.();
|
||||
});
|
||||
if (!hasDoneEvent && !controller.signal.aborted) {
|
||||
throw new GaoAiStreamError("智能助手连接中断,请重试", "DIFY_STREAM_ERROR");
|
||||
}
|
||||
}
|
||||
|
||||
async function handleStreamEvent(event: GaoAiStreamEvent, assistantId: number, hasDoneEvent: boolean): Promise<boolean> {
|
||||
const payload = parseSseData(event.data);
|
||||
switch (event.event) {
|
||||
case "message":
|
||||
appendAssistantText(assistantId, extractText(payload));
|
||||
return hasDoneEvent;
|
||||
case "tool_status":
|
||||
activeToolStatus.value = formatToolStatus(payload);
|
||||
return hasDoneEvent;
|
||||
case "citation":
|
||||
appendCitation(assistantId, normalizeCitation(payload));
|
||||
return hasDoneEvent;
|
||||
case "done":
|
||||
applyDonePayload(assistantId, payload);
|
||||
return true;
|
||||
case "error":
|
||||
throw createStreamError(payload);
|
||||
default:
|
||||
return hasDoneEvent;
|
||||
}
|
||||
}
|
||||
|
||||
function applyDonePayload(assistantId: number, payload: unknown): void {
|
||||
if (!isRecord(payload)) {
|
||||
return;
|
||||
}
|
||||
const nextConversationId = getString(payload.conversationId);
|
||||
if (nextConversationId) {
|
||||
conversationId.value = nextConversationId;
|
||||
}
|
||||
const duration = getNumber(payload.duration);
|
||||
updateMessage(assistantId, {
|
||||
createdAt: Date.now(),
|
||||
duration: duration === undefined ? undefined : duration
|
||||
});
|
||||
}
|
||||
|
||||
function appendAssistantText(assistantId: number, text: string): void {
|
||||
if (!text) {
|
||||
return;
|
||||
}
|
||||
const message = messages.value.find(item => item.id === assistantId);
|
||||
if (!message) {
|
||||
return;
|
||||
}
|
||||
updateMessage(assistantId, { content: message.content + text, statusText: undefined });
|
||||
}
|
||||
|
||||
function appendCitation(assistantId: number, citation?: AiCitation): void {
|
||||
if (!citation) {
|
||||
return;
|
||||
}
|
||||
const message = messages.value.find(item => item.id === assistantId);
|
||||
if (!message) {
|
||||
return;
|
||||
}
|
||||
updateMessage(assistantId, { citationList: [...message.citationList, citation] });
|
||||
}
|
||||
|
||||
function updateMessage(id: number, patch: Partial<AiChatMessage>): void {
|
||||
messages.value = messages.value.map(item => item.id === id ? { ...item, ...patch } : item);
|
||||
}
|
||||
|
||||
function resetAssistantMessage(id: number): void {
|
||||
updateMessage(id, {
|
||||
content: "",
|
||||
citationList: [],
|
||||
statusText: undefined,
|
||||
duration: undefined,
|
||||
createdAt: Date.now()
|
||||
});
|
||||
}
|
||||
|
||||
function handleChatError(error: unknown, assistantId: number, isAborted: boolean): void {
|
||||
if (isAborted) {
|
||||
return;
|
||||
}
|
||||
const message = getChatErrorMessage(error);
|
||||
lastError.value = message;
|
||||
updateMessage(assistantId, { statusText: message });
|
||||
}
|
||||
|
||||
function clearMessages(): void {
|
||||
messages.value = [];
|
||||
}
|
||||
|
||||
function nextMessageId(): number {
|
||||
messageSequence += 1;
|
||||
return messageSequence;
|
||||
}
|
||||
|
||||
async function scrollToBottom(): Promise<void> {
|
||||
await options.scrollToBottom?.();
|
||||
}
|
||||
|
||||
watch(() => toValue(options.sessionKey), () => {
|
||||
resetConversation();
|
||||
}, { flush: "sync" });
|
||||
|
||||
onUnmounted(() => {
|
||||
activeController?.abort();
|
||||
clearMessages();
|
||||
});
|
||||
|
||||
return {
|
||||
messages,
|
||||
isGenerating,
|
||||
activeToolStatus,
|
||||
lastError,
|
||||
canRetry,
|
||||
sendMessage,
|
||||
stopGeneration,
|
||||
resetConversation,
|
||||
retryLastMessage
|
||||
};
|
||||
}
|
||||
|
||||
function isExpiredConversationError(error: unknown): boolean {
|
||||
if (error instanceof GaoAiHttpError || error instanceof GaoAiStreamError) {
|
||||
return error.message.includes(conversationExpiredText)
|
||||
|| error.code?.toLowerCase().includes("session") === true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function extractText(payload: unknown): string {
|
||||
if (typeof payload === "string") {
|
||||
return payload === "[DONE]" ? "" : payload;
|
||||
}
|
||||
if (!isRecord(payload)) {
|
||||
return "";
|
||||
}
|
||||
return getString(payload.answer) || getString(payload.text) || getString(payload.content) || "";
|
||||
}
|
||||
|
||||
function formatToolStatus(payload: unknown): string {
|
||||
if (!isRecord(payload)) {
|
||||
return "正在查询实时业务数据…";
|
||||
}
|
||||
const status = getString(payload.status);
|
||||
return status === "finished" ? "实时业务数据查询完成" : "正在查询实时业务数据…";
|
||||
}
|
||||
|
||||
function normalizeCitation(payload: unknown): AiCitation | undefined {
|
||||
if (typeof payload === "string") {
|
||||
return payload ? { source: payload } : undefined;
|
||||
}
|
||||
if (!isRecord(payload)) {
|
||||
return undefined;
|
||||
}
|
||||
const citation: AiCitation = {
|
||||
source: getString(payload.source),
|
||||
dataDomain: getString(payload.dataDomain) || getString(payload.domain),
|
||||
timeRange: getString(payload.timeRange) || formatScope(payload.scope),
|
||||
caliber: getString(payload.caliber) || getString(payload.metric),
|
||||
generatedAt: getDisplayText(payload.generatedAt) || getDisplayText(payload.generated_at)
|
||||
};
|
||||
return Object.values(citation).some(Boolean) ? citation : undefined;
|
||||
}
|
||||
|
||||
function createStreamError(payload: unknown): GaoAiStreamError {
|
||||
if (!isRecord(payload)) {
|
||||
return new GaoAiStreamError("智能助手查询失败,请稍后重试", "DIFY_ERROR");
|
||||
}
|
||||
return new GaoAiStreamError(
|
||||
getString(payload.message) || "智能助手查询失败,请稍后重试",
|
||||
getString(payload.code)
|
||||
);
|
||||
}
|
||||
|
||||
function getChatErrorMessage(error: unknown): string {
|
||||
if (error instanceof GaoAiHttpError) {
|
||||
if (error.status === 401) {
|
||||
return error.message.includes("会话") ? error.message : "登录已过期,请重新登录";
|
||||
}
|
||||
if (error.status === 403) {
|
||||
return "当前账号无权使用门店智能助手";
|
||||
}
|
||||
if (error.status === 429) {
|
||||
return "请求过于频繁,请稍后再试";
|
||||
}
|
||||
return error.message;
|
||||
}
|
||||
if (error instanceof GaoAiStreamError) {
|
||||
if (error.code === "DIFY_TIMEOUT") {
|
||||
return "数据查询超时,请缩小时间范围后重试";
|
||||
}
|
||||
return error.message;
|
||||
}
|
||||
if (error instanceof DOMException && error.name === "AbortError") {
|
||||
return "已停止生成,可重新提问";
|
||||
}
|
||||
if (error instanceof TypeError) {
|
||||
return "连接中断,可重新提问";
|
||||
}
|
||||
return "智能助手暂时不可用,请稍后重试";
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null;
|
||||
}
|
||||
|
||||
function getString(value: unknown): string | undefined {
|
||||
return typeof value === "string" && value.trim() ? value.trim() : undefined;
|
||||
}
|
||||
|
||||
function getDisplayText(value: unknown): string | undefined {
|
||||
const text = getString(value);
|
||||
if (text) {
|
||||
return text;
|
||||
}
|
||||
const timestamp = getNumber(value);
|
||||
if (timestamp === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
const milliseconds = timestamp < 100000000000 ? timestamp * 1000 : timestamp;
|
||||
return new Date(milliseconds).toLocaleString("zh-CN", { hour12: false });
|
||||
}
|
||||
|
||||
function formatScope(value: unknown): string | undefined {
|
||||
const text = getString(value);
|
||||
if (text) {
|
||||
return text;
|
||||
}
|
||||
if (!isRecord(value)) {
|
||||
return undefined;
|
||||
}
|
||||
const beginAt = getDisplayText(value.beginAt) || getDisplayText(value.begin);
|
||||
const endAt = getDisplayText(value.endAt) || getDisplayText(value.end);
|
||||
if (beginAt && endAt) {
|
||||
return `${beginAt} 至 ${endAt}`;
|
||||
}
|
||||
return beginAt || endAt;
|
||||
}
|
||||
|
||||
function getNumber(value: unknown): number | undefined {
|
||||
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
||||
}
|
||||
Reference in New Issue
Block a user