LLM系列 | 16: 构建端到端智能客服

本文涉及的产品
智能开放搜索 OpenSearch行业算法版,1GB 20LCU 1个月
实时计算 Flink 版,1000CU*H 3个月
实时数仓Hologres,5000CU*H 100GB 3个月
简介: 本文将综合之前多篇文章搭建一个带评估功能的**端到端智能客服系统**。整体流程大致如下: 检查输入,看看用户输入的query是否能够通过审核API;抽取出商品和对应的类别;抽取出商品信息;模型根据商品信息回答用户问题;将模型的回复输入审核API对回复进行审核。

简介

漠漠水田飞白鹭,阴阴夏木啭黄鹂。

小伙伴们好,我是微信公众号《小窗幽记机器学习》的小编:卖海蛎煎的小男孩。紧接前面几篇ChatGPT Prompt工程和应用系列文章:

今天这篇小作文是吴恩达《Building Systems with the ChatGPT API》课程的第3篇笔记。本文将综合之前多篇文章搭建一个带评估功能的端到端智能客服系统。整体流程大致如下:

  • 检查输入,看看用户输入的query是否能够通过审核API。
  • 抽取出商品和对应的类别。
  • 抽取出商品信息。
  • 模型根据商品信息回答用户问题。
  • 将模型的回复输入审核API对回复进行审核。

完整代码请到微信公众号《小窗幽记机器学习》添加小编微信。

准备工作

import os
import openai
import sys
sys.path.append('../..')
import utils_cn as utils

import panel as pn  # GUI
pn.extension()

openai.api_key  = "sk-XXX"
os.environ['HTTP_PROXY'] = "xxx"
os.environ['HTTPS_PROXY'] = "xxx"


def get_completion_from_messages(messages, model="gpt-3.5-turbo", temperature=0, max_tokens=500):
    response = openai.ChatCompletion.create(
        model=model,
        messages=messages,
        temperature=temperature, 
        max_tokens=max_tokens, 
    )
    return response.choices[0].message["content"]

智能客服

以智能客服为例,介绍完整的服务链路,包括对输入文本进行安全检查、通过用户咨询查找到相关产品和类别、回答用户问题、对回答结果进行内容安全检查、对回答结果进行问题关联检查。

def process_user_message(user_input, all_messages, debug=True):
    delimiter = "```"

    # Step 1: Check input to see if it flags the Moderation API or is a prompt injection
    response = openai.Moderation.create(input=user_input)
    moderation_output = response["results"][0]

    if moderation_output["flagged"]:
        print("Step 1: Input flagged by Moderation API.")
        return "Sorry, we cannot process this request."

    if debug: print("Step 1: Input passed moderation check.")

    products_and_category_dict = utils.get_products_and_category()
    if debug:
        print("products_and_category_dict=", products_and_category_dict)
        print("start do find_category_and_product_only")
    category_and_product_response = utils.find_category_and_product_only(user_input, products_and_category_dict)
    if debug: 
        print("category_and_product_response=", category_and_product_response)
        print("start do Extract the list of products")
    # Step 2: Extract the list of products
    category_and_product_list = utils.read_string_to_list(category_and_product_response)
    if debug: 
        print("category_and_product_list=", category_and_product_list)

    if debug: 
        print("Step 2: Extracted list of products.")

    # Step 3: If products are found, look them up
    product_information = utils.generate_output_string(category_and_product_list)
    if debug:
        print("product_information=", product_information)
    if debug:
        print("Step 3: Looked up product information.")

    # Step 4: Answer the user question
    system_message = f"""
    你是一位大型电子商店的客户助理。以友好和乐于助人的口吻回答,给出简明的答案。确保询问用户相关的后续问题。
    """
    messages = [
        {'role': 'system', 'content': system_message},
        {'role': 'user', 'content': f"{delimiter}{user_input}{delimiter}"},
        {'role': 'assistant', 'content': f"Relevant product information:\n{product_information}"}
    ]

    final_response = get_completion_from_messages(all_messages + messages)
    if debug:
        print("Step 4: Generated response to user question.")
        print("final_response=", final_response)
    all_messages = all_messages + messages[1:]

    # Step 5: Put the answer through the Moderation API
    response = openai.Moderation.create(input=final_response)
    moderation_output = response["results"][0]

    if moderation_output["flagged"]:
        if debug: print("Step 5: Response flagged by Moderation API.")
        return "Sorry, we cannot provide this information."

    if debug:
        print("Step 5: Response passed moderation check.")

    # Step 6: Ask the model if the response answers the initial user query well
    user_message = f"""
    你是一个客服助理,负责评估客服助理的回答是否足够回答客户的问题,并验证助理从产品信息中引用的所有事实是否正确。\
    产品信息、用户和客服助理的消息将用三个反引号分隔,即```.\
    请用一个字母回答,不带标点符号:\
    Y - 如果输出足够回答问题,并且回答正确使用了产品信息 \
    N - 否则 \

    只输出一个字母。

    Customer message: {delimiter}{user_input}{delimiter}
    Product information: {delimiter}{product_information}{delimiter}
    Agent response: {delimiter}{final_response}{delimiter}

    回复是否充分回答了问题?
    """
    messages = [
        {'role': 'system', 'content': system_message},
        {'role': 'user', 'content': user_message}
    ]
    evaluation_response = get_completion_from_messages(messages)
    if debug:
        print("Step 6: Model evaluated the response.")
        print("evaluation_response=", evaluation_response)

    # Step 7: If yes, use this answer; if not, say that you will connect the user to a human
    if "Y" in evaluation_response:  # Using "in" instead of "==" to be safer for model output variation (e.g., "Y." or "Yes")
        if debug: print("Step 7: Model approved the response.")
        return final_response, all_messages
    else:
        if debug: print("Step 7: Model disapproved the response.")
        neg_str = "很抱歉,我无法提供您所需的信息。我将为您转接到一位人工客服以获得进一步帮助。"
        return neg_str, all_messages

