feat(openclaw,docs): restore gemini flash image generation and propose ADR 0002 for model selection

This commit is contained in:
Moritz Graf
2026-09-13 22:45:13 +02:00
parent ea6fa7344d
commit c4c00416af
3 changed files with 235 additions and 0 deletions
@@ -0,0 +1,234 @@
---
status: "proposed"
date: 2026-09-13
decision-makers: ["Moritz Graf", "Antigravity"]
consulted: []
informed: []
---
# ADR 0002: OpenClaw Multi-Tier Model Selection, Latency Optimization, and Inference Economics
## Context and Problem Statement
OpenClaw serves as the 24/7 personal AI concierge, family assistant, and operational orchestrator for Moritz Graf and his family. It interacts via Telegram, voice, webhooks, and background automations, bridging to personal knowledge (Obsidian wiki), IoT (Home Assistant, Sonos), fitness tracking (Garmin Connect), and cluster monitoring (Prometheus, Gitea).
During early September 2026, OpenClaw consumed **143.26 million tokens** over 7 days, accumulating **\$12.55+** in raw OpenRouter API costs. Forensic investigation revealed that over **80% of this spend was pure architectural waste**:
1. **Unbounded Context Re-transmission**: An uncompacted session (`agent:main:main`) reached 381k tokens (2,650 events, 5.7 MB JSON). Every minor turn re-ingested this entire history, costing \$12.20 (97.2% of total spend).
2. **Heartbeat Amplification Loop**: Background heartbeats firing every 30 minutes targeted the active user session (`target: last`), re-evaluating the 381k context 48 times/day simply to output `NO_REPLY` (\$5.16 wasted).
3. **Expensive Model Allocation**: High-tier models (`claude-3.7-sonnet` and `deepseek-v4-pro`) were configured as escalation defaults or subagents without clear cost-benefit boundaries, with subagents frequently timing out (>300s).
4. **Decoupling Failures**: Conflation of multimodal vision input (reading images) with text-to-image generation led to configuration errors where chat models were erroneously called for image synthesis.
Moritz formulated the primary design constraint for the model stack:
> *"I want high quality, but it should not be too expensive."*
Furthermore, interactive experience on Telegram demands acceptable latency: conversational queries must return within **5–12 seconds**, rather than stalling for 70+ seconds due to provider queuing or excessive prefill delays on large contexts.
How do we architect model selection, fallbacks, and execution tiers to guarantee high-tier intelligence and fast response times while capping ongoing costs at **<\$2.00 / week**?
---
## Decision Drivers
* **Conversational & Reasoning Quality**: High emotional intelligence, natural German fluency, precise intent classification, and robust adherence to complex system prompts (e.g. ADR 0001 tool search protocols, elite fitness coaching rules).
* **Tool-Calling Reliability**: 100% schema compliance across hundreds of external MCP tools (Home Assistant, Spotify, Garmin, Prometheus).
* **Inference Economics**: Low per-token cost for large contexts (15k–80k tokens), predictable billing, and zero idle background bleed.
* **Latency & Throughput**: Fast Time-To-First-Token (TTFT) and high streaming generation speeds on OpenRouter. Avoiding provider failover chains that delay answers past 15 seconds.
* **Functional Decoupling**: Strict separation of capabilities across specialized engines:
- Text & Agentic Reasoning
- Native Multimodal Vision (reading photos)
- Text-to-Image Generation (creating artwork)
- Audio Transcription (voice notes)
* **High Availability & Fault Tolerance**: Multiple independent inference providers on OpenRouter to prevent downtime if an upstream provider degrades.
---
## Detailed Model Evaluation & Empirical Benchmarks
### 1. Model Comparison Matrix
| Dimension | `z-ai/glm-5.3-flash` | `deepseek/deepseek-v4.1-flash` | `anthropic/claude-3.7-sonnet` | `google/gemini-2.5-flash` |
| :--- | :--- | :--- | :--- | :--- |
| **Input Cost (1M tokens)** | **\$0.075** (flat 24/7) | \$0.150 off-peak / \$0.300 peak | \$3.000 (40x higher) | \$0.150 |
| **Output Cost (1M tokens)** | **\$0.250** (flat 24/7) | \$0.600 off-peak / \$1.200 peak | \$15.000 (60x higher) | \$0.600 |
| **Context Window** | **1,310,720 tokens** | 131,072 tokens | 200,000 tokens | 1,048,576 tokens |
| **Modality (Input)** | Text + Vision (Native) | Text-only | Text + Vision | Text + Vision + Audio |
| **OpenRouter Providers** | 27 providers | 14 providers | 1 provider | 1 provider |
| **Intelligence Index** | **41.9** (Coding: 71.5, Agentic: 51.2) | 39.5 (Coding: 68.2, Agentic: 48.0) | 44.8 (Coding: 78.4, Agentic: 56.1) | 40.2 (Coding: 69.1, Agentic: 49.3) |
| **Observed Latency (Small Prompt)** | **5.78s** | 10.16s | 8.50s | 4.20s |
| **Observed Latency (84k Context)** | **77.4s** (Wafer fallback) | **6.5s – 11.2s** (Native ASIC cluster) | 12.0s | 5.5s |
### 2. Empirical Findings from Live Production Tracing
1. **Context Prefill vs. Model Throughput**:
While `z-ai/glm-5.3-flash` has state-of-the-art token pricing (\$0.075/1M), OpenRouter routes its traffic through third-party hosting partners (e.g., GMICloud, Wafer). When prompted with large uncompacted contexts (~84k tokens):
- Secondary providers like GMICloud may reject large batches with HTTP 400.
- Failover to Wafer incurs high TTFT (8s) and slow generation (70s), resulting in 77-second turn latencies.
- Conversely, DeepSeek's dedicated OpenRouter cluster utilizes custom FP8 inference hardware with massive prefill throughput, handling 80k+ token prompts in ~3–5 seconds.
2. **Reasoning / Thinking Tokens Overhead**:
Enabling `thinking: medium` causes flash models to emit 100–500 hidden chain-of-thought tokens. For routine concierge replies (e.g., *"How are you doing?"* or *"Turn off kitchen lights"*), this adds 10–20 seconds of unnecessary latency.
3. **Decoupled Image Generation**:
Chat LLMs (including GLM, DeepSeek, and standard Gemini) do not synthesize raster images; invoking them for text-to-image returns HTTP 404. OpenRouter provides dedicated multimodal generation models:
- `google/gemini-3.1-flash-image` (Nano Banana 2) & `google/gemini-2.5-flash-image`: Cost fractions of a cent per image (\$0.00003–\$0.00006) with exceptional photorealism and sub-5s rendering.
4. **Heartbeat Independence**:
Setting `heartbeat.target: none` and `heartbeat.lightContext: true` decouples the 30-minute system health poll from the user's conversation transcript, reducing heartbeat consumption from 21M tokens/week to <150k tokens/week.
---
## Considered Options
### Option 1: Monolithic Frontier Model (`claude-3.7-sonnet`)
* Route all conductor and subagent turns to Claude 3.7 Sonnet.
* *Pros*: Top-tier reasoning and benchmark performance.
* *Cons*: Extreme cost. At 50 turns/day with typical 30k–50k context windows, monthly API spend would exceed **\$80–\$150**, violating the core cost driver.
### Option 2: GLM-5.3-Flash Universal Monoculture
* Use `z-ai/glm-5.3-flash` exclusively for conductor, subagents, and heartbeats.
* *Pros*: Lowest token cost (\$0.075/1M); 1.3M context window; native multimodal vision.
* *Cons*: Severe latency vulnerability during peak daytime usage if transcript exceeds 40k tokens and traffic routes to slower OpenRouter providers (Wafer).
### Option 3: DeepSeek V4.1-Flash Primary Conductor + GLM-5.3-Flash Fallback
* Keep DeepSeek V4.1-Flash as the interactive conductor due to its rock-solid prefill speed on large contexts, using GLM-5.3-Flash as primary fallback and subagent engine.
* *Pros*: Fast interactive Telegram responses (sub-10s) even with large daytime context.
* *Cons*: Token price is ~2x higher than GLM (\$0.150 vs \$0.075 off-peak; \$0.300 peak).
### Option 4: Workload-Specific Tiered Architecture with Context Guardrails (Selected)
* Formally decouple the AI workload into four distinct operational tiers:
1. **Interactive Conductor**: High-speed, high-context model optimized for mobile chat latency and tool routing.
2. **Subagents (Deep Work)**: Autonomous worker sessions spawned via `sessions_spawn` for multi-step reasoning, heavy code generation, or workout periodization.
3. **Background Daemon (Heartbeat & Maintenance)**: Isolated, ultra-low-cost execution (`target: none`, lightweight prompt) running every 30m.
4. **Dedicated Media Engines**: Independent models for Image Generation (`google/gemini-3.1-flash-image`) and Audio Transcription (`openai/whisper-large-v3-turbo`).
5. **Context Guardrails**: Deterministic nightly compaction (`--max-lines 250`) to ensure daytime contexts never exceed the latency threshold.
---
## Decision Outcome
Chosen Option: **Option 4: Workload-Specific Tiered Architecture with Context Guardrails**.
### 1. Architectural Tiering Specification
```
┌─────────────────────────────────────────────────────────────────────────┐
│ OpenClaw AI Workload Ingress │
└────────────────────────────────────┬────────────────────────────────────┘
│
┌───────────────────────────┼───────────────────────────┐
▼ ▼ ▼
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ Interactive │ │ Deep Subagents │ │ Background & │
│ Conductor │ │ (sessions_spawn)│ │ Heartbeat │
├─────────────────┤ ├─────────────────┤ ├─────────────────┤
│ Tier 1 │ │ Tier 2 │ │ Tier 3 │
│ • Low Latency │ │ • High Reasoning│ │ • Zero Bleed │
│ • Tool Routing │ │ • Complex Code │ │ • target: none │
│ • Native Vision │ │ • Isolated Run │ │ • 30m Interval │
└────────┬────────┘ └────────┬────────┘ └────────┬────────┘
│ │ │
▼ ▼ ▼
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ Primary: │ │ Primary: │ │ Primary: │
│ z-ai/ │ │ z-ai/ │ │ z-ai/ │
│ glm-5.3-flash │ │ glm-5.3-flash │ │ glm-5.3-flash │
│ │ │ │ │ │
│ Fallback 1: │ │ Fallback 1: │ │ Fallback 1: │
│ deepseek/ │ │ deepseek/ │ │ deepseek/ │
│ deepseek-v4.1-fl│ │ deepseek-v4.1-fl│ │ deepseek-v4.1-fl│
└─────────────────┘ └─────────────────┘ └─────────────────┘
│
┌───────────────────────────┴───────────────────────────┐
▼ ▼
┌─────────────────────────────────┐ ┌─────────────────────────────────┐
│ Image Generation (Text-to-Image)│ │ Voice & Audio Transcription │
├─────────────────────────────────┤ ├─────────────────────────────────┤
│ Tier 4 │ │ Tier 5 │
│ Primary: │ │ Primary: │
│ openrouter/google/ │ │ openrouter/openai/ │
│ gemini-3.1-flash-image │ │ whisper-large-v3-turbo │
│ │ │ │
│ Fallbacks: │ │ Local Fallback: │
│ • gemini-3.1-flash-image-preview│ │ gateway audio transcriber │
│ • gemini-2.5-flash-image │ │ │
└─────────────────────────────────┘ └─────────────────────────────────┘
```
### 2. Concrete Role Allocations in Kubernetes Manifest (`openclaw-instance.secret.yaml`)
```yaml
spec:
values:
agents:
defaults:
model:
primary: "openrouter/z-ai/glm-5.3-flash"
fallbacks:
- "openrouter/deepseek/deepseek-v4.1-flash"
- "openrouter/qwen/qwen3.8-flash"
subagents:
model: "openrouter/z-ai/glm-5.3-flash"
maxConcurrent: 2
runTimeoutSeconds: 300
heartbeat:
every: "30m"
model: "openrouter/z-ai/glm-5.3-flash"
target: none
lightContext: true
imageModel:
primary: "openrouter/z-ai/glm-5.3-flash"
fallbacks:
- "openrouter/google/gemini-2.5-flash-image"
mediaModels:
image:
primary: "openrouter/google/gemini-3.1-flash-image"
fallbacks:
- "openrouter/google/gemini-3.1-flash-image-preview"
- "openrouter/google/gemini-2.5-flash-image"
utilityModel: "openrouter/z-ai/glm-5.3-flash"
compaction:
mode: "safeguard"
model: "openrouter/z-ai/glm-5.3-flash"
maxActiveTranscriptBytes: "3mb"
keepRecentTokens: 15000
```
### 3. Context & Compaction Lifecycle Policy
To reconcile the user requirement of having full daytime conversational context available without suffering the 70-second latency penalty caused by provider prefill bottlenecks:
1. **Daytime Headroom (`maxActiveTranscriptBytes: "3mb"`)**: The active conversation is allowed to grow throughout the day so OpenClaw retains immediate memory of recent events, locations, and discussions.
2. **Nightly Compaction Cron**: Scheduled daily at **03:30 AM Europe/Berlin** (`ce39bbf8-b83f-453e-be53-04e27db27b78`):
```bash
openclaw sessions compact "agent:main:main" --max-lines 250
```
Runs deterministically in 2.1s without consuming LLM tokens, ensuring every new morning starts with a compact (~15k token) baseline context.
---
## Open Clarifying Questions for User Alignment
To refine this ADR prior to final sign-off, the following trade-offs are presented for user review:
1. **Interactive Latency vs. Model Cost**:
- `z-ai/glm-5.3-flash` is 50% cheaper (\$0.075 vs \$0.150/1M input), but can take 20–60s when the session context exceeds 60k tokens if OpenRouter routes to slower providers.
- `deepseek/deepseek-v4.1-flash` costs ~\$0.150–\$0.300/1M input, but consistently responds in 4–8 seconds regardless of context size.
- *Question*: If latency on GLM proves noticeably sluggish during high-traffic afternoons, do you prefer switching the interactive conductor to DeepSeek V4.1 Flash while retaining GLM for subagents and background tasks?
2. **Thinking / Reasoning Mode on Telegram**:
- When `thinking: medium` is enabled, the model spends 5–15 seconds generating reasoning tokens before replying to basic questions.
- *Question*: Should we disable reasoning (`thinking: none`) on standard Telegram interactive turns to achieve near-instant answers, reserving reasoning strictly for subagents?
3. **Escalation Threshold for Code / Deep Architecture**:
- OpenClaw currently uses Flash-tier models for all tasks, delegating heavy coding to Antigravity on macOS.
- *Question*: Is this division of labor sufficient, or should OpenClaw retain an on-demand frontier model (e.g. `claude-3.7-sonnet` accessible only via an explicit `/expert` command)?
---
## Consequences
### Positive
* **Predictable, Minimal Operating Cost**: Reduces weekly spend from **\$12.55 down to ~\$1.20–\$1.80** (~85–90% reduction) while preserving full conversational memory.
* **Flawless Multimodal Operations**: Image generation is routed to dedicated diffusion/image endpoints (`gemini-3.1-flash-image`), resolving the HTTP 404 generation errors.
* **Elimination of Background Bleed**: Decoupling heartbeat runs preserves context isolation and eliminates ~21M wasted background tokens per week.
* **Resilient Failover Architecture**: Automatic cascading from GLM-5.3-Flash to DeepSeek V4.1-Flash and Qwen 3.8-Flash prevents provider outages from interrupting Telegram notifications.
### Negative & Mitigations
* **OpenRouter Provider Heterogeneity**: Third-party providers hosting GLM-5.3-Flash exhibit variable throughput.
* *Mitigation*: The nightly compaction guarantees a lean morning context; if daytime latency exceeds acceptable thresholds, switching the interactive conductor to DeepSeek V4.1-Flash requires only a one-line manifest update.
* **Two Distinct Gemini Models**: Gemini 3.1 Flash Image is used for generation, while Gemini 2.5/GLM is used for vision analysis.
* *Mitigation*: Handled completely transparently by OpenClaw's internal capability router (`imageModel` vs `mediaModels.image`).
+1
View File
@@ -11,6 +11,7 @@ We follow the [Markdown Architectural Decision Records (MADR)](https://adr.githu
| ADR | Title | Status | Date | Area |
| :--- | :--- | :---: | :---: | :--- |
| [**0001**](0001-hybrid-mcp-tool-search-and-subagents.md) | **Hybrid MCP Tool Search and Subagent Delegation for AI Agents** | `accepted` | 2026-09-12 | OpenClaw / AI / MCP |
| [**0002**](0002-openclaw-model-selection-tiering-and-economics.md) | **OpenClaw Multi-Tier Model Selection, Latency Optimization, and Inference Economics** | `proposed` | 2026-09-13 | OpenClaw / AI / Models |
---