> ## Documentation Index
> Fetch the complete documentation index at: https://langchain-docs-zh.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# 快速入门

> 本快速开始指南演示了如何使用LangGraph图API或功能API构建计算器智能体。

本快速开始指南演示了如何使用LangGraph图API或功能API构建计算器智能体。

构建LangGraph计算器快速开始指南

按照LangGraph快速开始指南的要求，在本工作目录中构建LangGraph计算器智能体。

## 步骤1：阅读指南

检测项目使用的编程语言（Python或TypeScript/JavaScript），获取并遵循对应页面；将其视为包名称、模型字符串和代码的权威来源：

* Python: [https://docs.langchain.com/oss/python/langgraph/quickstart.md](https://docs.langchain.com/oss/python/langgraph/quickstart.md)
* TypeScript: [https://docs.langchain.com/oss/javascript/langgraph/quickstart.md](https://docs.langchain.com/oss/javascript/langgraph/quickstart.md)

询问用户是否使用图API或功能API。若无偏好，则使用图API路径。

## 步骤2：安装依赖

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

## 步骤3：配置模型凭据

本快速开始指南默认使用Anthropic。检查 `ANTHROPIC_API_KEY` 是否已设置。若未设置，请用户创建密钥并在终端或 `.env` 文件中设置，然后等待确认。不要编造、硬编码或提交API密钥。若用户偏好其他聊天模型集成文档中的服务提供商，在确认后相应修改示例。

## 步骤4：实现计算器智能体

完整实现所选快速开始路径：加减乘除工具、智能体图或功能工作流，以及触发工具调用的样例调用。输出最终结果供用户验证执行。

## 规则

* 仅聚焦本快速开始指南。除非用户要求，否则不添加部署、评估或无关框架。
* 优先采用获取到的指南中展示的API和结构，而非自创智能体模式。
* 对未明确的密钥、API选择或项目约定，应询问而非猜测。

> [!TIP]
>
> **使用AI编程助手？**
>
> * 安装 [LangChain 文档MCP服务器](https://langchain-docs-zh.mintlify.site/use-these-docs) 以使智能体访问最新LangChain文档和示例。
>
>   连接LangChain文档MCP服务器
>
>   将LangChain文档MCP服务器与我的编程智能体连接，使其能够查询最新的LangChain、LangGraph和LangSmith文档及API参考。
>
>   需添加的服务器：
>
>   * `docs-langchain`: [https://docs.langchain.com/mcp](https://docs.langchain.com/mcp)
>   * `reference-langchain`: [https://reference.langchain.com/mcp](https://reference.langchain.com/mcp)
>
>   检测我正在使用的智能体或编辑器（Claude代码、Cursor、Codex CLI、Claude桌面、Deep Agents代码、VS Code、Antigravity或其他MCP兼容客户端），并从[https://docs.langchain.com/use-these-docs.md获取对应配置：](https://docs.langchain.com/use-these-docs.md获取对应配置：)
>
>   * Claude代码：使用`claude mcp add --transport http`为每个服务器（默认项目级访问；仅在要求全局访问时使用`--scope user`）
>   * Codex CLI：使用`codex mcp add`与每个服务器URL
>   * Cursor、Deep Agents代码、VS Code或Antigravity：将两个条目合并到MCP设置JSON中，使用页面中显示的对应客户端字段名称
>   * Claude桌面：在Settings > Connectors下添加两个URL
>
>   不要编造MCP URL。配置完成后确认两个服务器均被列出且可访问。
> * 安装 [LangChain Skills](https://github.com/langchain-ai/langchain-skills) 以提升智能体在LangChain生态任务中的性能。
>
>   安装 LangChain 技能
>
>   为我的编码智能体安装 LangChain 技能，以便它在 LangChain、LangGraph 和 Deep Agents 任务上表现更好。
>
>   使用 [https://github.com/langchain-ai/langchain-skills](https://github.com/langchain-ai/langchain-skills) 上的智能体技能安装程序：
>
>   ```bash theme={null}
>   npx skills add langchain-ai/langchain-skills --skill '*' --yes
>   ```
>
>   如果改为请求全局安装，请使用：
>
>   ```bash theme={null}
>   npx skills add langchain-ai/langchain-skills --skill '*' --yes --global
>   ```
>
>   检测您正在使用哪个智能体或编辑器。如果您使用 Claude Code 并偏好插件路径，请从该仓库的 README 文件中遵循市场安装方法（`/plugin marketplace add` 然后 `/plugin install`）。不要编造替代的技能包名称或安装 URL。安装完成后，确认这些技能对智能体可用。

* [使用图API](#use-the-graph-api) 若您倾向于将智能体定义为节点和边组成的图]
* [使用功能API](#use-the-functional-api) 若您倾向于将智能体定义为单一函数]

概念信息请参考 [图API概览](https://langchain-docs-zh.mintlify.site/langchain/oss/langgraph/graph-api.md) 和 [功能API概览](https://langchain-docs-zh.mintlify.site/langchain/oss/langgraph/functional-api.md)。

> [!NOTE]
>
> 本示例需要您设置 [Claude (Anthropic)](https://www.anthropic.com/) 账户并获取API密钥。然后在终端中设置 `ANTHROPIC_API_KEY` 环境变量。详见 [聊天模型集成](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/chat.md) 获取所有可用提供商。若使用LangSmith的 [LLM网关](https://docs.langchain.com/langsmith/llm-gateway)，通过LangSmith路由服务提供商流量。此时使用网关密钥作为API密钥。

> [tab] Use the Graph API
>
> ## 1. 定义工具和模型
>
> :::python
>
> ```python theme={null}
> 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)
> ```
>
> :::
>
> :::js
>
> ```typescript theme={null}
> import { ChatAnthropic } from "@langchain/anthropic";
> import { tool } from "@langchain/core/tools";
> import * as z from "zod";
>
> const model = new ChatAnthropic({
>   model: "claude-sonnet-4-6",
>   temperature: 0,
> });
>
> // Define tools
> const add = tool(({ a, b }) => a + b, {
>   name: "add",
>   description: "Add two numbers",
>   schema: z.object({
>     a: z.number().describe("First number"),
>     b: z.number().describe("Second number"),
>   }),
> });
>
> const multiply = tool(({ a, b }) => a * b, {
>   name: "multiply",
>   description: "Multiply two numbers",
>   schema: z.object({
>     a: z.number().describe("First number"),
>     b: z.number().describe("Second number"),
>   }),
> });
>
> const divide = tool(({ a, b }) => a / b, {
>   name: "divide",
>   description: "Divide two numbers",
>   schema: z.object({
>     a: z.number().describe("First number"),
>     b: z.number().describe("Second number"),
>   }),
> });
>
> // Augment the LLM with tools
> const toolsByName = {
>   [add.name]: add,
>   [multiply.name]: multiply,
>   [divide.name]: divide,
> };
> const tools = Object.values(toolsByName);
> const modelWithTools = model.bindTools(tools);
> ```
>
> :::
>
> ## 2. 定义状态
>
> 图的状态用于存储消息和LLM调用的次数。
>
> :::python
>
> > [!TIP]
> >
> > LangGraph中的状态会持久化存储在整个智能体执行过程中。
> >
> > `Annotated`类型通过`operator.add`确保新消息会追加到现有列表而非替换它。
>
> :::
>
> :::js
>
> > [!TIP]
> >
> > LangGraph中的状态会持久化存储在整个智能体执行过程中。
> >
> > `MessagesValue`内置了消息追加的reducer。`llmCalls`字段通过使用`ReducedValue`（具有`(x, y) => x + y`）来累积计数。
>
> :::
>
> :::python
>
> ```python theme={null}
> 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
> ```
>
> :::
>
> :::js
>
> ```typescript theme={null}
> import {
>   StateGraph,
>   StateSchema,
>   MessagesValue,
>   ReducedValue,
>   GraphNode,
>   ConditionalEdgeRouter,
>   START,
>   END,
> } from "@langchain/langgraph";
> import { z } from "zod/v4";
>
> const MessagesState = new StateSchema({
>   messages: MessagesValue,
>   llmCalls: new ReducedValue(
>     z.number().default(0),
>     { reducer: (x, y) => x + y }
>   ),
> });
> ```
>
> :::
>
> ## 3. 定义模型节点
>
> 模型节点用于调用LLM并决定是否调用工具。
>
> :::python
>
> ```python theme={null}
> 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
>     }
> ```
>
> :::
>
> :::js
>
> ```typescript theme={null}
> import { SystemMessage } from "@langchain/core/messages";
>
> const llmCall: GraphNode<typeof MessagesState> = async (state) => {
>   const response = await modelWithTools.invoke([
>     new SystemMessage(
>       "You are a helpful assistant tasked with performing arithmetic on a set of inputs."
>     ),
>     ...state.messages,
>   ]);
>   return {
>     messages: [response],
>     llmCalls: 1,
>   };
> };
> ```
>
> :::
>
> ## 4. 定义工具节点
>
> 工具节点用于调用工具并返回结果。
>
> :::python
>
> ```python theme={null}
> 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}
> ```
>
> :::
>
> :::js
>
> ```typescript theme={null}
> import { AIMessage, ToolMessage } from "@langchain/core/messages";
>
> const toolNode: GraphNode<typeof MessagesState> = async (state) => {
>   const lastMessage = state.messages.at(-1);
>
>   if (lastMessage == null || !AIMessage.isInstance(lastMessage)) {
>     return { messages: [] };
>   }
>
>   const result: ToolMessage[] = [];
>   for (const toolCall of lastMessage.tool_calls ?? []) {
>     const tool = toolsByName[toolCall.name];
>     const observation = await tool.invoke(toolCall);
>     result.push(observation);
>   }
>
>   return { messages: result };
> };
> ```
>
> :::
>
> ## 5. 定义结束逻辑
>
> 条件边函数根据LLM是否调用工具决定路由到工具节点或结束。
>
> :::python
>
> ```python theme={null}
> 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
> ```
>
> :::
>
> :::js
>
> ```typescript theme={null}
> const shouldContinue: ConditionalEdgeRouter<{ InputSchema: typeof MessagesState; Nodes: "toolNode" }> = (state) => {
>   const lastMessage = state.messages.at(-1);
>
>   // Check if it's an AIMessage before accessing tool_calls
>   if (!lastMessage || !AIMessage.isInstance(lastMessage)) {
>     return END;
>   }
>
>   // If the LLM makes a tool call, then perform an action
>   if (lastMessage.tool_calls?.length) {
>     return "toolNode";
>   }
>
>   // Otherwise, we stop (reply to the user)
>   return END;
> };
> ```
>
> :::
>
> ## 6. 构建并编译智能体
>
> 智能体通过@\[`StateGraph`]类构建，使用@\[`compile`]\[StateGraph.compile]方法编译。
>
> :::python
>
> ```python theme={null}
> # 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()
> ```
>
> :::
>
> :::js
>
> ```typescript theme={null}
> const agent = new StateGraph(MessagesState)
>   .addNode("llmCall", llmCall)
>   .addNode("toolNode", toolNode)
>   .addEdge(START, "llmCall")
>   .addConditionalEdges("llmCall", shouldContinue, ["toolNode", END])
>   .addEdge("toolNode", "llmCall")
>   .compile();
>
> // Invoke
> import { HumanMessage } from "@langchain/core/messages";
> const result = await agent.invoke({
>   messages: [new HumanMessage("Add 3 and 4.")],
> });
>
> for (const message of result.messages) {
>   console.log(`[${message.type}]: ${message.text}`);
> }
> ```
>
> :::
>
> > [!TIP]
> >
> > 通过[LangSmith](https://smith.langchain.com)跟踪调试智能体。按照[追踪快速入门](https://docs.langchain.com/langsmith/trace-with-langgraph)进行配置。准备好生产部署时请参考[部署](https://docs.langchain.com/langsmith/deployment)查看托管选项。
> >
> > 我们推荐您同时配置[LangSmith Engine](https://docs.langchain.com/langsmith/engine)以监控追踪数据、检测问题并提出修复方案。
>
> 恭喜！您已使用LangGraph图API构建首个智能体。
>
> > [accordion] Full code example
> >
> > :::python
> >
> > ```python theme={null}
> > # 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()
> >
> > ```
> >
> > :::
> >
> > :::js
> >
> > ```typescript theme={null}
> > // Step 1: Define tools and model
> >
> > import { ChatAnthropic } from "@langchain/anthropic";
> > import { tool } from "@langchain/core/tools";
> > import * as z from "zod";
> >
> > const model = new ChatAnthropic({
> >   model: "claude-sonnet-4-6",
> >   temperature: 0,
> > });
> >
> > // Define tools
> > const add = tool(({ a, b }) => a + b, {
> >   name: "add",
> >   description: "Add two numbers",
> >   schema: z.object({
> >     a: z.number().describe("First number"),
> >     b: z.number().describe("Second number"),
> >   }),
> > });
> >
> > const multiply = tool(({ a, b }) => a * b, {
> >   name: "multiply",
> >   description: "Multiply two numbers",
> >   schema: z.object({
> >     a: z.number().describe("First number"),
> >     b: z.number().describe("Second number"),
> >   }),
> > });
> >
> > const divide = tool(({ a, b }) => a / b, {
> >   name: "divide",
> >   description: "Divide two numbers",
> >   schema: z.object({
> >     a: z.number().describe("First number"),
> >     b: z.number().describe("Second number"),
> >   }),
> > });
> >
> > // Augment the LLM with tools
> > const toolsByName = {
> >   [add.name]: add,
> >   [multiply.name]: multiply,
> >   [divide.name]: divide,
> > };
> > const tools = Object.values(toolsByName);
> > const modelWithTools = model.bindTools(tools);
> > ```
> >
> > ```typescript theme={null}
> > // Step 2: Define state
> >
> > import {
> >   StateGraph,
> >   StateSchema,
> >   MessagesValue,
> >   ReducedValue,
> >   GraphNode,
> >   ConditionalEdgeRouter,
> >   START,
> >   END,
> > } from "@langchain/langgraph";
> > import * as z from "zod";
> >
> > const MessagesState = new StateSchema({
> >   messages: MessagesValue,
> >   llmCalls: new ReducedValue(
> >     z.number().default(0),
> >     { reducer: (x, y) => x + y }
> >   ),
> > });
> > ```
> >
> > ```typescript theme={null}
> > // Step 3: Define model node
> >
> > import { SystemMessage, AIMessage, ToolMessage } from "@langchain/core/messages";
> >
> > const llmCall: GraphNode<typeof MessagesState> = async (state) => {
> >   return {
> >     messages: [await modelWithTools.invoke([
> >       new SystemMessage(
> >         "You are a helpful assistant tasked with performing arithmetic on a set of inputs."
> >       ),
> >       ...state.messages,
> >     ])],
> >     llmCalls: 1,
> >   };
> > };
> >
> > // Step 4: Define tool node
> >
> > const toolNode: GraphNode<typeof MessagesState> = async (state) => {
> >   const lastMessage = state.messages.at(-1);
> >
> >   if (lastMessage == null || !AIMessage.isInstance(lastMessage)) {
> >     return { messages: [] };
> >   }
> >
> >   const result: ToolMessage[] = [];
> >   for (const toolCall of lastMessage.tool_calls ?? []) {
> >     const tool = toolsByName[toolCall.name];
> >     const observation = await tool.invoke(toolCall);
> >     result.push(observation);
> >   }
> >
> >   return { messages: result };
> > };
> > ```
> >
> > ```typescript theme={null}
> > // Step 5: Define logic to determine whether to end
> > import { ConditionalEdgeRouter, END } from "@langchain/langgraph";
> >
> > const shouldContinue: ConditionalEdgeRouter<{ InputSchema: typeof MessagesState; Nodes: "toolNode" }> = (state) => {
> >   const lastMessage = state.messages.at(-1);
> >
> >   // Check if it's an AIMessage before accessing tool_calls
> >   if (!lastMessage || !AIMessage.isInstance(lastMessage)) {
> >     return END;
> >   }
> >
> >   // If the LLM makes a tool call, then perform an action
> >   if (lastMessage.tool_calls?.length) {
> >     return "toolNode";
> >   }
> >
> >   // Otherwise, we stop (reply to the user)
> >   return END;
> > };
> > ```
> >
> > ```typescript theme={null}
> > // Step 6: Build and compile the agent
> > import { HumanMessage } from "@langchain/core/messages";
> > import { StateGraph, START, END } from "@langchain/langgraph";
> >
> > const agent = new StateGraph(MessagesState)
> >   .addNode("llmCall", llmCall)
> >   .addNode("toolNode", toolNode)
> >   .addEdge(START, "llmCall")
> >   .addConditionalEdges("llmCall", shouldContinue, ["toolNode", END])
> >   .addEdge("toolNode", "llmCall")
> >   .compile();
> >
> > // Invoke
> > const result = await agent.invoke({
> >   messages: [new HumanMessage("Add 3 and 4.")],
> > });
> >
> > for (const message of result.messages) {
> >   console.log(`[${message.type}]: ${message.text}`);
> > }
> > ```
> >
> > :::

> [tab] Use the Functional API
>
> ## 1. 定义工具和模型
>
> 本示例使用Claude Sonnet 4.5模型并定义加减乘除工具。
>
> :::python
>
> ```python theme={null}
> 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)
>
> from langgraph.graph import add_messages
> from langchain.messages import (
>     SystemMessage,
>     HumanMessage,
>     ToolCall,
> )
> from langchain_core.messages import BaseMessage
> from langgraph.func import entrypoint, task
> ```
>
> :::
>
> :::js
>
> ```typescript theme={null}
> import { ChatAnthropic } from "@langchain/anthropic";
> import { tool } from "@langchain/core/tools";
> import * as z from "zod";
>
> const model = new ChatAnthropic({
>   model: "claude-sonnet-4-6",
>   temperature: 0,
> });
>
> // Define tools
> const add = tool(({ a, b }) => a + b, {
>   name: "add",
>   description: "Add two numbers",
>   schema: z.object({
>     a: z.number().describe("First number"),
>     b: z.number().describe("Second number"),
>   }),
> });
>
> const multiply = tool(({ a, b }) => a * b, {
>   name: "multiply",
>   description: "Multiply two numbers",
>   schema: z.object({
>     a: z.number().describe("First number"),
>     b: z.number().describe("Second number"),
>   }),
> });
>
> const divide = tool(({ a, b }) => a / b, {
>   name: "divide",
>   description: "Divide two numbers",
>   schema: z.object({
>     a: z.number().describe("First number"),
>     b: z.number().describe("Second number"),
>   }),
> });
>
> // Augment the LLM with tools
> const toolsByName = {
>   [add.name]: add,
>   [multiply.name]: multiply,
>   [divide.name]: divide,
> };
> const tools = Object.values(toolsByName);
> const modelWithTools = model.bindTools(tools);
>
> ```
>
> :::
>
> ## 2. 定义模型节点
>
> 模型节点用于调用LLM并决定是否调用工具。
>
> :::python
>
> > [!TIP]
> >
> > @\[`@task`]装饰器标记函数为可执行智能体任务。任务可在入口函数中同步或异步调用。
>
> ```python theme={null}
> @task
> def call_llm(messages: list[BaseMessage]):
>     """LLM decides whether to call a tool or not"""
>     return model_with_tools.invoke(
>         [
>             SystemMessage(
>                 content="You are a helpful assistant tasked with performing arithmetic on a set of inputs."
>             )
>         ]
>         + messages
>     )
> ```
>
> :::
>
> :::js
>
> ```typescript theme={null}
> import { task, entrypoint } from "@langchain/langgraph";
> import { SystemMessage } from "@langchain/core/messages";
>
> const callLlm = task({ name: "callLlm" }, async (messages: BaseMessage[]) => {
>   return modelWithTools.invoke([
>     new SystemMessage(
>       "You are a helpful assistant tasked with performing arithmetic on a set of inputs."
>     ),
>     ...messages,
>   ]);
> });
> ```
>
> :::
>
> ## 3. 定义工具节点
>
> 工具节点用于调用工具并返回结果。
>
> :::python
>
> ```python theme={null}
> @task
> def call_tool(tool_call: ToolCall):
>     """Performs the tool call"""
>     tool = tools_by_name[tool_call["name"]]
>     return tool.invoke(tool_call)
>
> ```
>
> :::
>
> :::js
>
> ```typescript theme={null}
> import type { ToolCall } from "@langchain/core/messages/tool";
>
> const callTool = task({ name: "callTool" }, async (toolCall: ToolCall) => {
>   const tool = toolsByName[toolCall.name];
>   return tool.invoke(toolCall);
> });
> ```
>
> :::
>
> ## 4. 定义智能体
>
> :::python
>
> 智能体通过@\[`@entrypoint`]函数构建。
>
> > [!NOTE]
> >
> > 在函数式API中，您通过在单个函数内编写标准控制流逻辑（循环、条件）来替代显式定义节点和边。
>
> ```python theme={null}
> @entrypoint()
> def agent(messages: list[BaseMessage]):
>     model_response = call_llm(messages).result()
>
>     while True:
>         if not model_response.tool_calls:
>             break
>
>         # Execute tools
>         tool_result_futures = [
>             call_tool(tool_call) for tool_call in model_response.tool_calls
>         ]
>         tool_results = [fut.result() for fut in tool_result_futures]
>         messages = add_messages(messages, [model_response, *tool_results])
>         model_response = call_llm(messages).result()
>
>     messages = add_messages(messages, model_response)
>     return messages
>
> # Invoke
> messages = [HumanMessage(content="Add 3 and 4.")]
> stream = agent.stream_events(messages, version="v3")
> for snapshot in stream.values:
>     print(snapshot)
>     print("\n")
> ```
>
> :::
>
> :::js
>
> ```typescript theme={null}
> import { addMessages } from "@langchain/langgraph";
> import { type BaseMessage } from "@langchain/core/messages";
>
> const agent = entrypoint({ name: "agent" }, async (messages: BaseMessage[]) => {
>   let modelResponse = await callLlm(messages);
>
>   while (true) {
>     if (!modelResponse.tool_calls?.length) {
>       break;
>     }
>
>     // Execute tools
>     const toolResults = await Promise.all(
>       modelResponse.tool_calls.map((toolCall) => callTool(toolCall))
>     );
>     messages = addMessages(messages, [modelResponse, ...toolResults]);
>     modelResponse = await callLlm(messages);
>   }
>
>   return messages;
> });
>
> // Invoke
> import { HumanMessage } from "@langchain/core/messages";
>
> const result = await agent.invoke([new HumanMessage("Add 3 and 4.")]);
>
> for (const message of result) {
>   console.log(`[${message.getType()}]: ${message.text}`);
> }
> ```
>
> :::
>
> > [!TIP]
> >
> > 通过[LangSmith](https://smith.langchain.com)跟踪调试智能体。按照[追踪快速入门](https://docs.langchain.com/langsmith/trace-with-langgraph)进行配置。准备好生产部署时请参考[部署](https://docs.langchain.com/langsmith/deployment)查看托管选项。
> >
> > 我们推荐您同时配置[LangSmith Engine](https://docs.langchain.com/langsmith/engine)以监控追踪数据、检测问题并提出修复方案。
>
> 恭喜！您已使用LangGraph Functional API构建了第一个智能体。
>
> > [accordion] Full code example
> >
> > :::python
> >
> > ```python theme={null}
> > # 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)
> >
> > from langgraph.graph import add_messages
> > from langchain.messages import (
> >     SystemMessage,
> >     HumanMessage,
> >     ToolCall,
> > )
> > from langchain_core.messages import BaseMessage
> > from langgraph.func import entrypoint, task
> >
> >
> > # Step 2: Define model node
> >
> > @task
> > def call_llm(messages: list[BaseMessage]):
> >     """LLM decides whether to call a tool or not"""
> >     return model_with_tools.invoke(
> >         [
> >             SystemMessage(
> >                 content="You are a helpful assistant tasked with performing arithmetic on a set of inputs."
> >             )
> >         ]
> >         + messages
> >     )
> >
> >
> > # Step 3: Define tool node
> >
> > @task
> > def call_tool(tool_call: ToolCall):
> >     """Performs the tool call"""
> >     tool = tools_by_name[tool_call["name"]]
> >     return tool.invoke(tool_call)
> >
> >
> > # Step 4: Define agent
> >
> > @entrypoint()
> > def agent(messages: list[BaseMessage]):
> >     model_response = call_llm(messages).result()
> >
> >     while True:
> >         if not model_response.tool_calls:
> >             break
> >
> >         # Execute tools
> >         tool_result_futures = [
> >             call_tool(tool_call) for tool_call in model_response.tool_calls
> >         ]
> >         tool_results = [fut.result() for fut in tool_result_futures]
> >         messages = add_messages(messages, [model_response, *tool_results])
> >         model_response = call_llm(messages).result()
> >
> >     messages = add_messages(messages, model_response)
> >     return messages
> >
> > # Invoke
> > messages = [HumanMessage(content="Add 3 and 4.")]
> > stream = agent.stream_events(messages, version="v3")
> > for snapshot in stream.values:
> >     print(snapshot)
> >     print("\n")
> > ```
> >
> > :::
> >
> > :::js
> >
> > ```typescript theme={null}
> > import { ChatAnthropic } from "@langchain/anthropic";
> > import { tool } from "@langchain/core/tools";
> > import {
> >   task,
> >   entrypoint,
> >   addMessages,
> > } from "@langchain/langgraph";
> > import {
> >   SystemMessage,
> >   HumanMessage,
> >   type BaseMessage,
> > } from "@langchain/core/messages";
> > import type { ToolCall } from "@langchain/core/messages/tool";
> > import * as z from "zod";
> >
> > // Step 1: Define tools and model
> >
> > const model = new ChatAnthropic({
> >   model: "claude-sonnet-4-6",
> >   temperature: 0,
> > });
> >
> > // Define tools
> > const add = tool(({ a, b }) => a + b, {
> >   name: "add",
> >   description: "Add two numbers",
> >   schema: z.object({
> >     a: z.number().describe("First number"),
> >     b: z.number().describe("Second number"),
> >   }),
> > });
> >
> > const multiply = tool(({ a, b }) => a * b, {
> >   name: "multiply",
> >   description: "Multiply two numbers",
> >   schema: z.object({
> >     a: z.number().describe("First number"),
> >     b: z.number().describe("Second number"),
> >   }),
> > });
> >
> > const divide = tool(({ a, b }) => a / b, {
> >   name: "divide",
> >   description: "Divide two numbers",
> >   schema: z.object({
> >     a: z.number().describe("First number"),
> >     b: z.number().describe("Second number"),
> >   }),
> > });
> >
> > // Augment the LLM with tools
> > const toolsByName = {
> >   [add.name]: add,
> >   [multiply.name]: multiply,
> >   [divide.name]: divide,
> > };
> > const tools = Object.values(toolsByName);
> > const modelWithTools = model.bindTools(tools);
> >
> > // Step 2: Define model node
> >
> > const callLlm = task({ name: "callLlm" }, async (messages: BaseMessage[]) => {
> >   return modelWithTools.invoke([
> >     new SystemMessage(
> >       "You are a helpful assistant tasked with performing arithmetic on a set of inputs."
> >     ),
> >     ...messages,
> >   ]);
> > });
> >
> > // Step 3: Define tool node
> >
> > const callTool = task({ name: "callTool" }, async (toolCall: ToolCall) => {
> >   const tool = toolsByName[toolCall.name];
> >   return tool.invoke(toolCall);
> > });
> >
> > // Step 4: Define agent
> >
> > const agent = entrypoint({ name: "agent" }, async (messages: BaseMessage[]) => {
> >   let modelResponse = await callLlm(messages);
> >
> >   while (true) {
> >     if (!modelResponse.tool_calls?.length) {
> >       break;
> >     }
> >
> >     // Execute tools
> >     const toolResults = await Promise.all(
> >       modelResponse.tool_calls.map((toolCall) => callTool(toolCall))
> >     );
> >     messages = addMessages(messages, [modelResponse, ...toolResults]);
> >     modelResponse = await callLlm(messages);
> >   }
> >
> >   return messages;
> > });
> >
> > // Invoke
> >
> > const result = await agent.invoke([new HumanMessage("Add 3 and 4.")]);
> >
> > for (const message of result) {
> >   console.log(`[${message.type}]: ${message.text}`);
> > }
> > ```
> >
> > :::

***

> 官方原文：[src/oss/langgraph/quickstart.mdx](https://github.com/langchain-ai/docs/blob/main/src/oss/langgraph/quickstart.mdx) · 非官方翻译，译文由 AI 生成，以英文原文为准。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.