1. 工具定义
from typing import Listfrom langchain_core.tools import tool
from langchain_core.runnables.config import RunnableConfigfrom langgraph.prebuilt import ToolNodeuser_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 LLMpets: 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 ToolNodefrom langchain_openai import ChatOpenAIllm = 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 Literalfrom langgraph.graph import StateGraph, MessagesState, START, ENDdef should_continue(state: MessagesState):messages = state["messages"]last_message = messages[-1]if last_message.tool_calls:return "tools"return ENDdef 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, displaytry:display(Image(graph.get_graph().draw_mermaid_png()))
except Exception:# This requires some extra dependencies and is optionalpass
3. graph 测试
3.1 update_favorite_pets
from langchain_core.messages import HumanMessageuser_to_pets.clear() # Clear the stateprint(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_-9186120101326831553Args:pets: ['cats', 'dogs']
=================================[1m Tool Message [0m=================================
Name: update_favorite_petsnull
==================================[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 HumanMessageprint(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_-9186123399862058748Args:
=================================[1m Tool Message [0m=================================
Name: list_favorite_petscats, 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_-9186117215107514141Args:
=================================[1m Tool Message [0m=================================
Name: delete_favorite_petsnull
==================================[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/
如果有任何问题,欢迎在评论区提问。