Skip to content
LangChain 文档版本 跟随上游 源快照 095d2943 更新于 2026-10-08

快速开始

本快速入门演示如何使用 LangGraph Graph API 或函数式 API 构建一个计算器智能体。

按照 LangGraph 快速入门,在此工作目录中构建一个 LangGraph 计算器智能体。

第 1 步:阅读指南

检测此项目使用的是 Python 还是 TypeScript/JavaScript。获取并遵循匹配的页面;将其视为包名、模型字符串和代码的权威来源:

询问用户是使用 Graph API 还是函数式 API。如果他们没有偏好,就使用 Graph API 路径。

第 2 步:安装依赖

使用该项目已经使用的包管理器安装所选路径所需的包。

第 3 步:配置模型凭证

本快速入门默认使用 Anthropic。检查是否设置了 ANTHROPIC_API_KEY。如果没有,请让用户创建一个密钥,并在 shell 或 .env 文件中设置它,然后停止并等待确认。不要杜撰、硬编码或提交 API 密钥。如果用户更喜欢集成文档中的其他聊天模型服务商,请在确认后相应地调整示例。

步骤 4:实现计算器智能体

端到端地实现所选的快速入门路径:用于加法、乘法和除法的工具;智能体图或函数式工作流;以及一个演练工具调用的示例调用。打印最终结果,以便用户可以验证这次运行。

规则

  • 保持在本快速入门的范围内。除非用户要求,否则不要添加部署、评估或无关的框架。
  • 优先使用所获取指南中展示的 API 和结构,而不是自行发明不同的智能体模式。
  • 当密钥、API 选择或项目约定不清楚时,要询问而不是猜测。

TIP

使用 AI 编码助手?

将两个 LangChain 文档 MCP 服务器都连接到我的编码智能体,以便它能查询最新的 LangChain、LangGraph 和 LangSmith 文档及 API 参考。

要添加的服务器:

