DeveloperBootstrap

AI & Machine Learning

OpenAI API Complete Guide

Master OpenAI API integration with GPT-4, ChatGPT, DALL-E, Whisper, and Embeddings. Build production-ready AI applications with Python 3.12 and FastAPI on Ubuntu 24.04 LTS.

What you'll learn

  • Authenticate and make requests to the OpenAI API
  • Build chat completions with GPT-4 and function calling
  • Generate images with DALL-E 3
  • Transcribe audio with Whisper
  • Create and query embeddings for semantic search
  • Implement streaming responses for real-time UX
  • Handle rate limits, errors, and costs in production

Setup & Authentication

Python
1pip install openai python-dotenv
2
3# .env
4OPENAI_API_KEY=sk-...
5
6# client.py
7from openai import OpenAI
8import os
9
10client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
11
12# List available models
13models = client.models.list()
14for model in models.data:
15    print(model.id)

Chat Completions

Python
1from openai import OpenAI
2client = OpenAI()
3
4response = client.chat.completions.create(
5    model="gpt-4o",
6    messages=[
7        {"role": "system", "content": "You are a senior Python developer. Be concise."},
8        {"role": "user",   "content": "Explain async/await in Python in 3 sentences."},
9    ],
10    temperature=0.7,
11    max_tokens=200,
12)
13
14print(response.choices[0].message.content)
15print(f"Tokens used: {response.usage.total_tokens}")

Function Calling

Python
1tools = [
2    {
3        "type": "function",
4        "function": {
5            "name": "get_weather",
6            "description": "Get current weather for a city",
7            "parameters": {
8                "type": "object",
9                "properties": {
10                    "city": {"type": "string", "description": "City name"},
11                    "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
12                },
13                "required": ["city"],
14            },
15        },
16    }
17]
18
19response = client.chat.completions.create(
20    model="gpt-4o",
21    messages=[{"role": "user", "content": "What's the weather in London?"}],
22    tools=tools,
23    tool_choice="auto",
24)
25
26if response.choices[0].finish_reason == "tool_calls":
27    tool_call = response.choices[0].message.tool_calls[0]
28    args = json.loads(tool_call.function.arguments)
29    result = get_weather(**args)   # call your actual function

Streaming Responses

Python
1# Python streaming
2with client.chat.completions.stream(
3    model="gpt-4o",
4    messages=[{"role": "user", "content": "Write a poem about Python."}],
5) as stream:
6    for text in stream.text_stream:
7        print(text, end="", flush=True)
8
9# FastAPI SSE endpoint
10from fastapi import FastAPI
11from fastapi.responses import StreamingResponse
12
13app = FastAPI()
14
15@app.post("/chat")
16async def chat(request: ChatRequest):
17    async def generate():
18        with client.chat.completions.stream(
19            model="gpt-4o",
20            messages=request.messages,
21        ) as stream:
22            for text in stream.text_stream:
23                yield f"data: {json.dumps({'text': text})}
24
25"
26        yield "data: [DONE]
27
28"
29
30    return StreamingResponse(generate(), media_type="text/event-stream")

Embeddings & Semantic Search

Python
1import numpy as np
2
3def embed(text: str) -> list[float]:
4    response = client.embeddings.create(
5        model="text-embedding-3-small",
6        input=text,
7    )
8    return response.data[0].embedding
9
10def cosine_similarity(a: list[float], b: list[float]) -> float:
11    a_arr, b_arr = np.array(a), np.array(b)
12    return float(np.dot(a_arr, b_arr) / (np.linalg.norm(a_arr) * np.linalg.norm(b_arr)))
13
14# Semantic search over a document store
15query_embedding = embed("how to deploy docker")
16results = sorted(
17    documents,
18    key=lambda doc: cosine_similarity(query_embedding, doc["embedding"]),
19    reverse=True
20)[:5]

DALL-E Image Generation

Python
1response = client.images.generate(
2    model="dall-e-3",
3    prompt="A futuristic developer workspace with holographic monitors, photorealistic",
4    size="1792x1024",
5    quality="hd",
6    n=1,
7)
8image_url = response.data[0].url
9print(image_url)

Whisper Audio Transcription

Python
1# Transcribe audio
2with open("lecture.mp3", "rb") as audio_file:
3    transcript = client.audio.transcriptions.create(
4        model="whisper-1",
5        file=audio_file,
6        language="en",
7        response_format="verbose_json",
8        timestamp_granularities=["segment"],
9    )
10
11print(transcript.text)
12for segment in transcript.segments:
13    print(f"[{segment.start:.1f}s] {segment.text}")

Production Best Practices

  • Rate limits: Implement exponential backoff with tenacity — retry on 429 and 503 errors.
  • Cost control: Set max_tokens on every call; use gpt-4o-mini for simpler tasks.
  • Caching: Cache deterministic prompts (temperature=0) in Redis with a content hash as the key.
  • Security: Never expose your API key client-side — proxy all calls through your backend.
  • Monitoring: Log token usage, latency, and errors per model per endpoint in your observability stack.