llm-to-agent/src/index.ts
2026-06-08 18:16:42 +08:00

62 lines
2.0 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { ContextManager } from './context.js';
import { chat } from './llm.js';
import { PROMPTS } from './prompts/system.js';
import { getOpenAITools, findTool } from './tools/registry.js';
import * as readline from 'node:readline/promises';
const promptName = process.argv[2] || 'reAct';
const systemPrompt = PROMPTS[promptName as keyof typeof PROMPTS];
if (!systemPrompt) {
console.error(`未知提示词: ${promptName},可选: ${Object.keys(PROMPTS).join(', ')}`);
process.exit(1);
}
const context = new ContextManager();
context.add({ role: 'system', content: systemPrompt });
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
console.log(`提示词模式: ${promptName},输入 "exit" 退出。\n`);
while (true) {
const userInput = await rl.question('我: ');
if (userInput.toLowerCase() === 'exit') break;
context.add({ role: 'user', content: userInput });
// 第一轮:带工具定义调用
const tools = getOpenAITools();
let reply = await chat(context.getMessages(), tools);
// 如果模型要求调用工具,执行并在上下文中构造 tool 消息
while (reply.tool_calls && reply.tool_calls.length > 0) {
// 先把 assistant 消息(含 tool_calls加入上下文
context.add({ role: 'assistant', content: '', tool_calls: reply.tool_calls } as any);
for (const tc of reply.tool_calls) {
const tool = findTool(tc.function.name);
const args = JSON.parse(tc.function.arguments);
const result = await tool!.execute(args);
console.log(` [工具] ${tc.function.name}(${tc.function.arguments}) -> ${result}`);
// tool 消息:必须回传 tool_call_id
context.add({
role: 'tool',
tool_call_id: tc.id,
content: result,
} as any);
}
// 继续调用,看模型还需要不需要更多工具
reply = await chat(context.getMessages(), tools);
}
console.log('助手:', reply.content);
context.add({ role: 'assistant', content: reply.content! });
}
rl.close();