AI

OpenAI API

Interact with OpenAI models via the REST API — chat, tools, vision, embeddings, and more.

#openai #gpt #chatgpt #ai #llm #api #embeddings #dall-e #whisper

Authentication

All requests require a Bearer token in the Authorization header.

export OPENAI_API_KEY="[api_key]"

curl https://api.openai.com/v1/models \
  -H "Authorization: Bearer $OPENAI_API_KEY"

Chat Completions

Basic Completion

Parameters:

  • model (Required): ID of the model to use.
  • messages (Required): Array of message objects with role and content.
  • max_tokens (Optional): Maximum tokens to generate.
curl https://api.openai.com/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer [api_key]" \
  -d '{
    "model": "[model]",
    "messages": [
      {"role": "user", "content": "[prompt]"}
    ]
  }'

With System Prompt

curl https://api.openai.com/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer [api_key]" \
  -d '{
    "model": "[model]",
    "messages": [
      {"role": "system", "content": "You are a concise technical writer. Reply in plain text only."},
      {"role": "user",   "content": "[prompt]"}
    ],
    "temperature": 0.2,
    "max_tokens": 512
  }'

Multi-Turn Conversation

curl https://api.openai.com/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer [api_key]" \
  -d '{
    "model": "[model]",
    "messages": [
      {"role": "system",    "content": "You are a helpful assistant."},
      {"role": "user",      "content": "What is Rust ownership?"},
      {"role": "assistant", "content": "Rust ownership is a set of rules..."},
      {"role": "user",      "content": "Give me a concrete example."}
    ]
  }'

Streaming Response

curl https://api.openai.com/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer [api_key]" \
  -d '{
    "model": "[model]",
    "stream": true,
    "messages": [
      {"role": "user", "content": "[prompt]"}
    ]
  }'

💡 Tip: Each streamed chunk is a data: SSE event. The stream ends with data: [DONE].


Structured Outputs

Force the model to return valid JSON matching an exact schema.

Parameters:

  • response_format.type: Set to "json_schema" to enable structured output.
  • strict: Set to true to guarantee schema adherence.
curl https://api.openai.com/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer [api_key]" \
  -d '{
    "model": "gpt-4o-2024-08-06",
    "messages": [
      {"role": "user", "content": "Extract name, age and job from: John Doe, 32, engineer"}
    ],
    "response_format": {
      "type": "json_schema",
      "json_schema": {
        "name": "person",
        "strict": true,
        "schema": {
          "type": "object",
          "properties": {
            "name": {"type": "string"},
            "age":  {"type": "integer"},
            "job":  {"type": "string"}
          },
          "required": ["name","age","job"],
          "additionalProperties": false
        }
      }
    }
  }'

Function Calling / Tools

Define and Call a Tool

Parameters:

  • tools (Optional): Array of tool definitions.
  • tool_choice (Optional): "auto", "none", or {"type":"function","function":{"name":"fn"}}.
curl https://api.openai.com/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer [api_key]" \
  -d '{
    "model": "[model]",
    "messages": [
      {"role": "user", "content": "What is the weather in Tokyo?"}
    ],
    "tools": [{
      "type": "function",
      "function": {
        "name": "get_weather",
        "description": "Get current weather for a location.",
        "parameters": {
          "type": "object",
          "properties": {
            "location": {"type": "string", "description": "City and country, e.g. Tokyo, Japan"},
            "unit":     {"type": "string", "enum": ["celsius","fahrenheit"]}
          },
          "required": ["location"]
        }
      }
    }],
    "tool_choice": "auto"
  }'

Submit Tool Result

After calling the tool locally, return the result to continue the conversation:

curl https://api.openai.com/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer [api_key]" \
  -d '{
    "model": "[model]",
    "messages": [
      {"role": "user",      "content": "What is the weather in Tokyo?"},
      {"role": "assistant", "content": null,
        "tool_calls": [{
          "id": "call_abc123", "type": "function",
          "function": {"name": "get_weather", "arguments": "{\"location\":\"Tokyo, Japan\"}"}
        }]
      },
      {"role": "tool", "tool_call_id": "call_abc123", "content": "{\"temp\":22, \"condition\":\"Sunny\"}"}
    ],
    "tools": [{"type":"function","function":{"name":"get_weather","description":"...","parameters":{}}}]
  }'

Vision

Analyze an Image URL

Parameters:

  • detail (Optional): "low" (fast, fixed cost) or "high" (full resolution, tiles).
