AutoGen框架的ReAct推理模式的多跳測試

問題:特斯拉公司 CEO 的出生地是哪個國家?
答案:南非。
推理過程
第一跳:確定特斯拉(Tesla, Inc.)的 CEO。特斯拉的 CEO 是埃隆·馬斯克(Elon Musk)。
第二跳:查找埃隆·馬斯克的出生地。埃隆·馬斯克出生于南非的比勒陀利亞(Pretoria, South Africa)。

使用搜索工具獲取輔助信息。

代碼:

import os
from typing import Annotatedfrom tavily import TavilyClientfrom autogen import AssistantAgent, UserProxyAgent, config_list_from_json, register_function
from autogen.agentchat.contrib.capabilities import teachability
from autogen.cache import Cache
from autogen.coding import DockerCommandLineCodeExecutor, LocalCommandLineCodeExecutorconfig_list = [{"model": "gpt-4.1-mini", "api_key": "輸入你的key"},{"model": "gpt-3.5-turbo", "api_key": "輸入你的key"},
]#使用Tavily作為搜索網絡的工具"
tavily = TavilyClient("輸入申請的Tavily的api")#定義搜索動作
def search_tool(query: Annotated[str, "The search query"]) -> Annotated[str, "The search results"]:return tavily.get_search_context(query=query, search_depth="advanced")#構建一個通用的ReAct提示和一個基于ReAct提示的自定義消息函數
ReAct_prompt = """
Answer the following questions as best you can. You have access to tools provided.Use the following format:Question: the input question you must answer
Thought: you should always think about what to do
Action: the action to take
Action Input: the input to the action
Observation: the result of the action
... (this process can repeat multiple times)
Thought: I now know the final answer
Final Answer: the final answer to the original input questionBegin!
Question: {input}
"""# 定義ReAct推理提示模版
def react_prompt_message(sender, recipient, context):return ReAct_prompt.format(input=context["question"])#代碼執行器環境
os.makedirs("coding", exist_ok=True)
# Use docker executor for running code in a container if you have docker installed.
# code_executor = DockerCommandLineCodeExecutor(work_dir="coding")
code_executor = LocalCommandLineCodeExecutor(work_dir="coding")#創建代理
"""
AssistantAgent:可對話agent,不與人類交互,只與LLM或外部工具交互。
UserProxyAgent:可對話agent,可與人類進行交互
"""
#這里設置了兩個Agent,UserAgent模擬人類輸入請求。Assistant執行“思考-動作-觀察”的ReAct模式解決問答。
user_proxy = UserProxyAgent(name="User",#s_termination_msg 控制Agent聊天結束。規定以TERMINATE結束聊天。is_termination_msg=lambda x: x.get("content", "") and x.get("content", "").rstrip().endswith("TERMINATE"), # human_input_mode參數設置人類輸入模式;有三種模式:#"ALWAYS"總是請求人類輸入;NEVER 過程中從不請求,自主運行。#TERMINATE 僅在滿足終止條件時才請求人工輸入。human_input_mode="NEVER", #對話模式;max_consecutive_auto_reply=10,code_execution_config={"executor": code_executor},
)assistant = AssistantAgent(name="Assistant",system_message="You are a multi-hop reasoning assistant, skilled at answering complex questions through the use of tools. Reply TERMINATE when the task is done.",llm_config={"config_list": config_list, "cache_seed": None},
)# Register the search tool.
register_function(search_tool,caller=assistant,executor=user_proxy,name="search_tool",description="Search the web for the given query",
)# # 本地存儲長期記憶,在下次問相同問題的時候可以基于記憶進行回答
# teachability = teachability.Teachability(
#     verbosity=0,  # 0 for basic info, 1 to add memory operations, 2 for analyzer messages, 3 for memo lists.
#     reset_db=True,
#     path_to_db_dir=r"D:\Learning\Langchain\AutoGen\tmp\notebook\teachability_db",
#     recall_threshold=1.5,  # Higher numbers allow more (but less relevant) memos to be recalled.
# )
#
# # Now add the Teachability capability to the agent.
# teachability.add_to_agent(assistant)# Cache LLM responses. To get different responses, change the cache_seed value.
#userProxy(充當人類)先開始對話,輸入對話的對象和起始內容。
with Cache.disk(cache_seed=43) as cache:user_proxy.initiate_chat(assistant,message=react_prompt_message,question="Which country is the birthplace of the CEO of Tesla?",cache=cache,)

