首页 > 其他分享 >平时有使用过AI服务吗——AI人工服务案例助力你了解底层代码逻辑!

平时有使用过AI服务吗——AI人工服务案例助力你了解底层代码逻辑!

时间:2024-11-11 19:19:44浏览次数:3  
标签:助力 服务 sentiment AI text order user message response

让我们详细说明这个智能客服系统包含的内容,并提供完整的代码示例。

我们将涵盖以下几个方面:

  1. 智能客服(使用Rasa)
  2. 情感分析(使用Hugging Face Transformers)
  3. 自然语言生成(NLG)(使用Hugging Face Transformers)
  4. 语音识别(ASR)(使用SpeechRecognition)
  5. 语音合成(TTS)(使用gTTS)
  6. 用户行为分析(使用Pandas和Matplotlib)

1. 智能客服(使用Rasa)

安装Rasa
pip install rasa
创建Rasa项目
rasa init --no-prompt
编辑NLU数据

编辑 data/nlu.yml 文件,添加一些训练数据:

version: "2.0"
nlu:
  - intent: greet
    examples: |
      - hi
      - hello
      - hey
  - intent: goodbye
    examples: |
      - bye
      - goodbye
      - see you later
  - intent: ask_order_status
    examples: |
      - Where is my order?
      - What's the status of my order?
      - Has my order been shipped?
  - intent: express_disappointment
    examples: |
      - I'm really disappointed with the service.
      - The delivery was late, and the product was damaged.
      - The customer support is terrible.
  - intent: express_satisfaction
    examples: |
      - I love the product!
      - It works perfectly and arrived on time.
      - The customer support is excellent.
编辑Domain文件

编辑 domain.yml 文件,定义意图、响应和动作:

version: "2.0"
intents:
  - greet
  - goodbye
  - ask_order_status
  - express_disappointment
  - express_satisfaction
responses:
  utter_greet:
    - text: "Hello! How can I assist you today?"
  utter_goodbye:
    - text: "Goodbye! Have a great day!"
  utter_ask_order_status:
    - text: "Let me check the status of your order. Could you please provide me with your order number?"
  utter_express_disappointment:
    - text: "I'm really sorry to hear that. We will look into it right away."
  utter_express_satisfaction:
    - text: "Thank you for your positive feedback! We strive to provide the best service possible."
编辑Actions文件

编辑 actions/actions.py 文件,添加自定义动作:

from typing import Any, Text, Dict, List
from rasa_sdk import Action, Tracker
from rasa_sdk.executor import CollectingDispatcher
from transformers import pipeline
import speech_recognition as sr
from gtts import gTTS
import os
import pandas as pd
import matplotlib.pyplot as plt

# 创建情感分析器
sentiment_analyzer = pipeline("sentiment-analysis")

# 创建NLG模型
nlg_model = pipeline("text-generation", model="distilgpt2")

# 创建语音识别器
recognizer = sr.Recognizer()

def transcribe_audio(file_path):
    with sr.AudioFile(file_path) as source:
        audio_data = recognizer.record(source)
        text = recognizer.recognize_google(audio_data)
        return text

def text_to_speech(text, output_file):
    tts = gTTS(text=text, lang='en')
    tts.save(output_file)

class ActionCheckOrderStatus(Action):
    def name(self) -> Text:
        return "action_check_order_status"

    def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
        # 获取用户的最新消息
        user_message = tracker.latest_message['text']
        
        # 进行情感分析
        sentiment_result = sentiment_analyzer(user_message)[0]
        sentiment_label = sentiment_result['label']
        sentiment_score = sentiment_result['score']

        # 使用NLG生成回复
        prompt = f"Customer: {user_message} Assistant:"
        response = generate_response(prompt)

        # 根据情感提供不同的响应
        if sentiment_label == 'NEGATIVE' and sentiment_score > 0.8:
            response = "I'm really sorry to hear that. " + response
        else:
            response = "Let me check the status of your order. " + response

        # 将文本转换为语音
        output_file = "response.mp3"
        text_to_speech(response, output_file)

        # 发送回复给用户
        dispatcher.utter_message(text=response)
        dispatcher.utter_message(text=f"Please listen to the audio response: {output_file}")

        return []

def generate_response(prompt):
    response = nlg_model(prompt, max_length=50, num_return_sequences=1)
    return response[0]['generated_text']

