运行智能代理¶
智能代理支持同步和异步执行,使用 .invoke() / await .ainvoke() 获取完整响应,或使用 .stream() / .astream() 获取**增量**流式传输输出。本节说明如何提供输入、解释输出、启用流式传输以及控制执行限制。
基本用法¶
智能代理可以在两种主要模式下执行:
- **同步**使用
.invoke()或.stream() - **异步**使用
await .ainvoke()或async for与.astream()
- **同步**使用
.invoke()或.stream() - **异步**使用
await .invoke()或for await与.stream()
import { createReactAgent } from "@langchain/langgraph/prebuilt";
const agent = createReactAgent(...);
// highlight-next-line
const response = await agent.invoke({
"messages": [
{ "role": "user", "content": "what is the weather in sf" }
]
});
输入和输出¶
智能代理使用语言模型,该模型期望输入是 messages 列表。因此,智能代理的输入和输出存储为智能代理状态中 messages 键下的 messages 列表。
输入格式¶
智能代理输入必须是带有 messages 键的字典。支持的格式有:
| 格式 | 示例 |
|---|---|
| 字符串 | {"messages": "Hello"} — 解释为 HumanMessage |
| 消息字典 | {"messages": {"role": "user", "content": "Hello"}} |
| 消息列表 | {"messages": [{"role": "user", "content": "Hello"}]} |
| 带自定义状态 | {"messages": [{"role": "user", "content": "Hello"}], "user_name": "Alice"} — 如果使用自定义 state_schema |
| 格式 | 示例 |
|---|---|
| 字符串 | {"messages": "Hello"} — 解释为 HumanMessage |
| 消息字典 | {"messages": {"role": "user", "content": "Hello"}} |
| 消息列表 | {"messages": [{"role": "user", "content": "Hello"}]} |
| 带自定义状态 | {"messages": [{"role": "user", "content": "Hello"}], "user_name": "Alice"} — 如果使用自定义状态定义 |
消息会自动转换为 LangChain 的内部消息格式。你可以在 LangChain 文档中阅读更多关于 LangChain 消息的信息。
消息会自动转换为 LangChain 的内部消息格式。你可以在 LangChain 文档中阅读更多关于 LangChain 消息的信息。
使用自定义智能代理状态
你可以直接在输入字典中提供智能代理状态模式中定义的其他字段。这允许基于运行时数据或先前工具输出的动态行为。 有关完整详细信息,请参阅上下文指南。
你可以直接在状态定义中提供智能代理状态中定义的其他字段。这允许基于运行时数据或先前工具输出的动态行为。 有关完整详细信息,请参阅上下文指南。
Note
messages 的字符串输入会被转换为 HumanMessage。此行为与 create_react_agent 中的 prompt 参数不同,后者在作为字符串传递时被解释为 SystemMessage。
messages 的字符串输入会被转换为 HumanMessage。此行为与 createReactAgent 中的 prompt 参数不同,后者在作为字符串传递时被解释为 SystemMessage。
输出格式¶
智能代理输出是包含以下内容的字典:
messages: 执行期间交换的所有消息列表(用户输入、助手回复、工具调用)。- 如果配置了结构化输出,则可选地包含
structured_response。 - 如果使用自定义
state_schema,输出中还可能存在与你定义的字段对应的其他键。这些可以保存来自工具执行或提示逻辑的更新状态值。
智能代理输出是包含以下内容的字典:
messages: 执行期间交换的所有消息列表(用户输入、助手回复、工具调用)。- 如果配置了结构化输出,则可选地包含
structuredResponse。 - 如果使用自定义状态定义,输出中还可能存在与你定义的字段对应的其他键。这些可以保存来自工具执行或提示逻辑的更新状态值。
有关使用自定义状态模式和访问上下文的更多详细信息,请参阅上下文指南。
流式输出¶
智能代理支持流式响应,以实现更具响应性的应用程序。这包括:
- 每一步之后的**进度更新**
- 生成的 LLM 标记
- 执行期间的**自定义工具消息**
流式传输在同步和异步模式下都可用:
for await (const chunk of agent.stream(
{ messages: [{ role: "user", content: "what is the weather in sf" }] },
{ streamMode: "updates" }
)) {
console.log(chunk);
}
Tip
有关完整详细信息,请参阅流式传输指南。
最大迭代¶
要控制智能代理执行并避免无限循环,请设置递归限制。这定义了智能代理在引发 GraphRecursionError 之前可以采取的最大步骤数。你可以在运行时配置 recursion_limit,或在通过 .with_config() 定义智能代理时配置:
要控制智能代理执行并避免无限循环,请设置递归限制。这定义了智能代理在引发 GraphRecursionError 之前可以采取的最大步骤数。你可以在运行时配置 recursionLimit,或在通过 .withConfig() 定义智能代理时配置:
from langgraph.errors import GraphRecursionError
from langgraph.prebuilt import create_react_agent
max_iterations = 3
# highlight-next-line
recursion_limit = 2 * max_iterations + 1
agent = create_react_agent(
model="anthropic:claude-3-5-haiku-latest",
tools=[get_weather]
)
try:
response = agent.invoke(
{"messages": [{"role": "user", "content": "what's the weather in sf"}]},
# highlight-next-line
{"recursion_limit": recursion_limit},
)
except GraphRecursionError:
print("Agent stopped due to max iterations.")
from langgraph.errors import GraphRecursionError
from langgraph.prebuilt import create_react_agent
max_iterations = 3
# highlight-next-line
recursion_limit = 2 * max_iterations + 1
agent = create_react_agent(
model="anthropic:claude-3-5-haiku-latest",
tools=[get_weather]
)
# highlight-next-line
agent_with_recursion_limit = agent.with_config(recursion_limit=recursion_limit)
try:
response = agent_with_recursion_limit.invoke(
{"messages": [{"role": "user", "content": "what's the weather in sf"}]},
)
except GraphRecursionError:
print("Agent stopped due to max iterations.")
import { GraphRecursionError } from "@langchain/langgraph";
import { ChatAnthropic } from "@langchain/langgraph/prebuilt";
import { createReactAgent } from "@langchain/langgraph/prebuilt";
const maxIterations = 3;
// highlight-next-line
const recursionLimit = 2 * maxIterations + 1;
const agent = createReactAgent({
llm: new ChatAnthropic({ model: "claude-3-5-haiku-latest" }),
tools: [getWeather]
});
try {
const response = await agent.invoke(
{"messages": [{"role": "user", "content": "what's the weather in sf"}]},
// highlight-next-line
{ recursionLimit }
);
} catch (error) {
if (error instanceof GraphRecursionError) {
console.log("Agent stopped due to max iterations.");
}
}
import { GraphRecursionError } from "@langchain/langgraph";
import { ChatAnthropic } from "@langchain/langgraph/prebuilt";
import { createReactAgent } from "@langchain/langgraph/prebuilt";
const maxIterations = 3;
// highlight-next-line
const recursionLimit = 2 * maxIterations + 1;
const agent = createReactAgent({
llm: new ChatAnthropic({ model: "claude-3-5-haiku-latest" }),
tools: [getWeather]
});
// highlight-next-line
const agentWithRecursionLimit = agent.withConfig({ recursionLimit });
try {
const response = await agentWithRecursionLimit.invoke(
{"messages": [{"role": "user", "content": "what's the weather in sf"}]},
);
} catch (error) {
if (error instanceof GraphRecursionError) {
console.log("Agent stopped due to max iterations.");
}
}