feat: 自主循环

This commit is contained in:
李岩岩 2026-06-08 17:34:29 +08:00
parent c2a906773f
commit a0023c49f4
5 changed files with 45 additions and 4 deletions

View File

@ -4,7 +4,7 @@ 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] || 'agent';
const promptName = process.argv[2] || 'reAct';
const systemPrompt = PROMPTS[promptName as keyof typeof PROMPTS];
if (!systemPrompt) {
@ -33,7 +33,7 @@ while (true) {
let reply = await chat(context.getMessages(), tools);
// 如果模型要求调用工具,执行并在上下文中构造 tool 消息
if (reply.tool_calls && reply.tool_calls.length > 0) {
while (reply.tool_calls && reply.tool_calls.length > 0) {
// 先把 assistant 消息(含 tool_calls加入上下文
context.add({ role: 'assistant', content: '', tool_calls: reply.tool_calls } as any);

16
src/prompts/reAct.ts Normal file
View File

@ -0,0 +1,16 @@
export const REACT_SYSTEM_PROMPT = `你是一个自主智能体,能够使用工具来完成目标。
##
1. ****
2. ****
##
- JSON
##
-
-
-
- 使`;

View File

@ -1,3 +1,5 @@
import { REACT_SYSTEM_PROMPT } from './reAct.js';
export const PROMPTS = {
default: '你是一个直爽的代码审查员,回答尽量简洁。',
toxic: '你是一个毒舌代码审查员,用讽刺的语气表达。',
@ -6,6 +8,8 @@ export const PROMPTS = {
"answer": "你的回答",
"confidence": 0.0-1.0
}`,
agent: `你是一个有工具调用能力的助手。当需要查询信息或执行计算时,请使用提供的工具。
agent: `你是一个有工具调用能力的助手。当需要查询信息/执行计算或者玩猜谜游戏时,请使用提供的工具。
`,
reAct: REACT_SYSTEM_PROMPT,
} as const;

20
src/tools/guess.ts Normal file
View File

@ -0,0 +1,20 @@
import { Tool } from '../types/index.js';
export const guessTool: Tool = {
name: 'guess_number',
description: '猜一个1到100之间的整数。返回“大了”、“小了”或“猜对了”。',
parameters: {
type: 'object',
properties: {
number: { type: 'number', description: '你猜的数字' },
},
required: ['number'],
},
execute: async (args) => {
// 答案写死在工具内部,模型绝对不知道
const answer = 67;
const guess = args.number;
if (guess === answer) return '猜对了!';
return guess > answer ? '大了' : '小了';
},
};

View File

@ -1,8 +1,9 @@
import { weatherTool } from './weather.js';
import { calculatorTool } from './calculator.js';
import { guessTool } from './guess.js';
import { Tool } from '../types/index.js';
const tools: Tool[] = [weatherTool, calculatorTool];
const tools: Tool[] = [weatherTool, calculatorTool, guessTool];
export function getTools(): Tool[] {
return tools;