跳到内容

LangGraph 快速入门

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

先决条件

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

1. 安装依赖

如果您还没有安装 LangGraph 和 LangChain,请先安装它们

pip install -U langgraph "langchain[anthropic]"

信息

安装了 langchain[anthropic],以便智能体可以调用模型

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

要使用特定参数(如 temperature)配置 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 以生成结构化响应。
    To provide a system prompt to this LLM, use a tuple `(prompt, schema)`, e.g., `response_format=(prompt, WeatherResponse)`.
    

LLM 后处理

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

下一步