支持私有化部署
AI知识库

53AI知识库

学习大模型的前沿技术与行业应用场景


基于 GPT与 lLamaIndex 构建客服聊天机器人

发布日期:2025-04-16 15:39:42 浏览次数: 1547 作者:测试窝
推荐语

利用GPT-3.5和lLamaIndex打造企业级客服聊天机器人,轻松管理私域数据。

核心内容:
1. GPT-3.5模型介绍与企业私域数据挑战
2. 项目设置与lLamaIndex框架安装
3. 创建个人知识库,实现聊天机器人定制化响应

杨芳贤
53A创始人/腾讯云(TVP)最具价值专家

在本教程中,我们将使用 OpenAI API 提供的 GPT-3.5。GPT-3.5 是一个机器学习模型,如同 OpenAI 打造的超级智能计算机伙伴。它通过互联网上的海量数据训练而成,能够进行对话、回答问题,并协助完成各类语言任务。

但关键问题来了:未经改造的GPT-3.5能理解企业私域数据吗?

答案是否定的,因GPT 模型仅训练于截至 2021 年的公开数据。这正是我们需要像 lLamaIndex 这类开源框架的原因!这些框架帮助你将内部数据源与 GPT-3.5 连接,使聊天机器人能基于常规 ChatGPT 未知的数据生成定制化响应 。

很酷吧?让我们开始吧!

项目设置

首先,我将指导你如何为聊天机器人设置项目。

通过运行以下终端代码创建项目文件夹和 Python 虚拟环境:

mkdir customer-support-chatbot
cd customer-support-chatbot
python3 -m venv venv
source venv/bin/activate

终端现在应显示类似以下内容:

(venv)

安装依赖

运行下面的代码安装lLamaIndex:

pip install llama-index

注意我们不需要单独安装 openai 库,因为 lLamaIndex 已在底层提供了调用 OpenAI API 的封装器。

创建新的 main.py 文件——作为聊天机器人的入口点,以及 chatbot.py——包含聊天机器人的具体实现。

touch main.py chatbot.py

设置个人知识库

新建一个 data文件夹,并在其中创建包含 MadeUpCompany 虚构数据的data.txt文件:

mkdir data
cd data
touch data.txt

该文件将包含聊天机器人生成响应所依赖的数据。幸运的是,ChatGPT 已为 MadeUpCompany 准备了虚构信息 , 将以下文本粘贴至 data.txt

About MadeUpCompanyMadeUpCompany is a pioneering technology firm founded in 2010, specializing in cloud computing, data analytics, and machine learning. Our headquarters is based in San Francisco, California, with satellite offices spread across New York, London, and Tokyo. We are committed to offering state-of-the-art solutions that help businesses and individuals achieve their full potential. With a diverse team of experts from various industries, we strive to redefine the boundaries of innovation and efficiency.Products and ServicesWe offer a suite of services ranging from cloud storage solutions, data analytics platforms, to custom machine learning models tailored for specific business needs. Our most popular product is CloudMate, a cloud storage solution designed for businesses of all sizes. It offers seamless data migration, top-tier security protocols, and an easy-to-use interface. 
Our data analytics service, DataWiz, helps companies turn raw data into actionable insights using advanced algorithms.PricingWe have a variety of pricing options tailored to different needs. Our basic cloud storage package starts at $9.99 per month, with premium plans offering more storage and functionalities. We also provide enterprise solutions on a case-by-case basis, so it’s best to consult with our sales team for customized pricing.
Technical SupportOur customer support team is available 24/7 to assist with any technical issues. We offer multiple channels for support including live chat, email, and a toll-free number. Most issues are typically resolved within 24 hours. We also have an extensive FAQ section on our website and a community forum for peer support.Security and ComplianceMadeUpCompany places the utmost importance on security and compliance. All our products are GDPR compliant and adhere to the highest security standards, including end-to-end encryption and multi-factor authentication.Account ManagementCustomers can easily manage their accounts through our online portal, which allows you to upgrade your service, view billing history, and manage users in your organization. If you encounter any issues or have questions about your account, our account management team is available weekdays from 9 AM to 6 PM.Refund and Cancellation Policy
We offer a 30-day money-back guarantee on all our products. If you're not satisfied for any reason, you can request a full refund within the first 30 days of your purchase. After that, you can still cancel your service at any time, but a prorated refund will be issued based on the remaining term of your subscription.Upcoming FeaturesWe’re constantly working to improve our services and offer new features. 
Keep an eye out for updates on machine learning functionalities in DataWiz and more collaborative tools in CloudMate in the upcoming quarters.Your customer support staff can use these paragraphs to build their responses to customer inquiries, providing both detailed and precise information to address various questions.

最后,返回到包含 main.py 的 customer-support-chatbot 目录,并将OpenAI API 密钥设置为环境变量。在终端中粘贴以下内容(请替换为API 密钥):

export OPENAI_API_KEY="your-api-key-here"

环境配置就绪,进入代码实战!

基于 lLamaIndex 构建聊天机器人

首先,我们需要将 data.txt 中的文本分块并索引为 GPT-3.5 可读的格式。你可能会疑惑:什么是'可读格式'?

GPT-3.5 存在称为上下文限制的特性,指模型单次能'看到'或处理的文本量上限。这类似于模型的短期记忆。若输入过长段落或复杂对话历史,模型可能达到限制而无法有效处理。触及限制时,必须缩短文本以保证模型正常响应。

此外,若向 GPT-3.5 输入过多文本,其表现会显著下降——就像人类在冗长故事中容易分心。这正是lLamaIndex 的价值所在:它将大规模文本分解为 GPT-3.5 可处理的分块。

