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

1. 安装 LangGraph CLI & 创建一个 LangGraph 应用

新的langgraph项目python模板创建新的应用程序。此模板演示了一个可以用自己的逻辑扩展的单节点应用程序。

1
2
3
# Python >= 3.11 is required.
pip install --upgrade "langgraph-cli[inmem]"
langgraph new /Users/king/workspace-test/llm/chatbot-server --template new-langgraph-project-python

如果遇见问题,也可以尝试下面的方式

1
2
3
4
# 找到 macOS 系统根证书export SSL_CERT_FILE=/etc/ssl/cert.pem

# 再执行
langgraph new /Users/king/workspace-test/llm/chatbot-server --template new-langgraph-project-python

如果您使用时langgraph new没有指定模板,您将看到一个交互式菜单,可让您从可用模板列表中进行选择。

将/src/agent/graph.py的内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
"""LangGraph single-node graph template.

Returns a predefined response. Replace logic and configuration as needed.
"""

from __future__ import annotations

from dataclasses import dataclass
from typing import Any, Dict, TypedDict

from langgraph.graph import StateGraph
from langgraph.runtime import Runtime


class Context(TypedDict):
"""Context parameters for the agent.

Set these when creating assistants OR when invoking the graph.
See: https://langchain-ai.github.io/langgraph/cloud/how-tos/configuration_cloud/
"""

my_configurable_param: str


@dataclass
class State:
"""Input state for the agent.

Defines the initial structure of incoming data.
See: https://langchain-ai.github.io/langgraph/concepts/low_level/#state
"""

changeme: str = "example"


async def call_model(state: State, runtime: Runtime[Context]) -> Dict[str, Any]:
param = (
runtime.context.get("my_configurable_param")
if runtime.context is not None
else "default-value"
)
return {"changeme": f"output from call_model. Configured with {param}"}

# Define the graph
graph = (
StateGraph(State, context_schema=Context)
.add_node(call_model)
.add_edge("__start__", "call_model")
.compile(name="New Graph")
)

2. 安装依赖项

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

1
2
cd /Users/king/workspace-test/llm/chatbot-server
pip3 install -e .

3. 创建.env文件

您将在新LangGraph应用程序的根目录中找到一个.env.示例。在新的LangGraph应用程序的根目录中创建.env文件,并将.env.example文件的内容复制到其中,填写必要的API键:

1
LANGSMITH_API_KEY=lsv2...

这里按需去配置即可。

4. 启动 LangGraph 服务器

在本地启动 LangGraph API 服务器:

1
langgraph dev
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
➜  chatbot-server 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 LangGraph Platform.