user_input = "给我介绍下SmartX Pro phone和fotosnap DSLR camera。还有,我也想了解下你们的电视。"
response,_ = process_user_message(user_input,[])
print(response)

输出结果如下:

Step 1: Input passed moderation check.
products_and_category_dict= {'计算机和笔记本电脑': ['TechPro超极本', 'BlueWave游戏笔记本电脑', 'PowerLite可转换本', 'TechPro台式机', 'BlueWave Chromebook'], '智能手机和配件': ['SmartX ProPhone', 'MobiTech PowerCase', 'SmartX MiniPhone', 'MobiTech Wireless Charger', 'SmartX EarBuds'], '电视和家庭影院系统': ['CineView 4K TV', 'SoundMax Home Theater', 'CineView 8K TV', 'SoundMax Soundbar', 'CineView OLED TV'], '游戏机和配件': ['GameSphere X', 'ProGamer Controller', 'GameSphere Y', 'ProGamer Racing Wheel', 'GameSphere VR Headset'], '音频设备': ['AudioPhonic Noise-Canceling Headphones', 'WaveSound Bluetooth Speaker', 'AudioPhonic True Wireless Earbuds', 'WaveSound Soundbar', 'AudioPhonic Turntable'], '相机和摄像机': ['FotoSnap DSLR Camera', 'ActionCam 4K', 'FotoSnap Mirrorless Camera', 'ZoomMaster Camcorder', 'FotoSnap Instant Camera']}
start do find_category_and_product_only
category_and_product_response= [{'category': '智能手机及配件', 'products': ['MobiTech PowerCase', 'SmartX MiniPhone', 'MobiTech Wireless Charger', 'SmartX EarBuds']}, {'category': '相机和摄像机', 'products': ['ActionCam 4K', 'FotoSnap Mirrorless Camera', 'ZoomMaster Camcorder', 'FotoSnap Instant Camera']}, {'category': '电视和家庭影院系统', 'products': ['CineView 4K TV', 'SoundMax Home Theater', 'CineView 8K TV', 'SoundMax Soundbar', 'CineView OLED TV']}]
start do Extract the list of products
category_and_product_list= [{'category': '智能手机及配件', 'products': ['MobiTech PowerCase', 'SmartX MiniPhone', 'MobiTech Wireless Charger', 'SmartX EarBuds']}, {'category': '相机和摄像机', 'products': ['ActionCam 4K', 'FotoSnap Mirrorless Camera', 'ZoomMaster Camcorder', 'FotoSnap Instant Camera']}, {'category': '电视和家庭影院系统', 'products': ['CineView 4K TV', 'SoundMax Home Theater', 'CineView 8K TV', 'SoundMax Soundbar', 'CineView OLED TV']}]
Step 2: Extracted list of products.
product_information= {
    "name": "MobiTech PowerCase",
    "category": "智能手机和配件",
    "brand": "MobiTech",
    "model_number": "MT-PC20",
    "warranty": "1年",
    "rating": 4.3,
    "features": [
        "5000mAh电池",
        "无线充电",
        "与SmartX ProPhone兼容"
    ],
    "description": "带有内置电池的保护壳,可延长使用时间。",
    "price": 59.99
}
{
    "name": "SmartX MiniPhone",
    "category": "智能手机和配件",
    "brand": "SmartX",
    "model_number": "SX-MP5",
    "warranty": "1年",
    "rating": 4.2,
    "features": [
        "4.7英寸显示屏",
        "64GB存储",
        "8MP相机",
        "4G"
    ],
    "description": "一款紧凑且价格实惠的智能手机,适用于基本任务。",
    "price": 399.99
}
{
    "name": "MobiTech Wireless Charger",
    "category": "智能手机和配件",
    "brand": "MobiTech",
    "model_number": "MT-WC10",
    "warranty": "1年",
    "rating": 4.5,
    "features": [
        "10W快速充电",
        "Qi兼容",
        "LED指示灯",
        "紧凑设计"
    ],
    "description": "一款便捷的无线充电器,为整洁的工作区提供便利。",
    "price": 29.99
}
{
    "name": "SmartX EarBuds",
    "category": "智能手机和配件",
    "brand": "SmartX",
    "model_number": "SX-EB20",
    "warranty": "1年",
    "rating": 4.4,
    "features": [
        "真无线",
        "蓝牙5.0",
        "触控控制",
        "24小时电池续航"
    ],
    "description": "通过这款舒适的耳机体验真正的无线自由。",
    "price": 99.99
}
{
    "name": "ActionCam 4K",
    "category": "相机和摄像机",
    "brand": "ActionCam",
    "model_number": "AC-4K",
    "warranty": "1年",
    "rating": 4.4,
    "features": [
        "4K视频",
        "防水",
        "图像稳定",
        "Wi-Fi"
    ],
    "description": "通过这款坚固而紧凑的4K运动相机记录您的冒险旅程。",
    "price": 299.99
}
{
    "name": "FotoSnap Mirrorless Camera",
    "category": "相机和摄像机",
    "brand": "FotoSnap",
    "model_number": "FS-ML100",
    "warranty": "1年",
    "rating": 4.6,
    "features": [
        "2010万像素传感器",
        "4K视频",
        "3英寸触摸屏",
        "可更换镜头"
    ],
    "description": "这款小巧轻便的无反相机具备先进功能。",
    "price": 799.99
}
{
    "name": "ZoomMaster Camcorder",
    "category": "相机和摄像机",
    "brand": "ZoomMaster",
    "model_number": "ZM-CM50",
    "warranty": "1年",
    "rating": 4.3,
    "features": [
        "1080p视频",
        "30倍光学变焦",
        "3英寸液晶屏",
        "图像稳定"
    ],
    "description": "通过这款易于使用的摄像机捕捉生活的瞬间。",
    "price": 249.99
}
{
    "name": "FotoSnap Instant Camera",
    "category": "相机和摄像机",
    "brand": "FotoSnap",
    "model_number": "FS-IC10",
    "warranty": "1年",
    "rating": 4.1,
    "features": [
        "即时打印",
        "内置闪光灯",
        "自拍镜",
        "电池供电"
    ],
    "description": "通过这款有趣便携的即时相机创造瞬间回忆。",
    "price": 69.99
}
{
    "name": "CineView 4K TV",
    "category": "电视和家庭影院系统",
    "brand": "CineView",
    "model_number": "CV-4K55",
    "warranty": "2年",
    "rating": 4.8,
    "features": [
        "55英寸显示屏",
        "4K分辨率",
        "HDR",
        "智能电视"
    ],
    "description": "一款具有生动色彩和智能功能的令人惊叹的4K电视。",
    "price": 599.99
}
{
    "name": "SoundMax Home Theater",
    "category": "电视和家庭影院系统",
    "brand": "SoundMax",
    "model_number": "SM-HT100",
    "warranty": "1年",
    "rating": 4.4,
    "features": [
        "5.1声道",
        "1000W输出",
        "无线低音炮",
        "蓝牙"
    ],
    "description": "一款强大的家庭影院系统,带来身临其境的音频体验。",
    "price": 399.99
}
{
    "name": "CineView 8K TV",
    "category": "电视和家庭影院系统",
    "brand": "CineView",
    "model_number": "CV-8K65",
    "warranty": "2年",
    "rating": 4.9,
    "features": [
        "65英寸显示屏",
        "8K分辨率",
        "HDR",
        "智能电视"
    ],
    "description": "通过这款令人惊叹的8K电视体验电视的未来。",
    "price": 2999.99
}
{
    "name": "SoundMax Soundbar",
    "category": "电视和家庭影院系统",
    "brand": "SoundMax",
    "model_number": "SM-SB50",
    "warranty": "1年",
    "rating": 4.3,
    "features": [
        "2.1声道",
        "300W输出",
        "无线低音炮",
        "蓝牙"
    ],
    "description": "通过这款时尚且功能强大的声音栏升级您的电视音频。",
    "price": 199.99
}
{
    "name": "CineView OLED TV",
    "category": "电视和家庭影院系统",
    "brand": "CineView",
    "model_number": "CV-OLED55",
    "warranty": "2年",
    "rating": 4.7,
    "features": [
        "55英寸显示屏",
        "4K分辨率",
        "HDR",
        "智能电视"
    ],
    "description": "通过这款OLED电视体验真正的黑色和生动色彩。",
    "price": 1499.99
}

