Einführung
Wir werden einen KI-Agenten erstellen, der in der Lage ist, Wikipedia zu durchsuchen und Fragen basierend auf den gesammelten Informationen zu beantworten.
Dieser ReAct-Agent (Reasoning and Action) verwendet die Google Generative AI API, um Abfragen zu verarbeiten und Antworten zu generieren.
Unser Agent kann:
- Suchen Sie nach relevanten Informationen auf Wikipedia.
- Bestimmte Abschnitte aus Wikipedia-Seiten extrahieren.
- Begründen Sie die gesammelten Informationen und formulieren Sie Antworten.
[2] Was ist ein ReAct-Agent?
Ein ReAct-Agent ist ein bestimmter Agententyp, der einem Reflexions-Aktions-Zyklus folgt. Es reflektiert die aktuelle Aufgabe auf der Grundlage der verfügbaren Informationen und der möglichen Maßnahmen und entscheidet dann, welche Maßnahmen ergriffen werden sollen oder ob die Aufgabe abgeschlossen werden soll.
[3] Planung des Agenten
3.1 Erforderliche Werkzeuge
- Node.js
- Axios-Bibliothek für HTTP-Anfragen
- Google Generative AI API (gemini-1.5-flash)
- Wikipedia-API
3.2 Agentenstruktur
Unser ReAct Agent wird drei Hauptzustände haben:
- GEDANKE (Reflexion)
- AKTION (Ausführung)
- ANTWORT (Antwort)
3.3 Denkstand
Der Denkzustand ist der Moment, in dem ReactAgent über die gesammelten Informationen nachdenkt und entscheidet, was der nächste Schritt sein soll.
async thought() { // ... }
3.4 Aktionsstatus (ACTION)
Im Aktionszustand führt der Agent eine der verfügbaren Funktionen basierend auf dem vorherigen Gedanken aus.
Beachten Sie, dass es die Aktion (Ausführung) und die Entscheidung (welche Aktion) gibt.
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] Implementierung des Agenten
Lassen Sie uns Schritt für Schritt den ReAct Agent erstellen und dabei jeden Zustand hervorheben.
4.1 Erstkonfiguration
Konfigurieren Sie zunächst das Projekt und installieren Sie die Abhängigkeiten:
mkdir projeto-agente-react cd projeto-agente-react npm init -y npm install axios dotenv @google/generative-ai
Erstellen Sie eine .env-Datei im Projektstammverzeichnis:
GOOGLE_AI_API_KEY=sua_chave_api_aqui
KOSTENLOSER API-Schlüssel hier
4.2 Rollenerklärung
Diese Datei ist die JavaScript-Datei, die Node.js verwendet, um einen API-Aufruf an Wikipedia durchzuführen.
Wir beschreiben den Inhalt dieser Datei in FunctionDescription.
Erstellen Sie Tools.js mit folgendem Inhalt:
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 Erstellen der ReactAgent.js-Datei
Erstellen Sie ReactAgent.js mit folgendem Inhalt:
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 Ausführen des Agenten und Erläutern der verfügbaren Tools (index.js) </h3> <p>Erstellen Sie index.js mit folgendem Inhalt:<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);
Rollenbeschreibung
Wenn Sie versuchen, ein neues Werkzeug oder eine neue Funktion hinzuzufügen, stellen Sie sicher, dass Sie diese gut beschreiben.
In unserem Beispiel ist dies bereits erledigt und beim Aufruf einer neuen Instanz zu unserer ReActAgent-Klasse hinzugefügt.
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] So funktioniert der Wikipedia-Teil
Die Interaktion mit Wikipedia erfolgt in zwei Hauptschritten:
-
Erste Suche (Wikipedia-Funktion):
- Stellt eine Anfrage an die Wikipedia-Such-API.
- Gibt bis zu 4 für die Abfrage relevante Ergebnisse zurück.
- Durchsuchen Sie für jedes Ergebnis die Abschnitte der Seite.
-
Detaillierte Suche (wikipedia_with_pageId-Funktion):
- Verwendet Seiten-ID und Abschnitts-ID, um nach bestimmten Inhalten zu suchen.
- Gibt den Text des angeforderten Abschnitts zurück.
Dieser Prozess ermöglicht es dem Agenten, sich zunächst einen Überblick über Themen im Zusammenhang mit der Abfrage zu verschaffen und dann bei Bedarf einen Drilldown in bestimmte Abschnitte durchzuführen.
[6] 執行流程範例
- 使用者提問。
- 智能體進入思考狀態並反思問題。
- 他決定搜尋維基百科並進入 ACTION 狀態。
- 運行維基百科函數並取得結果。
- 返回THOUGHT狀態反思結果。
- 您可以決定尋找更多細節或不同的方法。
- 根據需要重複思想和行動循環。
- 當它有足夠的資訊時,它進入ANSWER狀態。
- 根據收集到的所有資訊產生最終回應。
- 只要維基百科沒有可收集的數據,就進入無限循環。用計時器解決這個問題=P
[7] 最後的考慮
- 模組化結構可以輕鬆新增工具或 API。
- 實作錯誤處理和時間/迭代限制非常重要,以避免無限循環或過度的資源使用。
- 此範例使用溫度 2。溫度越低,代理在迭代過程中的創造力就越低。透過實驗了解溫度對 LLM 的影響。
以上是使用 Node.js 建立 ReAct AI 代理程式(維基百科搜尋)en的詳細內容。更多資訊請關注PHP中文網其他相關文章!

