Prerequisites

Quick Start in 3 Steps

💡
Get OpenClaw running with OpenAI in under 2 minutes.

Step 1 — Set your API key:

openclaw config set openai.api_key "sk-proj-..."

Step 2 — Set OpenAI as your provider:

openclaw config set provider openai
openclaw config set openai.model gpt-4o

Step 3 — Run your first task:

openclaw run "Summarize the latest AI research trends in 5 bullet points"

Supported Models

ModelContext WindowBest ForCost Tier
gpt-4o128K tokensComplex reasoning, coding, visionMedium
gpt-4o-mini128K tokensCost-effective automation, classificationVery Low
gpt-4-turbo128K tokensLong documents, analysisMedium-High
gpt-48K tokensHigh-quality tasksHigh
gpt-3.5-turbo16K tokensFast, routine tasksLow
o1-preview128K tokensComplex multi-step reasoningHigh
o1-mini128K tokensFast reasoning, math, codeMedium
o3-mini200K tokensAdvanced reasoning, researchMedium-High

API Key Setup

# Get your key at platform.openai.com/api-keys
openclaw config set openai.api_key "sk-proj-..."

# Or via environment variable
export OPENAI_API_KEY="sk-proj-..."

# Set OpenAI as default provider
openclaw config set provider openai

Selecting a Model

# Per-run model selection
openclaw run "Summarize this report" --model gpt-4o

# Set default model in config
openclaw config set openai.model gpt-4o

# Use cheaper model for simple tasks
openclaw run "List 5 ideas" --model gpt-4o-mini

Advanced Parameters

# config.yaml
provider: openai
openai:
  api_key: "${OPENAI_API_KEY}"
  model: gpt-4o
  temperature: 0.3       # Lower = more deterministic (0.0–2.0)
  max_tokens: 4096       # Max tokens in response
  top_p: 0.9             # Nucleus sampling
  frequency_penalty: 0   # Reduce repetition (-2.0 to 2.0)
  presence_penalty: 0    # Encourage new topics (-2.0 to 2.0)
  timeout: 120           # Request timeout in seconds

Rate Limits & Errors

OpenAI enforces requests-per-minute (RPM) and tokens-per-minute (TPM) limits per API key tier. OpenClaw handles rate limit errors automatically with exponential backoff.

# config.yaml — tune retry behavior
openai:
  retry_attempts: 5
  retry_delay: 2.0      # seconds between retries
  backoff_factor: 2.0   # multiply delay each retry

Cost Optimization

  • Use gpt-4o-mini for classification, extraction, and short-answer tasks
  • Set a low max_tokens for tasks that need brief responses
  • Enable prompt caching where available (GPT-4o supports it)
  • Monitor usage at platform.openai.com/usage
  • Set monthly spend limits in the OpenAI billing dashboard

Using Azure OpenAI

OpenClaw supports Azure OpenAI Service as a drop-in replacement for the standard OpenAI API. Configure your Azure endpoint and deployment name:

# config.yaml — Azure OpenAI setup
provider: openai
openai:
  api_key: "${AZURE_OPENAI_KEY}"
  api_base: "https://your-resource.openai.azure.com/"
  api_version: "2024-02-15-preview"
  deployment_name: "my-gpt4o-deployment"
  api_type: azure

Structured Outputs (JSON Mode)

Force GPT to return valid JSON using OpenAI's structured outputs feature. Useful for data extraction and processing pipelines:

openclaw run "Extract name, email, and company from this text: ..." \
  --format json \
  --schema '{"name": "string", "email": "string", "company": "string"}'
# config.yaml
openai:
  response_format: json_object  # Forces valid JSON output

Troubleshooting OpenAI Errors

Error CodeCauseFix
401 UnauthorizedInvalid or missing API keyCheck OPENAI_API_KEY is set correctly
429 Rate LimitToo many requests or quota exceededAdd retry_attempts: 5 to config; upgrade OpenAI tier
500 Server ErrorTemporary OpenAI outageCheck status.openai.com; retry later
400 Bad RequestInvalid parameters or model nameVerify model name and parameter values in config
context_length_exceededInput too long for modelSwitch to gpt-4o (128K) or reduce input size

Cost Optimisation Tips

OpenAI API costs can accumulate quickly in production workflows. These strategies keep costs under control without sacrificing quality:

  • Use the right model for the task: gpt-4o-mini costs ~20x less than gpt-4o and is sufficient for classification, summarisation, and extraction tasks
  • Cache repeated prompts: If you run the same base prompt many times, OpenAI's prompt caching (available on eligible models) can reduce costs by up to 50%
  • Limit max_tokens: Set max_tokens in your config to prevent runaway long responses that inflate costs
  • Batch similar tasks: Instead of making 50 individual API calls, combine inputs in a single prompt to process them together
  • Monitor usage: Set billing alerts in the OpenAI dashboard; use OpenClaw's log output to track token consumption per run
# openclaw config: cost-optimised OpenAI setup
provider: openai
api_key: ${OPENAI_API_KEY}
model: gpt-4o-mini      # cost-effective for most tasks
max_tokens: 1024        # cap response length
temperature: 0.3        # lower temp = more deterministic = fewer retries

Try It Yourself

These ready-to-run commands work as soon as your API key is configured. Copy, paste, and adapt them to your workflow.

Example 1: Summarise a local file with GPT-4o

openclaw run "Summarise this document in 5 bullet points, focusing on action items" \
  --file ~/Documents/meeting-notes.txt \
  --model gpt-4o

# Expected output:
# • Action: Schedule follow-up with design team by Friday
# • Decision: Switch to new API endpoint from March 15
# ...

Example 2: Extract structured data from text

openclaw run "Extract all company names and their estimated budgets from this text. Output as JSON array." \
  --file ~/Downloads/report.txt \
  --model gpt-4o-mini \
  --format json

# Expected output (raw JSON):
# [{"company": "Acme Corp", "budget": "$50K"}, ...]

Example 3: Cost-conscious batch classification

#!/usr/bin/env bash
# Classify 100 support tickets at minimum cost
cat support-tickets.txt | while IFS= read -r ticket; do
  echo "$ticket" | openclaw run \
    "Classify as: bug / feature-request / billing / general. One word only." \
    --model gpt-4o-mini \
    --max-tokens 5 \
    --stdin
done

# gpt-4o-mini: ~100x cheaper than gpt-4o for simple classification
Model selection shortcut: Use --model gpt-4o-mini for tasks under 200 words that need a short answer. Switch to --model gpt-4o for reasoning, code, or multi-step workflows. You will save ~95% on API costs without sacrificing quality on simple tasks.

What's Next