|
| 1 | +import { TOOLKIT, type ToolName } from "./tools" |
| 2 | + |
| 3 | +type Role = "system" | "user" | "assistant" |
| 4 | + |
| 5 | +type ChatMessage = { |
| 6 | + role: Role |
| 7 | + content: string |
| 8 | +} |
| 9 | + |
| 10 | +type ParsedAssistant = { |
| 11 | + action?: { tool: string; input: string } |
| 12 | + final?: string |
| 13 | +} |
| 14 | + |
| 15 | +type DeepSeekMessage = { content?: string } |
| 16 | +type DeepSeekChoice = { message?: DeepSeekMessage } |
| 17 | +type DeepSeekResponse = { choices?: DeepSeekChoice[] } |
| 18 | + |
| 19 | +/** |
| 20 | + * 调用 DeepSeek API 获取模型回复 |
| 21 | + * @param messages 对话消息列表,包含 system、user 和 assistant 角色的消息 |
| 22 | + * @returns 模型生成的回复文本 |
| 23 | + * @throws 如果 API 请求失败或返回格式不正确,将抛出错误 |
| 24 | + */ |
| 25 | +async function callLLMs(messages: ChatMessage[]): Promise<string> { |
| 26 | + const res = await fetch("https://api.deepseek.com/v1/chat/completions", { |
| 27 | + method: "POST", |
| 28 | + headers: { |
| 29 | + "Content-Type": "application/json", |
| 30 | + Authorization: `Bearer ${process.env.DEEPSEEK_API_KEY}`, |
| 31 | + }, |
| 32 | + body: JSON.stringify({ |
| 33 | + model: "deepseek-chat", |
| 34 | + messages, |
| 35 | + temperature: 0.35, |
| 36 | + }), |
| 37 | + }) |
| 38 | + |
| 39 | + if (!res.ok) { |
| 40 | + const text = await res.text() |
| 41 | + throw new Error(`DeepSeek API 错误: ${res.status} ${text}`) |
| 42 | + } |
| 43 | + |
| 44 | + const data = (await res.json()) as DeepSeekResponse |
| 45 | + const content = data.choices?.[0]?.message?.content |
| 46 | + if (typeof content !== "string") { |
| 47 | + throw new Error("DeepSeek 返回内容为空") |
| 48 | + } |
| 49 | + return content |
| 50 | +} |
| 51 | + |
| 52 | +/** |
| 53 | + * 解析 Assistant 回复,提取工具调用信息或最终回答 |
| 54 | + * @param content Assistant 回复的文本内容,可能包含 <action> 或 <final> 标签 |
| 55 | + * @returns ParsedAssistant 对象,包含 action(工具调用信息)或 final(最终回答)字段 |
| 56 | + */ |
| 57 | +function parseAssistant(content: string): ParsedAssistant { |
| 58 | + const actionMatch = content.match( |
| 59 | + /<action[^>]*tool="([^"]+)"[^>]*>([\s\S]*?)<\/action>/i, |
| 60 | + ) |
| 61 | + const finalMatch = content.match(/<final>([\s\S]*?)<\/final>/i) |
| 62 | + |
| 63 | + const parsed: ParsedAssistant = {} |
| 64 | + if (actionMatch) { |
| 65 | + parsed.action = { |
| 66 | + tool: actionMatch[1] as ToolName, |
| 67 | + input: actionMatch[2]?.trim() ?? "", |
| 68 | + } |
| 69 | + } |
| 70 | + if (finalMatch) { |
| 71 | + parsed.final = finalMatch[1]?.trim() |
| 72 | + } |
| 73 | + |
| 74 | + return parsed |
| 75 | +} |
| 76 | + |
| 77 | +/** |
| 78 | + * Agent 主循环,负责与 LLM 交互、解析回复、调用工具并更新对话历史 |
| 79 | + * @param question |
| 80 | + * @returns 最终回答字符串,或错误提示 |
| 81 | + */ |
| 82 | +async function AgentLoop(question: string) { |
| 83 | + const systemPrompt = await Bun.file("prompt.md").text() |
| 84 | + |
| 85 | + const history: ChatMessage[] = [ |
| 86 | + { role: "system", content: systemPrompt }, |
| 87 | + { role: "user", content: question }, |
| 88 | + ] |
| 89 | + |
| 90 | + for (let step = 0; step < 10; step++) { |
| 91 | + const assistantText = await callLLMs(history) |
| 92 | + console.log(`\n[LLM 第 ${step + 1} 轮输出]\n${assistantText}\n`) |
| 93 | + history.push({ role: "assistant", content: assistantText }) |
| 94 | + |
| 95 | + const parsed = parseAssistant(assistantText) |
| 96 | + if (parsed.final) { |
| 97 | + return parsed.final |
| 98 | + } |
| 99 | + |
| 100 | + if (parsed.action) { |
| 101 | + const toolFn = TOOLKIT[parsed.action.tool as ToolName] |
| 102 | + let observation: string |
| 103 | + |
| 104 | + if (toolFn) { |
| 105 | + observation = await toolFn(parsed.action.input) |
| 106 | + } else { |
| 107 | + observation = `未知工具: ${parsed.action.tool}` |
| 108 | + } |
| 109 | + |
| 110 | + console.log(`<observation>${observation}</observation>\n`) |
| 111 | + |
| 112 | + history.push({ |
| 113 | + role: "user", |
| 114 | + content: `<observation>${observation}</observation>`, |
| 115 | + }) |
| 116 | + continue |
| 117 | + } |
| 118 | + |
| 119 | + break // 未产生 action 或 final |
| 120 | + } |
| 121 | + |
| 122 | + return "未能生成最终回答,请重试或调整问题。" |
| 123 | +} |
| 124 | + |
| 125 | +/** |
| 126 | + * 程序入口,读取用户问题,调用 AgentLoop 获取回答并输出 |
| 127 | + */ |
| 128 | +async function main() { |
| 129 | + const userQuestion = process.argv.slice(2).join(" ") || "上海现在天气如何?" |
| 130 | + console.log(`用户问题: ${userQuestion}`) |
| 131 | + |
| 132 | + try { |
| 133 | + const answer = await AgentLoop(userQuestion) |
| 134 | + console.log("\n=== 最终回答 ===") |
| 135 | + console.log(answer) |
| 136 | + } catch (err) { |
| 137 | + console.error(`运行失败: ${(err as Error).message}`) |
| 138 | + } |
| 139 | +} |
| 140 | + |
| 141 | +await main() |
0 commit comments