search
HomeWeb Front-endJS TutorialCreating a ReAct AI Agent with Node.js (Wikipedia search) en

Criando um Agente de IA ReAct com Node.js (pesquisa na Wikipedia ) pt-br

Introduction

We will create an AI agent capable of searching Wikipedia and answering questions based on the information collected.
This ReAct (Reasoning and Action) Agent uses the Google Generative AI API to process queries and generate responses.

Our agent will be able to:

  1. Search for relevant information on Wikipedia.
  2. Extract specific sections from Wikipedia pages.
  3. Reason about the information collected and formulate responses.

[2] What is a ReAct Agent?

A ReAct Agent is a specific type of agent that follows a Reflection-Action cycle. It reflects on the current task, based on the information available and the actions it can take, and then decides what action to take or whether to complete the task.

[3] Planning the Agent

3.1 Required Tools

  • Node.js
  • Axios library for HTTP requests
  • Google Generative AI API (gemini-1.5-flash)
  • Wikipedia API

3.2 Agent Structure

Our ReAct Agent will have three main states:

  1. THOUGHT (Reflection)
  2. ACTION (Execution)
  3. ANSWER (Reply)

3.3 State of Thought

The thinking state is the moment in which ReactAgent will reflect on the information collected and decide what the next step should be.

async thought() {
    // ...
}

3.4 Action State (ACTION)

In the action state, the agent performs one of the available functions based on the previous Thought.
Note that there is the action (execution) and the decision (which action).

async action() {
    // chama a decisão
    // executa a ação e retorna um ActionResult
}

async decideAction() {
    // Chama o LLM com base no Pensamento (reflexão) para formatar e adequar a chamada de função.
    // Procure por um modo de função-ferramenta na [documentação da API do Google](https://ai.google.dev/gemini-api/docs/function-calling)
}

[4] Implementing the Agent

Let's build the ReAct Agent step by step, highlighting each state.

4.1 Initial Configuration

First, configure the project and install the dependencies:

mkdir projeto-agente-react
cd projeto-agente-react
npm init -y
npm install axios dotenv @google/generative-ai

Create a .env file in the project root:

GOOGLE_AI_API_KEY=sua_chave_api_aqui

FREE API Key here

4.2 Role Statement

This file is the JavaScript file that Node.js will use to perform an API call to Wikipedia.
We describe the contents of this file in FunctionDescription.

Create Tools.js with the following content:

const axios = require("axios");

class Tools {
  static async wikipedia(q) {
    try {
      const response = await axios.get("https://pt.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://pt.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://pt.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://pt.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 Creating the ReactAgent.js File

Create ReactAgent.js with the following content:

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: 1.8,
    });
  }

