LangGraph 快速入门¶
本指南将向您展示如何设置和使用 LangGraph 的 预构建、可复用 组件,这些组件旨在帮助您快速且可靠地构建代理系统。
先决条件¶
在开始本教程之前,请确保您具备以下条件:
- 一个 Anthropic API 密钥
1. 安装依赖项¶
如果你尚未安装,请安装 LangGraph 和 LangChain:
Info
安装 LangChain 是为了让代理能够调用 模型。
2. 创建一个代理¶
要创建一个代理,请使用 create_react_agent
:
API Reference: create_react_agent
from langgraph.prebuilt import create_react_agent
def get_weather(city: str) -> str: # (1)!
"""获取给定城市的天气情况。"""
return f"{city}的天气总是晴朗!"
agent = create_react_agent(
model="anthropic:claude-3-7-sonnet-latest", # (2)!
tools=[get_weather], # (3)!
prompt="你是一个乐于助人的助手" # (4)!
)
# 运行代理
agent.invoke(
{"messages": [{"role": "user", "content": "sf的天气如何"}]}
)
- 为代理定义一个工具。工具可以定义为普通的 Python 函数。有关更高级的工具使用和自定义,请查看 tools 页面。
- 为代理提供一个语言模型。如需了解如何配置代理的语言模型,请查看 models 页面。
- 为模型提供一个工具列表。
- 为代理使用的语言模型提供一个系统提示(指令)。
3. 配置 LLM¶
要使用特定参数(如温度)配置 LLM,请使用 init_chat_model:
API Reference: init_chat_model | create_react_agent
from langchain.chat_models import init_chat_model
from langgraph.prebuilt import create_react_agent
model = init_chat_model(
"anthropic:claude-3-7-sonnet-latest",
temperature=0
)
agent = create_react_agent(
model=model,
tools=[get_weather],
)
有关如何配置 LLM 的更多信息,请参阅 Models。
4. 添加自定义提示¶
提示指导 LLM 的行为。添加以下类型的提示之一:
- 静态:字符串被解释为 系统消息。
- 动态:在 运行时 基于输入或配置生成的消息列表。
定义一个固定提示字符串或消息列表:
定义一个函数,根据代理的状态和配置返回消息列表:
from langchain_core.messages import AnyMessage
from langchain_core.runnables import RunnableConfig
from langgraph.prebuilt.chat_agent_executor import AgentState
from langgraph.prebuilt import create_react_agent
def prompt(state: AgentState, config: RunnableConfig) -> list[AnyMessage]: # (1)!
user_name = config["configurable"].get("user_name")
system_msg = f"You are a helpful assistant. Address the user as {user_name}."
return [{"role": "system", "content": system_msg}] + state["messages"]
agent = create_react_agent(
model="anthropic:claude-3-7-sonnet-latest",
tools=[get_weather],
prompt=prompt
)
agent.invoke(
{"messages": [{"role": "user", "content": "what is the weather in sf"}]},
config={"configurable": {"user_name": "John Smith"}}
)
-
动态提示允许在构建发送给 LLM 的输入时包含非消息 上下文,例如:
- 在运行时传递的信息,如
user_id
或 API 凭据(使用config
)。 - 多步骤推理过程中更新的内部代理状态(使用
state
)。
动态提示可以定义为接受
state
和config
并返回要发送给 LLM 的消息列表的函数。 - 在运行时传递的信息,如
有关更多信息,请参阅 Context。
5. 添加内存¶
要允许与代理进行多轮对话,需要通过在创建代理时提供 checkpointer
来启用 持久化。在运行时,你需要提供一个包含 thread_id
的配置 —— 这是对话(会话)的唯一标识符:
API Reference: create_react_agent | InMemorySaver
from langgraph.prebuilt import create_react_agent
from langgraph.checkpoint.memory import InMemorySaver
checkpointer = InMemorySaver()
agent = create_react_agent(
model="anthropic:claude-3-7-sonnet-latest",
tools=[get_weather],
checkpointer=checkpointer # (1)!
)
# Run the agent
config = {"configurable": {"thread_id": "1"}}
sf_response = agent.invoke(
{"messages": [{"role": "user", "content": "what is the weather in sf"}]},
config # (2)!
)
ny_response = agent.invoke(
{"messages": [{"role": "user", "content": "what about new york?"}]},
config
)
当你启用 checkpointer
时,它会在提供的 checkpointer
数据库中(或使用 InMemorySaver
时在内存中)在每个步骤存储代理的状态。
请注意,在上面的示例中,当使用相同的 thread_id
第二次调用代理时,第一次对话的原始消息历史会自动包含在内,并加上新的用户输入。
如需更多信息,请参阅 内存。
6. 配置结构化输出¶
要生成符合特定模式的结构化响应,请使用 response_format
参数。模式可以通过 Pydantic
模型或 TypedDict
来定义。结果可通过 structured_response
字段访问。
API Reference: create_react_agent
from pydantic import BaseModel
from langgraph.prebuilt import create_react_agent
class WeatherResponse(BaseModel):
conditions: str
agent = create_react_agent(
model="anthropic:claude-3-7-sonnet-latest",
tools=[get_weather],
response_format=WeatherResponse # (1)!
)
response = agent.invoke(
{"messages": [{"role": "user", "content": "what is the weather in sf"}]}
)
response["structured_response"]
-
当提供
response_format
时,会在代理循环的末尾添加一个单独的步骤:将代理消息历史传递给具有结构化输出的 LLM 以生成结构化响应。要为此 LLM 提供系统提示,请使用元组
(prompt, schema)
,例如response_format=(prompt, WeatherResponse)
。
LLM 后处理
结构化输出需要额外调用 LLM 来根据模式格式化响应。