Source code for langchain.agents.tool_calling_agent.base

from typing import Sequence

from langchain_core.language_models import BaseLanguageModel
from langchain_core.prompts.chat import ChatPromptTemplate
from langchain_core.runnables import Runnable, RunnablePassthrough
from langchain_core.tools import BaseTool

from langchain.agents.format_scratchpad.tools import (
    format_to_tool_messages,
)
from langchain.agents.output_parsers.tools import ToolsAgentOutputParser


[docs]def create_tool_calling_agent( llm: BaseLanguageModel, tools: Sequence[BaseTool], prompt: ChatPromptTemplate ) -> Runnable: """创建一个使用工具的代理。 参数: llm: 作为代理使用的LLM。 tools: 该代理可以访问的工具。 prompt: 要使用的提示。有关预期输入变量的更多信息,请参见下面的提示部分。 返回: 代表代理的可运行序列。它接受与传入的提示相同的所有输入变量。它返回一个AgentAction或AgentFinish。 示例: .. code-block:: python from langchain.agents import AgentExecutor, create_tool_calling_agent, tool from langchain_anthropic import ChatAnthropic from langchain_core.prompts import ChatPromptTemplate prompt = ChatPromptTemplate.from_messages( [ ("system", "You are a helpful assistant"), ("placeholder", "{chat_history}"), ("human", "{input}"), ("placeholder", "{agent_scratchpad}"), ] ) model = ChatAnthropic(model="claude-3-opus-20240229") @tool def magic_function(input: int) -> int: \"\"\"对输入应用一个魔术函数。\"\"\" return input + 2 tools = [magic_function] agent = create_tool_calling_agent(model, tools, prompt) agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True) agent_executor.invoke({"input": "what is the value of magic_function(3)?"}) # 使用聊天历史 from langchain_core.messages import AIMessage, HumanMessage agent_executor.invoke( { "input": "what's my name?", "chat_history": [ HumanMessage(content="hi! my name is bob"), AIMessage(content="Hello Bob! How can I assist you today?"), ], } ) 提示: 代理提示必须有一个`agent_scratchpad`键,它是一个``MessagesPlaceholder``。中间代理操作和工具输出消息将传递到这里。 """ missing_vars = {"agent_scratchpad"}.difference( prompt.input_variables + list(prompt.partial_variables) ) if missing_vars: raise ValueError(f"Prompt missing required variables: {missing_vars}") if not hasattr(llm, "bind_tools"): raise ValueError( "This function requires a .bind_tools method be implemented on the LLM.", ) llm_with_tools = llm.bind_tools(tools) agent = ( RunnablePassthrough.assign( agent_scratchpad=lambda x: format_to_tool_messages(x["intermediate_steps"]) ) | prompt | llm_with_tools | ToolsAgentOutputParser() ) return agent