Step 3: Looked up product information.
Step 4: Generated response to user question.
final_response= 当然,我很乐意为您介绍我们的产品。SmartX Pro phone是一款高端智能手机,具有先进的功能和性能。它配备了大屏幕、高像素相机、大内存和快速处理器。而Fotosnap DSLR相机则是一款专业级别的相机,具有高像素传感器、4K视频和可更换镜头等功能。至于我们的电视,我们有多种型号可供选择,包括4K和8K分辨率、HDR和智能电视等功能。您有什么具体的问题或需求吗?我可以为您提供更多详细信息。
Step 5: Response passed moderation check.
Step 6: Model evaluated the response.
evaluation_response= Y
Step 7: Model approved the response.
当然,我很乐意为您介绍我们的产品。SmartX Pro phone是一款高端智能手机,具有先进的功能和性能。它配备了大屏幕、高像素相机、大内存和快速处理器。而Fotosnap DSLR相机则是一款专业级别的相机,具有高像素传感器、4K视频和可更换镜头等功能。至于我们的电视,我们有多种型号可供选择,包括4K和8K分辨率、HDR和智能电视等功能。您有什么具体的问题或需求吗?我可以为您提供更多详细信息。

以ChatBot方式交流

以下使用panel构建一个简单的服务,通过对话框的方式进行交流。

