Skip to main content
本指南向您展示如何在本地运行 LangGraph 应用程序。

前提条件

在开始之前,请确保您拥有以下内容:
  • 用于 LangSmith 的 API 密钥 - 免费注册

1. 安装 LangGraph CLI

npx @langchain/langgraph-cli

2. 创建一个 LangGraph 应用 🌱

new-langgraph-project-js模板创建一个新的应用程序。此模板演示了一个单节点应用程序,您可以使用自己的逻辑对其进行扩展。
npm create langgraph

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. 启动 LangGraph 服务器 🚀

启动本地 LangGraph API 服务器:
npx @langchain/langgraph-cli dev
示例输出:
>    Ready!
>
>    - API: [http://localhost:2024](http://localhost:2024/)
>
>    - Docs: http://localhost:2024/docs
>
>    - LangGraph Studio Web UI: https://smith.langchain.com/studio/?baseUrl=http://127.0.0.1:2024
langgraph dev 命令以内存模式启动 LangGraph 服务器。此模式适用于开发和测试目的。对于生产使用,请部署 LangGraph 服务器并使其能够访问持久化存储后端。有关更多信息,请参阅托管概述

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

工作室 是一个专门的 UI,您可以通过连接到 LangGraph API 服务器来本地可视化、交互和调试您的应用程序。通过访问 langgraph dev 命令输出中提供的 URL 在工作室测试您的图:
>    - LangGraph Studio Web UI: https://smith.langchain.com/studio/?baseUrl=http://127.0.0.1:2024
对于在自定义主机/端口上运行的 LangGraph 服务器,更新 baseURL 参数。
使用您的命令与 --tunnel 标志创建安全隧道,因为 Safari 在连接到 localhost 服务器时存在限制:
langgraph dev --tunnel

7. 测试API

  1. 安装 LangGraph JS SDK:
npm install @langchain/langgraph-sdk
  1. 向助手发送消息(无线程运行):
const { Client } = await import("@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 应用,通过探索部署和高级功能,继续您的探索之旅: