Integrating OpenClaw with OpenAI
Connect OpenClaw to OpenAI GPT-4o, GPT-4, GPT-3.5-Turbo, o1, and o3 models. Includes prerequisites, API key setup, model selection, Azure OpenAI, structured outputs, and cost optimization.
Prerequisites
- OpenClaw v1.0.0 or later installed (Installation Guide)
- An OpenAI account with billing enabled
- An OpenAI API key from platform.openai.com/api-keys
- Basic familiarity with the command line
Quick Start in 3 Steps
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-4oStep 3 — Run your first task:
openclaw run "Summarize the latest AI research trends in 5 bullet points"Supported Models
| Model | Context Window | Best For | Cost Tier |
|---|---|---|---|
gpt-4o | 128K tokens | Complex reasoning, coding, vision | Medium |
gpt-4o-mini | 128K tokens | Cost-effective automation, classification | Very Low |
gpt-4-turbo | 128K tokens | Long documents, analysis | Medium-High |
gpt-4 | 8K tokens | High-quality tasks | High |
gpt-3.5-turbo | 16K tokens | Fast, routine tasks | Low |
o1-preview | 128K tokens | Complex multi-step reasoning | High |
o1-mini | 128K tokens | Fast reasoning, math, code | Medium |
o3-mini | 200K tokens | Advanced reasoning, research | Medium-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 openaiSelecting 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-miniAdvanced 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 secondsRate 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 retryCost Optimization
- Use
gpt-4o-minifor classification, extraction, and short-answer tasks - Set a low
max_tokensfor 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: azureStructured 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 outputTroubleshooting OpenAI Errors
| Error Code | Cause | Fix |
|---|---|---|
401 Unauthorized | Invalid or missing API key | Check OPENAI_API_KEY is set correctly |
429 Rate Limit | Too many requests or quota exceeded | Add retry_attempts: 5 to config; upgrade OpenAI tier |
500 Server Error | Temporary OpenAI outage | Check status.openai.com; retry later |
400 Bad Request | Invalid parameters or model name | Verify model name and parameter values in config |
context_length_exceeded | Input too long for model | Switch 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-minicosts ~20x less thangpt-4oand 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_tokensin 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 retriesTry 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 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
- Anthropic Claude Integration — compare Claude's strengths with GPT-4o
- Local LLM with Ollama — reduce API costs by running models locally
- API Keys Reference — securely manage all your API credentials
- LLM Integration Patterns — advanced patterns for production LLM pipelines