Systems Library / AI Model Setup / How to Connect GPT-4 to Your Business via API
AI Model Setup foundations

How to Connect GPT-4 to Your Business via API

Connect OpenAI GPT-4 to your business applications using the Python SDK.

Jay Banlasan

Jay Banlasan

The AI Systems Guy

Getting your business hooked into GPT-4 via the API is one of the highest-leverage moves I make for clients. The gpt-4 api business integration setup process takes under an hour, and once it is live you can automate tasks that were eating 10 to 20 hours a week. This tutorial walks you through the exact setup I use, from creating credentials to making your first production-ready call.

The difference between using ChatGPT manually and owning the API is ownership. You control the inputs, the outputs, the costs, and the logic. You are not constrained by the chat interface. Your app can call GPT-4 at 3am, process a thousand records, and write results to a spreadsheet without anyone touching a keyboard.

What You Need Before Starting

Step 1: Get Your OpenAI API Key

Log in to platform.openai.com. In the left sidebar, click "API keys." Click "Create new secret key." Name it something specific like my-business-prod so you can revoke the right key if needed.

Copy it immediately. OpenAI only shows it once. If you close the page before copying, you will need to create a new key.

Create a .env file in your project root:

OPENAI_API_KEY=sk-proj-your-key-here

Add .env to your .gitignore right now. Never commit API keys to version control.

Step 2: Install the OpenAI Python SDK

The official SDK handles auth, retries, and response parsing for you. Install it:

pip install openai python-dotenv

If you are using a virtual environment (recommended):

python -m venv venv
source venv/bin/activate  # Mac/Linux
venv\Scripts\activate     # Windows
pip install openai python-dotenv

Step 3: Make Your First API Call

Create a file called gpt4_test.py:

import os
from openai import OpenAI
from dotenv import load_dotenv

load_dotenv()

client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))

response = client.chat.completions.create(
    model="gpt-4o",
    messages=[
        {
            "role": "system",
            "content": "You are a business analyst. Be concise and specific."
        },
        {
            "role": "user",
            "content": "Summarize why API access to GPT-4 is better than using ChatGPT manually for business automation."
        }
    ],
    temperature=0.3,
    max_tokens=300
)

print(response.choices[0].message.content)
print(f"\nTokens used: {response.usage.total_tokens}")

Run it:

python gpt4_test.py

You should see a response and a token count. That token count is your cost indicator. At current pricing, 1,000 tokens is roughly $0.005 for input and $0.015 for output on GPT-4o.

Step 4: Build a Reusable Business Function

For real business use, wrap the API call in a function you can import anywhere:

import os
from openai import OpenAI
from dotenv import load_dotenv

load_dotenv()
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))

def ask_gpt4(prompt: str, system_prompt: str = None, temperature: float = 0.3) -> str:
    """
    Send a prompt to GPT-4 and return the response text.
    
    Args:
        prompt: The user message to send
        system_prompt: Optional system instructions
        temperature: 0.0 = deterministic, 1.0 = creative (default 0.3 for business tasks)
    
    Returns:
        Response text as string
    """
    messages = []
    
    if system_prompt:
        messages.append({"role": "system", "content": system_prompt})
    
    messages.append({"role": "user", "content": prompt})
    
    response = client.chat.completions.create(
        model="gpt-4o",
        messages=messages,
        temperature=temperature,
        max_tokens=1000
    )
    
    return response.choices[0].message.content


# Example: Classify customer emails
def classify_email(email_body: str) -> str:
    system = "Classify this customer email into one of: SUPPORT, BILLING, SALES, COMPLAINT, OTHER. Return only the category word."
    return ask_gpt4(email_body, system_prompt=system, temperature=0.0)


if __name__ == "__main__":
    test_email = "Hi, I was charged twice for my subscription this month. Can you help?"
    category = classify_email(test_email)
    print(f"Email category: {category}")

Step 5: Handle Errors Properly

Production code needs error handling. API calls can fail due to rate limits, network issues, or invalid inputs:

import time
from openai import OpenAI, RateLimitError, APIConnectionError, APIStatusError

def ask_gpt4_safe(prompt: str, system_prompt: str = None, retries: int = 3) -> str:
    """GPT-4 call with retry logic and error handling."""
    
    for attempt in range(retries):
        try:
            messages = []
            if system_prompt:
                messages.append({"role": "system", "content": system_prompt})
            messages.append({"role": "user", "content": prompt})
            
            response = client.chat.completions.create(
                model="gpt-4o",
                messages=messages,
                temperature=0.3,
                max_tokens=1000,
                timeout=30  # 30 second timeout
            )
            return response.choices[0].message.content
            
        except RateLimitError:
            wait_time = 2 ** attempt  # Exponential backoff: 1s, 2s, 4s
            print(f"Rate limited. Waiting {wait_time}s before retry {attempt + 1}/{retries}")
            time.sleep(wait_time)
            
        except APIConnectionError as e:
            print(f"Connection error: {e}. Retry {attempt + 1}/{retries}")
            time.sleep(2)
            
        except APIStatusError as e:
            print(f"API error {e.status_code}: {e.message}")
            raise  # Don't retry on 400/401 errors
    
    raise Exception(f"Failed after {retries} retries")

Step 6: Track Costs in Production

Add cost tracking so you know what you are spending:

import json
from datetime import datetime

def ask_gpt4_tracked(prompt: str, system_prompt: str = None, log_file: str = "api_usage.jsonl") -> str:
    """GPT-4 call with cost tracking logged to a JSONL file."""
    
    messages = []
    if system_prompt:
        messages.append({"role": "system", "content": system_prompt})
    messages.append({"role": "user", "content": prompt})
    
    response = client.chat.completions.create(
        model="gpt-4o",
        messages=messages,
        temperature=0.3,
        max_tokens=1000
    )
    
    # Log usage
    usage_record = {
        "timestamp": datetime.now().isoformat(),
        "model": "gpt-4o",
        "input_tokens": response.usage.prompt_tokens,
        "output_tokens": response.usage.completion_tokens,
        "total_tokens": response.usage.total_tokens,
        "estimated_cost_usd": (response.usage.prompt_tokens * 0.000005) + (response.usage.completion_tokens * 0.000015)
    }
    
    with open(log_file, "a") as f:
        f.write(json.dumps(usage_record) + "\n")
    
    return response.choices[0].message.content

What to Build Next

Related Reading

Want this system built for your business?

Get a free assessment. We will map every system your business needs and show you the ROI.

Get Your Free Assessment

Related Systems