实现一个简易的代码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...

相关推荐
软件技术NINI35 分钟前
html css网页制作成品——HTML+CSS盐津铺子网页设计(5页)附源码
前端·css·html
mapbar_front2 小时前
面试问题—我的问题问完了,你还有什么想问我的吗?
前端·面试
quweiie2 小时前
thinkphp8+layui多图上传,带删除\排序功能
前端·javascript·layui
李鸿耀2 小时前
React 项目 SVG 图标太难管?用这套自动化方案一键搞定!
前端
闲蛋小超人笑嘻嘻2 小时前
树形结构渲染 + 选择(Vue3 + ElementPlus)
前端·javascript·vue.js
叶梅树3 小时前
从零构建A股量化交易工具:基于Qlib的全栈系统指南
前端·后端·算法
巴博尔3 小时前
uniapp的IOS中首次进入,无网络问题
前端·javascript·ios·uni-app
Asthenia04123 小时前
技术复盘:从一次UAT环境CORS故障看配置冗余的危害与最佳实践
前端
csj503 小时前
前端基础之《React(1)—webpack简介》
前端·react
被巨款砸中3 小时前
前端 20 个零依赖浏览器原生 API 实战清单
前端·javascript·vue.js·web