1. 什么是智能體
將大語言模型作為一個推理引擎。給定一個任務,
智能體自動生成完成任務所需步驟,
執行相應動作(例如選擇并調用工具),
直到任務完成。
2. 先定義工具:Tools
- 可以是一個函數或三方 API
- 也可以把一個 Chain 或者 Agent 的 run()作為一個 Tool
# 需要注冊 SerpAPI(限量免費),并將 SERPAPI_API_KEY 寫在環境變量中
from langchain_community.utilities import SerpAPIWrapper
from langchain.tools import Tool, toolsearch = SerpAPIWrapper()
tools = [Tool.from_function(func=search.run,name="Search",description="useful for when you need to answer questions about current events"),
]
import calendar
import dateutil.parser as parser
from datetime import date# 自定義工具@tool("weekday")
def weekday(date_str: str) -> str:"""Convert date to weekday name"""d = parser.parse(date_str)return calendar.day_name[d.weekday()]tools += [weekday]
@tool
是 LangChain 框架中用于快速定義 Agent 工具的核心裝飾器,其作用如下:
1. 核心功能
- 工具注冊:將普通 Python 函數轉化為 LangChain Agent 可調用的工具
- 元數據生成:自動提取函數簽名和文檔字符串生成工具描述
- 接口標準化:封裝為符合 LangChain Tool 協議的格式
2. 代碼示例解析
from langchain.tools import tool@tool("weekday") # 👈 關鍵裝飾器
def weekday(date_str: str) -> str:"""Convert date to weekday name""" # 👈 工具描述(Agent決策依據)d = parser.parse(date_str)return calendar.day_name[d.weekday()]
3. 裝飾器執行細節
階段 | 操作 |
---|---|
裝飾器調用 | 創建 Tool 對象,將函數包裝為 structured_tool.StructuredTool 實例 |
元數據生成 | 自動提取以下信息: - 工具名稱 ( name="weekday" )- 功能描述(docstring) - 參數類型(從類型注解推斷) |
錯誤處理 | 添加參數驗證邏輯,確保輸入符合 date_str: str 類型聲明 |
4. 等價顯式寫法
裝飾器代碼等價于:
from langchain.tools import Tooldef weekday(date_str: str) -> str:"""Convert date to weekday name"""d = parser.parse(date_str)return calendar.day_name[d.weekday()]weekday_tool = Tool.from_function(name="weekday",description="Convert date to weekday name",func=weekday,args_schema={"date_str": {"type": "str", "description": "Date string"}}
)
5. 關鍵特性
特性 | 說明 |
---|---|
自動描述生成 | Agent 根據 docstring 判斷何時調用該工具 |
類型安全 | 強制檢查輸入參數類型(本例中確保 date_str 為字符串) |
錯誤反饋標準化 | 工具異常會被捕獲并格式化為 Agent 可理解的錯誤消息 |
多工具協同 | 可與其他 @tool 裝飾的函數組成工具集,供 Agent 智能調度 |
6. 調試建議
- 查看工具元數據:
print(weekday.name) # 輸出 "weekday" print(weekday.description) # 輸出 "Convert date to weekday name" print(weekday.args) # 輸出 {'date_str': {'type': 'str', 'description': 'Date string'}}
- 測試工具直接調用:
print(weekday.run("2024-06-10")) # 輸出 "Monday"
7. 進階用法
- 自定義參數描述:
@tool("weekday", args_schema={"date_str": "日期字符串,格式為YYYY-MM-DD"})
- 異步支持:
@tool("weekday") async def weekday_async(date_str: str) -> str:...
- 返回結構化數據:
@tool("weekday", return_direct=True) # 直接返回原始結果不經過LLM處理
該裝飾器極大簡化了 LangChain 工具的開發流程,是構建復雜 Agent 系統的核心基礎設施。
3. 智能體類型:ReAct
# !pip install google-search-results
# !pip install --upgrade langchainhub
from langchain import hub
import json# 下載一個現有的 Prompt 模板
react_prompt = hub.pull("hwchase17/react")print(react_prompt.template)
'''
輸出:
Answer the following questions as best you can. You have access to the following tools:{tools}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, should be one of [{tool_names}]
Action Input: the input to the action
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can repeat N times)
Thought: I now know the final answer
Final Answer: the final answer to the original input questionBegin!Question: {input}
Thought:{agent_scratchpad}
'''
from langchain_openai import ChatOpenAI
from langchain.agents import AgentExecutor, create_react_agentllm = ChatOpenAI(model_name='gpt-4o', temperature=0, seed=23)# 定義一個 agent: 需要大模型、工具集、和 Prompt 模板
agent = create_react_agent(llm, tools, react_prompt)
# 定義一個執行器:需要 agent 對象 和 工具集
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)# 執行
agent_executor.invoke({"input": "2024年周杰倫的演唱會星期幾"})'''> Entering new AgentExecutor chain...
To determine the weekday of Jay Chou's concert in 2024, I need to know the specific date of the concert. Once I have the date, I can find out the weekday. Action: Search
Action Input: "2024 Jay Chou concert dates"['Trending Performers · 8 events in all locations · Oct 11. Fri. 8:00 PM. This week. Singapore National Stadium. Singapore, Singapore · Oct 12. Sat. 7:30 PM.', 'Jay Chou Tour Dates See the Jay Chou concert schedule for 2024. · All Tour Dates · Oct. 11. 2024. Fri. Singapore National Stadium. Singapore, Singapore · Oct.', 'Unfortunately there are no concert dates for Jay Chou scheduled in 2024. Songkick is the first to know of new tour announcements and concert information, so if ...', 'Tour dates. edit. List of concert dates. Date, City, Country, Venue, Attendance ... ^ "Jay Chou Carnival World Tour 2024 - Singapore". Singapore Sports Hub ...', 'Jay Chou Singapore Concert 2024 Details · Jay Chou Carnival World Tour 2024 – Singapore · Date and time: 11 October 2024 (Friday) 20:00, 12-13 October 2024 ( ...', "Jay Chou is playing in Shenzhencun on Sep 12, 2024, 7:00 PM at 深圳大運中心體育場. Buy tickets, find concert information, and get ready for Jay Chou's show!", 'Concert tours ; 2019–2024, Carnival World Tour, October 17, 2019 – present ; The Carnival World Tour commenced in October 2019, and was halted by the COVID-19 ...', 'Tickets for Jay Chou Carnival World Tour Australia 2024 – Melbourne tickets will go on sale at 12pm on 26 October 2023, and Sydney tickets will go on sale at 2 ...', 'Jay Chou tickets for the upcoming concert tour are on sale at StubHub. Buy and sell your Jay Chou concert tickets today. Tickets are 100% guaranteed by ...', "'King of Mandopop' Jay Chou first to give solo concert at Taipei Dome | Taiwan News | Sep. 7, 2024 19:40."]I found that Jay Chou has a concert scheduled for October 11, 2024, which is a Friday. Final Answer: Jay Chou's concert on October 11, 2024, is on a Friday.
'''輸出:
{'input': '2024年周杰倫的演唱會星期幾','output': "Jay Chou's concert on October 11, 2024, is on a Friday."}
代碼功能解析
這段代碼實現了一個基于 ReAct 范式的智能問答系統,通過結合大語言模型的推理能力與外部工具調用,解決需要多步驟交互的復雜問題。以下是逐層解析:
1. 核心組件概覽
# 架構圖
graph TDA[用戶輸入] --> B(ReAct Agent)B --> C{是否需要工具}C -->|是| D[調用工具]C -->|否| E[直接回答]D --> BE --> F[最終響應]
2. 代碼逐層解析
2.1 模型初始化
llm = ChatOpenAI(model_name='gpt-4o', # 使用 GPT-4 Omni 模型temperature=0, # 確定性輸出seed=23 # 固定隨機種子保證可復現性
)
- 關鍵參數:
temperature=0
:禁用隨機性,相同輸入始終得到相同輸出seed=23
:與 temperature 配合確保結果確定性model_name
:最新多模態模型,支持文本/視覺/音頻混合輸入
2.2 代理創建
from langchain.agents import create_react_agentagent = create_react_agent(llm=llm, # 指定大模型tools=tools, # 工具集(需預先定義)prompt=react_prompt # ReAct 專用模板
)
- ReAct 范式核心:
# 偽代碼展示 ReAct 決策邏輯 for _ in max_steps:thought = generate_thought(question, history)if needs_tool(thought):action = decide_action(thought)observation = use_tool(action)else:answer = generate_final_answer(thought)break
2.3 執行器配置
agent_executor = AgentExecutor(agent=agent, tools=tools,verbose=True, # 顯示詳細執行過程# handle_parsing_errors=True # 可選錯誤處理
)
- Verbose 模式輸出示例:
[Thought] 需要先確定2024年周杰倫演唱會日期 [Action] 調用演唱會日期查詢工具 [Tool Input] {"artist": "周杰倫", "year": 2024} [Observation] 返回日期:2024-08-15 [Thought] 需要將2024-08-15轉換為星期 [Action] 調用日期轉換工具 [Tool Input] {"date_str": "2024-08-15"} [Observation] 星期四 [Final Answer] 2024年周杰倫演唱會在星期四舉行
3. 關鍵技術要點
3.1 ReAct 范式工作流程
- 思考 (Reason):分析問題并決定下一步行動
{"thought": "需要先獲取演唱會具體日期"}
- 行動 (Act):選擇工具并生成調用參數
{"action": "concert_date_search", "args": {"artist": "周杰倫", "year": 2024}}
- 觀察 (Observe):獲取工具返回結果
{"observation": "2024-08-15"}
- 循環:重復直到得出最終答案
3.2 工具集定義要求
# 需預先定義的工具示例(假設已存在)
tools = [Tool(name="concert_date_search",func=get_concert_date,description="查詢歌手演唱會日期"),Tool(name="date_to_weekday",func=convert_to_weekday,description="將日期轉換為星期")
]
- 命名規范:工具名稱需與 Action 選擇匹配
- 參數適配:工具函數參數需與模型生成的參數一致
3.3 Prompt 模板關鍵內容
# react_prompt 核心片段示例
template = '''
Answer the following questions using the tools provided. Format instructions:
{format_instructions}Tools:
{tools}History:
{history}Question: {input}
'''
- 必須包含:
- 工具描述列表
- 格式指令(JSON 模板)
- 歷史交互記錄(多輪對話場景)
4. 執行過程示例
response = agent_executor.invoke({"input": "2024年周杰倫的演唱會星期幾"}
)
分步解析:
- 初始思考:
{"thought": "需要先找到周杰倫2024年演唱會的具體日期"}
- 調用工具:
concert_date_search.run({"artist": "周杰倫", "year": 2024}) # 返回 "2024-08-15"
- 二次思考:
{"thought": "需要將2024-08-15轉換為星期"}
- 二次調用:
date_to_weekday.run({"date_str": "2024-08-15"}) # 返回 "Thursday"
- 最終答案:
"2024年周杰倫的演唱會在星期四(8月15日)舉行"
5. 關鍵配置項
參數 | 說明 | 推薦值 |
---|---|---|
max_iterations | 最大思考-行動循環次數 | 5(復雜問題可調高) |
early_stopping | 當模型輸出 “Final Answer” 時停止 | True |
handle_parsing_errors | 自動修復 JSON 格式錯誤 | True(生產環境必備) |
6. 性能優化建議
6.1 工具調用優化
# 為工具添加緩存(示例使用 diskcache)
from langchain.tools import tool
from diskcache import Cachecache = Cache("tool_cache")@tool
def concert_date_search(artist: str, year: int):cache_key = f"{artist}_{year}"if cache_key in cache:return cache[cache_key]result = api_call(...)cache.set(cache_key, result, expire=3600)return result
6.2 歷史管理
# 添加對話歷史支持
from langchain.memory import ConversationBufferMemorymemory = ConversationBufferMemory()
agent_executor.memory = memory# 后續調用自動攜帶歷史
agent_executor.invoke({"input": "那他的臺北場呢?"}) # 能理解"他"指代周杰倫
6.3 異步支持
# 異步執行提升吞吐量
async def main():async for chunk in agent_executor.astream({"input": "..."}):print(chunk)
7. 典型問題排查
現象 | 可能原因 | 解決方案 |
---|---|---|
無限循環 | max_iterations 設置過高 | 設置合理閾值(如 6-8 次) |
工具參數不匹配 | 模型生成的參數名與工具定義不一致 | 統一命名規范 |
中文輸出亂碼 | Prompt 未指定中文響應 | 在 Prompt 中添加 “用中文回答” |
工具調用超時 | 網絡延遲或工具響應慢 | 添加超時機制 |
8. 應用場景擴展
-
客戶服務:
agent_executor.invoke({"input": "我的訂單#123456物流狀態如何?"}) # 需要集成訂單查詢工具
-
數據分析:
agent_executor.invoke({"input": "統計2023 Q3銷售額最高的產品"}) # 需要連接數據庫工具
-
智能家居控制:
agent_executor.invoke({"input": "把客廳空調調到25度"}) # 需要物聯網控制工具
該代碼展示了如何利用 ReAct 范式構建具備自主決策能力的智能系統,是開發復雜業務場景下AI助手的典型方案。通過合理配置工具集與 Prompt 模板,可快速適配不同業務需求。
4. 智能體類型:SelfAskWithSearch
# 下載一個模板
self_ask_prompt = hub.pull("hwchase17/self-ask-with-search")print(self_ask_prompt.template)輸出:
# 下載一個模板
Question: Who lived longer, Muhammad Ali or Alan Turing?
Are follow up questions needed here: Yes.
Follow up: How old was Muhammad Ali when he died?
Intermediate answer: Muhammad Ali was 74 years old when he died.
Follow up: How old was Alan Turing when he died?
Intermediate answer: Alan Turing was 41 years old when he died.
So the final answer is: Muhammad AliQuestion: When was the founder of craigslist born?
Are follow up questions needed here: Yes.
Follow up: Who was the founder of craigslist?
Intermediate answer: Craigslist was founded by Craig Newmark.
Follow up: When was Craig Newmark born?
Intermediate answer: Craig Newmark was born on December 6, 1952.
So the final answer is: December 6, 1952Question: Who was the maternal grandfather of George Washington?
Are follow up questions needed here: Yes.
Follow up: Who was the mother of George Washington?
Intermediate answer: The mother of George Washington was Mary Ball Washington.
Follow up: Who was the father of Mary Ball Washington?
Intermediate answer: The father of Mary Ball Washington was Joseph Ball.
So the final answer is: Joseph BallQuestion: Are both the directors of Jaws and Casino Royale from the same country?
Are follow up questions needed here: Yes.
Follow up: Who is the director of Jaws?
Intermediate answer: The director of Jaws is Steven Spielberg.
Follow up: Where is Steven Spielberg from?
Intermediate answer: The United States.
Follow up: Who is the director of Casino Royale?
Intermediate answer: The director of Casino Royale is Martin Campbell.
Follow up: Where is Martin Campbell from?
Intermediate answer: New Zealand.
So the final answer is: NoQuestion: {input}
Are followup questions needed here:{agent_scratchpad}
from langchain.agents import create_self_ask_with_search_agenttools = [Tool(name="Intermediate Answer",func=search.run,description="搜素引擎",max_results=1)
]# self_ask_with_search_agent 只能傳一個名為 'Intermediate Answer' 的 tool
agent = create_self_ask_with_search_agent(llm, tools, self_ask_prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True, handle_parsing_errors=True)agent_executor.invoke({"input": "馮小剛的老婆演過哪些電影,用中文回答"})
> Entering new AgentExecutor chain...
是。
Follow up: 馮小剛的老婆是誰?['Feng Xiaogang is a Chinese film director, screenwriter, actor, producer and politician. He is well known in China as a highly successful commercial filmmaker whose comedy films do consistently well at the box office, although Feng has broken out from that mold by making some drama and period drama films.', 'Feng Xiaogang (馮小剛) type: Chinese film director and screenwriter.', 'Feng Xiaogang (馮小剛) entity_type: people.', 'Feng Xiaogang (馮小剛) kgmid: /m/04xhrq.', 'Feng Xiaogang (馮小剛) born: 1958 (age 66 years), Daxing District, Beijing, China.', 'Feng Xiaogang (馮小剛) awards: Golden Horse Award for Best Leading Actor.', 'Feng Xiaogang (馮小剛) children: Siyu Feng.', 'Feng Xiaogang (馮小剛) height: 5′ 10″.', '馮小剛妻子徐帆,是內地知名女演員,文藝世家出身,1991年,24歲的她畢業于央戲表演專業。當時徐帆剛和王志文分手,很是失落,于是馮小剛時常安慰和開導她,兩人 ...', '馮小剛老婆徐帆和好友熱聊,心情大好,面帶笑容,還和朋友相擁送別。從圖片看,身旁的好友是亞洲面孔。 ... 1999年,馮小剛和第一任妻子正式離婚,同年迎娶徐帆。', '徐帆是著名導演馮小剛的妻子,可以說是家喻戶曉的實力派女星。值得一提的是,如今已然五十二歲的徐帆看上去依舊是靚麗又顯年輕,整個人沒有半分老態, ...', '盡管馮小剛和徐帆已經結婚這么多年,但他們兩個人始終沒有孩子。 而是一直照顧著馮小剛和前妻的女兒馮思羽,最后兩個人也領養了一個女兒。', '徐帆,作為馮小剛老婆,這個女人相貌美麗,心態也非常好,對家庭非常包容,85分。馮小剛老婆85分,張藝謀老婆93分,而他的老婆我想打666分.', '馮小剛和徐帆自1991年因為《大撒把》相識,1999年結婚,相識33年結婚25年,為什么還有網友不看好他們的婚姻呢?其實細究他們的婚姻就知道,徐帆背后的付出并不 ...', '馮小剛一共有幾個妻子. 2任。馮小剛一共有2任老婆2段婚姻,原配妻子是張娣。馮小剛,1958年3月18日出生于北京市大興區,祖籍湖南省湘潭市,中國內地導演、編劇、演員。', '1. 徐帆,著名導演馮小剛的妻子,是一位才華橫溢的中國女演員。2. 她于1967年8月16日出生于湖北省武漢市江漢區,1991年畢業于中央戲劇學院表演系,并加入 ...', '1999年,徐帆和馮小剛如愿以償領證結婚,婚后的道路,其實跟前妻張娣并無二致。 慢慢成為大導演的馮小剛,身邊的鶯鶯燕燕 ...', '馮小剛的老婆是徐帆。 徐帆1967年8月16日出生于湖北省武漢市江漢區,是中國電視、電影演員。 她與馮小剛于1999年9月19日正式結婚。 原著同樣精彩,可以點擊《玫瑰的故事》 ...']Could not parse output: Intermediate answer: 馮小剛的老婆是徐帆。Follow up: 徐帆演過哪些電影?
Invalid or incomplete responseIntermediate answer: 徐帆演過的電影包括《唐山大地震》、《手機》、《一九四二》、《不見不散》等。So the final answer is: 徐帆演過的電影包括《唐山大地震》、《手機》、《一九四二》、《不見不散》等。> Finished chain.
輸出
{'input': '馮小剛的老婆演過哪些電影,用中文回答','output': '徐帆演過的電影包括《唐山大地震》、《手機》、《一九四二》、《不見不散》等。'}
代碼功能解析
Self-Ask 代碼實現了一個 具備自主問題拆解能力的問答系統,通過 Self-Ask(自問自答)機制結合搜索引擎,解決需要多步推理的復雜問題。以下是關鍵模塊解析:
1. 核心技術原理
Self-Ask with Search 是一種專門處理多跳推理(multi-hop reasoning)的 Agent 模式,其工作流程如下:
2. 代碼逐層解析
2.1 工具定義
from langchain.agents import Tooltools = [Tool(name="Intermediate Answer", # 固定名稱不可修改func=search.run, # 搜索引擎執行函數description="搜素引擎", # 工具描述(Agent決策依據)max_results=1 # 限制每次搜索返回1個結果)
]
- 強制命名:
name
必須為"Intermediate Answer"
,這是 Self-Ask 代理的硬性要求 - 結果限制:
max_results=1
確保每個中間問題只取最相關結果,避免信息過載
2.2 代理創建
from langchain.agents import create_self_ask_with_search_agentagent = create_self_ask_with_search_agent(llm, # 大語言模型(如GPT-4)tools, # 工具列表(必須包含Intermediate Answer)self_ask_prompt # 內置的專用Prompt模板
)
- 專有架構:使用 LangChain 內置的 Self-Ask 代理結構
- Prompt 約束:
self_ask_prompt
包含明確的中間問題生成指令,例如:Follow these steps: 1. Break the question into sub-questions 2. Search for each sub-question 3. Combine the answers
2.3 執行器配置
agent_executor = AgentExecutor(agent=agent,tools=tools,verbose=True, # 打印詳細執行過程handle_parsing_errors=True # 自動修復JSON解析錯誤
)
- 過程可視化:
verbose=True
時輸出類似以下信息:[Self-Ask] 生成中間問題:馮小剛的妻子是誰? [Search] 使用工具 Intermediate Answer 搜索:馮小剛 妻子 [Result] 獲得答案:徐帆 [Self-Ask] 生成中間問題:徐帆演過哪些電影 [Search] 使用工具 Intermediate Answer 搜索:徐帆 電影作品 [Result] 獲得答案:《唐山大地震》《甲方乙方》...
3. 執行過程示例
response = agent_executor.invoke({"input": "馮小剛的老婆演過哪些電影,用中文回答"}
)
分步解析:
- 問題拆解:
# 模型生成的中間問題 sub_question_1 = "馮小剛的妻子是誰?" sub_question_2 = "徐帆演過哪些電影?"
- 搜索調用:
search_result_1 = search.run(sub_question_1) # 返回"徐帆" search_result_2 = search.run(sub_question_2) # 返回電影列表
- 答案綜合:
final_answer = "徐帆(馮小剛妻子)演過的電影包括:《唐山大地震》《甲方乙方》..."
4. 關鍵技術約束
要素 | 約束條件 |
---|---|
工具名稱 | 必須為 "Intermediate Answer" ,否則代理無法識別 |
工具數量 | 只能有1個工具,因為 Self-Ask 代理設計為單一搜索工具場景 |
Prompt 模板 | 需使用 LangChain 內置模板,自定義模板可能破壞 Self-Ask 邏輯 |
輸入格式 | 問題必須為需要多步推理的復雜問題,簡單問題可能直接調用搜索無需拆解 |
5. 性能優化建議
5.1 搜索引擎優化
# 提升搜索精度(示例使用 Serper API)
from langchain_community.utilities import GoogleSerperAPIWrappersearch = GoogleSerperAPIWrapper(gl="cn", hl="zh-cn") # 指定中文結果
5.2 中間問題控制
# 在 Prompt 中添加約束(偽代碼)
self_ask_prompt = """...最多拆解3個子問題..."""
5.3 結果后處理
# 添加結果清洗邏輯
def clean_search_result(query: str):result = search.run(query)return remove_html_tags(result) # 示例:去除HTML標簽tools[0].func = clean_search_result
6. 典型問題場景
問題類型 | 示例 | 拆解步驟 |
---|---|---|
多實體關聯 | “馬云的第一任妻子的母校是哪所大學?” | 1. 馬云的第一任妻子是誰 → 2. 該人的母校 |
時間線推理 | “北京奧運會那年諾貝爾文學獎得主是誰” | 1. 北京奧運會年份 → 2. 該年諾貝爾文學獎得主 |
跨領域綜合 | “《三體》作者的母校最新排名多少” | 1. 《三體》作者 → 2. 該人的母校 → 3. 該學校最新排名 |
7. 錯誤處理機制
7.1 解析錯誤應對
handle_parsing_errors=True
可自動處理以下問題:
- 模型輸出的非結構化響應
- JSON 格式錯誤
- 工具調用參數缺失
7.2 失敗重試策略
# 自定義重試邏輯(需 LangChain 0.1+)
from langchain.retrievers import RetryOutputParseragent_executor = AgentExecutor(...,max_retries=3,retry_prompt=RetryPromptTemplate(...)
)
8. 應用場景擴展
-
知識圖譜補全
agent_executor.invoke({"input": "OpenAI CEO的母校的創辦時間是多少?"})
-
事實核查系統
agent_executor.invoke({"input": "驗證以下說法:特斯拉創始人畢業于斯坦福大學"})
-
研究助手
agent_executor.invoke({"input": "量子計算在藥物研發中的最新應用案例"})
該代碼展示了如何利用 Self-Ask 代理解決需要多步推理的復雜問題,是構建智能問答系統的有效方案,尤其適合需要事實性驗證的場景。
ReAct和Self-Ask的區別以及應用場景
在LangChain框架中,ReAct和Self-ASK是兩種不同的智能體類型,它們的核心設計思想和適用場景有顯著差異:
1. 最顯著的區別
特征 | ReAct | Self-ASK |
---|---|---|
核心機制 | 交替進行推理(Reasoning)和行動(Action),形成動態決策循環 | 通過自我提問(Self-Questioning)分解問題,逐層解決子問題 |
流程控制 | 推理與行動交替執行,依賴上下文動態調整 | 顯式拆分問題為子問題,獨立解決后整合答案 |
工具調用方式 | 靈活調用工具以支持當前推理步驟 | 每個子問題獨立調用工具或搜索 |
適用問題復雜度 | 多步驟、需動態調整策略的任務 | 復雜問答需分解為多個明確子任務 |
2. 應用場景
ReAct
- 場景特點:需要實時交互、多步驟推理且后續步驟依賴前序結果的任務。
- 典型用例:
- 交互式任務:如客服機器人處理用戶的多輪請求(如訂票需先查詢余票再確認支付)。
- 動態決策:機器人導航中根據環境反饋調整路徑。
- 代碼調試:通過執行代碼并觀察輸出來逐步修正錯誤。
Self-ASK
- 場景特點:問題需分解為多個獨立子問題,每個子問題需外部信息支持。
- 典型用例:
- 多跳問答:例如“某公司CEO的母校是哪所?”需先查詢CEO姓名,再查其教育背景。
- 事實核查:驗證復合陳述(如“某城市人口是否超過A國首都?”需分別查詢兩個城市數據)。
- 復雜分析:如比較多個產品的市場表現,需逐一獲取各產品數據后綜合對比。
3. 選擇建議
- 選ReAct:當任務需要靈活調整策略,且步驟間存在強依賴(如后續行動依賴前一步的結果)。
- 選Self-ASK:當問題可明確拆分為獨立子問題,且每個子問題需獨立檢索或計算(如多源信息整合)。
示例對比:
-
ReAct處理訂餐請求:
推理:“用戶要訂素食,需過濾餐廳菜單”→ 調用菜單API → 推理:“用戶偏好辣味”→ 篩選辣味素食。 -
Self-ASK回答復雜問題:
提問:“諾貝爾獎創始人是誰?”→ 搜索→“阿爾弗雷德·諾貝爾”→“他的職業?”→ 搜索→“工程師”→ 整合答案。
通過理解兩者的機制差異,可更高效地設計適合業務需求的智能體。