跳到主要内容

🚀 LangGraph Platform

引言

当你的 LangGraph 应用从原型阶段发展到生产环境时,部署和运维的复杂性会急剧增加。LangGraph Platform 是一个专为智能代理应用设计的商业部署解决方案,它基于开源的 LangGraph 框架,为生产环境提供了完整的基础设施支持。

对于前端开发者来说,这就像是从本地开发服务器迁移到 Vercel 或 Netlify 这样的专业平台 - 你可以专注于应用逻辑,而不用担心服务器配置、扩展性和运维问题。

核心组件

LangGraph Platform 由几个核心组件组成,它们协同工作为你的智能代理应用提供完整的开发和部署体验:

LangGraph Server

  • 作用:定义了部署智能代理应用的标准 API 和架构
  • 价值:让你专注于代理逻辑而非服务器基础设施
  • 类比:就像 Express.js 为 Node.js 应用提供标准化的 Web 框架

LangGraph Studio

  • 作用:专用的可视化 IDE,支持图形化调试和交互
  • 价值:提供直观的开发和调试体验
  • 类比:类似于 React DevTools 或 Vue DevTools,但专门为智能代理设计

LangGraph CLI

  • 作用:命令行工具,用于本地开发和部署管理
  • 价值:简化项目管理和部署流程
  • 类比:类似于 Vue CLI 或 Create React App 的项目管理工具

Python/JS SDK

  • 作用:编程接口,用于与部署的应用进行交互
  • 价值:提供类型安全的客户端集成
  • 类比:类似于 Firebase SDK 或 Supabase 客户端库

Remote Graph

  • 作用:让你像使用本地图一样与远程部署的应用交互
  • 价值:无缝的本地开发体验
  • 类比:类似于 GraphQL 的远程 schema 访问

部署选项对比

LangGraph Platform 提供四种主要的部署选项,每种都适合不同的使用场景:

1. Self-Hosted Lite(自托管轻量版)

  • 适用场景:学习、原型开发、小型项目
  • 特点:免费使用(最多 100 万节点执行)
  • 限制:功能受限,需要自行管理基础设施

2. Self-Hosted Enterprise(自托管企业版)

  • 适用场景:大型企业,对数据安全有严格要求
  • 特点:完整功能,完全控制
  • 要求:企业版订阅,自行管理数据库和 Redis

3. Cloud SaaS(云托管服务)

  • 适用场景:快速上线,专注业务逻辑
  • 特点:零运维,与 GitHub 集成
  • 要求:Plus 或 Enterprise 计划

4. Bring Your Own Cloud(专属云)

  • 适用场景:企业级,需要数据隔离但不想自行运维
  • 特点:在你的 AWS 环境中运行,但由 LangChain 管理
  • 要求:仅限企业版,目前只支持 AWS

简单部署 vs 平台部署

让我们通过对比来理解何时需要使用 LangGraph Platform:

简单部署方式

对于基础应用,你可以使用自定义服务器逻辑:

简单部署示例

import { StateGraph, Annotation } from '@langchain/langgraph';
import { BaseMessage, HumanMessage, AIMessage } from '@langchain/core/messages';

// 定义简单的状态
const StateAnnotation = Annotation.Root({
messages: Annotation<BaseMessage[]>({
reducer: (x, y) => x.concat(y),
}),
});

// 创建简单的助手节点
async function assistantNode(state: typeof StateAnnotation.State) {
const lastMessage = state.messages[state.messages.length - 1];
const content =
typeof lastMessage.content === 'string' ? lastMessage.content : '';

// 简单的响应逻辑
let response = '';
if (content.includes('hello')) {
response = 'Hello! How can I help you today?';
} else if (content.includes('weather')) {
response =
'I cannot check the weather right now, but you can check your local weather app.';
} else {
response = 'I understand. Is there anything specific I can help you with?';
}

return {
messages: [new AIMessage(response)],
};
}

// 创建图
const graph = new StateGraph(StateAnnotation)
.addNode('assistant', assistantNode)
.addEdge('__start__', 'assistant')
.addEdge('assistant', '__end__');

const compiledGraph = graph.compile();

// 简单的 HTTP 服务器示例(伪代码)
// 在实际项目中,你需要安装并导入 express 或其他 HTTP 框架
const createSimpleServer = () => {
// 这里是服务器设置的示例代码
console.log('创建简单的 HTTP 服务器...');

// 聊天端点处理逻辑
const handleChatRequest = async (message: string) => {
try {
if (!message) {
throw new Error('Message is required');
}

// 执行图
const result = await compiledGraph.invoke({
messages: [new HumanMessage(message)],
});

// 返回最后一条消息
const lastMessage = result.messages[result.messages.length - 1];

return {
response: lastMessage.content,
timestamp: new Date().toISOString(),
};
} catch (error) {
console.error('Chat error:', error);
throw error;
}
};

return { handleChatRequest };
};

