如何将运行时值传递给工具¶
有时,你希望让调用工具的LLM填充工具函数参数的*子集*,并在运行时提供其他参数的值。如果你使用的是LangChain风格的工具,可以通过注解函数参数为InjectedArg来轻松处理这种情况。此注解将排除该参数,使其不显示给LLM。
在LangGraph应用程序中,你可能希望在运行时将图状态或共享内存(存储)传递给工具。这种有状态的工具在工具的输出受过去代理步骤影响(例如,如果你使用子代理作为工具,并希望将消息历史传递给子代理)或工具的输入需要根据过去代理步骤的上下文进行验证时很有用。
在本指南中,我们将使用LangGraph的预构建ToolNode来演示如何做到这一点。
下面示例的核心技术是将一个参数标记为“注入”,这意味着它将由你的程序注入,不应被LLM看到或填充。以下代码片段可作为简要说明:
from typing import Annotated
from langchain_core.runnables import RunnableConfig
from langchain_core.tools import InjectedToolArg
from langgraph.store.base import BaseStore
from langgraph.prebuilt import InjectedState, InjectedStore
# 可以是同步或异步的;@tool装饰器不需要
async def my_tool(
# 这些参数由LLM填充
some_arg: str,
another_arg: float,
# config: RunnableConfig 总是在LangChain调用中可用
# 这个参数不暴露给LLM
config: RunnableConfig,
# 下面三个参数是预构建ToolNode特有的
# (以及`create_react_agent`的扩展)。如果你单独调用工具(在你自己的节点中),则需要自己提供这些参数。
store: Annotated[BaseStore, InjectedStore],
# 这里传递完整的状态。
state: Annotated[State, InjectedState],
# 你也可以从你的状态中注入单个字段
messages: Annotated[list, InjectedState("messages")]
# 下面的参数与create_react_agent或ToolNode不兼容
# 你也可以排除其他参数,使其不显示给模型。
# 这些参数必须手动提供,并在你自己的节点中调用工具/函数时很有用
# some_other_arg=Annotated["MyPrivateClass", InjectedToolArg],
):
"""调用my_tool以对现实世界产生影响。
Args:
some_arg: 一个非常重要的参数
another_arg: 另一个由LLM提供的参数
""" # 文档字符串成为你的工具描述,并传递给模型
print(some_arg, another_arg, config, store, state, messages)
# config、some_other_rag、store和state在传递给bind_tools或with_structured_output时都对LangChain模型隐藏
return "... some response"
API Reference: RunnableConfig | InjectedToolArg | InjectedState
环境搭建¶
首先我们需要安装所需的包
接下来,我们需要为OpenAI(我们将使用的聊天模型)设置API密钥。
import getpass
import os
def _set_env(var: str):
if not os.environ.get(var):
os.environ[var] = getpass.getpass(f"{var}: ")
_set_env("OPENAI_API_KEY")
为LangGraph开发设置LangSmith
注册LangSmith,可以快速发现并解决您的LangGraph项目中的问题,从而提高性能。LangSmith允许您使用跟踪数据来调试、测试和监控使用LangGraph构建的LLM应用程序——有关如何开始的更多信息,请参阅此处。
将图状态传递给工具¶
让我们先来看看如何让工具能够访问图状态。首先,我们需要定义图状态:
from typing import List
# this is the state schema used by the prebuilt create_react_agent we'll be using below
from langgraph.prebuilt.chat_agent_executor import AgentState
from langchain_core.documents import Document
class State(AgentState):
docs: List[str]
API Reference: Document
定义工具¶
我们希望工具能够以图状态作为输入,但不希望模型在调用工具时尝试生成这些输入。我们可以使用 InjectedState
注解来标记需要图状态(或图状态的某个字段)的参数。这些参数不会由模型生成。当使用 ToolNode
时,图状态将自动传递给相关的工具和参数。
在这个例子中,我们将创建一个返回文档的工具,然后创建另一个工具来引用支持某个主张的文档。
使用Pydantic与LangChain
本笔记本使用Pydantic v2 BaseModel
,需要langchain-core >= 0.3
。使用langchain-core < 0.3
将会由于混合使用Pydantic v1和v2的BaseModels
而导致错误。
from typing import List, Tuple
from typing_extensions import Annotated
from langchain_core.messages import ToolMessage
from langchain_core.tools import tool
from langgraph.prebuilt import InjectedState
@tool
def get_context(question: str, state: Annotated[dict, InjectedState]):
"""Get relevant context for answering the question."""
return "\n\n".join(doc for doc in state["docs"])
API Reference: ToolMessage | tool | InjectedState
如果我们查看这些工具的输入模式,会发现state
仍然被列出:
{'description': 'Get relevant context for answering the question.',
'properties': {'question': {'title': 'Question', 'type': 'string'},
'state': {'title': 'State', 'type': 'object'}},
'required': ['question', 'state'],
'title': 'get_context',
'type': 'object'}
但是如果我们查看工具调用模式,即传递给模型以进行工具调用的数据模式,state
已经被移除:
{'description': 'Get relevant context for answering the question.',
'properties': {'question': {'title': 'Question', 'type': 'string'}},
'required': ['question'],
'title': 'get_context',
'type': 'object'}
定义图¶
在这个示例中,我们将使用一个预构建的ReAct代理。首先,我们需要定义我们的模型和一个工具调用节点(ToolNode):
from langchain_openai import ChatOpenAI
from langgraph.prebuilt import ToolNode, create_react_agent
from langgraph.checkpoint.memory import MemorySaver
model = ChatOpenAI(model="gpt-4o", temperature=0)
tools = [get_context]
# ToolNode will automatically take care of injecting state into tools
tool_node = ToolNode(tools)
checkpointer = MemorySaver()
graph = create_react_agent(model, tools, state_schema=State, checkpointer=checkpointer)
API Reference: ChatOpenAI | ToolNode | create_react_agent | MemorySaver
使用它!¶
docs = [
"FooBar company just raised 1 Billion dollars!",
"FooBar company was founded in 2019",
]
inputs = {
"messages": [{"type": "user", "content": "what's the latest news about FooBar"}],
"docs": docs,
}
config = {"configurable": {"thread_id": "1"}}
for chunk in graph.stream(inputs, config, stream_mode="values"):
chunk["messages"][-1].pretty_print()
================================[1m Human Message [0m=================================
what's the latest news about FooBar
==================================[1m Ai Message [0m==================================
Tool Calls:
get_context (call_UkqfR7z2cLJQjhatUpDeEa5H)
Call ID: call_UkqfR7z2cLJQjhatUpDeEa5H
Args:
question: latest news about FooBar
=================================[1m Tool Message [0m=================================
Name: get_context
FooBar company just raised 1 Billion dollars!
FooBar company was founded in 2019
==================================[1m Ai Message [0m==================================
The latest news about FooBar is that the company has just raised 1 billion dollars.
将共享内存(存储)传递给图¶
你可能也希望给工具提供访问跨多个对话或用户的共享内存的能力。我们可以通过将 LangGraph Store 传递给工具,并使用不同的注解 -- InjectedStore
来实现这一点。
让我们修改示例,将文档保存在内存存储中,并使用 get_context
工具检索它们。我们还将根据用户 ID 让文档变得可访问,因此某些文档仅对特定用户可见。工具将使用在 配置 中提供的 user_id
来检索正确的文档集。
注意
Store
API和InjectedStore
,支持在LangGraph v0.2.34
版本中添加。
InjectedStore
注解需要langchain-core >= 0.3.8
from langgraph.store.memory import InMemoryStore
doc_store = InMemoryStore()
namespace = ("documents", "1") # user ID
doc_store.put(
namespace, "doc_0", {"doc": "FooBar company just raised 1 Billion dollars!"}
)
namespace = ("documents", "2") # user ID
doc_store.put(namespace, "doc_1", {"doc": "FooBar company was founded in 2019"})
定义工具¶
from langgraph.store.base import BaseStore
from langchain_core.runnables import RunnableConfig
from langgraph.prebuilt import InjectedStore
@tool
def get_context(
question: str,
config: RunnableConfig,
store: Annotated[BaseStore, InjectedStore()],
) -> Tuple[str, List[Document]]:
"""Get relevant context for answering the question."""
user_id = config.get("configurable", {}).get("user_id")
docs = [item.value["doc"] for item in store.search(("documents", user_id))]
return "\n\n".join(doc for doc in docs)
API Reference: RunnableConfig
我们还可以验证该工具调用模型会忽略get_context
工具的store
参数:
{'description': 'Get relevant context for answering the question.',
'properties': {'question': {'title': 'Question', 'type': 'string'}},
'required': ['question'],
'title': 'get_context',
'type': 'object'}
定义图¶
让我们更新我们的ReAct代理:
tools = [get_context]
# ToolNode will automatically take care of injecting Store into tools
tool_node = ToolNode(tools)
checkpointer = MemorySaver()
# NOTE: we need to pass our store to `create_react_agent` to make sure our graph is aware of it
graph = create_react_agent(model, tools, checkpointer=checkpointer, store=doc_store)
使用它!¶
让我们尝试在配置中使用一个"user_id"
来运行我们的图。
messages = [{"type": "user", "content": "what's the latest news about FooBar"}]
config = {"configurable": {"thread_id": "1", "user_id": "1"}}
for chunk in graph.stream({"messages": messages}, config, stream_mode="values"):
chunk["messages"][-1].pretty_print()
================================[1m Human Message [0m=================================
what's the latest news about FooBar
==================================[1m Ai Message [0m==================================
Tool Calls:
get_context (call_ocyHBpGgF3LPFOgRKURBfkGG)
Call ID: call_ocyHBpGgF3LPFOgRKURBfkGG
Args:
question: latest news about FooBar
=================================[1m Tool Message [0m=================================
Name: get_context
FooBar company just raised 1 Billion dollars!
==================================[1m Ai Message [0m==================================
The latest news about FooBar is that the company has just raised 1 billion dollars.
messages = [{"type": "user", "content": "what's the latest news about FooBar"}]
config = {"configurable": {"thread_id": "2", "user_id": "2"}}
for chunk in graph.stream({"messages": messages}, config, stream_mode="values"):
chunk["messages"][-1].pretty_print()
================================[1m Human Message [0m=================================
what's the latest news about FooBar
==================================[1m Ai Message [0m==================================
Tool Calls:
get_context (call_zxO9KVlL8UxFQUMb8ETeHNvs)
Call ID: call_zxO9KVlL8UxFQUMb8ETeHNvs
Args:
question: latest news about FooBar
=================================[1m Tool Message [0m=================================
Name: get_context
FooBar company was founded in 2019
==================================[1m Ai Message [0m==================================
FooBar company was founded in 2019. If you need more specific or recent news, please let me know!