只需几行代码,我们就能使用 lLamaIndex 构建聊天机器人。从对 data.txt 的文本分块到调用 OpenAI API 的所有操作,均由 lLamaIndex 自动处理。将以下代码粘贴至 chatbot.py 文件中:

from llama_index import VectorStoreIndex, SimpleDirectoryReader

documents = SimpleDirectoryReader('data').load_data()
index = VectorStoreIndex.from_documents(documents)
query_engine = index.as_query_engine()

def query(user_input):  
    return query_engine.query(user_input).response

下面这些粘贴到 main.py 

from chatbot import query
while True:  
    user_input = input("Enter your question: ")  
    response = query(user_input)  
    print("Bot response:", response)

接下来运行测试:

python3 main.py

提示:可将 data/data.txt 替换为你自己的知识库文件

性能优化方案

你可能会遇到聊天机器人在处理某些特定问题/输入时表现不如预期的情况。幸运的是,有多种方法可以优化聊天机器人。

调整数据分块大小

聊天机器人的输出质量直接受文本分块大小的影响(向下滚动查看详细原理说明)。

在 chatbot.py 中,通过向 VectorStoreIndex 添加 service_context = ServiceContext.from_defaults(chunk_size=1000) 来修改分块大小:

from llama_index import VectorStoreIndex, SimpleDirectoryReader  
from llama_index import ServiceContext  

service_context = ServiceContext.from_defaults(chunk_size=1000)  
documents = SimpleDirectoryReader('data').load_data()  
index = VectorStoreIndex.from_documents(documents)  
query_engine = index.as_query_engine()  

def query(user_input):  
    return query_engine.query(user_input).response  

通过调整 size 参数找到最佳值。

为 GPT-3.5 提供更多上下文

根据数据特性,可能需要为 GPT-3.5 提供更少/更多文本块。通过在 chatbot.py 中设置 query_engine = index.as_query_engine(similarity_top_k=5) 实现:

from llama_index import VectorStoreIndex, SimpleDirectoryReader  
from llama_index import ServiceContext  

service_context = ServiceContext.from_defaults(chunk_size=1000)  
documents = SimpleDirectoryReader('data').load_data()  
index = VectorStoreIndex.from_documents(documents)  
query_engine = index.as_query_engine(similarity_top_k=5)  

def query(user_input):  
    return query_engine.query(user_input).response  

聊天机器人评测指南

你可能已经陷入这样的困境:每次调整参数(如修改检索文本块数量)后,都需要手动运行 main.py,反复输入相同问题,等待5秒观察结果是否改善这种低效的方式是否似曾相识?

当需要同时验证多个不同查询的响应质量时,问题会变得更糟。可以阅读这篇指南在 20 分钟内自建评估框架,但如果不想重复造轮子,建议使用 DeepEval 等开源工具。它能自动化评估流程,解放人工检查。

安装 DeepEval

pip install deepeval

创建测试文件

touch test_chatbot.py

粘贴下面代码:

import pytest
from chatbot import query
from deepeval.metrics import HallucinationMetric
from deepeval.test_case import LLMTestCase
from deepeval import assert_test

def test_chatbot():  
     hallucination_metric = FactualConsistencyMetric(minimum_score=0.7)
    test_case = LLMTestCase(
      input="What does your company do?",
      actual_output=query(input), 
    context=[
    "Our company specializes in cloud computing, data analytics, and machine learning. We offer a range of services including cloud storage solutions, data analytics platforms, and custom machine learning models."
        ]
   )  
    assert_test(test_case, [hallucination_metric])

执行测试

deepeval test run test_chatbot.py

你的测试应该已通过!让我们来解析一下整个过程:

  • • input 变量模拟用户输入

  • • actual_output 是聊天机器人基于该查询生成的响应

  • • context 包含知识库中的相关信息

  • • HallucinationMetric(minimum_score=0.7) 是 DeepEval 提供的开箱即用指标,用于评估聊天机器人输出与所提供上下文的事实一致性

评分范围为 0-1,其中 minimum_score=0.7 决定测试是否通过。

添加更多测试用例,避免因破坏性变更(breaking changes)修复聊天机器人而浪费时间

聊天机器人底层原理

我们构建的聊天机器人实际上依赖于 检索增强生成(Retrieval Augmented Generation, RAG) 架构。该架构通过让 GPT-3.5 从外部数据源(本例中为 data.txt)获取最新或特定信息,显著提升模型效能。当用户提问时,系统能据此生成更及时、更相关的响应。

在前两个章节中,我们探讨了调整两个关键参数——文本块大小(text chunk size)与使用的文本块数量(number of text chunks used)——如何影响从 GPT-3.5 获得的应答质量。这是因为当用户向聊天机器人提问时:

  1. 1. lLamaIndex 从 data.txt 中检索最相关的文本块

  2. 2. GPT-3.5 基于这些文本块生成数据增强(data augmented)的响应

总结

通过本文,你已掌握:

  • • OpenAI GPT-3.5 是什么

  • • 如何使用 LlamaIndex 基于自有数据构建简单聊天机器人

  • • 如何优化聊天机器人的响应质量

  • • 如何通过 DeepEval 评估聊天机器人性能

  • • 检索增强生成(RAG)的原理与工作流程

本教程演示了如何利用 lLamaIndex 和 GPT-3.5 构建生产级聊天机器人。通过 lLamaIndex,可以创建适用于以下场景的定制化对话系统:

53AI,企业落地大模型首选服务商

产品:场景落地咨询+大模型应用平台+行业解决方案

承诺:免费场景POC验证,效果验证后签署服务协议。零风险落地应用大模型,已交付160+中大型企业

联系我们

售前咨询
186 6662 7370
预约演示
185 8882 0121

微信扫码

添加专属顾问

回到顶部

加载中...

扫码咨询