curl https://api.openai.com/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer [api_key]" \
  -d '{
    "model": "gpt-4o",
    "messages": [{
      "role": "user",
      "content": [
        {"type": "text",      "text": "Describe this image in detail."},
        {"type": "image_url", "image_url": {"url": "https://example.com/image.jpg", "detail": "high"}}
      ]
    }]
  }'

Analyze a Local Image (Base64)

IMG_B64=$(base64 -w 0 /path/to/image.png)

curl https://api.openai.com/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer [api_key]" \
  -d '{
    "model": "gpt-4o",
    "messages": [{
      "role": "user",
      "content": [
        {"type": "text",      "text": "What is shown here?"},
        {"type": "image_url", "image_url": {"url": "data:image/png;base64,'"$IMG_B64"'"}}
      ]
    }]
  }'

Embeddings

Parameters:

  • input (Required): String or array of strings/tokens to embed.
  • dimensions (Optional): Shorten embedding length (text-embedding-3-* only).
curl https://api.openai.com/v1/embeddings \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer [api_key]" \
  -d '{
    "model": "text-embedding-3-large",
    "input": "The quick brown fox jumps over the lazy dog",
    "dimensions": 512
  }'

Batch Embeddings

curl https://api.openai.com/v1/embeddings \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer [api_key]" \
  -d '{
    "model": "text-embedding-3-large",
    "input": ["First sentence", "Second sentence", "Third sentence"]
  }'

Image Generation (DALL-E 3)

Parameters:

  • quality (Optional): "standard" or "hd".
  • style (Optional): "vivid" (hyper-real) or "natural" (realistic).
  • size (Optional): "1024x1024", "1792x1024", or "1024x1792".
curl https://api.openai.com/v1/images/generations \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer [api_key]" \
  -d '{
    "model": "dall-e-3",
    "prompt": "A photorealistic satellite image of a server farm surrounded by forest, golden hour",
    "size": "1792x1024",
    "quality": "hd",
    "style": "natural",
    "n": 1
  }'

Audio

Transcribe Audio (Whisper)

Parameters:

  • file (Required): Audio file (mp3, mp4, wav, webm, etc.).
  • language (Optional): ISO-639-1 code (e.g. "en") for improved accuracy.
curl https://api.openai.com/v1/audio/transcriptions \
  -H "Authorization: Bearer [api_key]" \
  -F model="whisper-1" \
  -F language="en" \
  -F file=@recording.mp3

Text-to-Speech

Parameters:

  • voice (Required): alloy, echo, fable, onyx, nova, shimmer.
  • speed (Optional): Range 0.25–4.0.
curl https://api.openai.com/v1/audio/speech \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer [api_key]" \
  -d '{"model":"tts-1-hd","input":"Hello world.","voice":"onyx","speed":1.0}' \
  --output speech.mp3

Moderation

Check whether content violates OpenAI usage policies:

curl https://api.openai.com/v1/moderations \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer [api_key]" \
  -d '{"model":"omni-moderation-latest","input":"[text to check]"}'

Models Reference

ModelContextBest For
gpt-4o128kMultimodal, reasoning, tools
gpt-4o-mini128kFast, cost-efficient tasks
o1200kDeep multi-step reasoning
o3-mini200kAffordable advanced reasoning
text-embedding-3-large8kHighest-quality embeddings
text-embedding-3-small8kFast, cost-efficient embeddings
dall-e-3Image generation
whisper-1Speech-to-text transcription
tts-1-hdHigh-quality text-to-speech

Key Parameters

ParameterTypeRangeDescription
temperaturefloat0.0–2.0Randomness (0 = deterministic)
top_pfloat0.0–1.0Nucleus sampling probability
max_tokensinteger1–contextMax tokens to generate
frequency_penaltyfloat-2.0–2.0Penalise repeated tokens
presence_penaltyfloat-2.0–2.0Penalise already-used topics
seedintegeranyReproducible outputs (best-effort)
ninteger1–∞Number of completion choices

💡 Tip: Do not set both temperature and top_p at the same time — adjust only one.


Error Handling

HTTP CodeError CodeSolution
400invalid_request_errorCheck required params and types
401authentication_errorVerify API key or org ID
403permission_errorCheck key scope / tier
404model_not_foundVerify model ID and access tier
429rate_limit_exceededImplement exponential backoff
500server_errorRetry; report if persistent

Resources