跳过内容

LangGraph 快速入门

本指南将向您展示如何设置和使用 LangGraph 的预构建可重用组件,这些组件旨在帮助您快速可靠地构建代理系统。

先决条件

在开始本教程之前,请确保您具备以下条件

1. 安装依赖

如果您还没有安装 LangGraph 和 LangChain

pip install -U langgraph "langchain[anthropic]"

信息

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"}]}
)
  1. 定义一个供代理使用的工具。工具可以定义为普通的 Python 函数。有关更高级的工具使用和自定义,请查看工具页面。
  2. 为代理提供要使用的语言模型。要了解有关为代理配置语言模型的更多信息,请查看模型页面。
  3. 提供一个工具列表供模型使用。
  4. 向代理使用的语言模型提供系统提示(指令)。

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"}}
)
  1. 动态提示允许在构建 LLM 输入时包含非消息上下文,例如

    • 运行时传递的信息,例如 user_id 或 API 凭据(使用 config)。
    • 在多步骤推理过程中更新的内部代理状态(使用 state)。

    动态提示可以定义为接受 stateconfig 并返回要发送给 LLM 的消息列表的函数。

有关更多信息,请参见上下文

5. 添加记忆

为了允许与代理进行多轮对话,您需要通过在创建代理时提供一个 checkpointer 来启用持久化。在运行时,您需要提供一个包含 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
)
  1. checkpointer 允许代理在工具调用循环的每一步存储其状态。这使得短期记忆人工介入能力成为可能。
  2. 传递带有 thread_id 的配置,以便在未来的代理调用中恢复相同的对话。

当您启用检查点时,它会在提供的检查点数据库中(如果使用 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"]
  1. 当提供 response_format 时,在代理循环的末尾会添加一个单独的步骤:代理消息历史记录被传递给具有结构化输出的 LLM,以生成结构化响应。

    要为此 LLM 提供系统提示,请使用元组 (prompt, schema),例如 response_format=(prompt, WeatherResponse)

LLM 后处理

结构化输出需要额外调用 LLM 以根据模式格式化响应。

下一步