本指南介绍如何在本地运行 LangGraph 应用程序。
前提条件
在开始之前,请确保您具备以下条件:
- * 用于 LangSmith - 免费注册
1. 安装 LangGraph CLI
npm install --save-dev @langchain/langgraph-cli
2. 创建 LangGraph 应用
从 new-langgraph-project-js 模板创建新应用。此模板演示了一个单节点应用程序,您可以将其扩展为包含您自己的逻辑。
npm create langgraph
Adding LangGraph to an existing project
如果您有包含 LangGraph 代理的现有项目,可以自动生成 langgraph.json 配置文件使用 config command:
npm create langgraph config
此命令扫描您的项目中的 LangGraph 代理(如 createAgent(), StateGraph.compile(), or workflow.compile() 模式)并生成包含所有导出代理的配置文件。
示例输出:
{
"node_version": "24",
"graphs": {
"agent": "./src/agent.ts:agent",
"searchAgent": "./src/search.ts:searchAgent"
},
"env": ".env"
}
3. 安装依赖项
在新的 LangGraph 应用根目录中,以 edit 模式安装依赖项,以便服务器使用您的本地更改:
cd path/to/your/app
npm install
4. 创建 .env 文件
您会在新的 LangGraph 应用根目录找到 .env.example 。在 .env 中创建一个文件,并将 .env.example 文件内容复制到其中,填写必要的 API 密钥:
LANGSMITH_API_KEY=lsv2...
5. 启动代理服务器
在本地启动 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 平台设置概述 6. 在 Studio 中测试应用.
Studio
是专门的用户界面,可连接到 LangGraph API 服务器,用于在本地可视化、交互和调试应用。通过访问 输出中的 URL 在 Studio 中测试您的图表。例如,如果您的服务器运行在 langgraph dev command:
> - LangGraph Studio Web UI: https://smith.langchain.com/studio/?baseUrl=http://127.0.0.1:2024
For an Agent Server running on a custom host/port, update the baseUrl 查询参数中的 URL。例如,如果您的服务器运行在 http://myhost:3000:
https://smith.langchain.com/studio/?baseUrl=http://myhost:3000
Safari compatibility
使用 --tunnel 标志配合命令创建安全隧道,因为 Safari 连接本地服务器存在限制:
langgraph dev --tunnel
7. 测试 API
Javascript SDK
1. 安装 LangGraph JS SDK:
npm install @langchain/langgraph-sdk
2. 向助手发送消息(无线程运行):
// only set the apiUrl if you changed the default port when calling langgraph dev
const client = new Client({ apiUrl: "http://localhost:2024"});
const streamResponse = client.runs.stream(
null, // Threadless run
"agent", // Assistant 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 应用在本地运行,通过探索部署和高级功能来进一步深入您的学习之旅: