LangChain本地LLM自定义工具未触发问题及调用逻辑问询
解决LangChain本地LLM不调用自定义工具的问题及ReAct Agent逻辑解析
一、你的代码问题修复
模型不愿调用工具的核心原因是Prompt模板不符合ReAct Agent的格式要求,加上几处语法错误,导致模型不知道该触发工具调用逻辑。以下是修正后的代码:
from langchain.agents import create_react_agent, AgentExecutor from langchain.prompts import PromptTemplate from langchain.tools import tool from langchain.llms import LlamaCpp # 移除model_path的多余引号 llm = LlamaCpp(model_path="./mistral_7b_instruct/mistral-7b-instruct-v0.1.Q4_K_M.gguf", verbose=True) # 补全ReAct必需的思考-行动-观察引导规则 template = """ You are a helpful chat agent that is fun and quirky. Follow these rules strictly: 1. First, think about whether you need to use a tool to answer the user's question. 2. If you need to use a tool, format your response like this: Thought: I need to use the confetti tool to add a random word to the string. Action: confetti Action Input: "The input string here" 3. If you don't need a tool or have received the tool's result, format your final answer like this: Final Answer: [Your answer] Here are your tools: {tools} User's input: {input} Previous thoughts, actions and observations: {agent_scratchpad} """ @tool def confetti(string: str) -> str: """Adds a random word to the string""" # 修正返回值的字符串拼接逻辑 return f"confetti + {string}" # 创建Agent,确保工具参数一致 agent = create_react_agent( tools=[confetti], llm=llm, prompt=PromptTemplate.from_template(template), ) # 绑定工具到执行器 agent_executor = AgentExecutor(agent=agent, tools=[confetti], verbose=True) # 修复输入的引号嵌套问题 agent_executor.invoke(input="Could you add confetti to 'My (blank) seahorse?'")
关键修正点:
- Prompt模板:明确告知模型调用工具的格式规则,包含Thought/Action/Action Input的引导,这是模型触发工具的核心依据。
- 语法错误:移除model_path的多余引号、修复输入的引号嵌套、调整工具返回值的拼接逻辑。
- 工具绑定:确保AgentExecutor与create_react_agent的工具参数完全一致。
二、ReAct Agent触发工具的具体逻辑
ReAct Agent的工具调用循环核心在AgentExecutor类中,流程拆解如下:
- Prompt组装:每次循环将用户输入、工具列表、历史思考/行动/观察记录(
agent_scratchpad)拼接成完整Prompt,传给LLM。 - LLM响应生成:LLM根据Prompt输出自然语言响应,若Prompt引导正确,响应会包含Thought(判断是否需要工具)、Action(工具名)、Action Input(工具入参)。
- 响应解析:
ReActSingleInputOutputParser解析LLM响应,区分是工具调用请求还是最终答案。若为工具调用,提取工具名和入参。 - 工具执行:AgentExecutor根据解析结果匹配对应工具实例,传入入参执行,得到Observation(工具返回结果)。
- 循环迭代:将本次的Thought/Action/Action Input/Observation加入
agent_scratchpad,重新组装Prompt进入下一轮循环,直到LLM返回Final Answer。
核心代码位置参考:
ReActSingleInputOutputParser:负责解析响应并判断是否触发工具(位于langchain/agents/react/output_parser.py)。AgentExecutor._iteration方法:处理单次循环的完整流程,包括工具调用、scratchpad更新(位于langchain/agents/agent.py)。Tool.run方法:所有自定义工具的执行入口(位于langchain/tools/base.py)。
内容的提问来源于stack exchange,提问作者bitwise
相关产品推荐
相关产品推荐

