langchain.agents.tool_calling_agent.base.create_tool_calling_agent

langchain.agents.tool_calling_agent.base.create_tool_calling_agent(llm: ~langchain_core.language_models.base.BaseLanguageModel, tools: ~typing.Sequence[~langchain_core.tools.BaseTool], prompt: ~langchain_core.prompts.chat.ChatPromptTemplate, *, message_formatter: ~typing.Callable[[~typing.Sequence[~typing.Tuple[~langchain_core.agents.AgentAction, str]]], ~typing.List[~langchain_core.messages.base.BaseMessage]] = <function format_to_tool_messages>) Runnable[来源]

创建一个使用工具的智能体。

参数
  • llm (BaseLanguageModel) – 作为智能体使用的LLM。

  • tools (Sequence[BaseTool]) – 智能体可访问的工具。

  • prompt (ChatPromptTemplate) – 要使用的提示语。有关期望输入变量的更多内容,请参阅下面的提示部分。

  • message_formatter (Callable[[Sequence[Tuple[AgentAction, str]]], List[BaseMessage]]) – 将(智能体动作,工具输出)元组转换为FunctionMessages的格式化函数。

返回值

表示智能体的Runnable序列。它接受与传递给提示相同的所有输入变量。它返回的输出是AgentAction或AgentFinish。

返回类型

Runnable

示例

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:
    """Applies a magic function to an input."""
    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)?"})

# Using with chat history
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。中间的智能体动作和工具输出消息将传递到这里。

使用create_tool_calling_agent的示例