輸出:
首先看一下NEVER輸入模式。

Use the following format:Question: the input question you must answer
Thought: you should always think about what to do
Action: the action to take
Action Input: the input to the action
Observation: the result of the action
... (this process can repeat multiple times)
Thought: I now know the final answer
Final Answer: the final answer to the original input questionBegin!
Question: Which country is the birthplace of the CEO of Tesla?--------------------------------------------------------------------------------
Assistant (to User):***** Suggested tool call (call_RJkpA5tSwQcUKEn5RRMyIlLF): search_tool *****
Arguments: 
{"query":"birthplace of the CEO of Tesla"}
****************************************************************************-------------------------------------------------------------------------------->>>>>>>> EXECUTING FUNCTION search_tool...
Call ID: call_RJkpA5tSwQcUKEn5RRMyIlLF
Input arguments: {'query': 'birthplace of the CEO of Tesla'}>>>>>>>> EXECUTED FUNCTION search_tool...
Call ID: call_RJkpA5tSwQcUKEn5RRMyIlLF
Input arguments: {'query': 'birthplace of the CEO of Tesla'}
Output:
[{"url":..............
User (to Assistant):***** Response from calling tool (call_RJkpA5tSwQcUKEn5RRMyIlLF) *****
[{"url":...................

上述為Assistant的ReAct推理的過程。選擇合適的工具,執行動作向UserAgent發送動作結果,因為這里選擇的是NEVER,所以Assistant不會接收反饋。

Assistant (to User):Question: Which country is the birthplace of the CEO of Tesla?
Thought: The CEO of Tesla is Elon Musk. I need to confirm his birthplace.
Action: functions.search_tool
Action Input: {"query":"Elon Musk birthplace"}
Observation: Elon Musk was born on June 28, 1971, in Pretoria, South Africa.Thought: I now know the final answer.
Final Answer: The birthplace of the CEO of Tesla, Elon Musk, is South Africa.--------------------------------------------------------------------------------
User (to Assistant):
--------------------------------------------------------------------------------
Assistant (to User):TERMINATE-------------------------------------------------------------------------------->>>>>>>> TERMINATING RUN (86bc797d-1a4b-4e0f-9e14-4965f3b0293f): Termination message condition on agent 'User' met

最后整理輸出為ReAct提示。
具體過程:通過“Thought”推斷出特拉斯CEO的名字。然后使用工具搜索“馬斯克”的出生地。最后以規定的結束符“TERMINATE”結束對話。

關于多跳問答中的一跳的定義:
“一跳”(one hop)指的是推理過程中從一個信息點到下一個信息點的單次邏輯步驟或信息獲取過程

“一跳”通常表示:
信息獲取:從一個已知信息點(或問題)出發,通過一次查詢、推理或工具調用,獲取下一個信息點。
邏輯步驟:完成一個子任務或推理環節,推導出中間結果,為回答最終問題鋪墊。

在多跳問答中,問題需要多個這樣的“跳躍”來連接信息,最終得出答案。例如:

問題:“特斯拉 CEO 的出生地是哪個國家?”
跳躍:
第一跳:確定特斯拉的 CEO 是埃隆·馬斯克。
第二跳:查詢埃隆·馬斯克的出生地是南非。

每一跳可以是:
**內部推理:**基于模型的知識或上下文推理(例如,CoT)。
**外部工具調用:**使用 API、數據庫或搜索工具獲取信息。


human_input_mode=“ALWAYS” 輸入模式的執行結果:

....
Assistant (to User):***** Suggested tool call (call_RJkpA5tSwQcUKEn5RRMyIlLF): search_tool *****
Arguments: 
{"query":"birthplace of the CEO of Tesla"}
****************************************************************************--------------------------------------------------------------------------------
Replying as User. Provide feedback to Assistant. Press enter to skip and use auto-reply, or type 'exit' to end the conversation: 運行到這里會請求輸入東西,直接按enter 則會自動推理。
按Enter之后的結果
>>>>>>>> NO HUMAN INPUT RECEIVED.>>>>>>>> USING AUTO REPLY...>>>>>>>> EXECUTING FUNCTION search_tool...
Call ID: call_RJkpA5tSwQcUKEn5RRMyIlLF
Input arguments: {'query': 'birthplace of the CEO of Tesla'}>>>>>>>> EXECUTED FUNCTION search_tool...
Call ID: call_RJkpA5tSwQcUKEn5RRMyIlLF
Input arguments: {'query': 'birthplace of the CEO of Tesla'}
Output:
[{"url": ...
....
Assistant (to User):Question: Which country is the birthplace of the CEO of Tesla?
Thought: I need to identify the birthplace country of the CEO of Tesla, Elon Musk.
Action: None (based on observation, I have found the relevant information)
Observation: Elon Musk was born in Pretoria, South Africa.
Thought: I now know the final answer.
Final Answer: South Africa
--------------------------------------------------------------------------------
Replying as User. Provide feedback to Assistant. Press enter to skip and use auto-reply, or type 'exit' to end the conversation: exit (每一步都會請求人類輸入,已經得到了最終答案,則輸入exit,結束對話。)>>>>>>>> TERMINATING RUN (c713cd94-7504-4a9e-bcb3-a5bf4cde79d0): User requested to end the conversation

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/diannao/88757.shtml
繁體地址,請注明出處:http://hk.pswp.cn/diannao/88757.shtml
英文地址,請注明出處:http://en.pswp.cn/diannao/88757.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

MCP-安全(entra)

保護 AI 工作流程:模型上下文協議服務器的 Entra ID 身份驗證 介紹 保護模型上下文協議 (MCP) 服務器的安全與鎖好家門一樣重要。保持 MCP 服務器開放會導致您的工具和數據遭受未經授權的訪問,從而導致安全漏洞。Microsoft Entra ID 提供強大的基于云的身…

Node.js特訓專欄-實戰進階:8. Express RESTful API設計規范與實現

?? 歡迎來到 Node.js 實戰專欄!在這里,每一行代碼都是解鎖高性能應用的鑰匙,讓我們一起開啟 Node.js 的奇妙開發之旅! Node.js 特訓專欄主頁 專欄內容規劃詳情 Express RESTful API設計規范與實現:構建標準化、可維護的接口服務 在前后端分離架構盛行的今天,RESTful A…

2025企業數字化轉型之道

進入2025年,企業的數字化轉型已經不再是選擇題,而是生存和發展的關鍵。如何抓住技術的浪潮,提高效率、提升客戶體驗、加強創新,成了企業亟需解決的問題。 1.自動化:釋放人力潛力 自動化是數字化轉型的起點。通過RPA&a…

TCP 保活定時器詳解:原理、配置與最佳實踐

一、TCP 保活定時器基礎原理 TCP 保活定時器(TCP Keepalive Timer)是 TCP 協議中用于檢測長時間無數據傳輸的連接是否仍然有效的機制。它通過在連接空閑一段時間后發送探測報文,確認對方主機是否仍然可達,從而避免在對端異常斷開…

瀏覽器工作原理27 [#]PWA:解決了web應用哪些問題

引用 《瀏覽器工作原理與實踐》 PWA,全稱是 Progressive Web App ,翻譯過來就是漸進式網頁應用。根據字面意思,它就是“漸進式 Web 應用”。對于 Web 應用很好理解了,就是目前普通的 Web 頁面,所以 PWA 所支持的首先是…

Leetcode百題斬-圖論

再開下一個坑,圖論專題居然以前都刷過了,三道Medium也沒什么好說的,直接過 994. Rotting Oranges[Medium] 發現一個很神奇的事,這一題我再5年前的時候做,還是個Easy,現在已經漲到Medium了。看來隨著通貨膨…

將Python Tkinter程序轉換為手機可運行的Web應用 - 詳細教程

前言 作為一名Python開發者,你可能已經使用Tkinter創建了一些桌面GUI應用。但是如何讓這些應用也能在手機上運行呢?本教程將詳細介紹如何將基于Tkinter的Python程序轉換為手機可訪問的Web應用,讓你的應用隨時隨地可用! 一、為什…

Markdown批量轉PDF工具:高效便捷的文檔轉換解決方案

Markdown批量轉PDF工具:高效便捷的文檔轉換解決方案 前言 在日常工作和學習中,我們經常需要將Markdown文檔轉換為PDF格式,無論是為了分享、打印還是歸檔。雖然有很多在線工具可以實現這一功能,但當面對大量文檔時,逐…

51c~嵌入式~PLC~歐姆龍~合集1

我自己的原文哦~ https://blog.51cto.com/whaosoft/14017854 > PLC-- 歐姆龍 --專輯 一、歐姆龍PLC指令應用 歐姆龍PLC是一種功能完善的緊湊型PLC,能為業界領先的輸送分散控制等提供高附加值機器控制;它還具有通過各種高級內裝板進行升級的能…

機器人 URDF學習筆記

目錄 URDF(Unified Robot Description Format) ? URDF 描述的內容包括: URDF(Unified Robot Description Format) 意思是:統一機器人描述格式。 它是一種用 XML 編寫的格式,專門用于描述機器…

MySQL-主從復制分庫分表

5 MySQL-主從復制&分庫分表 5.1mysql 主從復制 5.1.1. 概述 主從復制是將主數據庫的DDL和DML操作通過二進制日志(binlog文件)傳送到從庫服務器,然后在從庫上對這些日志重新執行,從而使得主庫和從庫的數據保持同步。 MySQL…

7.6.平衡二叉樹(英文縮寫為AVL樹)

一.平衡二叉樹的定義: 1.平衡二叉樹簡稱平衡樹(AVL樹,該縮寫來源于平衡二叉樹的發明人的名字簡稱); 2.結點的平衡因子左子樹高-右子樹高; 3.以上述圖片左下角的二叉樹為例,結點50的左子樹的高度為2,右子樹…

OpenCV CUDA模塊設備層-----將指向共享內存(shared memory)的指針封裝成一個 tuple函數smem_tuple()

操作系統:ubuntu22.04 OpenCV版本:OpenCV4.9 IDE:Visual Studio Code 編程語言:C11 算法描述 OpenCV的cv::cudev模塊中的一個用于 CUDA 編程的輔助函數,用于將指向共享內存(shared memory)的指針封裝成一…

paddlepaddle在RTX40系安裝注意事項

1 安裝簡介 1.1 安裝注意事項 顯卡型號:RTX4090 驅動版本:550.54.14 宿主機cuda版本:12.4 安裝方式:conda 注意cuda和cudnn的搭配 最初安裝是為了使用PaddleOCR,根據官網提示需要安裝cuda和cudnn。這里最關鍵的就是針…

車載以太網-組播

目錄 車載以太網中的組播:從原理到車載應用**一、組播的核心概念與車載網絡價值****二、車載以太網組播的關鍵協議與機制**1. **組播IP地址管理(IGMP協議)**2. **組播數據鏈路層實現(MAC地址映射)****三、車載以太網組播的典型應用場景**1. **自動駕駛與傳感器數據分發**2…

【雅思播客013】what do you do

【dialog】 A: Oh, look, there’s Veronica and her boyfriend.She’s always going on about him at the of?ce. Oh, great, they saw us. They’re coming this way. B: Oh, man... C: Jessica! Arthur! Hi! I’d like you to meet my boyfriend Greg, he’s the VP. of q…

Freebsd 14.2系統下 wifi網卡硬件驅動軟件配置調試大全

Freebsd 14.2系統下,網卡是AX200 先檢查網卡sysctl net.wlan.devices sysctl net.wlan.devices 能識別出已經安裝的 sysctl net.wlan.devices net.wlan.devices: iwlwifi0配置wlan0 # ifconfig wlan0 create wlandev iwlwifi0 # ifconfig wlan0 up # ifconfig …

Python打卡:Day39

知識點回顧 圖像數據的格式:灰度和彩色數據模型的定義顯存占用的4種地方 模型參數梯度參數優化器參數數據批量所占顯存神經元輸出中間狀態 batchisize和訓練的關系 浙大疏錦行

使用 GcExcel .NET 將 Excel 導出為 PDF

引言 在企業級應用開發中,經常需要將Excel數據導出為PDF格式以便于共享和打印。GrapeCity Documents for Excel(簡稱GcExcel)作為一款高性能的.NET Excel組件,提供了強大的PDF導出功能。本文將詳細介紹如何使用GcExcel .NET實現E…

每日算法刷題Day39 6.26:leetcode前綴和2道題,用時1h20min

8. 2055.蠟燭之間的盤子(中等,學習替換查詢區間) 2055. 蠟燭之間的盤子 - 力扣(LeetCode) 思想 1.給你一個長桌子,桌子上盤子和蠟燭排成一列。給你一個下標從 0 開始的字符串 s ,它只包含字符 * 和 | ,其中 * 表示一…