class ActionExpressDisappointment(Action):
    def name(self) -> Text:
        return "action_express_disappointment"

    def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
        # 获取用户的最新消息
        user_message = tracker.latest_message['text']
        
        # 进行情感分析
        sentiment_result = sentiment_analyzer(user_message)[0]
        sentiment_label = sentiment_result['label']
        sentiment_score = sentiment_result['score']

        # 使用NLG生成回复
        prompt = f"Customer: {user_message} Assistant:"
        response = generate_response(prompt)

        # 根据情感提供不同的响应
        if sentiment_label == 'NEGATIVE' and sentiment_score > 0.8:
            response = "I'm really sorry to hear that. " + response

        # 将文本转换为语音
        output_file = "response.mp3"
        text_to_speech(response, output_file)

        # 发送回复给用户
        dispatcher.utter_message(text=response)
        dispatcher.utter_message(text=f"Please listen to the audio response: {output_file}")

        return []

class ActionExpressSatisfaction(Action):
    def name(self) -> Text:
        return "action_express_satisfaction"

    def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
        # 获取用户的最新消息
        user_message = tracker.latest_message['text']
        
        # 进行情感分析
        sentiment_result = sentiment_analyzer(user_message)[0]
        sentiment_label = sentiment_result['label']
        sentiment_score = sentiment_result['score']

        # 使用NLG生成回复
        prompt = f"Customer: {user_message} Assistant:"
        response = generate_response(prompt)

        # 根据情感提供不同的响应
        if sentiment_label == 'POSITIVE' and sentiment_score > 0.8:
            response = "Thank you for your positive feedback! " + response

        # 将文本转换为语音
        output_file = "response.mp3"
        text_to_speech(response, output_file)

        # 发送回复给用户
        dispatcher.utter_message(text=response)
        dispatcher.utter_message(text=f"Please listen to the audio response: {output_file}")

        return []

# 示例用户行为分析
def analyze_user_behavior():
    data = pd.read_csv('user_interactions.csv')
    interaction_counts = data['user_id'].value_counts()
    plt.figure(figsize=(10, 6))
    interaction_counts.plot(kind='bar')
    plt.xlabel('User ID')
    plt.ylabel('Interaction Count')
    plt.title('User Interaction Frequency')
    plt.show()

# 调用用户行为分析函数
# analyze_user_behavior()

2. 训练模型

rasa train

3. 运行聊天机器人

rasa run

4. 测试智能客服

你可以使用Rasa的命令行界面来测试智能客服:

rasa shell

5. 用户行为分析

假设你有一个包含用户交互数据的CSV文件 user_interactions.csv,格式如下:

user_id,interaction_time,interaction_type
1,2023-10-01 10:00:00,message
2,2023-10-01 10:05:00,message
1,2023-10-01 10:10:00,message
3,2023-10-01 10:15:00,message

你可以调用 analyze_user_behavior 函数来分析用户行为:

# 在 actions.py 中调用
analyze_user_behavior()

通过以上步骤,我们构建了一个包含智能客服、情感分析、自然语言生成、语音识别、语音合成和用户行为分析的完整系统。每个部分都有详细的代码示例和说明。

客户服务

智能客服
  • 英文表达:Smart Customer Service
  • 详细描述:通过聊天机器人和语音助手提供24小时在线客户服务。这些智能工具可以自动回答常见问题,处理简单请求,并在必要时转接至人工客服。
  • 示例句子:Our smart customer service system is available 24/7 to assist you with any questions or issues you may have.(我们的智能客服系统全天候为您提供帮助,解答您的任何问题或处理您的任何问题。)
情感分析
  • 英文表达:Sentiment Analysis
  • 详细描述:通过分析客户反馈,识别客户的情绪状态,从而及时发现并解决问题。情感分析可以帮助企业了解客户的满意度,优化产品和服务。
  • 示例句子:We use sentiment analysis to monitor customer feedback and ensure we address any concerns promptly.(我们使用情感分析来监控客户反馈,确保及时解决任何问题。)

示例对话

客户:I've been having trouble with my order. It hasn't arrived yet, and I haven't received any updates.

智能客服:I'm sorry to hear that. Let me check the status of your order for you. Could you please provide me with your order number?

客户:Sure, it's 123456789.

智能客服:Thank you. I see that there has been a delay in shipping due to recent weather conditions. Your order should arrive within the next 2-3 days. Is there anything else I can assist you with?

客户:That's good to know. Thanks for the update.

智能客服:You're welcome! If you have any other questions or concerns, feel free to contact us anytime.

情感分析应用

客户反馈:I'm really disappointed with the service. The delivery was late, and the product was damaged.

情感分析结果:Negative sentiment detected.