  async run() {
    this.pushHistory(`**Tarefa: ${this.query} **`);
    try {
      return await this.step();
    } catch (e) {
      console.error("Erro durante a execução:", e);
      return "Desculpe, não consegui processar sua solicitação.";
    }
  }

  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":
        return await this.thought();
        break;
      case "ACTION":
        return await this.action();
        break;
      case "ANSWER":
        return await this.answer();
    }
  }

  async thought() {
    const funcoesDisponiveis = JSON.stringify(Array.from(this.functions));
    const contextoHistorico = this.history.join("\n");
    const prompt = `Sua Tarefa é ${this.consulta}
O Contexto posui todas as reflexões que você fez até agora e os ResultadoAção que coletou.
AçõesDisponíveis são funções que você pode chamar sempre que precisar de mais dados.

Contexto: "${contextoHistorico}" 



<h3>
  
  
  4.4 Running the Agent and Explaining Available Tools (index.js)
</h3>

<p>Create index.js with the following content:<br>
</p>

<pre class="brush:php;toolbar:false">const ReactAgent = require("./ReactAgentPTBR.js");

async function main() {
  const query = "Que clubes ronaldinho gaúcho jogou para?";
  // const query = "Quais os bairros de Joinville?";
  // const query = "Qual a capital da frança?";

  const functions = [
    [
      "wikipedia",
      "params: query",
      "Busca semântica na Wikipedia API por pageId e sectionIds >> \n ex: Pontos turísticos de são paulo \n São Paulo é uma cidade com muitos pontos turísticos, pageId, sections : []",
    ],
    [
      "wikipedia_with_pageId",
      "params: pageId, sectionId",
      "Busca na Wikipedia API usando pageId e sectionIndex como parametros. \n ex: 1500,1234 \n Informações sobre a seção blablalbal",
    ],
  ];

  const agent = new ReactAgent(query, functions);
  const result = await agent.run();
  console.log("Resultado do Agente:", result);
}

main().catch(console.error);

Role Description

When trying to add a new tool or function, be sure to describe it well.
In our example, this is already done and added to our ReActAgent class when calling a new Instance.

const functions = [
    [
        "google", // nomeDaFuncao
        "params: query", // NomeDoParâmetroLocal
        "Pesquisa semântica na API da Wikipedia por snippets, pageIds e sectionIds >> \n ex: Quando o Brasil foi colonizado? \n O Brasil foi colonizado em 1500, pageId, sections : []", // breve explicação e exemplo (isso será encaminhado para o LLM)
    ]
];

[5] How the Wikipedia Part Works

Interaction with Wikipedia is done in two main steps:

  1. Initial search (wikipedia function):

    • Makes a request to the Wikipedia search API.
    • Returns up to 4 results relevant to the query.
    • For each result, search the sections of the page.
  2. Detailed search (wikipedia_with_pageId function):

    • Uses page ID and section ID to search for specific content.
    • Returns the text of the requested section.

This process allows the agent to first get an overview of topics related to the query and then drill down into specific sections as needed.

[6] Execution Flow Example

  1. User asks a question.
  2. The agent enters the THOUGHT state and reflects on the question.
  3. He decides to search Wikipedia and enters the ACTION state.
  4. Runs the wikipedia function and gets results.
  5. Returns to the THOUGHT state to reflect on the results.
  6. You can decide to look for more details or a different approach.
  7. Repeat the THOUGHT and ACTION cycle as needed.
  8. When it has enough information, it enters the ANSWER state.
  9. Generates a final response based on all the information collected.
  10. Enter an infinite loop whenever Wikipedia does not have the data to collect. Fix this with a timer =P

[7] Final Considerations

  • The modular structure allows for easy addition of new tools or APIs.
  • It is important to implement error handling and time/iteration limits to avoid infinite loops or excessive resource usage.
  • This example uses temperature 2. The lower the temperature, the less creative the agent becomes during iterations. Experiment to understand the influence of temperature on LLMs.

The above is the detailed content of Creating a ReAct AI Agent with Node.js (Wikipedia search) en. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Replace String Characters in JavaScriptReplace String Characters in JavaScriptMar 11, 2025 am 12:07 AM

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

Build Your Own AJAX Web ApplicationsBuild Your Own AJAX Web ApplicationsMar 09, 2025 am 12:11 AM

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

10 jQuery Fun and Games Plugins10 jQuery Fun and Games PluginsMar 08, 2025 am 12:42 AM

10 fun jQuery game plugins to make your website more attractive and enhance user stickiness! While Flash is still the best software for developing casual web games, jQuery can also create surprising effects, and while not comparable to pure action Flash games, in some cases you can also have unexpected fun in your browser. jQuery tic toe game The "Hello world" of game programming now has a jQuery version. Source code jQuery Crazy Word Composition Game This is a fill-in-the-blank game, and it can produce some weird results due to not knowing the context of the word. Source code jQuery mine sweeping game

How do I create and publish my own JavaScript libraries?How do I create and publish my own JavaScript libraries?Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

jQuery Parallax Tutorial - Animated Header BackgroundjQuery Parallax Tutorial - Animated Header BackgroundMar 08, 2025 am 12:39 AM

This tutorial demonstrates how to create a captivating parallax background effect using jQuery. We'll build a header banner with layered images that create a stunning visual depth. The updated plugin works with jQuery 1.6.4 and later. Download the

How do I optimize JavaScript code for performance in the browser?How do I optimize JavaScript code for performance in the browser?Mar 18, 2025 pm 03:14 PM

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

Getting Started With Matter.js: IntroductionGetting Started With Matter.js: IntroductionMar 08, 2025 am 12:53 AM

Matter.js is a 2D rigid body physics engine written in JavaScript. This library can help you easily simulate 2D physics in your browser. It provides many features, such as the ability to create rigid bodies and assign physical properties such as mass, area, or density. You can also simulate different types of collisions and forces, such as gravity friction. Matter.js supports all mainstream browsers. Additionally, it is suitable for mobile devices as it detects touches and is responsive. All of these features make it worth your time to learn how to use the engine, as this makes it easy to create a physics-based 2D game or simulation. In this tutorial, I will cover the basics of this library, including its installation and usage, and provide a

Auto Refresh Div Content Using jQuery and AJAXAuto Refresh Div Content Using jQuery and AJAXMar 08, 2025 am 12:58 AM

This article demonstrates how to automatically refresh a div's content every 5 seconds using jQuery and AJAX. The example fetches and displays the latest blog posts from an RSS feed, along with the last refresh timestamp. A loading image is optiona

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools