权威的手机网站制作,苏州网站备案查询,视频素材网免费,wordpress选取文章图片作为缩略图1. 什么是智能体
将大语言模型作为一个推理引擎。给定一个任务#xff0c; 智能体自动生成完成任务所需步骤#xff0c; 执行相应动作#xff08;例如选择并调用工具#xff09;#xff0c; 直到任务完成。
2. 先定义工具#xff1a;Tools
可以是一个函数或三方 API也…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(funcsearch.run,nameSearch,descriptionuseful 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 named 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 tooltool(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 实例元数据生成自动提取以下信息 - 工具名称 (nameweekday) - 功能描述docstring - 参数类型从类型注解推断错误处理添加参数验证逻辑确保输入符合 date_str: str 类型声明 4. 等价显式写法
装饰器代码等价于
from langchain.tools import Tooldef weekday(date_str: str) - str:Convert date to weekday named parser.parse(date_str)return calendar.day_name[d.weekday()]weekday_tool Tool.from_function(nameweekday,descriptionConvert date to weekday name,funcweekday,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)) # 输出 Monday7. 进阶用法
自定义参数描述tool(weekday, args_schema{date_str: 日期字符串格式为YYYY-MM-DD})异步支持tool(weekday)
async def weekday_async(date_str: str) - str:...返回结构化数据tool(weekday, return_directTrue) # 直接返回原始结果不经过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_namegpt-4o, temperature0, seed23)# 定义一个 agent: 需要大模型、工具集、和 Prompt 模板
agent create_react_agent(llm, tools, react_prompt)
# 定义一个执行器需要 agent 对象 和 工具集
agent_executor AgentExecutor(agentagent, toolstools, verboseTrue)# 执行
agent_executor.invoke({input: 2024年周杰伦的演唱会星期几}) Entering new AgentExecutor chain...
To determine the weekday of Jay Chous 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 Chous 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 Chous concert on October 11, 2024, is on a Friday.
输出
{input: 2024年周杰伦的演唱会星期几,output: Jay Chous 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_namegpt-4o, # 使用 GPT-4 Omni 模型temperature0, # 确定性输出seed23 # 固定随机种子保证可复现性
)关键参数 temperature0禁用随机性相同输入始终得到相同输出seed23与 temperature 配合确保结果确定性model_name最新多模态模型支持文本/视觉/音频混合输入
2.2 代理创建
from langchain.agents import create_react_agentagent create_react_agent(llmllm, # 指定大模型toolstools, # 工具集需预先定义promptreact_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)break2.3 执行器配置
agent_executor AgentExecutor(agentagent, toolstools,verboseTrue, # 显示详细执行过程# handle_parsing_errorsTrue # 可选错误处理
)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(nameconcert_date_search,funcget_concert_date,description查询歌手演唱会日期),Tool(namedate_to_weekday,funcconvert_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” 时停止Truehandle_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, expire3600)return result6.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(nameIntermediate Answer,funcsearch.run,description搜素引擎,max_results1)
]# self_ask_with_search_agent 只能传一个名为 Intermediate Answer 的 tool
agent create_self_ask_with_search_agent(llm, tools, self_ask_prompt)
agent_executor AgentExecutor(agentagent, toolstools, verboseTrue, handle_parsing_errorsTrue)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 模式其工作流程如下 #mermaid-svg-CLlNXWG8V3raX6li {font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}#mermaid-svg-CLlNXWG8V3raX6li .error-icon{fill:#552222;}#mermaid-svg-CLlNXWG8V3raX6li .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-CLlNXWG8V3raX6li .edge-thickness-normal{stroke-width:2px;}#mermaid-svg-CLlNXWG8V3raX6li .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-CLlNXWG8V3raX6li .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-CLlNXWG8V3raX6li .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-CLlNXWG8V3raX6li .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-CLlNXWG8V3raX6li .marker{fill:#333333;stroke:#333333;}#mermaid-svg-CLlNXWG8V3raX6li .marker.cross{stroke:#333333;}#mermaid-svg-CLlNXWG8V3raX6li svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-CLlNXWG8V3raX6li .actor{stroke:hsl(259.6261682243, 59.7765363128%, 87.9019607843%);fill:#ECECFF;}#mermaid-svg-CLlNXWG8V3raX6li text.actortspan{fill:black;stroke:none;}#mermaid-svg-CLlNXWG8V3raX6li .actor-line{stroke:grey;}#mermaid-svg-CLlNXWG8V3raX6li .messageLine0{stroke-width:1.5;stroke-dasharray:none;stroke:#333;}#mermaid-svg-CLlNXWG8V3raX6li .messageLine1{stroke-width:1.5;stroke-dasharray:2,2;stroke:#333;}#mermaid-svg-CLlNXWG8V3raX6li #arrowhead path{fill:#333;stroke:#333;}#mermaid-svg-CLlNXWG8V3raX6li .sequenceNumber{fill:white;}#mermaid-svg-CLlNXWG8V3raX6li #sequencenumber{fill:#333;}#mermaid-svg-CLlNXWG8V3raX6li #crosshead path{fill:#333;stroke:#333;}#mermaid-svg-CLlNXWG8V3raX6li .messageText{fill:#333;stroke:#333;}#mermaid-svg-CLlNXWG8V3raX6li .labelBox{stroke:hsl(259.6261682243, 59.7765363128%, 87.9019607843%);fill:#ECECFF;}#mermaid-svg-CLlNXWG8V3raX6li .labelText,#mermaid-svg-CLlNXWG8V3raX6li .labelTexttspan{fill:black;stroke:none;}#mermaid-svg-CLlNXWG8V3raX6li .loopText,#mermaid-svg-CLlNXWG8V3raX6li .loopTexttspan{fill:black;stroke:none;}#mermaid-svg-CLlNXWG8V3raX6li .loopLine{stroke-width:2px;stroke-dasharray:2,2;stroke:hsl(259.6261682243, 59.7765363128%, 87.9019607843%);fill:hsl(259.6261682243, 59.7765363128%, 87.9019607843%);}#mermaid-svg-CLlNXWG8V3raX6li .note{stroke:#aaaa33;fill:#fff5ad;}#mermaid-svg-CLlNXWG8V3raX6li .noteText,#mermaid-svg-CLlNXWG8V3raX6li .noteTexttspan{fill:black;stroke:none;}#mermaid-svg-CLlNXWG8V3raX6li .activation0{fill:#f4f4f4;stroke:#666;}#mermaid-svg-CLlNXWG8V3raX6li .activation1{fill:#f4f4f4;stroke:#666;}#mermaid-svg-CLlNXWG8V3raX6li .activation2{fill:#f4f4f4;stroke:#666;}#mermaid-svg-CLlNXWG8V3raX6li .actorPopupMenu{position:absolute;}#mermaid-svg-CLlNXWG8V3raX6li .actorPopupMenuPanel{position:absolute;fill:#ECECFF;box-shadow:0px 8px 16px 0px rgba(0,0,0,0.2);filter:drop-shadow(3px 5px 2px rgb(0 0 0 / 0.4));}#mermaid-svg-CLlNXWG8V3raX6li .actor-man line{stroke:hsl(259.6261682243, 59.7765363128%, 87.9019607843%);fill:#ECECFF;}#mermaid-svg-CLlNXWG8V3raX6li .actor-man circle,#mermaid-svg-CLlNXWG8V3raX6li line{stroke:hsl(259.6261682243, 59.7765363128%, 87.9019607843%);fill:#ECECFF;stroke-width:2px;}#mermaid-svg-CLlNXWG8V3raX6li :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} 用户 Self-Ask Agent 搜索引擎 复杂问题如冯小刚的老婆演过哪些电影 拆解基础问题1冯小刚的妻子是谁 搜索问题1 返回答案1徐帆 拆解基础问题2徐帆演过哪些电影 搜索问题2 返回答案2《唐山大地震》《甲方乙方》等 综合答案输出最终结果 用户 Self-Ask Agent 搜索引擎 2. 代码逐层解析
2.1 工具定义
from langchain.agents import Tooltools [Tool(nameIntermediate Answer, # 固定名称不可修改funcsearch.run, # 搜索引擎执行函数description搜素引擎, # 工具描述Agent决策依据max_results1 # 限制每次搜索返回1个结果)
]强制命名name 必须为 Intermediate Answer这是 Self-Ask 代理的硬性要求结果限制max_results1 确保每个中间问题只取最相关结果避免信息过载
2.2 代理创建
from langchain.agents import create_self_ask_with_search_agentagent create_self_ask_with_search_agent(llm, # 大语言模型如GPT-4tools, # 工具列表必须包含Intermediate Answerself_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 answers2.3 执行器配置
agent_executor AgentExecutor(agentagent,toolstools,verboseTrue, # 打印详细执行过程handle_parsing_errorsTrue # 自动修复JSON解析错误
)过程可视化verboseTrue 时输出类似以下信息[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(glcn, hlzh-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_result6. 典型问题场景
问题类型示例拆解步骤多实体关联“马云的第一任妻子的母校是哪所大学”1. 马云的第一任妻子是谁 → 2. 该人的母校时间线推理“北京奥运会那年诺贝尔文学奖得主是谁”1. 北京奥运会年份 → 2. 该年诺贝尔文学奖得主跨领域综合“《三体》作者的母校最新排名多少”1. 《三体》作者 → 2. 该人的母校 → 3. 该学校最新排名 7. 错误处理机制
7.1 解析错误应对
handle_parsing_errorsTrue 可自动处理以下问题
模型输出的非结构化响应JSON 格式错误工具调用参数缺失
7.2 失败重试策略
# 自定义重试逻辑需 LangChain 0.1
from langchain.retrievers import RetryOutputParseragent_executor AgentExecutor(...,max_retries3,retry_promptRetryPromptTemplate(...)
)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. 最显著的区别
特征ReActSelf-ASK核心机制交替进行推理Reasoning和行动Action形成动态决策循环通过自我提问Self-Questioning分解问题逐层解决子问题流程控制推理与行动交替执行依赖上下文动态调整显式拆分问题为子问题独立解决后整合答案工具调用方式灵活调用工具以支持当前推理步骤每个子问题独立调用工具或搜索适用问题复杂度多步骤、需动态调整策略的任务复杂问答需分解为多个明确子任务 2. 应用场景
ReAct
场景特点需要实时交互、多步骤推理且后续步骤依赖前序结果的任务。典型用例 交互式任务如客服机器人处理用户的多轮请求如订票需先查询余票再确认支付。动态决策机器人导航中根据环境反馈调整路径。代码调试通过执行代码并观察输出来逐步修正错误。
Self-ASK
场景特点问题需分解为多个独立子问题每个子问题需外部信息支持。典型用例 多跳问答例如“某公司CEO的母校是哪所”需先查询CEO姓名再查其教育背景。事实核查验证复合陈述如“某城市人口是否超过A国首都”需分别查询两个城市数据。复杂分析如比较多个产品的市场表现需逐一获取各产品数据后综合对比。 3. 选择建议
选ReAct当任务需要灵活调整策略且步骤间存在强依赖如后续行动依赖前一步的结果。选Self-ASK当问题可明确拆分为独立子问题且每个子问题需独立检索或计算如多源信息整合。
示例对比 ReAct处理订餐请求 推理“用户要订素食需过滤餐厅菜单”→ 调用菜单API → 推理“用户偏好辣味”→ 筛选辣味素食。 Self-ASK回答复杂问题 提问“诺贝尔奖创始人是谁”→ 搜索→“阿尔弗雷德·诺贝尔”→“他的职业”→ 搜索→“工程师”→ 整合答案。
通过理解两者的机制差异可更高效地设计适合业务需求的智能体。 文章转载自: http://www.morning.bgqr.cn.gov.cn.bgqr.cn http://www.morning.hhxkl.cn.gov.cn.hhxkl.cn http://www.morning.lgznc.cn.gov.cn.lgznc.cn http://www.morning.rtkz.cn.gov.cn.rtkz.cn http://www.morning.jkmjm.cn.gov.cn.jkmjm.cn http://www.morning.prlgn.cn.gov.cn.prlgn.cn http://www.morning.wcjk.cn.gov.cn.wcjk.cn http://www.morning.klltg.cn.gov.cn.klltg.cn http://www.morning.gwkwt.cn.gov.cn.gwkwt.cn http://www.morning.mkkcr.cn.gov.cn.mkkcr.cn http://www.morning.jxmjr.cn.gov.cn.jxmjr.cn http://www.morning.kzcfr.cn.gov.cn.kzcfr.cn http://www.morning.mlgsc.com.gov.cn.mlgsc.com http://www.morning.gtjkh.cn.gov.cn.gtjkh.cn http://www.morning.kqgsn.cn.gov.cn.kqgsn.cn http://www.morning.zbhfs.cn.gov.cn.zbhfs.cn http://www.morning.rgfx.cn.gov.cn.rgfx.cn http://www.morning.pjfmq.cn.gov.cn.pjfmq.cn http://www.morning.haibuli.com.gov.cn.haibuli.com http://www.morning.hqbnx.cn.gov.cn.hqbnx.cn http://www.morning.rkwwy.cn.gov.cn.rkwwy.cn http://www.morning.qllcp.cn.gov.cn.qllcp.cn http://www.morning.qlxgc.cn.gov.cn.qlxgc.cn http://www.morning.cbpkr.cn.gov.cn.cbpkr.cn http://www.morning.tsrg.cn.gov.cn.tsrg.cn http://www.morning.dfckx.cn.gov.cn.dfckx.cn http://www.morning.nkdmd.cn.gov.cn.nkdmd.cn http://www.morning.lynmt.cn.gov.cn.lynmt.cn http://www.morning.fjfjm.cn.gov.cn.fjfjm.cn http://www.morning.ntqjh.cn.gov.cn.ntqjh.cn http://www.morning.dkqr.cn.gov.cn.dkqr.cn http://www.morning.jhqcr.cn.gov.cn.jhqcr.cn http://www.morning.cfhwn.cn.gov.cn.cfhwn.cn http://www.morning.fhghy.cn.gov.cn.fhghy.cn http://www.morning.nxnrt.cn.gov.cn.nxnrt.cn http://www.morning.gstmn.cn.gov.cn.gstmn.cn http://www.morning.msgcj.cn.gov.cn.msgcj.cn http://www.morning.darwallet.cn.gov.cn.darwallet.cn http://www.morning.rlsd.cn.gov.cn.rlsd.cn http://www.morning.gsqw.cn.gov.cn.gsqw.cn http://www.morning.rui931.cn.gov.cn.rui931.cn http://www.morning.bpyps.cn.gov.cn.bpyps.cn http://www.morning.nnhfz.cn.gov.cn.nnhfz.cn http://www.morning.fdrch.cn.gov.cn.fdrch.cn http://www.morning.tdqhs.cn.gov.cn.tdqhs.cn http://www.morning.tthmg.cn.gov.cn.tthmg.cn http://www.morning.yslfn.cn.gov.cn.yslfn.cn http://www.morning.ljdhj.cn.gov.cn.ljdhj.cn http://www.morning.tsxg.cn.gov.cn.tsxg.cn http://www.morning.rsmtx.cn.gov.cn.rsmtx.cn http://www.morning.nwjzc.cn.gov.cn.nwjzc.cn http://www.morning.fllx.cn.gov.cn.fllx.cn http://www.morning.lsfbb.cn.gov.cn.lsfbb.cn http://www.morning.wjlrw.cn.gov.cn.wjlrw.cn http://www.morning.mbhdl.cn.gov.cn.mbhdl.cn http://www.morning.lnyds.cn.gov.cn.lnyds.cn http://www.morning.rhph.cn.gov.cn.rhph.cn http://www.morning.wfbs.cn.gov.cn.wfbs.cn http://www.morning.sfswj.cn.gov.cn.sfswj.cn http://www.morning.dbqg.cn.gov.cn.dbqg.cn http://www.morning.mgnrc.cn.gov.cn.mgnrc.cn http://www.morning.wjwfj.cn.gov.cn.wjwfj.cn http://www.morning.mbzlg.cn.gov.cn.mbzlg.cn http://www.morning.wlstn.cn.gov.cn.wlstn.cn http://www.morning.xjwtq.cn.gov.cn.xjwtq.cn http://www.morning.rfwgg.cn.gov.cn.rfwgg.cn http://www.morning.cnwpb.cn.gov.cn.cnwpb.cn http://www.morning.skbhl.cn.gov.cn.skbhl.cn http://www.morning.rqjl.cn.gov.cn.rqjl.cn http://www.morning.iknty.cn.gov.cn.iknty.cn http://www.morning.ckfqt.cn.gov.cn.ckfqt.cn http://www.morning.ytrbq.cn.gov.cn.ytrbq.cn http://www.morning.nqbcj.cn.gov.cn.nqbcj.cn http://www.morning.rhnn.cn.gov.cn.rhnn.cn http://www.morning.nnpwg.cn.gov.cn.nnpwg.cn http://www.morning.wqbrg.cn.gov.cn.wqbrg.cn http://www.morning.lmxrt.cn.gov.cn.lmxrt.cn http://www.morning.fdrch.cn.gov.cn.fdrch.cn http://www.morning.kztpn.cn.gov.cn.kztpn.cn http://www.morning.yfwygl.cn.gov.cn.yfwygl.cn