要在langchain中启用react模式,必须显式构造agentexecutor并确保工具函数签名与llm输出解析器严格匹配;工具需用@tool装饰、docstring清晰描述、返回字符串;llm须选用支持react格式的模型并指定agent="react-docstore"或"react-chat";最后通过create_react_agent和agentexecutor.from_agent_and_tools组装,调用invoke时输入键必须为"input"。
☞☞☞AI 智能聊天, 问答助手, AI 智能搜索, 多模态理解力帮你轻松跨越从0到1的创作门槛☜☜☜

要在LangChain中启用ReAct模式实现工具调用,必须显式构造具有推理-行动循环逻辑的AgentExecutor,并确保工具函数签名与LLM输出解析器严格匹配,否则会因action parsing失败而卡死在第一步。
准备可调用工具函数
定义一个符合Tool接口的函数,例如查询天气:使用@tool装饰器包装函数,函数docstring必须用自然语言清晰描述用途和参数,LangChain靠它生成tool description供LLM决策;返回值必须是字符串,不能是dict或None。
from langchain.tools import tool
@tool
def get_weather(city: str) -> str:
"""根据城市名查询当前天气,输入必须是中文城市名,如'北京'"""
return f"{city}晴,25℃,东南风2级"
将工具放入列表:tools = [get_weather]
配置ReAct专用LLM链
选用支持function calling或能稳定输出ReAct格式(Thought/Action/Action Input/Observation)的模型。OpenAI的gpt-3.5-turbo-1106或gpt-4-turbo推荐开启temperature=0防止格式漂移。
本文档主要讲述的是React Native For Android 源码编译;希望对大家会有帮助;感兴趣的朋友可以过来看看
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(model="gpt-4-turbo", temperature=0)
【必须指定agent="react-docstore"或agent="react-chat"】,不能用"openai-tools"或"structured-chat"——后者走的是函数调用协议,不是ReAct文本推理流。
组装并运行AgentExecutor
第一步:用create_react_agent()工厂函数构建代理链,传入llm、tools和prompt(可选自定义prompt);
第二步:用AgentExecutor.from_agent_and_tools()封装,设置handle_parsing_errors=True避免解析失败直接报错退出;
第三步:调用invoke()传入{"input": "今天上海天气怎么样?"}字典,注意键名必须是"input"。
from langchain.agents import create_react_agent, AgentExecutor
from langchain_core.prompts import PromptTemplate
prompt = PromptTemplate.from_template("Answer the following questions as best you can. You have access to the following tools:\n{tools}\nUse the following format:\n\nQuestion: the input question you must answer\nThought: you should always think like you are answering the question step by step\nAction: the action to take, should be one of [{tool_names}]\nAction Input: the input to the action\nObservation: the result of the action\n... (this Thought/Action/Action Input/Observation can repeat N times)\nThought: I now know the final answer\nFinal Answer: the final answer to the original input question\n\nBegin!\n\nQuestion: {input}\nThought:")
agent = create_react_agent(llm, tools, prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools, handle_parsing_errors=True)
agent_executor.invoke({"input": "今天上海天气怎么样?"})










