from langchain.agents import AgentState from langchain.messages import ToolMessage from langchain.tools import ToolRuntime, tool from langgraph.types import Command
from dataclasses import dataclass from langchain_openai import ChatOpenAI from langchain.agents import create_agent from langchain.tools import tool, ToolRuntime
from typing importAny from langgraph.store.memory import InMemoryStore from langchain.agents import create_agent from langchain.tools import tool, ToolRuntime from langchain_openai import ChatOpenAI
# 读取长期存储中的用户信息 @tool defget_user_info(user_id: str, runtime: ToolRuntime) -> str: """Look up user info.""" store = runtime.store # get(命名空间, 键),命名空间用于组织数据,例如按类型分组 user_info = store.get(("users",), user_id) # .value 存储实际数据,如果不存在则返回 None returnstr(user_info.value) if user_info else"Unknown user"
# 保存信息到长期存储 @tool defsave_user_info(user_id: str, user_info: dict[str, Any], runtime: ToolRuntime) -> str: """Save user info.""" store = runtime.store store.put(("users",), user_id, user_info) # 存储到 "users" 命名空间下,键为 user_id return"Successfully saved user info."
model = ChatOpenAI(model="gpt-4o") store = InMemoryStore() # 内存存储(仅用于测试,重启后数据丢失) agent = create_agent( model, tools=[get_user_info, save_user_info], store=store # 将存储传入智能体,工具可通过 runtime 访问 )
# 第一次会话:保存用户信息 agent.invoke({ "messages": [{"role": "user", "content": "Save the following user: userid: abc123, name: Foo, age: 25, email: foo@langchain.dev"}] })
# 第二次会话(不同的对话线程):获取用户信息 agent.invoke({ "messages": [{"role": "user", "content": "Get user info for user with id 'abc123'"}] }) # 输出:Here is the user info for user with ID "abc123": Name: Foo, Age: 25, Email: foo@langchain.dev
补充说明:
Store API 设计为通用的键值存储,命名空间可以是元组,支持层级。例如 ("users", "premium") 与 ("users", "trial") 是不同的命名空间。
@tool defget_weather(city: str, runtime: ToolRuntime) -> str: """Get weather for a given city.""" writer = runtime.stream_writer # 流式发送中间状态,用户界面可以实时显示 writer(f"Looking up data for city: {city}") writer(f"Acquired data for city: {city}") returnf"It's always sunny in {city}!"
当你的工具在 LangGraph Server 上运行时,通过 runtime.server_info 访问助手 ID、图形 ID 和已认证用户:
1 2 3 4 5 6 7 8 9 10 11 12
from langchain.tools import tool, ToolRuntime
@tool defget_assistant_scoped_data(runtime: ToolRuntime) -> str: """Fetch data scoped to the current assistant.""" server = runtime.server_info if server isnotNone: # 仅在 LangGraph Server 环境中这些字段才不为 None print(f"Assistant: {server.assistant_id}, Graph: {server.graph_id}") if server.user isnotNone: print(f"User: {server.user.identity}") return"done"
当工具不在 LangGraph Server 上运行时(例如,在本地开发或测试期间),server_info 为 None。
from langchain.tools import tool, ToolRuntime from langgraph.prebuilt import ToolNode
@tool defget_message_count(runtime: ToolRuntime) -> str: """Get the number of messages in the conversation.""" messages = runtime.state["messages"] returnf"There are {len(messages)} messages."