LangGraph 快速入门¶
本指南将向您展示如何设置和使用 LangGraph 的预构建、可复用组件,这些组件旨在帮助您快速可靠地构建代理系统。
先决条件¶
在开始本教程之前,请确保您具备以下条件:
- 一个 Anthropic API 密钥
1. 安装依赖¶
如果您尚未安装,请安装 LangGraph 和 LangChain
信息
安装 LangChain 是为了让代理能够调用模型。
2. 创建代理¶
要创建代理,请使用 create_react_agent
API 参考: create_react_agent
from langgraph.prebuilt import create_react_agent
def get_weather(city: str) -> str: # (1)!
"""Get weather for a given city."""
return f"It's always sunny in {city}!"
agent = create_react_agent(
model="anthropic:claude-3-7-sonnet-latest", # (2)!
tools=[get_weather], # (3)!
prompt="You are a helpful assistant" # (4)!
)
# Run the agent
agent.invoke(
{"messages": [{"role": "user", "content": "what is the weather in sf"}]}
)
- 定义供代理使用的工具。工具可以定义为普通的 Python 函数。有关更高级的工具用法和自定义,请查阅工具页面。
- 提供供代理使用的语言模型。要了解更多关于为代理配置语言模型的信息,请查阅模型页面。
- 提供模型要使用的工具列表。
- 向代理使用的语言模型提供系统提示(指令)。
3. 配置LLM¶
要配置具有特定参数(例如温度)的LLM,请使用 init_chat_model
API 参考: 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的更多信息,请参阅模型。
4. 添加自定义提示¶
提示指导LLM如何行动。添加以下类型的提示之一:
- 静态:一个字符串被解释为系统消息。
- 动态:在运行时根据输入或配置生成的消息列表。
定义固定的提示字符串或消息列表
from langgraph.prebuilt import create_react_agent
agent = create_react_agent(
model="anthropic:claude-3-7-sonnet-latest",
tools=[get_weather],
# A static prompt that never changes
prompt="Never answer questions about the weather."
)
agent.invoke(
{"messages": [{"role": "user", "content": "what is the weather in sf"}]}
)
定义一个函数,根据代理的状态和配置返回消息列表
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的消息列表的函数。 - 在运行时传递的信息,例如
有关更多信息,请参阅上下文。
5. 添加记忆¶
为了允许与代理进行多轮对话,您需要在创建代理时通过提供checkpointer
来启用持久化。在运行时,您需要提供一个包含thread_id
的配置,thread_id
是对话(会话)的唯一标识符。
API 参考: 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 参考: 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进行额外调用,以根据架构格式化响应。