2026-06-15 16:29:09 +08:00

178 lines
3.9 KiB
TypeScript

import { ref } from "vue";
// 火山方舟 Chat Completions API 配置
const LLM_API_URL =
"https://ai.yantootech.com/polyhedron/api/ark/chat/completions";
const DEFAULT_MODEL = "bot-20260605135355-68pth";
// ChatBase API 配置
const CHATBASE_API_URL = "https://www.chatbase.co/api/v1/chat";
const CHATBASE_API_KEY = "ca4616db-417c-4dce-8c65-b9909621f53e";
const CHATBASE_CHATBOT_ID = "TRIe58TuVExBm6K0HKTfz";
interface LLMMessage {
role: "system" | "user" | "assistant";
content: string;
}
interface ChatBaseMessage {
content: string;
role: "user";
}
interface LLMChoice {
index: number;
message: {
role: string;
content: string;
};
finish_reason: string;
}
interface LLMResponse {
id?: string;
object?: string;
created?: number;
model?: string;
choices?: LLMChoice[];
usage?: {
prompt_tokens: number;
completion_tokens: number;
total_tokens: number;
};
error?: string;
details?: string;
}
export function useLLM() {
const isLoading = ref(false);
const error = ref("");
const conversationHistory = ref<LLMMessage[]>([]);
const SYSTEM_PROMPT: LLMMessage = {
role: "system",
content: "你是一个友好的数字人助手,请用简洁自然的语言回答用户的问题。",
};
const sendToLLM = async (userMessage: string): Promise<string> => {
if (!userMessage.trim()) return "";
isLoading.value = true;
error.value = "";
conversationHistory.value.push({
role: "user",
content: userMessage,
});
try {
const messages: LLMMessage[] = [
SYSTEM_PROMPT,
...conversationHistory.value,
];
const response = await fetch(LLM_API_URL, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
model: DEFAULT_MODEL,
stream: false,
messages,
}),
});
if (!response.ok) {
throw new Error(`HTTP错误: ${response.status}`);
}
const data: LLMResponse = await response.json();
if (data.error) {
throw new Error(`API错误: ${data.error}`);
}
const aiReply = data.choices?.[0]?.message?.content || "";
conversationHistory.value.push({
role: "assistant",
content: aiReply,
});
return aiReply;
} catch (err: any) {
const errorMsg = err.message || "请求失败";
error.value = errorMsg;
console.error("LLM请求错误:", err);
throw err;
} finally {
isLoading.value = false;
}
};
const clearHistory = () => {
conversationHistory.value = [];
};
const sendToChatBase = async (userMessage: string): Promise<string> => {
if (!userMessage.trim()) return "";
isLoading.value = true;
error.value = "";
try {
const messages: ChatBaseMessage[] = [
{ content: userMessage, role: "user" },
];
const response = await fetch(CHATBASE_API_URL, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${CHATBASE_API_KEY}`,
},
body: JSON.stringify({
messages,
chatbotId: CHATBASE_CHATBOT_ID,
}),
});
if (!response.ok) {
throw new Error(`HTTP错误: ${response.status}`);
}
const data = await response.json();
const aiReply = data.text || "";
conversationHistory.value.push({
role: "user",
content: userMessage,
});
conversationHistory.value.push({
role: "assistant",
content: aiReply,
});
return aiReply;
} catch (err: any) {
const errorMsg = err.message || "请求失败";
error.value = errorMsg;
console.error("ChatBase请求错误:", err);
throw err;
} finally {
isLoading.value = false;
}
};
return {
isLoading,
error,
conversationHistory,
sendToLLM,
sendToChatBase,
clearHistory,
};
}