Skip to content

本指南将向你展示如何在本地运行 LangGraph 应用程序。

前提条件

开始之前,请确保你具备以下条件:

  • 一个 LangSmith 的 API 密钥 - 免费注册

1. 安装 LangGraph CLI

bash
# 需要 Python >= 3.11。
pip install -U "langgraph-cli[inmem]"
bash
# 需要 Python >= 3.11。
uv add "langgraph-cli[inmem]"
bash
npm install --save-dev @langchain/langgraph-cli

2. 创建 LangGraph 应用

new-langgraph-project-python 模板 创建一个新应用。该模板演示了一个单节点应用程序,你可以用自己的逻辑扩展它。

bash
langgraph new path/to/your/app --template new-langgraph-project-python

TIP

其他模板 如果你使用 langgraph new 时不指定模板,系统将显示一个交互式菜单,允许你从可用模板列表中进行选择。

new-langgraph-project-js 模板 创建一个新应用。该模板演示了一个单节点应用程序,你可以用自己的逻辑扩展它。

bash
npm create langgraph

将 LangGraph 添加到现有项目

如果你有一个包含 LangGraph 智能体的现有项目,可以使用 config 命令自动生成 langgraph.json 配置文件:

bash
npm create langgraph config

该命令会扫描项目中存在的 LangGraph 智能体(例如 createAgent()StateGraph.compile()workflow.compile() 模式),并生成一个包含所有导出智能体的配置文件。

示例输出:

json
{
  "node_version": "24",
  "graphs": {
    "agent": "./src/agent.ts:agent",
    "searchAgent": "./src/search.ts:searchAgent"
  },
  "env": ".env"
}

TIP

配置中仅包含导出的智能体。如果某个智能体未导出,该命令会发出警告,以便你添加 export 关键字。

3. 安装依赖

在新 LangGraph 应用的根目录中,以 edit 模式安装依赖,以便服务器使用你的本地修改:

bash
cd path/to/your/app
pip install -e .
bash
cd path/to/your/app
uv sync
bash
cd path/to/your/app
npm install

4. 创建 .env 文件

你会在新 LangGraph 应用的根目录中找到 .env.example。在新 LangGraph 应用的根目录中创建一个 .env 文件,将 .env.example 文件的内容复制到其中,并填写必要的 API 密钥:

bash
LANGSMITH_API_KEY=lsv2...

5. 启动 Agent Server

在本地启动 LangGraph API 服务器:

bash
langgraph dev
bash
npx @langchain/langgraph-cli dev

示例输出:

INFO:langgraph_api.cli:

        Welcome to

╦  ┌─┐┌┐┌┌─┐╔═╗┬─┐┌─┐┌─┐┬ ┬
║  ├─┤││││ ┬║ ╦├┬┘├─┤├─┘├─┤
╩═╝┴ ┴┘└┘└─┘╚═╝┴└─┴ ┴┴  ┴ ┴

- 🚀 API: http://127.0.0.1:2024
- 🎨 Studio UI: https://smith.langchain.com/studio/?baseUrl=http://127.0.0.1:2024
- 📚 API Docs: http://127.0.0.1:2024/docs

This in-memory server is designed for development and testing.
For production use, please use LangSmith Deployment.

langgraph dev 命令以内存模式启动 Agent Server。此模式适用于开发和测试目的。对于生产环境,请将 Agent Server 部署为可访问持久化存储后端。如需了解更多信息,请参阅平台设置概述

6. 在 Studio 中测试你的应用程序

Studio 是一种专门的界面(UI),你可以将其连接到 LangGraph API 服务器,以在本地可视化、交互和调试你的应用程序。通过访问 langgraph dev 命令输出中提供的 URL 在 Studio 中测试你的图:

>    - LangGraph Studio Web UI: https://smith.langchain.com/studio/?baseUrl=http://127.0.0.1:2024

对于在自定义主机/端口上运行的 Agent Server,请更新 URL 中的 baseUrl 查询参数。例如,如果你的服务器运行在 http://myhost:3000

https://smith.langchain.com/studio/?baseUrl=http://myhost:3000

Safari 兼容性

由于 Safari 在连接 localhost 服务器时存在限制,请在命令中使用 `--tunnel` 标志创建安全隧道:
bash
langgraph dev --tunnel

7. 测试 API

Python SDK (async)

1. 安装 LangGraph Python SDK:
bash
pip install langgraph-sdk
2. 向助手发送消息(无线程运行):
python
from langgraph_sdk import get_client
import asyncio

client = get_client(url="http://localhost:2024")

async def main():
    async for chunk in client.runs.stream(
        None,  # 无线程运行
        "agent", # 助手的名称。定义在 langgraph.json 中。
        input={
        "messages": [{
            "role": "human",
            "content": "What is LangGraph?",
            }],
        },
    ):
        print(f"Receiving new event of type: {chunk.event}...")
        print(chunk.data)
        print("\n\n")

asyncio.run(main())

Python SDK (sync)

1. 安装 LangGraph Python SDK:
bash
pip install langgraph-sdk
2. 向助手发送消息(无线程运行):
python
from langgraph_sdk import get_sync_client

client = get_sync_client(url="http://localhost:2024")

for chunk in client.runs.stream(
    None,  # 无线程运行
    "agent", # 助手的名称。定义在 langgraph.json 中。
    input={
        "messages": [{
            "role": "human",
            "content": "What is LangGraph?",
        }],
    },
    stream_mode="messages-tuple",
):
    print(f"Receiving new event of type: {chunk.event}...")
    print(chunk.data)
    print("\n\n")

Rest API

bash
curl -s --request POST \
    --url "http://localhost:2024/runs/stream" \
    --header 'Content-Type: application/json' \
    --data "{
        \"assistant_id\": \"agent\",
        \"input\": {
            \"messages\": [
                {
                    \"role\": \"human\",
                    \"content\": \"What is LangGraph?\"
                }
            ]
        },
        \"stream_mode\": \"messages-tuple\"
    }"

Javascript SDK

1. 安装 LangGraph JS SDK:
bash
npm install @langchain/langgraph-sdk
2. 向助手发送消息(无线程运行):
js
import { Client } from "@langchain/langgraph-sdk";

// 仅当你在调用 langgraph dev 时更改了默认端口,才设置 apiUrl
const client = new Client({ apiUrl: "http://localhost:2024"});

const streamResponse = client.runs.stream(
  null, // 无线程运行
  "agent", // 助手 ID
  {
    input: {
      "messages": [
        { "role": "user", "content": "What is LangGraph?"}
      ]
    },
    streamMode: "messages-tuple",
  }
);

for await (const chunk of streamResponse) {
  console.log(`Receiving new event of type: ${chunk.event}...`);
  console.log(JSON.stringify(chunk.data));
  console.log("\n\n");
}

Rest API

bash
curl -s --request POST \
    --url "http://localhost:2024/runs/stream" \
    --header 'Content-Type: application/json' \
    --data "{
        \"assistant_id\": \"agent\",
        \"input\": {
            \"messages\": [
                {
                    \"role\": \"human\",
                    \"content\": \"What is LangGraph?\"
                }
            ]
        },
        \"stream_mode\": \"messages-tuple\"
    }"

后续步骤

现在你已经有一个在本地运行的 LangGraph 应用,接下来可以进一步探索部署和高级功能: