update AIChart, customer followup, media selector

This commit is contained in:
Timi
2026-09-18 17:38:55 +08:00
parent c6b398fa98
commit 57c4275a23
57 changed files with 3866 additions and 2071 deletions
-696
View File
@@ -1,696 +0,0 @@
import { computed, onUnmounted, shallowRef, toValue, watch, type MaybeRefOrGetter } from "vue";
import { useUserStore } from "timi-web-api/store";
import {
chat,
ensureChatResponse,
GaoAiHttpError,
GaoAiStreamError,
parseSseData,
readConversation as readConversationApi,
readSseStream,
type GaoAiConversationMessage,
type GaoAiConversationReadResponse,
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 AiThinking {
id: number;
content: string;
}
export interface AiChatMessage {
id: number;
role: AiMessageRole;
content: string;
thinkingList: AiThinking[];
citationList: AiCitation[];
createdAt: number;
statusText?: string;
duration?: number;
}
export interface UseAiChatOptions {
sessionKey: MaybeRefOrGetter<string>;
storeId?: MaybeRefOrGetter<string | undefined>;
scrollToBottom?: () => Promise<void>;
}
const conversationExpiredText = "AI 会话不存在或已过期";
const thinkOpenMarkers = ["<thinking>", "<think>"];
const thinkCloseMarkers = ["</thinking>", "</think>"];
interface AssistantResponseState {
rawText: string;
eventThinkingList: AiThinking[];
taggedThinkingList: AiThinking[];
}
/** 管理门店智能助手的会话、流式消息和取消操作。 */
export function useAiChat(options: UseAiChatOptions) {
const userStore = useUserStore();
const messages = shallowRef<AiChatMessage[]>([]);
const conversationId = shallowRef("");
const isGenerating = shallowRef(false);
const isLoadingConversation = shallowRef(false);
const activeToolStatus = shallowRef("");
const lastError = shallowRef("");
const lastQuestion = shallowRef("");
const canRetry = computed(() => !!lastError.value && !!lastQuestion.value && !isGenerating.value && !isLoadingConversation.value);
let activeController: AbortController | undefined;
let messageSequence = 0;
const responseStateMap = new Map<number, AssistantResponseState>();
async function sendMessage(message: string): Promise<void> {
const normalizedMessage = message.trim();
if (!normalizedMessage || isGenerating.value || isLoadingConversation.value) {
return;
}
const userMessage: AiChatMessage = {
id: nextMessageId(),
role: "user",
content: normalizedMessage,
thinkingList: [],
citationList: [],
createdAt: Date.now()
};
const assistantMessage: AiChatMessage = {
id: nextMessageId(),
role: "assistant",
content: "",
thinkingList: [],
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 = "";
responseStateMap.delete(assistantMessage.id);
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 = [];
responseStateMap.clear();
conversationId.value = "";
isGenerating.value = false;
activeToolStatus.value = "";
lastError.value = "";
lastQuestion.value = "";
}
/**
* 读取历史会话并转换成当前聊天页面使用的消息模型。
*
* @param id 历史会话 ID
*/
async function loadConversation(id: string): Promise<void> {
const normalizedId = id.trim();
if (!normalizedId || isGenerating.value || isLoadingConversation.value) {
return;
}
isLoadingConversation.value = true;
messages.value = [];
responseStateMap.clear();
conversationId.value = normalizedId;
lastError.value = "";
lastQuestion.value = "";
try {
const result = await readConversationHistory(normalizedId);
if (conversationId.value !== normalizedId) {
return;
}
messages.value = mapConversationMessages(result);
lastQuestion.value = [...messages.value].reverse().find(item => item.role === "user")?.content || "";
await scrollToBottom();
} catch (error) {
if (conversationId.value === normalizedId) {
resetConversation();
}
throw error;
} finally {
isLoadingConversation.value = false;
}
}
async function readConversationHistory(id: string): Promise<GaoAiConversationReadResponse> {
const messageList: GaoAiConversationMessage[] = [];
let firstId: string | undefined;
let result: GaoAiConversationReadResponse = {};
while (true) {
result = await readConversationApi({
conversationId: id,
firstId,
limit: 100
});
const currentList = Array.isArray(result.data) ? result.data : [];
messageList.push(...currentList);
if (result["has_more"] !== true || !currentList.length) {
break;
}
const nextFirstId = currentList[0]?.id;
if (!nextFirstId || nextFirstId === firstId) {
break;
}
firstId = nextFirstId;
}
return {
...result,
data: messageList
};
}
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 "think":
case "thinking":
appendAssistantThinking(assistantId, extractThinkingText(payload));
return hasDoneEvent;
case "agent_thought":
appendAssistantThinking(assistantId, extractThinkingText(payload), true);
return hasDoneEvent;
case "message":
appendAssistantResponse(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 appendAssistantResponse(assistantId: number, text: string): void {
if (!text) {
return;
}
const state = getAssistantResponseState(assistantId);
state.rawText = mergeResponseText(state.rawText, text);
const parsedResponse = parseAssistantResponse(state.rawText);
state.taggedThinkingList = parsedResponse.thinkingList.map((content, index) => ({
id: state.taggedThinkingList[index]?.id || nextThinkingId(),
content
}));
updateMessage(assistantId, {
content: parsedResponse.answer,
thinkingList: [...state.eventThinkingList, ...state.taggedThinkingList],
statusText: undefined
});
}
function getAssistantResponseState(assistantId: number): AssistantResponseState {
const currentState = responseStateMap.get(assistantId);
if (currentState) {
return currentState;
}
const nextState: AssistantResponseState = {
rawText: "",
eventThinkingList: [],
taggedThinkingList: []
};
responseStateMap.set(assistantId, nextState);
return nextState;
}
function appendAssistantThinking(assistantId: number, text: string, createSegment = false): void {
if (!text) {
return;
}
const state = getAssistantResponseState(assistantId);
const thinkingList = [...state.eventThinkingList];
const lastThinking = thinkingList[thinkingList.length - 1];
if (createSegment || !lastThinking) {
thinkingList.push({ id: nextThinkingId(), content: text });
} else {
thinkingList[thinkingList.length - 1] = {
...lastThinking,
content: lastThinking.content + text
};
}
state.eventThinkingList = thinkingList;
updateMessage(assistantId, {
thinkingList: [...state.eventThinkingList, ...state.taggedThinkingList],
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 {
responseStateMap.delete(id);
updateMessage(id, {
content: "",
thinkingList: [],
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 = [];
responseStateMap.clear();
}
function nextMessageId(): number {
messageSequence += 1;
return messageSequence;
}
let thinkingSequence = 0;
function nextThinkingId(): number {
thinkingSequence += 1;
return thinkingSequence;
}
function mapConversationMessages(response: GaoAiConversationReadResponse): AiChatMessage[] {
const sourceList = Array.isArray(response.data) ? response.data : [];
const orderedList = sourceList
.map((item, index) => ({
item,
index,
timestamp: getTimestamp(item["created_at"])
}))
.sort((left, right) => left.timestamp - right.timestamp || left.index - right.index)
.map(item => item.item);
const messageList: AiChatMessage[] = [];
for (const item of orderedList) {
const createdAt = getTimestamp(item["created_at"]);
const query = getRawString(item.query);
const answer = getRawString(item.answer);
if (query) {
messageList.push({
id: nextMessageId(),
role: "user",
content: query,
thinkingList: [],
citationList: [],
createdAt
});
}
if (answer || isFailedConversationMessage(item)) {
const parsedAnswer = parseAssistantResponse(answer);
messageList.push({
id: nextMessageId(),
role: "assistant",
content: parsedAnswer.answer,
thinkingList: parsedAnswer.thinkingList.map(content => ({
id: nextThinkingId(),
content
})),
citationList: [],
createdAt,
statusText: isFailedConversationMessage(item) ? "本次回答生成失败" : undefined
});
}
}
return messageList;
}
async function scrollToBottom(): Promise<void> {
await options.scrollToBottom?.();
}
watch(() => toValue(options.sessionKey), () => {
resetConversation();
}, { flush: "sync" });
onUnmounted(() => {
activeController?.abort();
clearMessages();
});
return {
messages,
conversationId: computed(() => conversationId.value),
isGenerating,
isLoadingConversation,
activeToolStatus,
lastError,
canRetry,
sendMessage,
loadConversation,
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 getRawString(payload.answer) || getRawString(payload.text) || getRawString(payload.content) || "";
}
function mergeResponseText(currentText: string, nextText: string): string {
if (currentText && nextText.startsWith(currentText)) {
return nextText;
}
return currentText + nextText;
}
function parseAssistantResponse(value: string): { answer: string; thinkingList: string[] } {
let answer = "";
let thinking = "";
let mode: "answer" | "thinking" = "answer";
let cursor = 0;
const thinkingList: string[] = [];
while (cursor < value.length) {
const marker = findMarker(value.slice(cursor), [...thinkOpenMarkers, ...thinkCloseMarkers]);
if (!marker) {
const rest = value.slice(cursor);
if (mode === "thinking") {
thinking += rest;
} else {
answer += rest;
}
break;
}
const content = value.slice(cursor, cursor + marker.index);
if (mode === "thinking") {
thinking += content;
if (thinking) {
thinkingList.push(thinking);
}
thinking = "";
mode = "answer";
} else if (isThinkOpenMarker(marker.value)) {
answer += content;
mode = "thinking";
} else {
if (content) {
thinkingList.push(content);
}
mode = "answer";
}
cursor += marker.index + marker.value.length;
}
if (mode === "thinking" && thinking) {
thinkingList.push(thinking);
}
return { answer, thinkingList };
}
function findMarker(value: string, markerList: string[]): { index: number; value: string } | undefined {
const lowerValue = value.toLowerCase();
return markerList.reduce<{ index: number; value: string } | undefined>((current, marker) => {
const index = lowerValue.indexOf(marker.toLowerCase());
if (index < 0 || (current && current.index <= index)) {
return current;
}
return { index, value: marker };
}, undefined);
}
function isThinkOpenMarker(value: string): boolean {
return thinkOpenMarkers.some(marker => marker.toLowerCase() === value.toLowerCase());
}
function extractThinkingText(payload: unknown): string {
if (typeof payload === "string") {
return payload === "[DONE]" ? "" : payload;
}
if (!isRecord(payload)) {
return "";
}
return getRawString(payload.thought)
|| getRawString(payload.thinking)
|| getRawString(payload.reasoning)
|| getRawString(payload.observation)
|| getRawString(payload.text)
|| getRawString(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 getRawString(value: unknown): string {
return typeof value === "string" ? value : "";
}
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;
}
function getTimestamp(value: number | string | undefined): number {
const timestamp = typeof value === "number" ? value : Number(value);
if (!Number.isFinite(timestamp) || timestamp <= 0) {
return Date.now();
}
return timestamp < 100000000000 ? timestamp * 1000 : timestamp;
}
function isFailedConversationMessage(message: GaoAiConversationMessage): boolean {
const status = getString(message.status)?.toLowerCase();
return status === "error" || status === "failed" || status === "failure";
}