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

相关推荐
满栀585几秒前
三级联动下拉框
开发语言·前端·jquery
杨超越luckly7 分钟前
HTML应用指南:利用GET请求获取网易云热歌榜
前端·python·html·数据可视化·网易云热榜
前端_yu小白8 分钟前
React实现Vue的watch和computed
前端·vue.js·react.js·watch·computed·hooks
多看书少吃饭10 分钟前
OnlyOffice 编辑器的实现及使用
前端·vue.js·编辑器
编程之路从0到117 分钟前
JSI入门指南
前端·c++·react native
开始学java19 分钟前
别再写“一锅端”的 useEffect!聊聊 React 副作用的逻辑分离
前端
百度地图汽车版23 分钟前
【智图译站】基于异步时空图卷积网络的不规则交通预测
前端·后端
qq_124987075327 分钟前
基于Spring Boot的“味蕾探索”线上零食购物平台的设计与实现(源码+论文+部署+安装)
java·前端·数据库·spring boot·后端·小程序
编程之路从0到129 分钟前
React Native 之Android端 Bolts库
android·前端·react native
小酒星小杜29 分钟前
在AI时代,技术人应该每天都要花两小时来构建一个自身的构建系统 - Build 篇
前端·vue.js·架构