We've shipped six AI-powered mobile apps in the past 18 months, and the pattern is always the same: the demo looks amazing, gets approved by the client, and then the first production week arrives with an API bill that triggers a 2 AM Slack message. This guide covers how to integrate GPT-4o correctly so that doesn't happen to you.
Architecture: Never Call OpenAI Directly from the App
The first and most important rule: never embed your OpenAI API key in the mobile app binary. It will be extracted. Instead, all AI calls must go through your own backend server, which holds the key and can enforce rate limits, caching, and access control.
// ❌ Never do this
let client = OpenAI(apiKey: "sk-proj-...")
// ✅ Call your own backend instead
let response = try await APIClient.shared.post("/ai/chat", body: request)
Your backend becomes the intermediary that talks to OpenAI. This also lets you switch AI providers (Anthropic, Google Gemini, local Llama) without updating the app.
Implement Streaming Responses
Nothing makes an AI chatbot feel slower than waiting 4 seconds for a complete response to appear all at
once. Use OpenAI's streaming API (stream: true) and pipe tokens to the UI as they arrive
via Server-Sent Events or WebSockets.
// Server-side (Node.js example)
const stream = await openai.chat.completions.create({
model: 'gpt-4o',
messages,
stream: true,
});
for await (const chunk of stream) {
const token = chunk.choices[0]?.delta?.content || '';
res.write(`data: ${JSON.stringify({ token })}\n\n`);
}
res.end();
On the mobile side, consume this with URLSessionDataTask (iOS) or OkHttp event
source (Android), appending each token to a @State / StateFlow variable.
Controlling Costs: The Four Levers
GPT-4o pricing as of mid-2025: $5 per million input tokens, $15 per million output tokens. Here's how to keep your bill predictable:
| Technique | Cost Reduction | Implementation Effort |
|---|---|---|
| Prompt Caching — OpenAI caches repeated system prompt prefixes | Up to 50% on input tokens | Low — structure prompts with long static prefix first |
| Model Selection — use GPT-4o mini for simple tasks | 60–90% on those calls | Low — route by query complexity |
| Context Pruning — trim conversation history | 20–40% on chat apps | Medium — summarise old messages |
| Response Caching — cache identical or near-identical queries | Varies widely | Medium — semantic hash or exact match |
Smart Model Routing
Not every query needs GPT-4o. Build a router that sends simple, factual questions to
gpt-4o-mini and complex reasoning tasks to gpt-4o. A simple heuristic: if the
system prompt is under 500 tokens and the query is under 100 tokens, use mini.
"Implementing model routing dropped our AI API spend by 68% with zero measurable quality degradation for 80% of queries."
On-Device Fallbacks with Apple Intelligence & ML Kit
For offline support and latency-sensitive features, consider on-device models. In 2025, the options are:
- Apple Intelligence (iOS 18+) — text summarisation, smart reply, image
classification via
FoundationModelsframework - Google ML Kit — text classification, translation, smart reply on Android
- Core ML / ONNX Runtime — run custom fine-tuned models (up to ~7B parameters on M-series chips, ~3B on high-end Android)
The pattern we use: attempt on-device first, fall back to cloud if confidence is below threshold or the query requires real-time knowledge.
Rate Limiting & User Quotas
Without rate limiting, a single user can exhaust your monthly API budget in hours. Implement per-user quotas in your backend (Redis counter, reset at midnight UTC) and expose remaining quota to the app so the UI can degrade gracefully — show a "You've used your 20 free messages today" prompt rather than a cryptic error.
Moderate AI outputs before displaying them. OpenAI's Moderation API is free and fast — run all AI responses through it to catch policy violations before they reach users. This also protects you legally.
UX Patterns That Work
- Skeleton loading while waiting for first token (better than a spinner)
- Cursor animation at the end of streaming text — feels like the AI is "thinking"
- Copy button on every AI response — users love this
- Regenerate option — surfaces quality of the model and reduces frustration
- Character/token counter for input fields in chat apps
OpenAI SDK → our Node.js proxy backend → Redis for caching & rate limits → SSE to mobile → SwiftUI / Compose for streaming text rendering. Total setup time: ~2 days for a senior engineer.