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

前提条件

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

1. 安装 LangGraph CLI

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

2. 创建 LangGraph 应用程序

new-langgraph-project-python 模板创建一个新应用程序。该模板演示了一个单节点应用程序,您可以用自己的逻辑进行扩展。
langgraph new path/to/your/app --template new-langgraph-project-python
其他模板 如果您使用 langgraph new 而不指定模板,将会显示一个交互式菜单,允许您从可用模板列表中进行选择。

3. 安装依赖

在新 LangGraph 应用程序的根目录下,以 edit 模式安装依赖,以便服务器使用您的本地更改:
cd path/to/your/app
pip install -e .

4. 创建 .env 文件

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

5. 启动 Agent 服务器

在本地启动 LangGraph API 服务器:
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
使用命令中的 --tunnel 标志创建安全隧道,因为 Safari 在连接到 localhost 服务器时有限制:
langgraph dev --tunnel

7. 测试 API

  1. 安装 LangGraph Python SDK:
    pip install langgraph-sdk
    
  2. 向助手发送消息(无线程运行):
    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 应用程序,通过探索部署和高级功能进一步推进您的旅程: