How to Use ChatGPT API in Python?

The ChatGPT API allows developers to integrate OpenAI's powerful language models into their Python applications. This enables you to build chatbots, content generators, and AI-powered tools using GPT-3.5 and GPT-4 models.

What is ChatGPT API?

ChatGPT is a large language model developed by OpenAI, based on GPT-3.5 and GPT-4 architectures. The API provides programmatic access to these models, allowing developers to send text prompts and receive AI-generated responses.

The ChatGPT API enables you to:

  • Build conversational AI applications

  • Generate text content automatically

  • Create intelligent assistants

  • Integrate AI capabilities into existing systems

API Pricing Overview

OpenAI offers flexible pricing models for the ChatGPT API:

Free Credits

New accounts receive $5 in free credits valid for the first three months, allowing you to test and experiment with the API.

Pay-as-you-go

After free credits are exhausted, you pay only for what you use. Pricing varies by model:

  • GPT-3.5-turbo: $0.002 per 1K tokens

  • GPT-4: Higher cost but more capable

Check OpenAI's pricing page for current rates.

Setting Up the Environment

Step 1: Get Your API Key

First, create an OpenAI account and generate an API key:

  • Visit platform.openai.com and sign up

  • Navigate to API Keys section

  • Click "Create new secret key" and copy it

  • Important: Store this key securely ? you can't view it again

Step 2: Install Required Libraries

Install the OpenAI Python library using pip:

pip install openai python-dotenv

Step 3: Configure Environment Variables

Create a .env file to store your API key securely:

OPENAI_API_KEY=your-api-key-here

Basic ChatGPT Implementation

Here's a simple chatbot implementation using the ChatGPT API:

import openai
import os
from dotenv import load_dotenv

# Load environment variables
load_dotenv()

# Configure OpenAI client
openai.api_key = os.getenv('OPENAI_API_KEY')

def chat_with_gpt(prompt):
    try:
        response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",
            messages=[
                {"role": "system", "content": "You are a helpful assistant."},
                {"role": "user", "content": prompt}
            ],
            max_tokens=150,
            temperature=0.7
        )
        return response.choices[0].message.content.strip()
    
    except Exception as e:
        return f"Error: {e}"

# Test the function
user_input = "What is Python programming?"
response = chat_with_gpt(user_input)
print(f"User: {user_input}")
print(f"ChatGPT: {response}")
User: What is Python programming?
ChatGPT: Python is a high-level, interpreted programming language known for its simplicity and readability. It supports multiple programming paradigms and has extensive libraries for various applications including web development, data science, and artificial intelligence.

Interactive Chat Application

Here's a more advanced implementation with conversation history:

import openai
import os
from dotenv import load_dotenv

load_dotenv()
openai.api_key = os.getenv('OPENAI_API_KEY')

class ChatGPTBot:
    def __init__(self):
        self.messages = [
            {"role": "system", "content": "You are a helpful assistant."}
        ]
    
    def send_message(self, user_message):
        # Add user message to conversation history
        self.messages.append({"role": "user", "content": user_message})
        
        try:
            # Get response from ChatGPT
            response = openai.ChatCompletion.create(
                model="gpt-3.5-turbo",
                messages=self.messages,
                max_tokens=200,
                temperature=0.7
            )
            
            assistant_message = response.choices[0].message.content.strip()
            
            # Add assistant response to history
            self.messages.append({"role": "assistant", "content": assistant_message})
            
            return assistant_message
            
        except Exception as e:
            return f"Error: {e}"

# Example usage
bot = ChatGPTBot()

# Simulate a conversation
questions = [
    "Hello! What's the weather like?",
    "Can you explain machine learning?",
    "What did I ask you about before this?"
]

for question in questions:
    response = bot.send_message(question)
    print(f"User: {question}")
    print(f"Bot: {response}\n")
User: Hello! What's the weather like?
Bot: Hello! I don't have access to real-time weather data, so I can't tell you the current weather conditions. To get accurate weather information, I'd recommend checking a weather app, website like Weather.com, or asking a voice assistant that has internet access.

User: Can you explain machine learning?
Bot: Machine learning is a subset of artificial intelligence where computers learn to make predictions or decisions by analyzing data patterns, rather than being explicitly programmed for each task. It works by training algorithms on datasets to recognize patterns and make predictions on new, unseen data.

User: What did I ask you about before this?
Bot: Before asking about machine learning, you first asked me about the weather. You greeted me and wanted to know what the weather was like, though I explained that I don't have access to real-time weather data.

Key Features and Parameters

Important parameters for the ChatGPT API:

Parameter Description Default
model GPT model to use gpt-3.5-turbo
temperature Creativity level (0-2) 1
max_tokens Maximum response length inf
messages Conversation history Required

Error Handling and Best Practices

Always implement proper error handling and follow security best practices:

import openai
import os
from dotenv import load_dotenv
import time

load_dotenv()
openai.api_key = os.getenv('OPENAI_API_KEY')

def safe_api_call(messages, max_retries=3):
    for attempt in range(max_retries):
        try:
            response = openai.ChatCompletion.create(
                model="gpt-3.5-turbo",
                messages=messages,
                max_tokens=100,
                timeout=30  # 30 second timeout
            )
            return response.choices[0].message.content.strip()
            
        except openai.error.RateLimitError:
            print(f"Rate limit exceeded. Waiting before retry {attempt + 1}...")
            time.sleep(2 ** attempt)  # Exponential backoff
            
        except openai.error.APIConnectionError:
            print("Connection error. Check your internet connection.")
            return "Sorry, I'm having trouble connecting right now."
            
        except Exception as e:
            print(f"Unexpected error: {e}")
            if attempt == max_retries - 1:
                return "Sorry, I encountered an error processing your request."
            
    return "Sorry, I'm temporarily unavailable."

# Example usage
messages = [
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "Tell me a fun fact about space."}
]

response = safe_api_call(messages)
print(f"Response: {response}")
Response: Here's a fun space fact: One day on Venus is longer than its year! Venus takes about 243 Earth days to complete one rotation on its axis, but only 225 Earth days to orbit around the Sun.

Conclusion

The ChatGPT API provides powerful AI capabilities for Python developers. Remember to secure your API keys, implement proper error handling, and monitor your usage to manage costs effectively. With these tools, you can build sophisticated AI-powered applications.

---
Updated on: 2026-03-27T16:24:31+05:30

395 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements