add AiConversationList.vue

This commit is contained in:
Timi
2026-09-16 21:32:03 +08:00
parent 91938f2427
commit a0fac39c99
6 changed files with 663 additions and 8 deletions
+131 -2
View File
@@ -6,7 +6,10 @@ import {
GaoAiHttpError,
GaoAiStreamError,
parseSseData,
readConversation as readConversationApi,
readSseStream,
type GaoAiConversationMessage,
type GaoAiConversationReadResponse,
type GaoAiStreamEvent
} from "@/api/GaoAiAPI";
@@ -58,17 +61,18 @@ export function useAiChat(options: UseAiChatOptions) {
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);
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) {
if (!normalizedMessage || isGenerating.value || isLoadingConversation.value) {
return;
}
@@ -152,6 +156,70 @@ export function useAiChat(options: UseAiChatOptions) {
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);
@@ -330,6 +398,51 @@ export function useAiChat(options: UseAiChatOptions) {
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?.();
}
@@ -345,11 +458,14 @@ export function useAiChat(options: UseAiChatOptions) {
return {
messages,
conversationId: computed(() => conversationId.value),
isGenerating,
isLoadingConversation,
activeToolStatus,
lastError,
canRetry,
sendMessage,
loadConversation,
stopGeneration,
resetConversation,
retryLastMessage
@@ -565,3 +681,16 @@ function formatScope(value: unknown): string | undefined {
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";
}