运行本地服务
本指南向你展示如何在本地运行 LangGraph 应用程序。
前置准备
在开始之前,请确保你具备以下条件:
- LangSmith 的 API 密钥 - 免费注册
1. 安装 LangGraph CLI
npm install --save-dev @langchain/langgraph-cli2. 创建 LangGraph 应用
从 new-langgraph-project-js 模板创建一个新应用程序。该模板演示了一个单节点应用程序,你可以使用自己的逻辑对其进行扩展。
npm create langgraph将 LangGraph 添加到现有项目
如果你有一个包含 LangGraph 智能体的现有项目,可以使用 config 命令自动生成 langgraph.json 配置文件:
npm create langgraph config此命令会扫描你的项目中是否有 LangGraph 智能体(例如 createAgent()、StateGraph.compile() 或 workflow.compile() 模式),并生成包含所有导出智能体的配置文件。
输出示例:
{
"node_version": "24",
"graphs": {
"agent": "./src/agent.ts:agent",
"searchAgent": "./src/search.ts:searchAgent"
},
"env": ".env"
}TIP
只有导出的(exported)智能体才会包含在配置中。如果智能体未导出,该命令将发出警告,以便你可以添加 export 关键字。
:::
3. 安装依赖项
在新的 LangGraph 应用程序的根目录中,安装依赖项:
cd path/to/your/app
npm install4. 创建 .env 文件
你将在新的 LangGraph 应用程序的根目录中找到一个 .env.example 文件。在根目录中创建一个 .env 文件,并将 .env.example 文件的内容复制到其中,填入必需的 API 密钥:
LANGSMITH_API_KEY=lsv2...5. 启动智能体服务(Agent server)
在本地启动 LangGraph API 服务器:
npx @langchain/langgraph-cli 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:3000Safari 兼容性
在命令中使用 --tunnel 标志创建安全隧道,因为 Safari 在连接到 localhost 服务器时存在限制:
langgraph dev --tunnel7. 测试 API
Javascript SDK
- 安装 LangGraph JS SDK:shell
npm install @langchain/langgraph-sdk - 向助手发送消息(无线程运行):
import { Client } from "@langchain/langgraph-sdk";
// 仅在调用 langgraph dev 时更改了默认端口的情况下设置 apiUrl
const client = new Client({ apiUrl: "http://localhost:2024"});
const streamResponse = client.runs.stream(
null, // 无线程运行
"agent", // 助手 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");
}Rest API
curl -s --request POST \
--url "http://localhost:2024/runs/stream" \
--header 'Content-Type: application/json' \
--data "{
\"assistant_id\": \"agent\",
\"input\": {
\"messages\": [
{
\"role\": \"human\",
\"content\": \"What is LangGraph?\"
}
]
},
\"stream_mode\": \"messages-tuple\"
}"后续步骤
既然你已经在本地运行了 LangGraph 应用程序,可以通过探索部署和高级功能进一步深入:
