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

前置条件

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

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
由于 Safari 在连接 localhost 服务器时存在限制,请在命令中使用 --tunnel 标志来创建安全隧道:
langgraph dev --tunnel

7. 测试 API

  1. 安装 LangGraph Python SDK:
    pip install langgraph-sdk
    
  2. 向 assistant 发送一条消息(无线程运行):
    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 应用,可以继续探索部署和高级功能,进一步深入学习: