讲师中心 微信公众号
AI工具推荐 视频效率加速

使用 nodeJS 从头开始​​创建 ReAct Agent(维基百科搜索)

雨静君_4698

雨静君_4698

发布时间:2024-09-25 11:22:00

|

1116人浏览过

|

来源于dev.to

转载

使用 nodejs 从头开始​​创建 react agent(维基百科搜索)

介绍

我们将创建一个能够搜索维基百科并根据找到的信息回答问题的人工智能代理。该 react(理性与行动)代理使用 google generative ai api 来处理查询并生成响应。我们的代理将能够:

  1. 搜索维基百科获取相关信息。
  2. 从维基百科页面中提取特定部分。
  3. 对收集到的信息进行推理并制定答案。

[2] 什么是react代理?

react agent 是一种遵循反射-操作循环的特定类型的代理。它根据可用信息和它可以执行的操作反映当前任务,然后决定采取哪个操作或是否结束任务。

[3] 规划代理

3.1 所需工具

  • node.js
  • 用于 http 请求的 axios 库
  • google 生成式 ai api (gemini-1.5-flash)
  • 维基百科 api

3.2 代理结构

我们的 react agent 将具有三个主要状态:

  1. 思想(反思)
  2. 行动(执行)
  3. 答案(回复)

[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

4.2 创建tools.js文件

使用以下内容创建 tools.js:

Model Switcher
Model Switcher

根据任务复杂度自动切换不同的AI模型。支持OpenClaw设置中的所有可用模型。当检测到复杂...

下载
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");
    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 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] 维基百科部分如何运作

与维基百科的交互主要分为两个步骤:

  1. 初始搜索(维基百科功能):

    • 向维基百科搜索 api 发出请求。
    • 最多返回 4 个相关的查询结果。
    • 对于每个结果,它都会获取页面的各个部分。
  2. 详细搜索(wikipedia_with_pageid函数):

    • 使用页面 id 和部分 id 来获取特定内容。
    • 返回请求部分的文本。

此过程允许代理首先获得与查询相关的主题的概述,然后根据需要深入研究特定部分。

[6] 执行流程示例

  1. 用户提出问题。
  2. 智能体进入思考状态并反思问题。
  3. 它决定搜索维基百科并进入 action 状态。
  4. 执行wikipedia函数并获取结果。
  5. 返回thought状态反思结果。
  6. 可能决定搜索更多详细信息或不同的方法。
  7. 根据需要重复思想和行动循环。
  8. 当它有足够的信息时,它进入answer状态。
  9. 根据收集到的所有信息生成最终答案。
  10. 只要维基百科没有可收集的数据,就会进入无限循环。用计时器修复它=p

[7] 最后的考虑

  • 模块化结构可以轻松添加新工具或 api。
  • 实施错误处理和时间/迭代限制非常重要,以避免无限循环或过度资源使用。
  • 使用温度:99999 哈哈

热门AI工具

更多
立刻MV
立刻MV Hot

立刻MV是一款AI文本写作工具,AI 音乐视频(MV)创作工具。

豆包大模型

豆包大模型是一款由字节跳动推出的企业级大语言模型服务平台。

小橡皮AI

一款AI工具,主要用于小橡皮一键去AI味,将机器味重的内容改得更有活人感,防止因为 AI 内容被平台打上 AI 标签,以及限流,适合需要提升相关任务效率的用户。

花生AI
花生AI Hot

一款AI视频创作工具,主要用于B站推出的AI视频创作工具,适合需要提升相关任务效率的用户。

蛙蛙写作

一款AI论文写作工具,主要用于超级AI智能写作助手,适合需要提升相关任务效率的用户。

PixPix
PixPix Hot

PixPix是一款面向电商视觉生产的AI商品图生成工具。

DeepSeek

DeepSeek是一款面向对话、写作、编程和推理场景的AI大模型工具。

WorkBuddy

一款AI办公效率工具,主要用于腾讯云推出的AI原生桌面智能体工作台,适合需要提升相关任务效率的用户。

火山引擎

火山引擎是一款面向企业的云计算与AI服务平台。

相关专题

更多
js正则表达式
js正则表达式

php中文网为大家提供各种js正则表达式语法大全以及各种js正则表达式使用的方法,还有更多js正则表达式的相关文章、相关下载、相关课程,供大家免费下载体验。

4656

2023.06.20

js获取当前时间
js获取当前时间

JS全称JavaScript,是一种具有函数优先的轻量级,解释型或即时编译型的编程语言;它是一种属于网络的高级脚本语言,主要用于Web,常用来为网页添加各式各样的动态功能。js怎么获取当前时间呢?php中文网给大家带来了相关的教程以及文章,欢迎大家前来学习阅读。

1395

2023.07.28

js 字符串转数组
js 字符串转数组

js字符串转数组的方法:1、使用“split()”方法;2、使用“Array.from()”方法;3、使用for循环遍历;4、使用“Array.split()”方法。本专题为大家提供js字符串转数组的相关的文章、下载、课程内容,供大家免费下载体验。

1838

2023.08.03

js是什么意思
js是什么意思

JS是JavaScript的缩写,它是一种广泛应用于网页开发的脚本语言。JavaScript是一种解释性的、基于对象和事件驱动的编程语言,通常用于为网页增加交互性和动态性。它可以在网页上实现复杂的功能和效果,如表单验证、页面元素操作、动画效果、数据交互等。

10203

2023.08.17

js删除节点的方法
js删除节点的方法

js删除节点的方法有:1、removeChild()方法,用于从父节点中移除指定的子节点,它需要两个参数,第一个参数是要删除的子节点,第二个参数是父节点;2、parentNode.removeChild()方法,可以直接通过父节点调用来删除子节点;3、remove()方法,可以直接删除节点,而无需指定父节点;4、innerHTML属性,用于删除节点的内容。

1000

2023.09.01

js截取字符串的方法
js截取字符串的方法

js截取字符串的方法有substring()方法、substr()方法、slice()方法、split()方法和slice()方法。本专题为大家提供字符串相关的文章、下载、课程内容,供大家免费下载体验。

2924

2023.09.04

Js中concat和push的区别
Js中concat和push的区别

Js中concat和push的区别:1、concat用于将两个或多个数组合并成一个新数组,并返回这个新数组,而push用于向数组的末尾添加一个或多个元素,并返回修改后的数组的新长度;2、concat不会修改原始数组,是创建新的数组,而push会修改原数组,将新元素添加到原数组的末尾等等。本专题为大家提供concat和push相关的文章、下载、课程内容,供大家免费下载体验。

1609

2023.09.14

js截取字符串的方法介绍
js截取字符串的方法介绍

JavaScript字符串截取方法,包括substring、slice、substr、charAt和split方法。这些方法可以根据具体需求,灵活地截取字符串的不同部分。在实际开发中,根据具体情况选择合适的方法进行字符串截取,能够提高代码的效率和可读性 。

5029

2023.09.21

Vite 项目如何打包和部署
Vite 项目如何打包和部署

Vite项目打包部署专题汇集生产构建、产物预览、输出目录、资源路径、Nginx与GitHub Pages部署及常见白屏和路由404问题的已审核文章,帮助读者完成上线流程。

60

2026.10.28

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
快速入门Node.JS全套完整版
快速入门Node.JS全套完整版

共83课时 | 13.6万人学习

nodejs开发基础教程
nodejs开发基础教程

共15课时 | 4.9万人学习

JavaScript设计模式视频教程
JavaScript设计模式视频教程

共28课时 | 6.3万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn