Chatgpt 简明教程

ChatGPT – Build a Chatbot

如今,几乎每个应用程序中都能找到聊天机器人。这是因为它们使用户能够进行交互式和动态对话。在 OpenAI 功能强大的语言模型(例如 GPT-3.5)的帮助下,开发人员可以创建复杂的聊天机器人,这些聊天机器人能够理解并生成类似人类的文本。

Chatbots are found in almost every application nowadays. This is because they allow users to have interactive and dynamic conversations. With the help of OpenAI’s powerful language models, such as GPT-3.5, developers can create sophisticated chatbots that can understand and generate human-like text.

在本章中,我们将探讨如何使用 Python 编程语言和 OpenAI API 创建聊天机器人。因此,让我们开始逐步实施聊天机器人。

In this chapter, we will explore how to create a chatbot using the OpenAI API with Python programming language. So, let’s get started with the step by step implementation of the chatbot.

Step 1: Set Up Your OpenAI Account

首先,你需要在 OpenAI 平台上设置一个帐户并获得 API 凭证。访问 OpenAI 网站,注册并按照说明生成 API 密钥。

First of all, you need to set up an account on the OpenAI platform and obtain your API credentials. Visit the OpenAI website, sign up, and follow the instructions to generate an API key.

始终建议你保护好你的 API 密钥,因为它将用于验证对 OpenAI API 的请求。

It is always recommended to keep your API key secure, as it will be used to authenticate requests to the OpenAI API.

Step 2: Install the OpenAI Python Library

现在,要与 OpenAI API 交互,你需要安装 OpenAI Python 库。在你的终端或命令提示符上运行以下命令:

Now, to interact with the OpenAI API, you need to install the OpenAI Python library. Run the following command on your terminal or command prompt −

pip install openai

此命令将把 OpenAI 库安装到你的 Python 环境中。

This command will install OpenAI library to your Python environment.

Step 3: Import Required Libraries

现在,在你的 Python 脚本中,你需要导入 OpenAI 库和实现可能需要的任何其他库。对于此实现,我们只需要 OpenAI 库。

Now, in your Python script, you need to import the OpenAI library and any other libraries you might need for your implementation. For this implementation we only need the OpenAI library.

以下命令导入 OpenAI 库:

The following command imports the OpenAI library −

import openai

Step 4: Configure OpenAI API Key

接下来,需要在 Python 脚本中设置 OpenAI 密钥来验证你的请求。在下面的命令中,用从 OpenAI 获得的实际 API 密钥替换“your-api-key-goes-here”。

Next, it is required to set up the OpenAI key in Python script to authenticate your requests. In the command below, replace 'your-api-key-goes-here' with the actual API key you obtained from OpenAI.

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

Step 5: Define the Initial Prompt

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

After configuring OpenAI API, we need to define the initial prompt variable that will be used to initiate the conversation with the chatbot. For example, we define the following prompt for our implementation purpose −

# Define the initial prompt
prompt = "You: "

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

You can experiment with different prompts such as your name or your nickname.

Step 6: Implement the Chat Loop

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

Next, we need to create a loop to simulate a conversation with the chatbot. It will allow the user to input messages and append them to the prompt. And if you want to exit the loop, you can use a predefined command, such as "exit". Check out the code below −

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"

Step 7: Generate Responses

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

Now, use the OpenAI API to generate responses based on the user’s input. For this we need to make a request to the API within the loop as follows −

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

Step 8: Display and Update the Prompt

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

At last, we need to display the generated response and update the prompt for the next iteration as well −

# 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"

Run the Chatbot

现在,让我们把它全部放在一个脚本中并运行聊天机器人 -

Now let’s put it all together in a script and run the chatbot −

# 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"

Note - 将“your-api-key-goes-here”替换为你实际的 OpenAI API 密钥。此脚本允许用户在连续循环中与聊天机器人交互,可以通过键入“退出”来退出。

Note − Replace 'your-api-key-goes-here' with your actual OpenAI API key. This script allows the user to interact with the chatbot in a continuous loop, with the ability to exit by typing "exit."

让我们看看我们与聊天机器人的对话 -

Let’s see the conversation we have done with our chatbot −

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!

Conclusion

在本章中,我们解释了如何使用 Python 和 OpenAI API 创建聊天机器人。这是一个起点,你可以通过处理用户输入验证、完善提示并探索 OpenAI 提供的高级 API 功能进一步增强你的聊天机器人。

In this chapter we explained how you can create a chatbot using the OpenAI API with Python. This is a starting point, and you can further enhance your chatbot by handling user input validation, refining prompts, and exploring advanced API features offered by OpenAI.

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

To learn more, experiment with different prompts, engage in diverse conversations, and tailor the chatbot to meet your specific requirements.