使用 nodeJS 从头开始创建 ReAct Agent(维基百科搜索)
哈喽!今天心血来潮给大家带来了《使用 nodeJS 从头开始创建 ReAct Agent(维基百科搜索)》,想必大家应该对文章都不陌生吧,那么阅读本文就都不会很困难,以下内容主要涉及到,若是你正在学习文章,千万别错过这篇文章~希望能帮助到你!

介绍
我们将创建一个能够搜索维基百科并根据找到的信息回答问题的人工智能代理。该 react(理性与行动)代理使用 google generative ai api 来处理查询并生成响应。我们的代理将能够:
- 搜索维基百科获取相关信息。
- 从维基百科页面中提取特定部分。
- 对收集到的信息进行推理并制定答案。
[2] 什么是react代理?
react agent 是一种遵循反射-操作循环的特定类型的代理。它根据可用信息和它可以执行的操作反映当前任务,然后决定采取哪个操作或是否结束任务。
[3] 规划代理
3.1 所需工具
- node.js
- 用于 http 请求的 axios 库
- google 生成式 ai api (gemini-1.5-flash)
- 维基百科 api
3.2 代理结构
我们的 react agent 将具有三个主要状态:
- 思想(反思)
- 行动(执行)
- 答案(回复)
3.3 思想状态
思想状态是reactagent反思收集到的信息并决定下一步应该做什么的时刻。
async thought() {
.....
}
4.4 动作状态(action)
在动作状态下,代理根据先前的想法执行可用功能之一。
请注意,存在操作(执行)和操作的决策。
这只是一个 llm 通话,内容为:
保证发送到函数的参数。
避免在 javascript 中使用大量正则表达式或转换。
async action() {
// call the decision
// execute the action and return a actionresult
}
async decideaction() {
// call the llm based on the thought ( reflection ) to format and adequate the functioncall.
// look around for a function-tool mode at [google dapi docs](https://ai.google.dev/gemini-api/docs/function-calling)
}
[4] 实现代理
让我们逐步构建 react agent,突出显示每个状态。
4.1 初始设置
首先,设置项目并安装依赖项:
mkdir react-agent-project cd react-agent-project npm init -y npm install axios dotenv @google/generative-ai
在项目根目录创建一个 .env 文件:
google_ai_api_key=your_api_key_here
在这里获取 apikey
4.2 创建tools.js文件
使用以下内容创建 tools.js:
const axios = require("axios");
class tools {
static async wikipedia(q) {
try {
const response = await axios.get("https://en.wikipedia.org/w/api.php", {
params: {
action: "query",
list: "search",
srsearch: q,
srwhat: "text",
format: "json",
srlimit: 4,
},
});
const results = await promise.all(
response.data.query.search.map(async (searchresult) => {
const sectionresponse = await axios.get(
"https://en.wikipedia.org/w/api.php",
{
params: {
action: "parse",
pageid: searchresult.pageid,
prop: "sections",
format: "json",
},
},
);
const sections = object.values(
sectionresponse.data.parse.sections,
).map((section) => `${section.index}, ${section.line}`);
return {
pagetitle: searchresult.title,
snippet: searchresult.snippet,
pageid: searchresult.pageid,
sections: sections,
};
}),
);
return results
.map(
(result) =>
`snippet: ${result.snippet}\npageid: ${result.pageid}\nsections: ${json.stringify(result.sections)}`,
)
.join("\n\n");
} catch (error) {
console.error("error fetching from wikipedia:", error);
return "error fetching data from wikipedia";
}
}
static async wikipedia_with_pageid(pageid, sectionid) {
if (sectionid) {
const response = await axios.get("https://en.wikipedia.org/w/api.php", {
params: {
action: "parse",
format: "json",
pageid: parseint(pageid),
prop: "wikitext",
section: parseint(sectionid),
disabletoc: 1,
},
});
return object.values(response.data.parse?.wikitext ?? {})[0]?.substring(
0,
25000,
);
} else {
const response = await axios.get("https://en.wikipedia.org/w/api.php", {
params: {
action: "query",
pageids: parseint(pageid),
prop: "extracts",
exintro: true,
explaintext: true,
format: "json",
},
});
return object.values(response.data?.query.pages)[0]?.extract;
}
}
}
module.exports = tools;
4.3 创建reactagent.js文件
使用以下内容创建 reactagent.js:
require("dotenv").config();
const { googlegenerativeai } = require("@google/generative-ai");
const tools = require("./tools");
const genai = new googlegenerativeai(process.env.google_ai_api_key);
class reactagent {
constructor(query, functions) {
this.query = query;
this.functions = new set(functions);
this.state = "thought";
this._history = [];
this.model = genai.getgenerativemodel({
model: "gemini-1.5-flash",
temperature: 2,
});
}
get history() {
return this._history;
}
pushhistory(value) {
this._history.push(`\n ${value}`);
}
async run() {
this.pushhistory(`**task: ${this.query} **`);
try {
return await this.step();
} catch (e) {
if (e.message.includes("exhausted")) {
return "sorry, i'm exhausted, i can't process your request anymore. ><";
}
return "unable to process your request, please try again? ><";
}
}
async step() {
const colors = {
reset: "\x1b[0m",
yellow: "\x1b[33m",
red: "\x1b[31m",
cyan: "\x1b[36m",
};
console.log("====================================");
console.log(
`next movement: ${
this.state === "thought"
? colors.yellow
: this.state === "action"
? colors.red
: this.state === "answer"
? colors.cyan
: colors.reset
}${this.state}${colors.reset}`,
);
console.log(`last movement: ${this.history[this.history.length - 1]}`);
console.log("====================================");
switch (this.state) {
case "thought":
await this.thought();
break;
case "action":
await this.action();
break;
case "answer":
await this.answer();
break;
}
}
async promptmodel(prompt) {
const result = await this.model.generatecontent(prompt);
const response = await result.response;
return response.text();
}
async thought() {
const availablefunctions = json.stringify(array.from(this.functions));
const historycontext = this.history.join("\n");
//play around with the prompt to perceive the differences.
//feel free to comment asking for guidance if anything.
//feel free to comment looking for guidance.
//improving the thought part can be as simple as adding this two lines to the beginning of the prompt: becoming :
//your task to fullfill ${this.query}.
//if you already have an answer for the task, you can go ahead and
fullfill it.
//otherwise you act accordingly to the following scenario >>>
const prompt = `your task to fullfill ${this.query}.
context contains all the reflection you made so far and the actionresult you collected.
availableactions are functions you can call whenever you need more data.
context: "${historycontext}" <<
availableactions: "${availablefunctions}" <<
task: "${this.query}" <<
reflect uppon your task using context, actionresult and availableactions to find your next_step.
print your next_step with a thought or fullfill your task `;
const thought = await this.promptmodel(prompt);
this.pushhistory(`\n **${thought.trim()}**`);
if (
thought.tolowercase().includes("fullfill") ||
thought.tolowercase().includes("fulfill")
) {
this.state = "answer";
return await this.step();
}
this.state = "action";
return await this.step();
}
async action() {
const action = await this.decideaction();
this.pushhistory(`** action: ${action} **`);
const result = await this.executefunctioncall(action);
this.pushhistory(`** actionresult: ${result} **`);
this.state = "thought";
return await this.step();
}
async decideaction() {
const availablefunctions = json.stringify(array.from(this.functions));
const historycontext = this.history;
const prompt = `reflect uppon the thought, query and availableactions
${historycontext[historycontext.length - 2]}
thought <<< ${historycontext[historycontext.length - 1]}
query: "${this.query}"
availableactions: ${availablefunctions}
output only the function,parametervalues separated by a comma. for example: "wikipedia,ronaldinho gaucho, 1450"`;
const decision = await this.promptmodel(prompt);
return `${decision.replace(/`/g, "").trim()}`;
}
async executefunctioncall(functioncall) {
const [functionname, ...args] = functioncall.split(",");
const func = tools[functionname.trim()];
if (func) {
return await func.call(null, ...args);
}
throw new error(`function ${functionname} not found`);
}
async answer() {
const historycontext = this.history;
const prompt = `based on the following context, provide a complete, detailed and descriptive formated answer for the following task: ${this.query} .
context:
${historycontext}
task: "${this.query}"`;
const finalanswer = await this.promptmodel(prompt);
this.history.push(`answer: ${this.finalanswer}`);
console.log("we will answer >>>>>>>", finalanswer);
return finalanswer;
}
}
module.exports = reactagent;
4.4 运行代理(index.js)
使用以下内容创建index.js:
const ReActAgent = require("./ReactAgent.js");
async function main() {
const query = "What does England border with?";
// const query = "what are the neighbourhoods of Joinville?";
// const query = "what is the capital of France?";
// const query = "What does england borders with?";
// const query = "what is the color of the sky?";
const functions = [
[
"wikipedia",
"params: query",
"Semantic Search Wikipedia API for snippets, pageIds and sectionIds >> \n ex: Date brazil has been colonized? \n Brazil was colonized at 1500, pageId, sections : []",
],
[
"wikipedia_with_pageId",
"params : pageId, sectionId",
"Search Wikipedia API for data using a pageId and a sectionIndex as params. \n ex: 1500, 1234 \n Section information about blablalbal",
],
];
const agent = new ReActAgent(query, functions);
try {
const result = await agent.run();
console.log("THE AGENT RETURN THE FOLLOWING >>>", result);
} catch (e) {
console.log("FAILED TO RUN T.T", e);
}
}
main().catch(console.error);
[5] 维基百科部分如何运作
与维基百科的交互主要分为两个步骤:
-
初始搜索(维基百科功能):
- 向维基百科搜索 api 发出请求。
- 最多返回 4 个相关的查询结果。
- 对于每个结果,它都会获取页面的各个部分。
-
详细搜索(wikipedia_with_pageid函数):
- 使用页面 id 和部分 id 来获取特定内容。
- 返回请求部分的文本。
此过程允许代理首先获得与查询相关的主题的概述,然后根据需要深入研究特定部分。
[6] 执行流程示例
- 用户提出问题。
- 智能体进入思考状态并反思问题。
- 它决定搜索维基百科并进入 action 状态。
- 执行wikipedia函数并获取结果。
- 返回thought状态反思结果。
- 可能决定搜索更多详细信息或不同的方法。
- 根据需要重复思想和行动循环。
- 当它有足够的信息时,它进入answer状态。
- 根据收集到的所有信息生成最终答案。
- 只要维基百科没有可收集的数据,就会进入无限循环。用计时器修复它=p
[7] 最后的考虑
- 模块化结构可以轻松添加新工具或 api。
- 实施错误处理和时间/迭代限制非常重要,以避免无限循环或过度资源使用。
- 此示例使用温度 2。温度越小,该代理在轮流中的创造力就越少。尝试使用它来感知 llms 中温度的影响。
以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于文章的相关知识,也可关注golang学习网公众号。
Quarkus 简介:Kubernetes 的 Java Native
- 上一篇
- Quarkus 简介:Kubernetes 的 Java Native
- 下一篇
- 理解 TypeScript 中的 infer 关键字
-
- 文章 · 前端 | 3分钟前 | HTML5代码
- HTML5绘制爱心方法与技巧详解
- 462浏览 收藏
-
- 文章 · 前端 | 3分钟前 |
- JavaScript调试技巧与工具推荐
- 321浏览 收藏
-
- 文章 · 前端 | 9分钟前 |
- React集成Express:同端口开发部署教程
- 485浏览 收藏
-
- 文章 · 前端 | 9分钟前 |
- CSS颜色管理技巧:用变量提升效率
- 376浏览 收藏
-
- 文章 · 前端 | 12分钟前 | html
- HTML添加水印技巧分享
- 145浏览 收藏
-
- 文章 · 前端 | 13分钟前 |
- Morris遍历:O(1)空间二叉树遍历方法
- 207浏览 收藏
-
- 文章 · 前端 | 19分钟前 |
- JavaScript消息队列与事件溯源技术解析
- 421浏览 收藏
-
- 文章 · 前端 | 21分钟前 | HTML滚动条样式
- HTML设置滚动条轨道边框技巧
- 276浏览 收藏
-
- 文章 · 前端 | 24分钟前 |
- CSS标记颜色改不了?试试color配合list-style-type
- 492浏览 收藏
-
- 文章 · 前端 | 26分钟前 |
- fetch与axios哪个更实用?
- 444浏览 收藏
-
- 文章 · 前端 | 35分钟前 |
- CSS背景固定怎么实现
- 354浏览 收藏
-
- 文章 · 前端 | 39分钟前 | html
- HBuilder运行HTML文件详细步骤教程
- 106浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 485次学习
-
- ChatExcel酷表
- ChatExcel酷表是由北京大学团队打造的Excel聊天机器人,用自然语言操控表格,简化数据处理,告别繁琐操作,提升工作效率!适用于学生、上班族及政府人员。
- 3419次使用
-
- Any绘本
- 探索Any绘本(anypicturebook.com/zh),一款开源免费的AI绘本创作工具,基于Google Gemini与Flux AI模型,让您轻松创作个性化绘本。适用于家庭、教育、创作等多种场景,零门槛,高自由度,技术透明,本地可控。
- 3624次使用
-
- 可赞AI
- 可赞AI,AI驱动的办公可视化智能工具,助您轻松实现文本与可视化元素高效转化。无论是智能文档生成、多格式文本解析,还是一键生成专业图表、脑图、知识卡片,可赞AI都能让信息处理更清晰高效。覆盖数据汇报、会议纪要、内容营销等全场景,大幅提升办公效率,降低专业门槛,是您提升工作效率的得力助手。
- 3659次使用
-
- 星月写作
- 星月写作是国内首款聚焦中文网络小说创作的AI辅助工具,解决网文作者从构思到变现的全流程痛点。AI扫榜、专属模板、全链路适配,助力新人快速上手,资深作者效率倍增。
- 4794次使用
-
- MagicLight
- MagicLight.ai是全球首款叙事驱动型AI动画视频创作平台,专注于解决从故事想法到完整动画的全流程痛点。它通过自研AI模型,保障角色、风格、场景高度一致性,让零动画经验者也能高效产出专业级叙事内容。广泛适用于独立创作者、动画工作室、教育机构及企业营销,助您轻松实现创意落地与商业化。
- 4025次使用
-
- JavaScript函数定义及示例详解
- 2025-05-11 502浏览
-
- 优化用户界面体验的秘密武器:CSS开发项目经验大揭秘
- 2023-11-03 501浏览
-
- 使用微信小程序实现图片轮播特效
- 2023-11-21 501浏览
-
- 解析sessionStorage的存储能力与限制
- 2024-01-11 501浏览
-
- 探索冒泡活动对于团队合作的推动力
- 2024-01-13 501浏览