客服团队:We need to address this issue immediately. Let's reach out to the customer and offer a solution.

标签:助力,服务,sentiment,AI,text,order,user,message,response
From: https://blog.csdn.net/speaking_me/article/details/143692997

相关文章

  • GPU云服务器的使用场景和功能有哪些?
    摘要:本文将全面介绍GPU云服务器的特点、优势及应用场景。并针对不同的使用需求,给出典型配置方案示例。包括:深度学习、高性能计算、3D渲染、区块链矿机、游戏直播等多种场景,旨在帮助用户深入理解GPU云服务器的功能,并快速上手应用。一、GPU云服务器简介1、GPU云服务器定义GPU......
  • AI智能直播话术功能设计开发!
    AI智能直播,作为当今直播行业的一大创新趋势,正逐步改变着我们的直播体验,随着人工智能技术的不断进步,AI智能直播话术功能的设计与开发成为了众多开发者关注的焦点。这一功能旨在通过智能算法,为直播内容提供更加丰富、多样且个性化的互动话术,从而提升直播的趣味性和观众的参与度......
  • 使用LangGraph构建复杂AI工作流:子图架构详解
    一、子图架构概述子图(Subgraph)是LangGraph中一个强大的特性,它允许我们将复杂的工作流程分解成更小、更易管理的组件。通过子图,我们可以实现模块化设计,提高代码的可重用性和可维护性。1.1子图的基本概念子图本质上是一个完整的图结构,可以作为更大图结构中的一个节点使用。它具......
  • swoole,websocket服务器(协程风格)--进阶篇
        swoole的websocket服务器(协程风格)示例真不算友善,从头了解到尾,那还好,但是谁有那么多时间从头到尾了解。示例不够针对性,写websocket就该单独写websocket的东西,偏偏又加上http的东西。这里我来解读一下websocket服务器(协程风格)示例<?php  useSwoole\Http\Reque......
  • AI数字人克隆分身开源源码震撼上线!
    第一:丰富公模系统内置几十款数字人公共形象模板,无需克隆即可直接使用,快速生成专业主播出镜的高逼真数字人口播视频。第二:形象克隆只需自助在线上传一段30秒的视频,即可快速1:1克隆属于你的个性化数字人分身。双模式可选:目前我们的数字人小程序软件自带两种形象克隆模式可......
  • AI大模型实现图片OCR识别
    AI大模型实现图片OCR识别背景    OCR(OpticalCharacterRecognition,光学字符识别)是一种将图像中的文字转换为机器编码文本的技术。这项技术可以自动读取纸质文档上的文字信息,并将其转换成电子格式,便于编辑、存储和检索。OCR技术在很多领域都有广泛应用,比如数据录入、文献数......
  • springboot 社区便民服务管理系统的设计与实现【附源码】
    博主介绍:✌CSDN新星计划导师、Java领域优质创作者、掘金/华为云/阿里云/InfoQ等平台优质作者、专注于Java技术领域和学生毕业项目实战,高校老师/讲师/同行前辈交流✌技术范围:SpringBoot、Vue、SSM、HTML、Jsp、PHP、Nodejs、Python、爬虫、数据可视化、小程序、安卓app、大数......
  • springboot 社区便民服务管理系统的设计与实现【附源码】
    博主介绍:✌CSDN新星计划导师、Java领域优质创作者、掘金/华为云/阿里云/InfoQ等平台优质作者、专注于Java技术领域和学生毕业项目实战,高校老师/讲师/同行前辈交流✌技术范围:SpringBoot、Vue、SSM、HTML、Jsp、PHP、Nodejs、Python、爬虫、数据可视化、小程序、安卓app、大数......
  • springboot 社区便民服务管理系统的设计与实现【附源码】
    博主介绍:✌CSDN新星计划导师、Java领域优质创作者、掘金/华为云/阿里云/InfoQ等平台优质作者、专注于Java技术领域和学生毕业项目实战,高校老师/讲师/同行前辈交流✌技术范围:SpringBoot、Vue、SSM、HTML、Jsp、PHP、Nodejs、Python、爬虫、数据可视化、小程序、安卓app、大数......
  • 安装influxdb2(解决 https://repos.influxdata.com/stable//main/repodata/repomd.xml:
    influxdb分1.x和2.x不要搞错cat/etc/os-release获取操作系统https://docs.influxdata.com/influxdb/v2/install/?t=Linux1.官网安装#UbuntuandDebian#AddtheInfluxDatakeytoverifydownloadsandaddtherepositorycurl--silent--location-O\https://rep......