这是一个综合使用 LangChain、LangGraph 和 LangSmith 的 JavaScript 代码示例。这个示例将演示如何构建一个智能的客户服务聊天机器人工作流。我为您创建了一个综合使用 LangChain、LangGraph 和 LangSmith 的完整示例。这个代码构建了一个智能客户服务聊天机器人,展示了三个工具的核心功能和集成方式。
## 代码结构说明:
### 1. **LangChain 的使用**
- **核心组件**:使用了 ChatOpenAI 模型、PromptTemplate 提示模板、StringOutputParser 输出解析器
- **链式处理**:通过 RunnableSequence 创建处理链,将提示→模型→解析器连接起来
- **多场景支持**:为不同的客服场景(技术支持、账单咨询、产品信息)创建了专门的提示模板
### 2. **LangGraph 的使用**
- **状态管理**:定义了 CustomerServiceState 类来管理整个工作流的状态
- **节点定义**:每个处理步骤都是一个节点(意图分析、技术支持、质量检查等)
- **条件路由**:根据意图分析结果和质量检查结果动态决定工作流走向
- **复杂工作流**:构建了一个完整的客服处理流程图
### 3. **LangSmith 的集成**
- **追踪监控**:使用 LangChainTracer 记录每个步骤的执行情况
- **性能分析**:通过 callbacks 参数将追踪器传递给各个链
- **运行记录**:将每次交互的输入输出记录到 LangSmith 平台
## 工作流程:
1. **意图分析** → 识别用户请求类型
2. **路由分发** → 根据意图选择处理方式
3. **专门处理** → 执行相应的业务逻辑
4. **质量检查** → 验证回复质量
5. **结果输出** → 返回最终回复或转人工
## 使用前准备:
1. 安装依赖包
2. 设置 OpenAI 和 LangSmith 的 API 密钥
3. 根据需要调整提示模板和业务逻辑
这个示例展示了如何将三个工具的优势结合起来:LangChain 提供基础构建块,LangGraph 管理复杂工作流,LangSmith 提供监控和调试能力,共同构建一个生产级的 LLM 应用。
``` javascript
// 导入必要的模块
import { ChatOpenAI } from "@langchain/openai";
import { PromptTemplate } from "@langchain/core/prompts";
import { StringOutputParser } from "@langchain/core/output_parsers";
import { RunnableSequence } from "@langchain/core/runnables";
import { StateGraph, END } from "@langchain/langgraph";
import { Client } from "langsmith";
import { LangChainTracer } from "langchain/callbacks";
// 1. LangSmith 配置 - 用于监控和追踪
// LangSmith 是 LangChain 的观测平台,用于调试、测试和监控 LLM 应用
const langsmithClient = new Client({
apiUrl: "https://api.smith.langchain.com",
apiKey: process.env.LANGCHAIN_API_KEY, // 需要在环境变量中设置
});
// 创建 LangSmith 追踪器,用于记录每个步骤的执行情况
const tracer = new LangChainTracer({
projectName: "customer-service-bot", // 项目名称
client: langsmithClient,
});
// 2. LangChain 基础组件配置
// 初始化 OpenAI 聊天模型
const chatModel = new ChatOpenAI({
modelName: "gpt-3.5-turbo",
temperature: 0.7, // 控制回答的创造性,0-1之间
openAIApiKey: process.env.OPENAI_API_KEY, // OpenAI API 密钥
});
// 定义不同场景的提示模板
// 意图分析模板 - 用于识别用户的请求类型
const intentAnalysisPrompt = PromptTemplate.fromTemplate(`
分析以下用户消息的意图,选择最合适的分类:
1. 技术支持 (technical_support)
2. 账单咨询 (billing_inquiry)
3. 产品信息 (product_info)
4. 投诉建议 (complaint_feedback)
5. 其他 (other)
用户消息: {userMessage}
请只返回分类标签,不要其他解释。
`);
// 技术支持回复模板
const techSupportPrompt = PromptTemplate.fromTemplate(`
你是一个专业的技术支持专家。用户遇到了技术问题,请提供详细的解决方案。
用户问题: {userMessage}
用户历史: {conversationHistory}
请提供:
1. 问题诊断
2. 解决步骤
3. 预防措施
回复:
`);
// 账单咨询回复模板
const billingPrompt = PromptTemplate.fromTemplate(`
你是一个友善的账单客服代表。请帮助用户解决账单相关问题。
用户问题: {userMessage}
用户历史: {conversationHistory}
请提供清晰的账单信息和解决方案。
回复:
`);
// 产品信息回复模板
const productInfoPrompt = PromptTemplate.fromTemplate(`
你是一个产品专家。请为用户提供详细的产品信息。
用户询问: {userMessage}
对话历史: {conversationHistory}
请提供准确、有用的产品信息。
回复:
`);
// 3. 定义 LangGraph 状态结构
// 状态管理 - 在整个工作流中传递和维护的数据结构
class CustomerServiceState {
constructor() {
this.userMessage = ""; // 用户当前消息
this.conversationHistory = []; // 对话历史记录
this.intent = ""; // 识别出的用户意图
this.response = ""; // 生成的回复
this.confidence = 0; // 意图识别的置信度
this.needsHumanHandoff = false; // 是否需要转人工
}
}
// 4. 定义 LangGraph 节点函数
// 每个节点代表工作流中的一个步骤
// 节点1: 意图分析
async function analyzeIntent(state) {
console.log("🔍 执行意图分析...");
try {
// 创建意图分析链
const intentChain = RunnableSequence.from([
intentAnalysisPrompt,
chatModel,
new StringOutputParser()
]);
// 执行意图分析,使用 LangSmith 追踪
const intentResult = await intentChain.invoke(
{ userMessage: state.userMessage },
{ callbacks: [tracer] }
);
// 更新状态
state.intent = intentResult.trim().toLowerCase();
state.confidence = 0.8; // 简化的置信度计算
console.log(`✅ 识别意图: ${state.intent}`);
return state;
} catch (error) {
console.error("❌ 意图分析失败:", error);
state.intent = "other";
state.confidence = 0.3;
return state;
}
}
// 节点2: 技术支持处理
async function handleTechnicalSupport(state) {
console.log("🔧 处理技术支持请求...");
const techChain = RunnableSequence.from([
techSupportPrompt,
chatModel,
new StringOutputParser()
]);
state.response = await techChain.invoke({
userMessage: state.userMessage,
conversationHistory: state.conversationHistory.join("\n")
}, { callbacks: [tracer] });
console.log("✅ 技术支持回复已生成");
return state;
}
// 节点3: 账单咨询处理
async function handleBillingInquiry(state) {
console.log("💰 处理账单咨询...");
const billingChain = RunnableSequence.from([
billingPrompt,
chatModel,
new StringOutputParser()
]);
state.response = await billingChain.invoke({
userMessage: state.userMessage,
conversationHistory: state.conversationHistory.join("\n")
}, { callbacks: [tracer] });
console.log("✅ 账单咨询回复已生成");
return state;
}
// 节点4: 产品信息处理
async function handleProductInfo(state) {
console.log("📋 处理产品信息询问...");
const productChain = RunnableSequence.from([
productInfoPrompt,
chatModel,
new StringOutputParser()
]);
state.response = await productChain.invoke({
userMessage: state.userMessage,
conversationHistory: state.conversationHistory.join("\n")
}, { callbacks: [tracer] });
console.log("✅ 产品信息回复已生成");
return state;
}
// 节点5: 通用处理
async function handleGeneral(state) {
console.log("🤖 执行通用处理...");
const generalPrompt = PromptTemplate.fromTemplate(`
你是一个友善的客服助手。请礼貌地回复用户的消息。
用户消息: {userMessage}
回复:
`);
const generalChain = RunnableSequence.from([
generalPrompt,
chatModel,
new StringOutputParser()
]);
state.response = await generalChain.invoke({
userMessage: state.userMessage
}, { callbacks: [tracer] });
console.log("✅ 通用回复已生成");
return state;
}
// 节点6: 质量检查
async function qualityCheck(state) {
console.log("🔍 执行回复质量检查...");
// 简单的质量检查逻辑
const responseLength = state.response.length;
const hasGreeting = state.response.includes("您好") || state.response.includes("你好");
// 如果回复太短或缺少礼貌用语,标记需要人工介入
if (responseLength < 20 || !hasGreeting) {
state.needsHumanHandoff = true;
console.log("⚠️ 回复质量不足,需要人工介入");
} else {
console.log("✅ 回复质量检查通过");
}
return state;
}
// 5. 定义路由决策函数
// 这些函数决定工作流的下一步走向
function routeAfterIntent(state) {
// 根据识别的意图决定下一步
switch (state.intent) {
case "technical_support":
return "technical_support";
case "billing_inquiry":
return "billing_inquiry";
case "product_info":
return "product_info";
default:
return "general";
}
}
function routeAfterQuality(state) {
// 根据质量检查结果决定是否结束
return state.needsHumanHandoff ? "human_handoff" : END;
}
// 6. 构建 LangGraph 工作流
// LangGraph 用于创建复杂的、有状态的工作流
function createCustomerServiceGraph() {
const workflow = new StateGraph(CustomerServiceState);
// 添加节点到图中
workflow.addNode("intent_analysis", analyzeIntent);
workflow.addNode("technical_support", handleTechnicalSupport);
workflow.addNode("billing_inquiry", handleBillingInquiry);
workflow.addNode("product_info", handleProductInfo);
workflow.addNode("general", handleGeneral);
workflow.addNode("quality_check", qualityCheck);
// 设置入口点
workflow.setEntryPoint("intent_analysis");
// 定义节点之间的连接和条件路由
workflow.addConditionalEdges(
"intent_analysis", // 从意图分析节点
routeAfterIntent, // 使用路由函数
{
"technical_support": "technical_support",
"billing_inquiry": "billing_inquiry",
"product_info": "product_info",
"general": "general"
}
);
// 所有处理节点都连接到质量检查
workflow.addEdge("technical_support", "quality_check");
workflow.addEdge("billing_inquiry", "quality_check");
workflow.addEdge("product_info", "quality_check");
workflow.addEdge("general", "quality_check");
// 质量检查后的条件路由
workflow.addConditionalEdges(
"quality_check",
routeAfterQuality,
{
"human_handoff": END, // 可以添加人工节点
[END]: END
}
);
return workflow.compile();
}
// 7. 主要使用示例
async function runCustomerServiceBot() {
console.log("🚀 启动客户服务机器人...\n");
// 创建工作流图
const serviceGraph = createCustomerServiceGraph();
// 测试用例
const testMessages = [
"我的网络连接有问题,无法正常上网",
"我想了解你们的会员套餐价格",
"上个月的账单为什么这么高?",
"你们的产品质量太差了,我要投诉!"
];
// 处理每个测试消息
for (let i = 0; i < testMessages.length; i++) {
const userMessage = testMessages[i];
console.log(`\n📨 处理消息 ${i + 1}: "${userMessage}"`);
console.log("=" * 50);
try {
// 创建初始状态
const initialState = new CustomerServiceState();
initialState.userMessage = userMessage;
initialState.conversationHistory = [
"用户: 你好",
"助手: 您好!我是客服助手,有什么可以帮助您的吗?"
];
// 执行工作流 - 这里整合了所有三个工具
const finalState = await serviceGraph.invoke(initialState);
// 输出结果
console.log("\n📊 处理结果:");
console.log(`意图: ${finalState.intent}`);
console.log(`置信度: ${finalState.confidence}`);
console.log(`需要人工: ${finalState.needsHumanHandoff ? "是" : "否"}`);
console.log(`\n💬 回复内容:\n${finalState.response}`);
// 模拟记录到 LangSmith
await langsmithClient.createRun({
name: "customer_service_interaction",
inputs: { userMessage: userMessage },
outputs: { response: finalState.response, intent: finalState.intent },
runType: "chain"
});
} catch (error) {
console.error(`❌ 处理消息时出错:`, error);
}
// 添加延迟以便观察输出
await new Promise(resolve => setTimeout(resolve, 1000));
}
}
// 8. 错误处理和监控
process.on('unhandledRejection', (reason, promise) => {
console.error('未处理的 Promise 拒绝:', reason);
// 可以在这里发送错误到 LangSmith 进行监控
});
// 9. 导出主要函数
export {
runCustomerServiceBot,
createCustomerServiceGraph,
CustomerServiceState
};
// 10. 如果直接运行此文件
if (import.meta.url === `file://${process.argv[1]}`) {
runCustomerServiceBot().catch(console.error);
}
/*
使用说明:
1. 安装依赖: npm install @langchain/openai @langchain/core @langchain/langgraph langsmith
2. 设置环境变量:
- OPENAI_API_KEY: OpenAI API 密钥
- LANGCHAIN_API_KEY: LangSmith API 密钥
3. 运行: node this-file.js
工具说明:
- LangChain: 提供 LLM 应用的核心构建块(提示、模型、解析器、链)
- LangGraph: 创建复杂的、有状态的工作流和决策图
- LangSmith: 监控、调试和改进 LLM 应用的性能
这个示例展示了如何将三个工具结合使用来构建一个完整的智能客服系统。
*/
```