Skip to content
LangChain 文档版本 跟随上游 源快照 c71b2e62 更新于 2026-10-08

运行本地服务器

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

前置条件

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

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

1. 安装 LangGraph CLI

bash
# Python >= 3.11 is required.
pip install -U "langgraph-cli[inmem]"
bash
# Python >= 3.11 is required.
uv add "langgraph-cli[inmem]"

2. 创建 LangGraph 应用

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

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

TIP

其他模板 如果你在不指定模板的情况下使用 langgraph new,系统会向你展示一个交互式菜单,让你从可用模板列表中进行选择。

3. 安装依赖项

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

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

4. 创建一个 .env 文件

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

bash
LANGSMITH_API_KEY=lsv2...

5. 启动 Agent 服务器

在本地启动 LangGraph API 服务器:

shell
langgraph 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 兼容性

将 --tunnel 标志与你的命令一起使用以创建安全隧道,因为 Safari 在连接到 localhost 服务器时存在限制:

shell
langgraph dev --tunnel

7. 测试 API

  1. 安装 LangGraph Python SDK:
    shell
    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,  # Threadless run
            "agent", # Name of assistant. Defined in 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())

后续步骤

现在你已经在本地运行了一个 LangGraph 应用,通过探索部署和高级功能,让你的旅程更进一步:


BytesRouter 是社区翻译站点,所有译文仅供参考,一切以官方英文原文为准。