Skip to main content

Documentation Index

Fetch the complete documentation index at: https://nvd-54.mintlify.app/llms.txt

Use this file to discover all available pages before exploring further.

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

前提条件

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

1. 安装 LangGraph CLI

npm install --save-dev @langchain/langgraph-cli

2. 创建 LangGraph 应用

new-langgraph-project-js 模板创建一个新应用。此模板展示了一个单节点应用,你可以用自己的逻辑扩展它。
npm create langgraph
如果你有一个包含 LangGraph 智能体的现有项目,可以使用 config 命令自动生成 langgraph.json 配置文件:
npm create langgraph config
此命令会扫描你的项目以查找 LangGraph 智能体(例如 createAgent()StateGraph.compile()workflow.compile() 模式),并生成包含所有已导出智能体的配置文件。示例输出:
{
  "node_version": "24",
  "graphs": {
    "agent": "./src/agent.ts:agent",
    "searchAgent": "./src/search.ts:searchAgent"
  },
  "env": ".env"
}
配置中仅包含已导出的智能体。如果某个智能体未导出,命令会发出警告,提示你添加 export 关键字。

3. 安装依赖

在新 LangGraph 应用的根目录中,以 edit 模式安装依赖,以便服务器使用你的本地更改:
cd path/to/your/app
npm install

4. 创建 .env 文件

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

5. 启动智能体服务器

在本地启动 LangGraph API 服务器:
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 命令以内存模式启动智能体服务器。此模式适用于开发和测试目的。对于生产使用,请部署具有持久化存储后端访问权限的智能体服务器。更多信息请参阅平台设置概述

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
对于运行在自定义主机/端口上的智能体服务器,请更新 URL 中的 baseUrl 查询参数。例如,如果你的服务器运行在 http://myhost:3000
https://smith.langchain.com/studio/?baseUrl=http://myhost:3000
使用 --tunnel 标志运行命令以创建安全隧道,因为 Safari 在连接 localhost 服务器时有限制:
langgraph dev --tunnel

7. 测试 API

  1. 安装 LangGraph JS SDK:
    npm install @langchain/langgraph-sdk
    
  2. 向助手发送消息(无线程运行):
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");
}

后续步骤

现在你已经在本地运行了 LangGraph 应用,可以通过探索部署和高级功能继续你的旅程: