使用 Python 構建聊天機器人


聊天機器人是一種旨在透過文字或語音與人類使用者模擬對話的計算機程式。它使用人工智慧和自然語言處理技術來幫助理解和解釋使用者的訊息,並提供相關的回覆。在本文中,我們將瞭解如何藉助 Python 建立聊天機器人。

像 ChatGPT 這樣的聊天機器人自 2022 年底以來變得流行起來,並且在不同領域的民眾中有著廣泛的用例。聊天機器人也整合到像 Swiggy 和 Zomato 這樣的移動應用程式中,以更快地解決客戶投訴。

聊天機器人有多種型別,如下所示

  • 基於規則的聊天機器人 - 它們被設計為根據預定義的一組規則或決策樹來響應使用者輸入。它們可以非常簡單或複雜,主要用於處理基本的使用者資訊請求。

  • 基於檢索的聊天機器人 - 它們利用自然語言處理來分析使用者輸入,然後將其與包含回覆的預先存在的資料庫進行匹配。然後,聊天機器人使用邏輯介面卡選擇最佳匹配項並將其呈現給使用者。

  • 生成式聊天機器人 - 它們利用人工智慧和機器學習演算法來生成對使用者輸入的獨特回覆。它們非常先進,能夠從使用者互動中學習以改進其回覆。

  • 混合聊天機器人 - 它們結合了基於規則和生成式的方法,以提供對使用者輸入的最佳回覆。它們通常包括其他功能,如情感分析、上下文感知以及個性化推薦。

使用 Python 構建聊天機器人的步驟

構建聊天機器人涉及多個步驟。以下是此過程的概述

1. 定義目的和範圍

在這裡,我們決定我們的聊天機器人需要完成什麼。它的目標受眾是誰?我們的聊天機器人應該使用什麼樣的語言和語氣?

2. 聊天機器人框架

Python 提供了各種框架,如 ChatterBot、NLTK、RASA 等等來幫助建立聊天機器人,所有這些框架都有其自身的優缺點。最佳選擇取決於您的需求。

3. 收集和預處理資料

訓練聊天機器人需要對諸如對話日誌、客戶支援電子郵件等資料進行清理,然後將其轉換為聊天機器人框架可以從中受益的格式。

4. 訓練聊天機器人

資料預處理完成後,它可以用於訓練聊天機器人,具體取決於所使用的框架和用例,您可以選擇如何建立知識庫。

5. 與訊息傳遞平臺整合

建立的聊天機器人本身沒有任何用途,必須為其提供使用者介面並將其連線到 Facebook Messenger、Telegram 或 WhatsApp 等平臺。每個平臺都有自己的一套 API 和文件,有助於連線此聊天機器人。像 Swiggy 這樣的聊天機器人連線到應用程式本身。

6. 測試您的聊天機器人

在最終部署聊天機器人並將其提供給使用者之前,應手動或藉助自動化測試對其進行測試。應格外小心,以確保聊天機器人不會提供可能導致法律問題的回覆。

7. 部署您的聊天機器人

一旦測試人員對聊天機器人感到滿意,就可以將其部署到伺服器或雲平臺。配置環境、設定 Webhook 或使用聊天機器人託管服務是此步驟的常見部分。

8. 監控和改進您的聊天機器人

聊天機器人部署後,必須監控其效能並考慮使用者反饋。Google Analytics 或 Mixpanel 等分析工具有助於跟蹤使用者參與度、留存率和滿意度等常見指標。

在繼續使用 Python 建立聊天機器人之前,我們必須使用以下命令安裝 chatterbot 庫

pip install chatterbot

以及

pip install chatterbot-corpus

問候聊天機器人

這是一個簡單的聊天機器人,它利用來自 english.greetings 和 english.conversations 語料庫的一些預先存在的對話資料來訓練機器人。藉助此程式碼,機器人可以回答基本問題。當然,可以透過使用更多資料訓練它並實現其他功能來自定義和改進聊天機器人。

訓練完成後,聊天機器人執行一個無限的 while 迴圈,以與使用者建立來回對話。當“end”列表中的任何字串被使用者作為回覆給出時,迴圈終止。

示例

from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer

bot = ChatBot('TPTBot')
trainer = ChatterBotCorpusTrainer(bot)

# if user enters any of the list elements, program is terminated
end=["q","exit", "end", "stop", "quit"]
trainer.train('chatterbot.corpus.english.greetings', 'chatterbot.corpus.english.conversations')
while True:
  # take user input
    user_input = input("You: ")    
    if user_input in end:
      break
    else:
      response = bot.get_response(user_input)
      print("TPTBot: ", response)