2025-08-25T14:50:14.554870Z [info ] Using langgraph_runtime_inmem [langgraph_runtime] api_variant=local_dev langgraph_api_version=0.3.1 thread_name=MainThread
2025-08-25T14:50:14.561245Z [info ] Using auth of type=noop [langgraph_api.auth.middleware] api_variant=local_dev langgraph_api_version=0.3.1 thread_name=MainThread
2025-08-25T14:50:14.562535Z [info ] Starting In-Memory runtime with langgraph-api=0.3.1 and in-memory runtime=0.8.1 [langgraph_runtime_inmem.lifespan] api_variant=local_dev langgraph_api_version=0.3.1 langgraph_runtime_inmem_version=0.8.1 thread_name=asyncio_0 version=0.3.1
2025-08-25T14:50:14.581597Z [info ] Starting thread TTL sweeper with interval 5 minutes [langgraph_api.thread_ttl] api_variant=local_dev interval_minutes=5 langgraph_api_version=0.3.1 strategy=delete thread_name=asyncio_1
2025-08-25T14:50:14.583084Z [info ] Registering graph with id 'agent' [langgraph_api.graph] api_variant=local_dev graph_id=agent langgraph_api_version=0.3.1 thread_name=asyncio_1
2025-08-25T14:50:14.647534Z [info ] Starting 1 background workers [langgraph_runtime_inmem.queue] api_variant=local_dev langgraph_api_version=0.3.1 thread_name=asyncio_0
2025-08-25T14:50:14.647917Z [info ] Worker stats [langgraph_runtime_inmem.queue] active=0 api_variant=local_dev available=1 langgraph_api_version=0.3.1 max=1 thread_name=asyncio_1
2025-08-25T14:50:14.654076Z [info ] 5 changes detected [watchfiles.main] api_variant=local_dev langgraph_api_version=0.3.1 thread_name=MainThread
Server started in 1.04s
2025-08-25T14:50:14.861974Z [info ] Server started in 1.04s [browser_opener] api_variant=local_dev langgraph_api_version=0.3.1 message='Server started in 1.04s' thread_name='Thread-2 (_open_browser)'
🎨 Opening Studio in your browser...
2025-08-25T14:50:14.862062Z [info ] 🎨 Opening Studio in your browser... [browser_opener] api_variant=local_dev langgraph_api_version=0.3.1 message='🎨 Opening Studio in your browser...' thread_name='Thread-2 (_open_browser)'
URL: https://smith.langchain.com/studio/?baseUrl=http://127.0.0.1:2024
2025-08-25T14:50:14.862123Z [info ] URL: https://smith.langchain.com/studio/?baseUrl=http://127.0.0.1:2024 [browser_opener] api_variant=local_dev langgraph_api_version=0.3.1 message='URL: https://smith.langchain.com/studio/?baseUrl=http://127.0.0.1:2024' thread_name='Thread-2 (_open_browser)'
2025-08-25T14:50:15.149840Z [info ] Queue stats [langgraph_runtime_inmem.queue] api_variant=local_dev langgraph_api_version=0.3.1 max_age_secs=None med_age_secs=None n_pending=0 n_running=0 thread_name=asyncio_0
2025-08-25T14:50:17.391294Z [info ] Getting auth instance: None [langgraph_api.auth.custom] api_variant=local_dev langgraph_api_version=0.3.1 langgraph_auth=None method=POST path=/assistants/search thread_name=MainThread
2025-08-25T14:51:14.796166Z [info ] Worker stats [langgraph_runtime_inmem.queue] active=0 api_variant=local_dev available=1 langgraph_api_version=0.3.1 max=1 thread_name=asyncio_1
2025-08-25T14:51:15.298560Z [info ] Queue stats [langgraph_runtime_inmem.queue] api_variant=local_dev langgraph_api_version=0.3.1 max_age_secs=None med_age_secs=None n_pending=0 n_running=0 thread_name=asyncio_0

image-20250826121052132

langgraph dev命令以内存模式启动 LangGraph 服务器。此模式适用于开发和测试。对于生产用途,请部署 LangGraph 服务器并使其能够访问持久存储后端。更多信息,请参阅部署选项

5. 在 LangGraph Studio 中测试你的应用程序

LangGraph Studio是一个专门的 UI,您可以连接到 LangGraph API 服务器,在本地可视化、交互和调试您的应用程序。通过访问命令输出中提供的 URL,在 LangGraph Studio 中测试您的图表langgraph dev

1
>    - LangGraph Studio Web UI: https://smith.langchain.com/studio/?baseUrl=http://127.0.0.1:2024

对于在自定义主机/端口上运行的 LangGraph 服务器,请更新 baseURL 参数。

使用--tunnel带有标志的命令来创建安全隧道,因为 Safari 在连接到本地主机服务器时有限制:

1
langgraph dev --tunnel

6. 测试 API

  1. 安装 LangGraph Python SDK:
1
pip3 install langgraph-sdk
  1. 向助手发送消息(无线程运行):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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())

客户端打印日志:

1
2
3
4
5
6
7
Receiving new event of type: metadata...
{'run_id': '0198e1c6-e74e-73f0-b3de-a68f59564c32', 'attempt': 1}



Receiving new event of type: values...
{'changeme': 'output from call_model. Configured with default-value'}

server端日志:

