HxHippy

OpenAI API Guide

Complete guide to using OpenAI's GPT models and API.

Last updated: 2024-12-18

OpenAI API Guide

Integrate OpenAI's GPT models into your applications.

Setup

Installation

pip install openai

Authentication

from openai import OpenAI

client = OpenAI(api_key="sk-...")
# Or set OPENAI_API_KEY environment variable
client = OpenAI()

Chat Completions

Basic Usage

response = client.chat.completions.create(
    model="gpt-4o",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Hello!"}
    ]
)
print(response.choices[0].message.content)

Streaming

stream = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "Write a story"}],
    stream=True
)

for chunk in stream:
    if chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="")

Function Calling

tools = [{
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "Get weather for a location",
        "parameters": {
            "type": "object",
            "properties": {
                "location": {
                    "type": "string",
                    "description": "City name"
                }
            },
            "required": ["location"]
        }
    }
}]

response = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "Weather in Tokyo?"}],
    tools=tools
)

# Handle tool call
tool_call = response.choices[0].message.tool_calls[0]

Vision (GPT-4o)

import base64

def encode_image(path):
    with open(path, "rb") as f:
        return base64.standard_b64encode(f.read()).decode("utf-8")

response = client.chat.completions.create(
    model="gpt-4o",
    messages=[{
        "role": "user",
        "content": [
            {"type": "text", "text": "What's in this image?"},
            {
                "type": "image_url",
                "image_url": {
                    "url": f"data:image/jpeg;base64,{encode_image('photo.jpg')}"
                }
            }
        ]
    }]
)

Embeddings

response = client.embeddings.create(
    model="text-embedding-3-small",
    input="Hello world"
)
embedding = response.data[0].embedding

Best Practices

Practice Recommendation
Model selection gpt-4o for quality, gpt-4o-mini for speed
Temperature 0 for deterministic, 0.7-1 for creative
Max tokens Set to control costs
Error handling Handle rate limits with retries
Streaming Use for long responses

Pricing Considerations

Model Input Output
gpt-4o $2.50/1M $10/1M
gpt-4o-mini $0.15/1M $0.60/1M
text-embedding-3-small $0.02/1M -
intermediate Tools & APIs Updated 2024-12-18
  • openai
  • gpt-4
  • gpt api
  • chatgpt api
  • openai python