輸出

Training greetings.yml: [########         ] 40%
[nltk_data] Downloading package stopwords to /root/nltk_data...
[nltk_data]   Package stopwords is already up-to-date!
[nltk_data] Downloading package averaged_perceptron_tagger to
[nltk_data]    /root/nltk_data...
[nltk_data]   Package averaged_perceptron_tagger is already up-to-
[nltk_data]      date!
Training greetings.yml: [####################] 100%
Training conversations.yml: [####################] 100%
You: Hi
TPTBot:  Hello
You: How are you?
TPTBot:  I am doing well.
You: end

心理治療聊天機器人

心理治療聊天機器人是人工智慧驅動的工具,可幫助心理學家、心理治療師和其他醫療保健提供者改善可能正在或正在應對精神障礙、壓力或創傷的患者的福祉。線上心理治療聊天機器人還可以使那些不習慣面對面治療或經濟拮据的人受益,因為即時治療可能很昂貴,而且通常不受保險覆蓋。

在這裡,我們使用邏輯介面卡來確定聊天機器人如何選擇對給定輸入語句的響應的邏輯。這裡使用的兩個邏輯介面卡是 BestMatch,它有助於根據與使用者輸入的相似性選擇最佳響應,以及 MathematicalEvaluation,它允許機器人處理與數學相關的查詢。

還指定了兩個預處理器,用於在將輸入傳遞到邏輯介面卡之前清理輸入。然後,我們使用包含與治療相關資料的語料庫來訓練聊天機器人。對於此示例,我們使用“chatterbot.corpus.english”語料庫和一個自定義的“therapy_corpus.yml”檔案,該檔案包含與治療相關的回覆,可在此處獲取。

請確保下載“therapy_corpus.yml”檔案,如果它不在與指令碼相同的資料夾中,請在程式碼中指定路徑。

示例

from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer

chatbot = ChatBot('TherapyBot',
   logic_adapters=[
      'chatterbot.logic.BestMatch',
      'chatterbot.logic.MathematicalEvaluation'
   ],
   preprocessors=[
   'chatterbot.preprocessors.clean_whitespace',
   'chatterbot.preprocessors.unescape_html'
])

trainer = ChatterBotCorpusTrainer(chatbot)
trainer.train('chatterbot.corpus.english')

# therapy_corpus.yml will be created seperately
trainer.train('/content/therapy_corpus.yml')
end=["q","exit", "end", "stop", "quit"]
while True:
    message = input('You: ')
    if message in end:
      break
    else:
      response = chatbot.get_response(message)
      print('TherapyBot:', response)

輸出

Training ai.yml: [##              ] 10%
[nltk_data] Downloading package stopwords to /root/nltk_data...
[nltk_data]   Package stopwords is already up-to-date!
[nltk_data] Downloading package averaged_perceptron_tagger to
[nltk_data]    /root/nltk_data...
[nltk_data]   Package averaged_perceptron_tagger is already up-to-
[nltk_data]      date!
Training ai.yml: [####################] 100%
Training botprofile.yml: [####################] 100%
Training computers.yml: [####################] 100%
Training conversations.yml: [####################] 100%
Training emotion.yml: [####################] 100%
Training food.yml: [####################] 100%
Training gossip.yml: [####################] 100%
Training greetings.yml: [####################] 100%
Training health.yml: [####################] 100%
Training history.yml: [####################] 100%
Training humor.yml: [####################] 100%
Training literature.yml: [####################] 100%
Training money.yml: [####################] 100%
Training movies.yml: [####################] 100%
Training politics.yml: [####################] 100%
Training psychology.yml: [####################] 100%
Training science.yml: [####################] 100%
Training sports.yml: [####################] 100%
Training trivia.yml: [####################] 100%
Training therapy_corpus.yml: [####################] 100%
You: Hi
TherapyBot: Hello
You: I'm feeling really stressed out lately
TherapyBot: I'm sorry to hear that. Can you tell me more about what's been going on?
You: nothing
TherapyBot: Or something
You: end

結論

聊天機器人是一種非常有用的工具,其用例範圍從自動客戶投訴解決到家庭自動化。Alexa(一個基於語音的聊天機器人)和 ChatGPT(或簡稱為 ChatGPT)是當今世界中常見的例子。Python 非常流行用於構建聊天機器人,並提供各種庫。總的來說,聊天機器人有可能徹底改變企業和組織與其使用者互動的方式。它們不僅提供 24/7 支援,還提供個性化推薦。有各種各樣的聊天機器人可用,選擇取決於用例。

更新於: 2023 年 10 月 4 日

349 次瀏覽

啟動您的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.