AI开发-python-langchain框架(3-16-angent的创建及注册tool)
LangChain ReAct Agent 实战:Tool 描述才是工具调用的 “灵魂”
一、先搭基础:ReAct Agent 的核心逻辑拆解
二、踩坑实录:Tool 描述不精准,Agent 就 “失灵”
场景 1:需求匹配工具,Agent 正常调用
场景 2:需求无关工具,Agent “瞎调用”
三、核心真相:Tool 描述是 Agent 的 “工具使用说明书”
四、实战优化:写好 Tool 描述的 3 个核心原则
原则 1:限定范围,明确 “能做什么”
原则 2:明确禁区,说明 “不能做什么”
原则 3:简洁具体,避免冗余
五、优化后代码效果:精准匹配,零误调用
场景 1:需求匹配工具
场景 2:需求无关工具
六、总结:Tool 描述是 Agent 调用的 “核心开关”
代码实现:
from langchain_openai import ChatOpenAI
from langchain_core.tools import Tool
from langchain.agents import create_react_agent # 改用 ReAct 智能体
from langchain.agents import AgentExecutor
from langchain_core.prompts import PromptTemplate # ReAct 用 PromptTemplate 而非 ChatPromptTemplate
# 1. 初始化 LLM(保持不变)
DEEPSEEK_API_KEY = "123" # 替换为实际的 API Key
llm = ChatOpenAI(
api_key=DEEPSEEK_API_KEY,
base_url="http://192.168.0.100:8085/v1",
model="qwen3.5-27b-awq",
temperature=0.3,
max_tokens=1024,
)
# 2. 工具函数
def huawei_mall_search(query: str) -> str:
"""华为商城搜索工具"""
print(f"[DEBUG] 工具被调用!搜索关键词:{query}")
search_results = {
"众测活动": "华为商城众测活动是让用户体验新品并反馈意见的活动。目前有Mate 60系列众测,参与可赢取礼品。",
"手机": "华为商城最新手机:Mate 60系列、P60系列、nova系列等。",
"笔记本": "华为MateBook X Pro、MateBook D系列笔记本电脑。",
"手表": "华为Watch 4、Watch GT系列智能手表。",
"默认": "请在华为商城官网查看详细信息或联系客服。"
}
for keyword in search_results:
if keyword in query:
return f"华为商城搜索结果:{search_results[keyword]}"
return search_results["默认"]
# 3. 创建工具
huawei_tool = Tool(
name="huawei_mall_search",
description="查询华为商城相关信息,包括产品、活动、政策等",
func=huawei_mall_search,
)
tools = [huawei_tool]
# 4. 定义 ReAct 提示词模板
react_prompt = PromptTemplate.from_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 question
Begin!
Question: {input}
Thought: {agent_scratchpad}
""")
# 5. 创建 ReAct 智能体
agent = create_react_agent(llm=llm, tools=tools, prompt=react_prompt)
# 6. 创建执行器
agent_executor = AgentExecutor(
agent=agent,
tools=tools,
verbose=True,
max_iterations=3,
handle_parsing_errors=True,
return_intermediate_steps=True
)
# 7. 测试(保持不变)
print("\n" + "=" * 60)
print("测试 Agent 工具调用")
print("=" * 60)
#会调用注册的方法
#result = agent_executor.invoke({"input": "华为商城最新的手机有哪些?"})
#不会调用
result = agent_executor.invoke({"input": "你可以告诉我各个星座的时间么?"})
print(f"\n最终输出: {result['output']}")
print(f"\n中间步骤: {result['intermediate_steps']}")
调用工具输出:
============================================================
测试 Agent 工具调用
============================================================
> Entering new AgentExecutor chain...
t.
</think>
Thought: 用户询问华为商城最新的手机有哪些,我需要使用华为商城搜索工具来查询相关信息。
Action: huawei_mall_search
Action Input: 华为商城最新手机 2024
[DEBUG] 工具被调用!搜索关键词:华为商城最新手机 2024
华为商城搜索结果:华为商城最新手机:Mate 60系列、P60系列、nova系列等。息。
</think>
Thought: 根据搜索结果,华为商城最新手机包括Mate 60系列、P60系列和nova系列。需要确认这些是否为当前最新型号,并补充具体信息。
Final Answer: 华为商城最新手机主要包括以下系列:
1. **Mate 60系列**(如Mate 60、Mate 60 Pro等)
2. **P60系列**(如P60、P60 Pro、P60 Art等)
3. **nova系列**(如nova 12系列等)
建议访问华为商城官网或线下门店获取具体型号、配置及最新活动信息。
> Finished chain.
最终输出: 华为商城最新手机主要包括以下系列:
1. **Mate 60系列**(如Mate 60、Mate 60 Pro等)
2. **P60系列**(如P60、P60 Pro、P60 Art等)
3. **nova系列**(如nova 12系列等)
建议访问华为商城官网或线下门店获取具体型号、配置及最新活动信息。
中间步骤: [(AgentAction(tool='huawei_mall_search', tool_input='华为商城最新手机 2024\n', log='t.\n</think>\n\nThought: 用户询问华为商城最新的手机有哪些,我需要使用华为商城搜索工具来查询相关信息。\n\nAction: huawei_mall_search\nAction Input: 华为商城最新手机 2024\n'), '华为商城搜索结果:华为商城最新手机:Mate 60系列、P60系列、nova系列等。')]
不调用工具输出:
============================================================
测试 Agent 工具调用
============================================================
> Entering new AgentExecutor chain...
制。
</think>
Thought: 这个问题涉及星座时间,属于天文或占星学知识,与华为商城的产品、活动、政策无关。当前可用工具huawei_mall_search无法提供此类信息。
Final Answer: 我无法通过华为商城工具查询星座时间。星座日期范围通常如下:白羊座(3.21-4.19)、金牛座(4.20-5.20)、双子座(5.21-6.21)、巨蟹座(6.22-7.22)、狮子座(7.23-8.22)、处女座(8.23-9.22)、天秤座(9.23-10.23)、天蝎座(10.24-11.22)、射手座(11.23-12.21)、摩羯座(12.22-1.19)、水瓶座(1.20-2.18)、双鱼座(2.19-3.20)。建议通过天文网站或专业占星应用获取更准确信息。
> Finished chain.
最终输出: 我无法通过华为商城工具查询星座时间。星座日期范围通常如下:白羊座(3.21-4.19)、金牛座(4.20-5.20)、双子座(5.21-6.21)、巨蟹座(6.22-7.22)、狮子座(7.23-8.22)、处女座(8.23-9.22)、天秤座(9.23-10.23)、天蝎座(10.24-11.22)、射手座(11.23-12.21)、摩羯座(12.22-1.19)、水瓶座(1.20-2.18)、双鱼座(2.19-3.20)。建议通过天文网站或专业占星应用获取更准确信息。
中间步骤: []
更多学习资料尽在 老虎网盘资源
浙公网安备 33010602011771号