JavaScript核心數據類型在瀏覽器和Node.js中一致,但處理方式和額外類型有所不同。 1)全局對像在瀏覽器中為window,在Node.js中為global。 2)Node.js獨有Buffer對象,用於處理二進制數據。 3)性能和時間處理在兩者間也有差異,需根據環境調整代碼。

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python和JavaScript的主要區別在於類型系統和應用場景。 1.Python使用動態類型,適合科學計算和數據分析。 2.JavaScript採用弱類型,廣泛用於前端和全棧開發。兩者在異步編程和性能優化上各有優勢,選擇時應根據項目需求決定。

選擇Python還是JavaScript取決於項目類型:1)數據科學和自動化任務選擇Python;2)前端和全棧開發選擇JavaScript。 Python因其在數據處理和自動化方面的強大庫而備受青睞,而JavaScript則因其在網頁交互和全棧開發中的優勢而不可或缺。

Python和JavaScript各有優勢,選擇取決於項目需求和個人偏好。 1.Python易學,語法簡潔,適用於數據科學和後端開發,但執行速度較慢。 2.JavaScript在前端開發中無處不在,異步編程能力強,Node.js使其適用於全棧開發,但語法可能複雜且易出錯。

javascriptisnotbuiltoncorc; sanInterpretedlanguagethatrunsonenginesoftenwritteninc.1)JavascriptwasdesignedAsignedAsalightWeight,drackendedlanguageforwebbrowsers.2)Enginesevolvedfromsimpleterterpretpretpretpretpreterterpretpretpretpretpretpretpretpretpretcompilerers,典型地,替代品。

JavaScript可用於前端和後端開發。前端通過DOM操作增強用戶體驗,後端通過Node.js處理服務器任務。 1.前端示例:改變網頁文本內容。 2.後端示例:創建Node.js服務器。

選擇Python還是JavaScript應基於職業發展、學習曲線和生態系統:1)職業發展:Python適合數據科學和後端開發,JavaScript適合前端和全棧開發。 2)學習曲線:Python語法簡潔,適合初學者;JavaScript語法靈活。 3)生態系統:Python有豐富的科學計算庫,JavaScript有強大的前端框架。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!

SecLists
SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

Safe Exam Browser
Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。