ChatGPT – 建立聊天機器人



如今,幾乎每個應用程式中都能找到聊天機器人。這是因為它們允許使用者進行互動式和動態的對話。藉助OpenAI強大的語言模型,例如GPT-3.5,開發者可以建立能夠理解和生成類似人類文字的複雜聊天機器人。

在本章中,我們將探討如何使用OpenAI API和Python程式語言建立一個聊天機器人。因此,讓我們開始一步一步地實現聊天機器人。

步驟1:設定您的OpenAI帳戶

首先,您需要在OpenAI平臺上設定一個帳戶並獲取您的API憑據。訪問OpenAI網站,註冊並按照說明生成API金鑰。

始終建議您確保API金鑰的安全,因為它將用於驗證對OpenAI API的請求。

步驟2:安裝OpenAI Python庫

現在,要與OpenAI API互動,您需要安裝OpenAI Python庫。在您的終端或命令提示符中執行以下命令:

pip install openai

此命令會將OpenAI庫安裝到您的Python環境中。

步驟3:匯入所需的庫

現在,在您的Python指令碼中,您需要匯入OpenAI庫以及實現可能需要的任何其他庫。對於此實現,我們只需要OpenAI庫。

以下命令匯入OpenAI庫:

import openai

步驟4:配置OpenAI API金鑰

接下來,需要在Python指令碼中設定OpenAI金鑰以驗證您的請求。在下面的命令中,將“your-api-key-goes-here”替換為您從OpenAI獲得的實際API金鑰。

# Set your OpenAI API key
openai.api_key = 'your-api-key-goes-here'

步驟5:定義初始提示

配置OpenAI API後,我們需要定義一個初始提示變數,該變數將用於啟動與聊天機器人的對話。例如,我們為我們的實現目的定義以下提示:

# Define the initial prompt
prompt = "You: "

您可以嘗試不同的提示,例如您的姓名或暱稱。

步驟6:實現聊天迴圈

接下來,我們需要建立一個迴圈來模擬與聊天機器人的對話。它將允許使用者輸入訊息並將它們新增到提示中。如果您想退出迴圈,可以使用預定義的命令,例如“exit”。檢視下面的程式碼:

while True:
   user_input = input("You: ")

   # Check for exit command
   if user_input.lower() == 'exit':
      print("Chatbot: Goodbye!")
      break

   # Update the prompt with user input
   prompt += user_input + "\n"

步驟7:生成回覆

現在,使用OpenAI API根據使用者的輸入生成回覆。為此,我們需要在迴圈中向API發出請求,如下所示:

# Generate responses using the OpenAI API
response = openai.Completion.create(
   engine="gpt-3.5-turbo-instruct",
   prompt=prompt,
   max_tokens=150
)

步驟8:顯示和更新提示

最後,我們需要顯示生成的回覆並更新下一個迭代的提示:

# Get and display the chatbot response
chatbot_response = get_chatbot_response(prompt)
print(f"Chatbot: {chatbot_response}")

# Update the prompt with chatbot's response
prompt += f"Chatbot: {chatbot_response}\n"

執行聊天機器人

現在讓我們將其整合到一個指令碼中並執行聊天機器人:

# Import the OpenAI library
import openai

# Set up your OpenAI API key for authentication
openai.api_key = 'your-api-key-goes-here'

# Define the initial prompt
prompt = "You: "

# Function to get chatbot response using OpenAI API
def get_chatbot_response(prompt):

   # Generate responses using the OpenAI API
   response = openai.Completion.create(
      engine="gpt-3.5-turbo-instruct",
      prompt=prompt,
      max_tokens=150
   )
   return response.choices[0].text.strip()

# Main execution loop
if __name__ == "__main__":

   # Continuous loop for user interaction
   while True:
   
      # Get user input
      user_input = input("You: ")

      # Check for exit command
      if user_input.lower() == 'exit':
         print("Chatbot: Goodbye!")
         break

      # Update the prompt with user input
      prompt += user_input + "\n"

      # Get and display the chatbot response
      chatbot_response = get_chatbot_response(prompt)
      print(f"Chatbot: {chatbot_response}")

      # Update the prompt with chatbot's response
      prompt += f"Chatbot: {chatbot_response}\n"

注意 - 將“your-api-key-goes-here”替換為您實際的OpenAI API金鑰。此指令碼允許使用者在一個連續迴圈中與聊天機器人進行互動,並能夠透過鍵入“exit”來退出。

讓我們看看我們與聊天機器人進行的對話:

You: Hi
Chatbot: > <@User> Hi there! Is there something I can help you with?

You: I want to know about Artificial Intelligence.
Chatbot: Chatbot: Sure! Artificial Intelligence, or AI, refers to the 
simulation of human intelligence processes by machines. This could include 
things like learning, problem solving, and decision making. 
AI has become increasingly important in various industries and has the 
potential to greatly impact our daily lives in the future. Is there something
specific you would like to know?

You: Suggest me some courses to learn AI using Python.
Chatbot: Chatbot: There are many great online courses available for learning 
AI with Python. Here are a few popular options: "Python for Data Science and 
AI" on Coursera, "Artificial Intelligence with Python" on Udemy, and 
"AI Programming with Python" on edX. 
Each course has its own focus and structure, so be sure to research and choose
the one that best fits your learning goals.

You: Is there any course related to learn AI using Python on tutorialspoint.com?
Chatbot: Chatbot: Yes, there are several courses related to 
AI on tutorialspoint.com. Some popular ones include "Python 
AI Tutorial," "Machine Learning with Python," and 
"Deep Learning with TensorFlow." You can explore these courses and their 
contents to see which one best fits your needs.

You: Can you tell me more about tutorialspoint.com?
Chatbot: Tutorialspoint.com is an online platform that offers a variety of 
tutorials and study materials on various subjects such as programming 
languages, database technologies, web development, and more. 
It was founded in 2006 and has become one of the leading online learning 
platforms for technical subjects. The website provides step-by-step tutorials, 
articles, and videos to help users learn and understand complex concepts
in an easy and interactive way. 
The tutorials are prepared and updated by a team of experts in the field and 
cover a wide range of topics from beginner level to advanced level. 
It also offers certifications and online courses for users to 
enhance their skills and knowledge. 
Overall, tutorialspoint.com is a valuable resource for students, professionals, 
and anyone interested in learning about technical courses.

You: exit
Chatbot: Goodbye!

結論

在本章中,我們解釋瞭如何使用OpenAI API和Python建立聊天機器人。這是一個起點,您可以透過處理使用者輸入驗證、改進提示和探索OpenAI提供的先進API功能來進一步增強您的聊天機器人。

要了解更多資訊,請嘗試不同的提示,進行不同的對話,並根據您的特定需求定製聊天機器人。

廣告