paint-brush
Using Python to Interact with OpenAI's GPT-3.5, GPT-4, and GPT-4o APIsby@luca1iu
2,145 reads
2,145 reads

Using Python to Interact with OpenAI's GPT-3.5, GPT-4, and GPT-4o APIs

by Luca LiuMay 24th, 2024
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

The development of powerful language models by OpenAI has revolutionized how businesses and individuals interact with AI-driven text generation. Python serves as an ideal language for integrating these AI capabilities into various applications. This article provides a detailed guide on how to use Python to interact with these OpenAI models.
featured image - Using Python to Interact with OpenAI's GPT-3.5, GPT-4, and GPT-4o APIs
Luca Liu HackerNoon profile picture

Introduction:

The development of powerful language models like GPT-3.5, GPT-4, and GPT-4o by OpenAI has revolutionized how businesses and individuals interact with AI-driven text generation. Python, with its simplicity and vast library ecosystem, serves as an ideal language for integrating these AI capabilities into various applications. This article provides a detailed guide on how to use Python to interact with these OpenAI models, enhancing your applications with advanced natural language processing features.

Setting Up Your Python Environment:

To begin, you need Python installed on your system along with the openai library, which can be installed using pip:

pip install openai

Ensure that you have an API key from OpenAI, which is necessary to authenticate and use their services.

Obtaining Your OpenAI API Key:

Before you can start using the OpenAI API, you'll need an API key, which serves as your unique identifier and token for accessing OpenAI's services. To obtain this key, first, create an account on the OpenAI platform. Visit the OpenAI website and sign up for an account. Once your account is set up, navigate to the API section, typically found in your account settings or dashboard. Here, you can generate a new API key. It’s important to handle this key securely: do not share it publicly or hardcode it directly into your applications. Instead, use environment variables or secure key management systems to incorporate them into your projects. This ensures your API key remains confidential and reduces the risk of unauthorized access.

Using Python to Interact with GPT Models:

Here’s a simple Python script to interact with the GPT-3.5 API:

import openai

# Set your API key securely
openai.api_key = "your_openai_api_key"

def generate_gpt_response(user_text, model_name="gpt-3.5-turbo-0125", print_output=False):
    try:
        # Creating text completions using the updated `ChatCompletion` class
        response = openai.ChatCompletion.create(
            model=model_name,  # Specify the model
            messages=[{"role": "system", "content": "You are a helpful assistant."},  # Initial system message
                      {"role": "user", "content": user_text}],  # User's message prompting a response
            max_tokens=3000  # Define the maximum length of the generated response
        )
        text_output = response['choices'][0]['message']['content'] if response['choices'] else "No response generated."
        if print_output:
            print(text_output)
        return text_output
    except Exception as e:
        print(f"An error occurred: {str(e)}")
        return None

# Example usage
result = generate_gpt_response("Will you like my article?")
print(result)

Adjusting the Python Code for GPT-4 or GPT-4o

To utilize GPT-4 or GPT-4o in your Python application, simply update the model_name parameter within the function to either gpt-4-turbo or gpt-4o. For the latest information on model options, capabilities, and updates, be sure to check the OpenAI documentation on Models. This resource provides detailed guidance on selecting the model that best fits your needs.

import openai

# Set your API key securely
openai.api_key = "your_openai_api_key"

def generate_gpt_response(user_text, model_name="gpt-4-turbo", print_output=False):
    try:
        # Creating text completions using the updated `ChatCompletion` class
        response = openai.ChatCompletion.create(
            model=model_name,  # Easily switch between "gpt-3.5-turbo-0613", "gpt-4", "text-davinci-004", or others
            messages=[{"role": "system", "content": "You are a helpful assistant."},
                      {"role": "user", "content": user_text}],
            max_tokens=3000
        )
        text_output = response['choices'][0]['message']['content'] if response['choices'] else "No response generated."
        if print_output:
            print(text_output)
        return text_output
    except Exception as e:
        print(f"An error occurred: {str(e)}")
        return None

# Example usage
result = generate_gpt_response("Will you like my article?", model_name="text-davinci-004")
print(result)

Note: Remember that accessing GPT-4 or GPT-4o APIs requires a billing setup with OpenAI. Ensure you have entered your payment details on the OpenAI platform to utilize these advanced models.

Conclusion:

This guide offers a straightforward approach for Python developers to utilize the OpenAI API to engage directly with ChatGPT. No matter what innovative products you aim to create with ChatGPT, the code examples provided in this guide represent the first step. They offer a simple and straightforward way to begin interacting with the ChatGPT API using Python. Use these foundational techniques as your starting point to explore the vast possibilities of integrating advanced AI interactions into your applications.


Thank you for taking the time to explore data-related insights with me. I appreciate your engagement. If you find this information helpful, I invite you to follow me or connect with me on LinkedIn or X(@Luca_DataTeam). Happy exploring!👋