def collect_messages(debug=True):
    user_input = inp.value_input
    if debug:
        print(f"User Input = {user_input}")
    if user_input == "":
        return
    inp.value = ''
    global context
    #response, context = process_user_message(user_input, context, utils.get_products_and_category(),debug=True)
    print("user_input=", user_input)
    print("context=", context)
    response, context = process_user_message(user_input, context, debug=debug)
    context.append({'role':'assistant', 'content':f"{response}"})
    panels.append(
        pn.Row('User:', pn.pane.Markdown(user_input, width=600)))
    panels.append(
        pn.Row('Assistant:', pn.pane.Markdown(response, width=600, style={'background-color': '#F6F6F6'})))

    return pn.Column(*panels)

panels = [] # collect display 

context = [ {'role':'system', 'content':"你是一个客户助理"} ]  

inp = pn.widgets.TextInput(placeholder='Enter text here…')
button_conversation = pn.widgets.Button(name="Service Assistant")

interactive_conversation = pn.bind(collect_messages, button_conversation)

dashboard = pn.Column(
    inp,
    pn.Row(button_conversation),
    pn.panel(interactive_conversation, loading_indicator=True, height=300),
)

客服助理.png

与ChatBot的交流结果如下:

User:

给我介绍下你们的相机

Assistant:

我们有多种不同类型的相机,包括数码相机、单反相机和无反相机。每种相机都有不同的功能和规格,您可以告诉我您需要相机用于什么目的,我可以为您提供更具体的信息。

User:

我想了解下Fotosnap DSLR

Assistant:

Fotosnap DSLR是一款功能强大的数码单反相机,具有24.2MP传感器、1080p视频、3英寸液晶屏和可更换镜头等功能。它适合那些想要更多控制和创造力的摄影师。您可以选择不同的镜头来适应不同的拍摄场景。这款相机的价格为599.99美元,我们还提供1年的保修服务。您是否还有其他问题需要了解?

User:

还想买一台手机,你们有哪些型号

Assistant:

很抱歉,我无法提供您所需的信息。我将为您转接到一位人工客服以获得进一步帮助。

User:

介绍下SmartX的产品

Assistant:

我们的SmartX品牌提供了多种电子产品,包括智能手机、平板电脑、笔记本电脑、智能手表和智能家居设备等。我们的产品都采用最新的技术和设计,以提供最佳的用户体验。您可以告诉我您需要哪种类型的产品,我可以为您提供更具体的信息。

User:

我想了解下SmartX ProPhone

Assistant:

