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 密钥。

# 设置您的 OpenAI API 密钥
openai.api_key = 'your-api-key-goes-here'

步骤 5:定义初始提示

配置 OpenAI API 后,我们需要定义将用于启动与聊天机器人对话的初始提示变量。例如,我们为实现目的定义了以下提示 −

# 定义初始提示
prompt = "You: "

您可以尝试不同的提示,例如您的姓名或昵称。

第 6 步:实现聊天循环

接下来,我们需要创建一个循环来模拟与聊天机器人的对话。它将允许用户输入消息并将其附加到提示中。如果您想退出循环,可以使用预定义的命令,例如"exit"。查看下面的代码 −

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

   # 检查退出命令
   if user_input.lower() == 'exit':
      print("Chatbot: Goodbye!")
      break

   # 使用用户输入更新提示
   prompt += user_input + "
"

第 7 步:生成响应

现在,使用 OpenAI API 根据用户的输入生成响应。为此,我们需要在循环内向 API 发出请求,如下所示 −

# 使用 OpenAI API 生成响应
response = openai.Completion.create(
   engine="gpt-3.5-turbo-instruct",
   prompt=prompt,
   max_tokens=150
)

第 8 步:显示和更新提示

最后,我们需要显示生成的响应并更新下一次迭代的提示 −

# 获取并显示聊天机器人响应
chatbot_response = get_chatbot_response(prompt)
print(f"Chatbot: {chatbot_response}")

# 使用聊天机器人的响应更新提示
prompt += f"Chatbot: {chatbot_response}
"

运行聊天机器人

现在让我们将所有内容放在一个脚本中并运行聊天机器人 −

# 导入 OpenAI 库
import openai

# 设置您的 OpenAI API 密钥用于身份验证
openai.api_key = 'your-api-key-goes-here'

# 定义初始提示
prompt = "You: "

# 使用 OpenAI API 获取聊天机器人响应的函数
def get_chatbot_response(prompt):

   # 使用 OpenAI API 生成响应
   response = openai.Completion.create(
      engine="gpt-3.5-turbo-instruct",
      prompt=prompt,
      max_tokens=150
   )
   return response.choices[0].text.strip()

# 主执行循环
if __name__ == "__main__":

   # 持续循环以进行用户交互
   while True:
   
      # 获取用户输入
      user_input = input("You: ")

      # 检查退出命令
      if user_input.lower() == 'exit':
         print("Chatbot: Goodbye!")
         break

      # 使用用户输入更新提示
      prompt += user_input + "
"

      # 获取并显示聊天机器人的响应
      chatbot_response = get_chatbot_response(prompt)
      print(f"Chatbot: {chatbot_response}")

      # 使用聊天机器人的响应更新提示
      prompt += f"Chatbot: {chatbot_response}
"

注意 − 将"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 功能来进一步增强您的聊天机器人。

要了解更多信息,请尝试不同的提示,参与不同的对话,并定制聊天机器人以满足您的特定要求。