chat.ts
1.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import { defineStore } from "pinia";
import { ref } from "vue";
import type { ChatMessage } from "../types";
import { fuseIntent } from "../api/intentFusion";
function makeId(): string {
return `${Date.now()}-${Math.random().toString(16).slice(2)}`;
}
export const useChatStore = defineStore("chat", () => {
const messages = ref<ChatMessage[]>([]);
const sending = ref(false);
const error = ref<string | null>(null);
async function send(text: string): Promise<void> {
const content = text.trim();
if (!content || sending.value) return;
error.value = null;
sending.value = true;
const now = Date.now();
messages.value.push({ id: makeId(), role: "user", content, createdAt: now });
try {
const result = await fuseIntent(content);
messages.value.push({
id: makeId(),
role: "assistant",
content: formatAssistantText(result),
createdAt: Date.now(),
result,
});
} catch (e: any) {
error.value = e?.message ? String(e.message) : "请求失败";
} finally {
sending.value = false;
}
}
function clear(): void {
messages.value = [];
error.value = null;
}
return { messages, sending, error, send, clear };
});
function formatAssistantText(result: any): string {
const resolvedIntents = Array.isArray(result?.resolved?.intents) ? result.resolved.intents : [];
if (resolvedIntents.length > 0) {
return resolvedIntents
.map((x: any) => (x?.name ? String(x.name) : ""))
.filter((s: string) => s)
.join(" | ");
}
const top = result?.top?.name ? String(result.top.name) : "—";
if (top === "orchestrate") {
const cands = Array.isArray(result?.candidates) ? result.candidates : [];
const picked = cands
.map((c: any) => (c?.name ? String(c.name) : ""))
.filter((n: string) => n && n !== "orchestrate")
.slice(0, 3);
if (picked.length > 0) return picked.join(" | ");
}
return top;
}