1
2
3
4
5
6
7
8
9
10
2025-08-25T15:10:24.742293Z [info     ] Getting auth instance: None    [langgraph_api.auth.custom] api_variant=local_dev langgraph_api_version=0.3.1 langgraph_auth=None method=POST path=/runs/stream request_id=0a96deec-40bb-48a1-a5ca-5ea9854e8042 thread_name=MainThread
2025-08-25T15:10:24.742589Z [info ] Creating thread [langgraph_runtime_inmem.ops] api_variant=local_dev langgraph_api_version=0.3.1 method=POST path=/runs/stream request_id=0a96deec-40bb-48a1-a5ca-5ea9854e8042 thread_id=UUID('1d81ffc1-ea38-4aa8-89f1-f9bb43ff14d0') thread_name=asyncio_1
2025-08-25T15:10:24.742894Z [info ] Created run [langgraph_api.models.run] after_seconds=0 api_variant=local_dev assistant_id=fe096781-5601-53d2-b2f6-0d3403f7e9ca checkpoint_id=None if_not_exists=reject langgraph_api_version=0.3.1 method=POST multitask_strategy=enqueue path=/runs/stream request_id=0a96deec-40bb-48a1-a5ca-5ea9854e8042 run_create_ms=1 run_id=0198e1c7-cde6-775d-9fc2-5fffa7841986 run_put_ms=0 stream_mode=['values'] stream_resumable=False temporary=True thread_id=None thread_name=MainThread
2025-08-25T15:10:25.334572Z [info ] Starting background run [langgraph_api.worker] api_variant=local_dev assistant_id=fe096781-5601-53d2-b2f6-0d3403f7e9ca graph_id=agent langgraph_api_version=0.3.1 request_id=0a96deec-40bb-48a1-a5ca-5ea9854e8042 resumable=False run_attempt=1 run_creation_ms=1 run_id=0198e1c7-cde6-775d-9fc2-5fffa7841986 run_queue_ms=591 run_started_at=2025-08-25T15:10:25.333924+00:00 run_stream_start_ms=0 temporary=True thread_id=1d81ffc1-ea38-4aa8-89f1-f9bb43ff14d0 thread_name=asyncio_0
2025-08-25T15:10:25.352181Z [warning ] /Library/Frameworks/Python.framework/Versions/3.13/lib/python3.13/site-packages/langgraph/pregel/main.py:2813: UserWarning: `durability` has no effect when no checkpointer is present.
warnings.warn(
[py.warnings] api_variant=local_dev assistant_id=fe096781-5601-53d2-b2f6-0d3403f7e9ca graph_id=agent langgraph_api_version=0.3.1 request_id=0a96deec-40bb-48a1-a5ca-5ea9854e8042 run_attempt=1 run_id=0198e1c7-cde6-775d-9fc2-5fffa7841986 thread_id=1d81ffc1-ea38-4aa8-89f1-f9bb43ff14d0 thread_name=MainThread
2025-08-25T15:10:25.357438Z [info ] Background run succeeded [langgraph_api.worker] api_variant=local_dev assistant_id=fe096781-5601-53d2-b2f6-0d3403f7e9ca graph_id=agent langgraph_api_version=0.3.1 request_id=0a96deec-40bb-48a1-a5ca-5ea9854e8042 run_attempt=1 run_completed_in_ms=616 run_created_at=2025-08-25T15:10:24.742858+00:00 run_ended_at=2025-08-25T15:10:25.357298+00:00 run_exec_ms=23 run_id=0198e1c7-cde6-775d-9fc2-5fffa7841986 run_started_at=2025-08-25T15:10:25.333924+00:00 thread_id=1d81ffc1-ea38-4aa8-89f1-f9bb43ff14d0 thread_name=asyncio_0
2025-08-25T15:10:26.837936Z [info ] Worker stats [langgraph_runtime_inmem.queue] active=0 api_variant=local_dev available=1 langgraph_api_version=0.3.1 max=1 thread_name=asyncio_1
2025-08-25T15:10:27.340621Z [info ] Queue stats [langgraph_runtime_inmem.queue] api_variant=local_dev langgraph_api_version=0.3.1 max_age_secs=None med_age_secs=None n_pending=0 n_running=0 thread_name=asyncio_0

也可以在UI直接进行:

image-20250826121226918