4. langgraph中的Tool Calling (How to pass config to tools)

1. 工具定义

from typing import List

from langchain_core.tools import tool
from langchain_core.runnables.config import RunnableConfig

from langgraph.prebuilt import ToolNode

user_to_pets = {}


@tool(parse_docstring=True)
def update_favorite_pets(
    # NOTE: config arg does not need to be added to docstring, as we don't want it to be included in the function signature attached to the LLM
    pets: List[str],
    config: RunnableConfig,
) -> None:
    """Add the list of favorite pets.

    Args:
        pets: List of favorite pets to set.
    """
    user_id = config.get("configurable", {}).get("user_id")
    user_to_pets[user_id] = pets


@tool
def delete_favorite_pets(config: RunnableConfig) -> None:
    """Delete the list of favorite pets."""
    user_id = config.get("configurable", {}).get("user_id")
    if user_id in user_to_pets:
        del user_to_pets[user_id]


@tool
def list_favorite_pets(config: RunnableConfig) -> None:
    """List favorite pets if any."""
    user_id = config.get("configurable", {}).get("user_id")
    return ", ".join(user_to_pets.get(user_id, []))

将工具转化为节点

tools = [update_favorite_pets, delete_favorite_pets, list_favorite_pets]
tool_node = ToolNode(tools)

2. 模型与工具绑定

from langgraph.graph import StateGraph, MessagesState
from langgraph.prebuilt import ToolNode


from langchain_openai import ChatOpenAI

llm = ChatOpenAI(
    temperature=0,
    model="GLM-4-plus",
    openai_api_key="your api key",
    openai_api_base="https://open.bigmodel.cn/api/paas/v4/"
)
model_with_tools= llm.bind_tools(tools)

3. graph 定义

from typing import Literal

from langgraph.graph import StateGraph, MessagesState, START, END


def should_continue(state: MessagesState):
    messages = state["messages"]
    last_message = messages[-1]
    if last_message.tool_calls:
        return "tools"
    return END


def call_model(state: MessagesState):
    messages = state["messages"]
    response = model_with_tools.invoke(messages)
    return {"messages": [response]}


builder = StateGraph(MessagesState)

# Define the two nodes we will cycle between
builder.add_node("agent", call_model)
builder.add_node("tools", tool_node)

builder.add_edge(START, "agent")
builder.add_conditional_edges("agent", should_continue, ["tools", END])
builder.add_edge("tools", "agent")

graph = builder.compile()

graph 可视化

from IPython.display import Image, display

try:
    display(Image(graph.get_graph().draw_mermaid_png()))
except Exception:
    # This requires some extra dependencies and is optional
    pass

请添加图片描述

3. graph 测试

3.1 update_favorite_pets

from langchain_core.messages import HumanMessage

user_to_pets.clear()  # Clear the state

print(f"User information prior to run: {user_to_pets}")

inputs = {"messages": [HumanMessage(content="my favorite pets are cats and dogs")]}
for chunk in graph.stream(
    inputs, {"configurable": {"user_id": "123"}}, stream_mode="values"
):
    chunk["messages"][-1].pretty_print()

print(f"User information after the run: {user_to_pets}")
User information prior to run: {}
================================[1m Human Message [0m=================================

my favorite pets are cats and dogs
==================================[1m Ai Message [0m==================================
Tool Calls:
  update_favorite_pets (call_-9186120101326831553)
 Call ID: call_-9186120101326831553
  Args:
    pets: ['cats', 'dogs']
=================================[1m Tool Message [0m=================================
Name: update_favorite_pets

null
==================================[1m Ai Message [0m==================================

Your favorite pets, cats and dogs, have been successfully updated in the system. If you need to check or modify this list in the future, just let me know!
User information after the run: {'123': ['cats', 'dogs']}

3.2 list_favorite_pets

from langchain_core.messages import HumanMessage

print(f"User information prior to run: {user_to_pets}")

inputs = {"messages": [HumanMessage(content="what are my favorite pets")]}
for chunk in graph.stream(
    inputs, {"configurable": {"user_id": "123"}}, stream_mode="values"
):
    chunk["messages"][-1].pretty_print()

print(f"User information prior to run: {user_to_pets}")
User information prior to run: {'123': ['cats', 'dogs']}
================================[1m Human Message [0m=================================

what are my favorite pets
==================================[1m Ai Message [0m==================================
Tool Calls:
  list_favorite_pets (call_-9186123399862058748)
 Call ID: call_-9186123399862058748
  Args:
=================================[1m Tool Message [0m=================================
Name: list_favorite_pets

cats, dogs
==================================[1m Ai Message [0m==================================

Your favorite pets are cats and dogs.
User information prior to run: {'123': ['cats', 'dogs']}

3.3 delete_favorite_pets

print(f"User information prior to run: {user_to_pets}")

inputs = {
    "messages": [
        HumanMessage(content="please forget what i told you about my favorite animals")
    ]
}
for chunk in graph.stream(
    inputs, {"configurable": {"user_id": "123"}}, stream_mode="values"
):
    chunk["messages"][-1].pretty_print()

print(f"User information prior to run: {user_to_pets}")
User information prior to run: {'123': ['cats', 'dogs']}
================================[1m Human Message [0m=================================

please forget what i told you about my favorite animals
==================================[1m Ai Message [0m==================================
Tool Calls:
  delete_favorite_pets (call_-9186117215107514141)
 Call ID: call_-9186117215107514141
  Args:
=================================[1m Tool Message [0m=================================
Name: delete_favorite_pets

null
==================================[1m Ai Message [0m==================================

Understood. I have forgotten the information about your favorite animals. If you have any other questions or need assistance with something else, feel free to ask!
User information prior to run: {}

参考链接:https://langchain-ai.github.io/langgraph/how-tos/pass-config-to-tools/
如果有任何问题,欢迎在评论区提问。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值