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

前置条件

开始之前,请确保你具备以下内容:
  • 一个 LangSmith API 密钥——可免费注册

1. 安装 LangGraph CLI

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

2. 创建 LangGraph 应用

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

3. 安装依赖

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

4. 创建 .env 文件

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

5. 启动 Agent 服务器

在本地启动 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 命令会以内存模式启动 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 在连接 localhost 服务器时存在限制,请在命令中使用 --tunnel 标志来创建安全隧道:
langgraph dev --tunnel

7. 测试 API

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

// only set the apiUrl if you changed the default port when calling langgraph dev
const client = new Client({ apiUrl: "http://localhost:2024"});

const streamResponse = client.runs.stream(
  null, // Threadless run
  "agent", // Assistant 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 应用,可以继续探索部署和高级功能,进一步深入学习: