Tool Call

前置准备

from langchain_core.messages import AIMessage
from langchain_core.tools import tool

from langgraph.prebuilt import ToolNode
import os


# os.environ['HTTP_PROXY'] = 'http://127.0.0.1:10809'
# os.environ['HTTPS_PROXY'] = 'http://127.0.0.1:10809'
os.environ['LANGSMITH_TRACING'] = 'true'
os.environ['LANGSMITH_ENDPOINT'] = 'https://api.smith.langchain.com'
os.environ['LANGSMITH_API_KEY'] = 'xxxxxxxxxxxxxxxxxxxx'
os.environ['LANGSMITH_PROJECT'] = 'xxxxxxxxxxxxxxxxxxxx'

定义工具

@tool
def get_weather(location: str):
    """Call to get the current weather."""
    if location.lower() in ["sf", "san francisco"]:
        return "It's 60 degrees and foggy."
    else:
        return "It's 90 degrees and sunny."


@tool
def get_coolest_cities():
    """Get a list of coolest cities"""
    return "nyc, sf"

定义的工具中,doc 注释和参数会告诉 LLM Agent,让其参考并选择合适的工具

手动调用 tool

ToolNode使用消息列表对图形状态进行操作。它要求列表中的最后一条消息是AIMessagewithtool_calls参数

可将多个工具调用传递给 AIMessage 的 tool_calls 参数,您还可以使用 ToolNode 进行并行工具调用:

与聊天模型一起使用

要将聊天模型与工具调用一起使用,我们首先需要确保模型知道可用的工具。调用 .bind_tools 方法来执行此操作

聊天模型生成的 AI 消息已经 tool_calls 填充,因此我们可以将其直接传递给 ToolNode

ReAct 代理

让我们看看如何在 LangGraph 图中使用 ToolNode。让我们设置 ReAct 代理的图形实现。此代理将一些查询作为输入,然后重复调用 tools,直到它有足够的信息来解析查询。

png

langsmith 上的追踪

最后更新于