SmartX ProPhone是一款功能强大的智能手机,具有6.1英寸显示屏、128GB存储、12MP双摄像头和5G等功能。它适合那些需要高速数据传输和大存储空间的用户。这款手机的价格为899.99美元,我们还提供1年的保修服务。您是否还有其他问题需要了解?
相关文章
|
3月前
|
SQL 人工智能 监控
SLS Copilot 实践:基于 SLS 灵活构建 LLM 应用的数据基础设施
本文将分享我们在构建 SLS SQL Copilot 过程中的工程实践,展示如何基于阿里云 SLS 打造一套完整的 LLM 应用数据基础设施。
706 56
|
3月前
|
人工智能 监控 测试技术
告别只会写提示词:构建生产级LLM系统的完整架构图​
本文系统梳理了从提示词到生产级LLM产品的八大核心能力:提示词工程、上下文工程、微调、RAG、智能体开发、部署、优化与可观测性,助你构建可落地、可迭代的AI产品体系。
537 51
|
2月前
|
缓存 物联网 PyTorch
使用TensorRT LLM构建和运行Qwen模型
本文档介绍如何在单GPU和单节点多GPU上使用TensorRT LLM构建和运行Qwen模型,涵盖模型转换、引擎构建、量化推理及LoRA微调等操作,并提供详细的代码示例与支持矩阵。
527 2
|
2月前
|
Web App开发 人工智能 自然语言处理
利用Playwright MCP与LLM构建复杂的工作流与AI智能体
本文介绍如何通过Playwright MCP与大语言模型(LLM)结合,构建智能AI代理与自动化工作流。Playwright MCP基于Model Context Protocol,打通LLM与浏览器自动化的能力,实现自然语言驱动的网页操作。涵盖环境配置、核心组件、智能任务规划、自适应执行及电商采集、自动化测试等实战应用,助力高效构建鲁棒性强、可扩展的AI自动化系统。
|
2月前
|
数据采集 存储 自然语言处理
113_数据收集:Common Crawl过滤与高质量LLM训练数据构建
在大型语言模型(LLM)的训练过程中,数据质量直接决定了模型的性能上限。即使拥有最先进的模型架构和训练算法,如果没有高质量的训练数据,也难以训练出优秀的语言模型。Common Crawl作为目前互联网上最大的公开网络爬虫数据集之一,为LLM训练提供了宝贵的资源。然而,从原始的Common Crawl数据中提取高质量的训练素材并非易事,需要经过严格的过滤和清洗。本文将全面探讨Common Crawl数据集的特性、过滤策略的设计原则、以及2025年最新的过滤技术,为构建高质量的LLM训练语料提供系统指导。
|
2月前
|
Prometheus 监控 Cloud Native
72_监控仪表盘:构建LLM开发环境的实时观测系统
在2025年的大模型(LLM)开发实践中,实时监控已成为确保模型训练效率和生产部署稳定性的关键环节。与传统软件开发不同,LLM项目面临着独特的监控挑战
|
2月前
|
监控 数据可视化 测试技术
16_LLM交互式调试:用Streamlit构建可视化工具
在大语言模型(LLM)的应用开发过程中,调试一直是一个复杂且具有挑战性的任务。传统的调试方法往往依赖于静态日志、断点调试和反复的命令行交互,这种方式在处理LLM这类黑盒模型时显得尤为低效。随着2025年LLM技术的普及和应用场景的多样化,开发人员迫切需要一种更加直观、高效的调试方式。
|
3月前
|
网络协议 NoSQL API
转转客服IM系统的WebSocket集群架构设计和部署方案
客服IM系统是转转自研的在线客服系统,是用户和转转客服沟通的重要工具,主要包括机器人客服、人工客服、会话分配、技能组管理等功能。在这套系统中,我们使用了很多开源框架和中间件,今天讲一下客服IM系统中WebSocket集群的的实践和应用。
228 0
|
5月前
|
前端开发 JavaScript Java
智能客服系统的技术栈解析-唯一客服系统技术架构优势
“唯一客服系统”采用 Vue.js 2.x + ElementUI 构建前端,实现响应式界面,支持多端适配;后端基于 Golang + Gin + GORM,具备高性能与高并发处理能力。系统支持私有化部署,提供灵活定制、AI 扩展能力,技术栈简洁易维护,兼顾开发者友好与企业级应用需求。
275 1
|
5月前
|
测试技术 Go
客服系统程序入口文件解析-唯一客服系统源码开发
该代码为 Go 语言编写的客服系统命令行程序入口,结构清晰,使用 cmd 包启动业务逻辑,可能基于 cobra 框架实现,具备良好可扩展性与可维护性,适用于服务启动与管理。
238 69