* `docs-langchain`: [https://docs.langchain.com/mcp](/mcp)
* `reference-langchain`: [https://reference.langchain.com/mcp](https://reference.langchain.com/mcp)

检测我正在使用哪个智能体或编辑器(Claude Code、Cursor、Codex CLI、Claude Desktop、Deep Agents Code、VS Code、Antigravity 或其他兼容 MCP 的客户端)。使用 [https://docs.langchain.com/use-these-docs.md](/langchain/use-these-docs) 中匹配的设置:

* Claude Code:为每个服务器使用 `claude mcp add --transport http`(默认项目范围;只有在我要求全局访问时才使用 `--scope user`)。
* Codex CLI:使用 `codex mcp add` 加上每个服务器的 URL。
* Cursor、Deep Agents Code、VS Code 或 Antigravity:使用该页面为我的客户端显示的字段名,将两个条目合并到 MCP 设置 JSON 中。
* Claude Desktop:在 Settings > Connectors 下添加两个 URL。

不要凭空编造其他 MCP URL。配置完成后,确认两个服务器都已列出且可访问。
  • 安装 LangChain Skills,以提升你的智能体在 LangChain 生态任务上的表现。
为我的编码智能体安装 LangChain Skills,使其在 LangChain、LangGraph 和 Deep Agents 任务上表现更好。

使用来自 [https://github.com/langchain-ai/langchain-skills](https://github.com/langchain-ai/langchain-skills) 的 Agent Skills 安装器:

```bash
npx skills add langchain-ai/langchain-skills --skill '*' --yes
```

如果我要求全局安装,请使用:

```bash
npx skills add langchain-ai/langchain-skills --skill '*' --yes --global
```

检测我正在使用哪个智能体或编辑器。如果我使用 Claude Code 并且偏好插件方式,请按照该仓库 README 中的市场安装流程操作(先 `/plugin marketplace add`,再 `/plugin install`)。不要凭空编造其他技能包名或安装 URL。安装完成后,确认这些技能对智能体可用。

有关概念信息,请参阅 Graph API 概览和函数式 API 概览。

INFO

对于此示例,你需要设置一个 Claude (Anthropic) 账户并获取 API 密钥。然后,在你的终端中设置 ANTHROPIC_API_KEY 环境变量。有关所有可用的服务商,请参阅聊天模型集成。如果你使用 LangSmith Gateway,你可以自带服务商密钥,或使用 Gateway Credits 在没有服务商密钥的情况下访问模型。

1. 定义工具和模型

在此示例中,我们将使用 Claude Sonnet 4.5 模型,并定义用于加法、乘法和除法的工具。

python
from langchain.tools import tool
from langchain.chat_models import init_chat_model

model = init_chat_model(
    "claude-sonnet-4-6",
    temperature=0
)

# Define tools
@tool
def multiply(a: int, b: int) -> int:
    """Multiply `a` and `b`.

    Args:
        a: First int
        b: Second int
    """
    return a * b

@tool
def add(a: int, b: int) -> int:
    """Adds `a` and `b`.

    Args:
        a: First int
        b: Second int
    """
    return a + b

@tool
def divide(a: int, b: int) -> float:
    """Divide `a` and `b`.

    Args:
        a: First int
        b: Second int
    """
    return a / b

# Augment the LLM with tools
tools = [add, multiply, divide]
tools_by_name = {tool.name: tool for tool in tools}
model_with_tools = model.bind_tools(tools)

2. 定义状态

图的状态用于存储消息和 LLM 调用的次数。

TIP

LangGraph 中的状态会贯穿智能体的整个执行过程而持久存在。

带有 operator.add 的 Annotated 类型确保新消息被追加到现有列表中,而不是替换它。

python
from langchain.messages import AnyMessage
from typing_extensions import TypedDict, Annotated
import operator

class MessagesState(TypedDict):
    messages: Annotated[list[AnyMessage], operator.add]
    llm_calls: int

3. 定义模型节点

模型节点用于调用 LLM,并决定是否调用工具。

python
from langchain.messages import SystemMessage

def llm_call(state: dict):
    """LLM decides whether to call a tool or not"""

    return {
        "messages": [
            model_with_tools.invoke(
                [
                    SystemMessage(
                        content="You are a helpful assistant tasked with performing arithmetic on a set of inputs."
                    )
                ]
                + state["messages"]
            )
        ],
        "llm_calls": state.get('llm_calls', 0) + 1
    }

4. 定义工具节点

工具节点用于调用工具并返回结果。

python
from langchain.messages import ToolMessage

def tool_node(state: dict):
    """Performs the tool call"""

    result = []
    for tool_call in state["messages"][-1].tool_calls:
        tool = tools_by_name[tool_call["name"]]
        observation = tool.invoke(tool_call["args"])
        result.append(ToolMessage(content=observation, tool_call_id=tool_call["id"]))
    return {"messages": result}

5. 定义结束逻辑

条件边函数用于根据 LLM 是否发起了工具调用来路由到工具节点或结束。

python
from typing import Literal
from langgraph.graph import StateGraph, START, END

def should_continue(state: MessagesState) -> Literal["tool_node", END]:
    """Decide if we should continue the loop or stop based upon whether the LLM made a tool call"""

    messages = state["messages"]
    last_message = messages[-1]

    # If the LLM makes a tool call, then perform an action
    if last_message.tool_calls:
        return "tool_node"

    # Otherwise, we stop (reply to the user)
    return END

6. 构建并编译智能体

该智能体使用 StateGraph 类构建,并使用 compile 方法编译。

python
# Build workflow
agent_builder = StateGraph(MessagesState)

# Add nodes
agent_builder.add_node("llm_call", llm_call)
agent_builder.add_node("tool_node", tool_node)

# Add edges to connect nodes
agent_builder.add_edge(START, "llm_call")
agent_builder.add_conditional_edges(
    "llm_call",
    should_continue,
    ["tool_node", END]
)
agent_builder.add_edge("tool_node", "llm_call")

# Compile the agent
agent = agent_builder.compile()

# Show the agent
from IPython.display import Image, display
display(Image(agent.get_graph(xray=True).draw_mermaid_png()))

# Invoke
from langchain.messages import HumanMessage
messages = [HumanMessage(content="Add 3 and 4.")]
messages = agent.invoke({"messages": messages})
for m in messages["messages"]:
    m.pretty_print()

TIP

使用 LangSmith 追踪和调试你的智能体。按照追踪快速入门进行设置。准备好投入生产时,请参阅部署了解托管选项。

我们还建议你设置 LangSmith Engine,它会监控你的追踪、检测问题并提出修复方案。

恭喜!你已使用 LangGraph Graph API 构建了你的第一个智能体。

完整代码示例
python
# Step 1: Define tools and model

from langchain.tools import tool
from langchain.chat_models import init_chat_model

model = init_chat_model(
    "claude-sonnet-4-6",
    temperature=0
)

# Define tools
@tool
def multiply(a: int, b: int) -> int:
    """Multiply `a` and `b`.

    Args:
        a: First int
        b: Second int
    """
    return a * b

@tool
def add(a: int, b: int) -> int:
    """Adds `a` and `b`.

    Args:
        a: First int
        b: Second int
    """
    return a + b

@tool
def divide(a: int, b: int) -> float:
    """Divide `a` and `b`.

    Args:
        a: First int
        b: Second int
    """
    return a / b

# Augment the LLM with tools
tools = [add, multiply, divide]
tools_by_name = {tool.name: tool for tool in tools}
model_with_tools = model.bind_tools(tools)

# Step 2: Define state

from langchain.messages import AnyMessage
from typing_extensions import TypedDict, Annotated
import operator

class MessagesState(TypedDict):
    messages: Annotated[list[AnyMessage], operator.add]
    llm_calls: int

# Step 3: Define model node
from langchain.messages import SystemMessage

def llm_call(state: MessagesState):
    """LLM decides whether to call a tool or not"""

    return {
        "messages": [
            model_with_tools.invoke(
                [
                    SystemMessage(
                        content="You are a helpful assistant tasked with performing arithmetic on a set of inputs."
                    )
                ]
                + state["messages"]
            )
        ],
        "llm_calls": state.get('llm_calls', 0) + 1
    }

# Step 4: Define tool node

from langchain.messages import ToolMessage

def tool_node(state: MessagesState):
    """Performs the tool call"""

    result = []
    for tool_call in state["messages"][-1].tool_calls:
        tool = tools_by_name[tool_call["name"]]
        observation = tool.invoke(tool_call["args"])
        result.append(ToolMessage(content=observation, tool_call_id=tool_call["id"]))
    return {"messages": result}

# Step 5: Define logic to determine whether to end

from typing import Literal
from langgraph.graph import StateGraph, START, END

# Conditional edge function to route to the tool node or end based upon whether the LLM made a tool call
def should_continue(state: MessagesState) -> Literal["tool_node", END]:
    """Decide if we should continue the loop or stop based upon whether the LLM made a tool call"""

    messages = state["messages"]
    last_message = messages[-1]

    # If the LLM makes a tool call, then perform an action
    if last_message.tool_calls:
        return "tool_node"

    # Otherwise, we stop (reply to the user)
    return END

# Step 6: Build agent

# Build workflow
agent_builder = StateGraph(MessagesState)

# Add nodes
agent_builder.add_node("llm_call", llm_call)
agent_builder.add_node("tool_node", tool_node)

# Add edges to connect nodes
agent_builder.add_edge(START, "llm_call")
agent_builder.add_conditional_edges(
    "llm_call",
    should_continue,
    ["tool_node", END]
)
agent_builder.add_edge("tool_node", "llm_call")

# Compile the agent
agent = agent_builder.compile()

from IPython.display import Image, display
# Show the agent
display(Image(agent.get_graph(xray=True).draw_mermaid_png()))

# Invoke
from langchain.messages import HumanMessage
messages = [HumanMessage(content="Add 3 and 4.")]
messages = agent.invoke({"messages": messages})
for m in messages["messages"]:
    m.pretty_print()

BytesRouter 是社区翻译站点,所有译文仅供参考,一切以官方英文原文为准。