介紹
我們將創建一個能夠搜尋維基百科並根據找到的資訊回答問題的人工智慧代理。該 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 將有三個主要狀態:
- 思想(反思)
- 行動(執行)
- 答案(回覆)
[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:
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. >>>>>>>", 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] 維基百科部分如何運作
與維基百科的互動主要分為兩個步驟:
-
初始搜尋(維基百科功能):
- 向維基百科搜尋 API 發出請求。
- 最多回傳 4 個相關的查詢結果。
- 對於每個結果,它都會取得頁面的各個部分。
-
詳細搜尋(wikipedia_with_pageId函數):
- 使用頁面 ID 和部分 ID 來取得特定內容。
- 傳回請求部分的文字。
此流程允許代理人首先獲得與查詢相關的主題的概述,然後根據需要深入研究特定部分。
[6] 執行流程範例
- 使用者提出問題。
- 智能體進入思考狀態並反思問題。
- 它決定搜尋維基百科並進入 ACTION 狀態。
- 執行wikipedia函數並取得結果。
- 返回THOUGHT狀態反思結果。
- 可能決定搜尋更多詳細資訊或不同的方法。
- 根據需要重複思想和行動循環。
- 當它有足夠的資訊時,它進入ANSWER狀態。
- 根據收集到的所有資訊產生最終答案。
- 只要維基百科沒有可收集的數據,就會進入無限循環。用計時器修復它=P
[7] 最後的考慮
- 模組化結構可以輕鬆新增工具或 API。
- 實作錯誤處理和時間/迭代限制非常重要,以避免無限循環或過度資源使用。
- 使用溫度:99999 哈哈
以上是使用 nodeJS 從頭開始建立 ReAct Agent(維基百科搜尋)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

JavaScript字符串替換方法詳解及常見問題解答 本文將探討兩種在JavaScript中替換字符串字符的方法:在JavaScript代碼內部替換和在網頁HTML內部替換。 在JavaScript代碼內部替換字符串 最直接的方法是使用replace()方法: str = str.replace("find","replace"); 該方法僅替換第一個匹配項。要替換所有匹配項,需使用正則表達式並添加全局標誌g: str = str.replace(/fi

簡單JavaScript函數用於檢查日期是否有效。 function isValidDate(s) { var bits = s.split('/'); var d = new Date(bits[2] '/' bits[1] '/' bits[0]); return !!(d && (d.getMonth() 1) == bits[1] && d.getDate() == Number(bits[0])); } //測試 var

本文探討如何使用 jQuery 獲取和設置 DOM 元素的內邊距和外邊距值,特別是元素外邊距和內邊距的具體位置。雖然可以使用 CSS 設置元素的內邊距和外邊距,但獲取準確的值可能會比較棘手。 // 設定 $("div.header").css("margin","10px"); $("div.header").css("padding","10px"); 你可能會認為這段代碼很

本文探討了十個特殊的jQuery選項卡和手風琴。 選項卡和手風琴之間的關鍵區別在於其內容面板的顯示和隱藏方式。讓我們深入研究這十個示例。 相關文章:10個jQuery選項卡插件

發現十個傑出的jQuery插件,以提升您的網站的活力和視覺吸引力!這個精選的收藏品提供了不同的功能,從圖像動畫到交互式畫廊。讓我們探索這些強大的工具:相關文章:1

HTTP-Console是一個節點模塊,可為您提供用於執行HTTP命令的命令行接口。不管您是否針對Web服務器,Web Serv

本教程向您展示瞭如何將自定義的Google搜索API集成到您的博客或網站中,提供了比標準WordPress主題搜索功能更精緻的搜索體驗。 令人驚訝的是簡單!您將能夠將搜索限制為Y

當div內容超出容器元素區域時,以下jQuery代碼片段可用於添加滾動條。 (無演示,請直接複製到Firebug中) //D = document //W = window //$ = jQuery var contentArea = $(this), wintop = contentArea.scrollTop(), docheight = $(D).height(), winheight = $(W).height(), divheight = $('#c


熱AI工具

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

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

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

DVWA
Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

Atom編輯器mac版下載
最受歡迎的的開源編輯器

Dreamweaver Mac版
視覺化網頁開發工具

PhpStorm Mac 版本
最新(2018.2.1 )專業的PHP整合開發工具

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