langchain.agents.react.agent
.create_react_agent¶
- langchain.agents.react.agent.create_react_agent(llm: ~langchain_core.language_models.base.BaseLanguageModel, tools: ~typing.Sequence[~langchain_core.tools.BaseTool], prompt: ~langchain_core.prompts.base.BasePromptTemplate, output_parser: ~typing.Optional[~langchain.agents.agent.AgentOutputParser] = None, tools_renderer: ~typing.Callable[[~typing.List[~langchain_core.tools.BaseTool]], str] = <function render_text_description>, *, stop_sequence: ~typing.Union[bool, ~typing.List[str]] = True) Runnable [source]¶
创建一个使用ReAct提示的智能体。
基于论文“ReAct: 语言模型中的推理与行动协同” (https://arxiv.org/abs/2210.03629)
- 参数
llm (BaseLanguageModel) – 要作为智能体使用的LLM。
tools (Sequence[BaseTool]) – 此智能体可以访问的工具。
prompt (BasePromptTemplate) – 要使用的提示。有关更多信息,请参阅下面的提示部分。
output_parser (Optional[AgentOutputParser]) – 用于解析LLM输出的AgentOutputParser。
tools_renderer (Callable[[List[BaseTool]], str]) – 这控制工具如何转换为字符串然后传递给LLM。默认为 render_text_description。
stop_sequence (Union[bool, List[str]]) –
布尔值或字符串列表。如果为True,添加“观察:”的停止标记以避免幻觉。如果为False,则不添加停止标记。如果为字符串列表,则使用提供的列表作为停止标记。
默认为True。您可以将此设置为False,如果所使用的LLM不支持停止序列。
- 返回
表示智能体的Runnable序列。它接受与传递给提示相同的所有输入变量。它返回输出是AgentAction或AgentFinish。
- 返回类型
示例
from langchain import hub from langchain_community.llms import OpenAI from langchain.agents import AgentExecutor, create_react_agent prompt = hub.pull("hwchase17/react") model = OpenAI() tools = ... agent = create_react_agent(model, tools, prompt) agent_executor = AgentExecutor(agent=agent, tools=tools) agent_executor.invoke({"input": "hi"}) # Use with chat history from langchain_core.messages import AIMessage, HumanMessage agent_executor.invoke( { "input": "what's my name?", # Notice that chat_history is a string # since this prompt is aimed at LLMs, not chat models "chat_history": "Human: My name is Bob\nAI: Hello Bob!", } )
提示
- 提示必须具有输入键
tools:包含每个工具的描述和参数。
tool_names:包含所有工具名称。
agent_scratchpad:包含先前智能体操作和工具输出的字符串。
以下是一个示例
from langchain_core.prompts import PromptTemplate 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}''' prompt = PromptTemplate.from_template(template)