实现一个简易的代码AI Agent

从零实现AI Agent

Agent的核心是ReAct循环:思考(Thought)→ 行动(Action)→ 观察(Observation)→ 思考...

1.系统提示模板

js 复制代码
export const react_system_prompt_template = `
你需要解决一个问题。为此,你需要将问题分解为多个步骤。对于每个步骤,首先使用 <thought> 思考要做什么,然后使用可用工具之一决定一个 <action>。接着,你将根据你的行动从环境/工具中收到一个 <observation>。持续这个思考和行动的过程,直到你有足够的信息来提供 <final_answer>。

所有步骤请严格使用以下 XML 标签格式输出:
- <question> 用户问题
- <thought> 思考
- <action> 采取的工具操作
- <observation> 工具或环境返回的结果
- <final_answer> 最终答案

请严格遵守:
- 你每次回答都必须包括两个标签,第一个是 <thought>,第二个是 <action> 或 <final_answer>
- 输出 <action> 后立即停止生成,等待真实的 <observation>
- 工具参数中的文件路径请使用绝对路径

本次任务可用工具:
\${tool_list}

环境信息:
操作系统:\${operating_system}
当前目录下文件列表:\${file_list}
`;

2.定义工具(tools)和agent对象

js 复制代码
const tools = [readFile, writeToFile];
const agent = new ReActAgent(tools, "Qwen/Qwen3-Coder-480B-A35B-Instruct", projectDir);
//调用方法返回结果
agent.run('问题xxxxxx');

// 读取工具实现
async function readFile(filePath) {
        const content = await fs.promises.readFile(filePath, 'utf8');
        return content;
}

async function writeToFile(filePath, content) {
        await fs.promises.writeFile(filePath, content.replace(/\\n/g, '\n'), 'utf8');
        return "写入成功";
}

3.实现agent对象核心方法

js 复制代码
//实现run方法
 async run(userInput) {
        const messages = [
            { role: "system", content: this.renderSystemPrompt(react_system_prompt_template) },
            { role: "user", content: `<question>${userInput}</question>` }
        ];
     
		//循环逻辑
        while (true) {
            const content = await this.callModel(messages);

            const thoughtMatch = content.match(/<thought>(.*?)<\/thought>/s);
            
            //最终退出返回结果逻辑
            if (content.includes("<final_answer>")) {
                const finalAnswer = content.match(/<final_answer>(.*?)<\/final_answer>/s);
                return finalAnswer[1];
            }
         
            const actionMatch = content.match(/<action>(.*?)<\/action>/s);
            
            //调用工具逻辑
            const action = actionMatch[1];
            //通过解析返回内容得到工具名和参数
            const [toolName, args] = this.parseAction(action);
            
			//tools方法调用
            try {
                const observation = await this.tools[toolName](...args);
                messages.push({ role: "user", content: `<observation>${observation}</observation>` });
            } catch (error) {
                const observation = `工具执行错误:${error.message}`;
                messages.push({ role: "user", content: `<observation>${observation}</observation>` });
            }
        }
    }

代码地址:github.com/chengqy0106...

相关推荐
fanruitian3 小时前
uniapp android开发 测试板本与发行版本
前端·javascript·uni-app
rayufo3 小时前
【工具】列出指定文件夹下所有的目录和文件
开发语言·前端·python
RANCE_atttackkk3 小时前
[Java]实现使用邮箱找回密码的功能
java·开发语言·前端·spring boot·intellij-idea·idea
2501_944525544 小时前
Flutter for OpenHarmony 个人理财管理App实战 - 支出分析页面
android·开发语言·前端·javascript·flutter
李白你好5 小时前
Burp Suite插件用于自动检测Web应用程序中的未授权访问漏洞
前端
刘一说6 小时前
Vue 组件不必要的重新渲染问题解析:为什么子组件总在“无故”刷新?
前端·javascript·vue.js
徐同保7 小时前
React useRef 完全指南:在异步回调中访问最新的 props/state引言
前端·javascript·react.js
刘一说7 小时前
Vue 导航守卫未生效问题解析:为什么路由守卫不执行或逻辑失效?
前端·javascript·vue.js
一周七喜h8 小时前
在Vue3和TypeScripts中使用pinia
前端·javascript·vue.js
weixin_395448918 小时前
main.c_cursor_0202
前端·网络·算法