export { compiledGraph, createSimpleServer };

// 使用示例
export async function demonstrateSimpleDeployment() {
console.log('=== 简单部署示例 ===');

// 模拟客户端请求
const testMessages = [
'Hello there!',
'What is the weather like?',
'Can you help me with something?',
];

for (const message of testMessages) {
console.log(`\n用户: ${message}`);

const result = await compiledGraph.invoke({
messages: [new HumanMessage(message)],
});

const response = result.messages[result.messages.length - 1];
console.log(`助手: ${response.content}`);
}
}

// 部署配置示例
export const deploymentConfig = {
// 基础配置
basic: {
port: 3000,
cors: true,
rateLimit: {
windowMs: 15 * 60 * 1000, // 15分钟
max: 100, // 限制每个IP 100个请求
},
},

// 生产配置
production: {
port: process.env.PORT || 8080,
cors: {
origin: process.env.ALLOWED_ORIGINS?.split(',') || [
'https://yourdomain.com',
],
},
rateLimit: {
windowMs: 15 * 60 * 1000,
max: 1000,
},
logging: {
level: 'info',
format: 'json',
},
monitoring: {
enabled: true,
endpoint: '/metrics',
},
},
};

// Docker 配置示例
export const dockerConfig = `
# Dockerfile
FROM node:18-alpine

WORKDIR /app

# 复制依赖文件
COPY package*.json ./
RUN npm ci --only=production

# 复制应用代码
COPY . .

# 构建应用
RUN npm run build

# 暴露端口
EXPOSE 3000

# 启动应用
CMD ["npm", "start"]
`;

// Docker Compose 配置
export const dockerComposeConfig = `
version: '3.8'

services:
app:
build: .
ports:
- "3000:3000"
environment:
- NODE_ENV=production
- PORT=3000
restart: unless-stopped

redis:
image: redis:alpine
ports:
- "6379:6379"
restart: unless-stopped

postgres:
image: postgres:15
environment:
- POSTGRES_DB=langgraph
- POSTGRES_USER=user
- POSTGRES_PASSWORD=password
ports:
- "5432:5432"
volumes:
- postgres_data:/var/lib/postgresql/data
restart: unless-stopped

volumes:
postgres_data:
`;

这种方式适合:

  • 单一助手应用
  • 不需要长时间运行的会话
  • 没有持久化内存需求
  • 简单的请求-响应模式

平台部署的优势

当应用变得复杂时,LangGraph Platform 解决了许多挑战:

平台解决的核心问题
  • 流式支持:多种流式模式,优化用户体验
  • 后台运行:支持长时间运行的任务
  • 长时间运行支持:防止超时和连接中断
  • 突发流量处理:任务队列确保请求不丢失
  • 双重发送处理:智能处理用户的快速连续消息
  • 检查点和内存管理:优化的状态持久化
  • 人机交互支持:专用的人工干预端点

开发到部署工作流

实践指导

选择合适的部署方式

  1. 学习阶段:使用 Self-Hosted Lite
  2. 原型验证:使用 Cloud SaaS
  3. 生产环境:根据数据安全要求选择 Cloud SaaS 或 Self-Hosted Enterprise
  4. 企业级应用:考虑 Bring Your Own Cloud

迁移策略

迁移检查清单
// 1. 评估当前应用复杂度
const needsPlatform = {
hasLongRunningTasks: true, // 需要后台任务
requiresStreaming: true, // 需要流式输出
hasMemoryRequirements: true, // 需要持久化
expectsHighTraffic: true, // 预期高流量
needsHumanInLoop: true // 需要人工干预
};

// 2. 准备迁移
if (Object.values(needsPlatform).some(Boolean)) {
console.log('建议使用 LangGraph Platform');
}

小结与延伸

LangGraph Platform 为智能代理应用提供了从开发到生产的完整解决方案。它就像是专门为 AI 应用设计的 Vercel - 让你专注于构建智能功能,而不用担心基础设施的复杂性。

选择合适的部署方式取决于你的具体需求:数据安全要求、运维能力、预算考虑和功能需求。无论选择哪种方式,平台都提供了统一的开发体验和强大的调试工具。

接下来我们将深入了解应用结构,学习如何组织和配置 LangGraph 应用以便部署。