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

相关推荐
b***74889 小时前
前端GraphQL案例
前端·后端·graphql
云飞云共享云桌面9 小时前
无需配置传统电脑——智能装备工厂10个SolidWorks共享一台工作站
运维·服务器·前端·网络·算法·电脑
ganshenml9 小时前
sed 流编辑器在前端部署中的作用
前端·编辑器
0***K89210 小时前
Vue数据挖掘开发
前端·javascript·vue.js
蓝胖子的多啦A梦10 小时前
ElementUI表格错位修复技巧
前端·css·vue.js·el-table表格错位
_OP_CHEN10 小时前
前端开发实战深度解析:(一)认识前端和 HTML 与开发环境的搭建
前端·vscode·html·web开发·前端开发
xiAo_Ju10 小时前
iOS一个Fancy UI的Tricky实现
前端·ios
H***997610 小时前
Vue深度学习实战
前端·javascript·vue.js
toooooop811 小时前
Vuex 中 state、mutations 和 actions 的原理和写法
前端·javascript·uni-app
y***866911 小时前
前端CSS-in-JS方案
前端·javascript·css