Chatbot Script Using The “requests” Library To Correctly Interact With The OpenAI Chat API
Yamil Garcia
I'm an Electrical Software Engineer with a passion for combining my knowledge in the intricacies of electrical systems with the power of programming.
In the digital age, chatbots have become increasingly popular for a variety of applications, from customer service to personal assistants. Leveraging powerful AI through APIs like OpenAI's Chat API can enable developers to create sophisticated and interactive chatbots. In this article, we will guide you through the process of creating a chatbot script in Python that interacts with the OpenAI Chat API using the "requests" library.
Introduction
The OpenAI Chat API offers access to advanced AI models capable of understanding and generating human-like text. By integrating this API, your chatbot can perform a wide range of tasks, such as answering questions, providing recommendations, or simply engaging in conversation. The Python requests library simplifies HTTP requests, making it an excellent choice for interacting with REST APIs like OpenAI's.
Prerequisites
Before we begin, ensure you have the following:
pip install requests.
Step 1: Import Required Libraries
Step 2: Defining the Chatbot Constructor
This is the constructor for the ChatBot class. It initializes the chatbot with a specified model, defaulting to "gpt-3.5-turbo". It also sets up the API key (assumed to be set as an environment variable OPENAI_API_KEY) and the API URL for making requests.
领英推荐
Step 3: Defining the Chatbot Query Method
Next, let's expand our Chatbot class to define the method send_message() that will send queries to the OpenAI Chat API.
This method sends a message to the OpenAI API and returns the response. It constructs the appropriate HTTP headers (including authorization with the API key) and the JSON payload containing the message and the model. If the request is successful, it extracts and returns the message content from the response. Error handling is included for HTTP errors and other exceptions, returning a default error message if something goes wrong.
Step 4: Implementing the Chat Interface
To interact with our chatbot, we'll implement a simple command-line interface:
This function provides a simple CLI (Command Line Interface) for interacting with the chatbot. It greets the user and enters a loop where it prompts the user for input, sends the input to the chatbot for processing, and displays the chatbot's response. The loop can be exited by typing "quit".
Step 5: Execution Entry Point
This line checks if the script is being run as the main program (as opposed to being imported as a module in another script) and calls the main function to start the application.
Complete Code
import os
import requests
class ChatBot:
def __init__(self, model: str = "gpt-3.5-turbo") -> None:
self.model = model
self.api_key = os.getenv("OPENAI_API_KEY")
self.api_url = "https://api.openai.com/v1/chat/completions"
def send_message(self, message: str) -> str:
# The headers include an Authorization header with your OpenAI API key and
# the Content-Type set to application/json.
headers = {
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json",
}
# The data payload includes your message and the model you want to use. You can add more
# parameters as per the API documentation to customize the behavior of the chat model.
data = {
"model": self.model,
"messages": [
{
"role": "user",
"content": message
}
],
}
# This code uses the "requests" library to make a POST request to the v1/chat/completions endpoint
# of the OpenAI API, which is the correct endpoint for chat models.
try:
response = requests.post(self.api_url, json=data, headers=headers)
response.raise_for_status() # This will raise an exception for HTTP error responses
response_data = response.json()
return response_data['choices'][0]['message']['content'].strip()
except requests.exceptions.HTTPError as err:
print(f"HTTP error occurred: {err}") # HTTP error
except Exception as err:
print(f"An error occurred: {err}") # Other errors
return "I'm sorry, I couldn't process your request."
def main():
print("Welcome to ChatBot! Type 'quit' to exit.")
chatbot = ChatBot()
while True:
user_input = input("You: ")
if user_input.lower() == 'quit':
break
response = chatbot.send_message(user_input)
print("ChatBot:\n", response)
if __name__ == "__main__":
main()
Conclusion
By following these steps, you've created a basic but powerful chatbot capable of conversing using the OpenAI Chat API. This script serves as a starting point; you can extend its functionality by integrating more features from the OpenAI API, customizing the behavior, or improving the user interface. The possibilities are vast, and with the power of OpenAI's language models at your fingertips, your chatbot can evolve to meet a wide range of needs.