Skip to main content
PlatformInferenceShipped

clawql-inference

Status: Shipped (July 2026)
Package: packages/clawql-inference
Epic: #556

clawql-inference is ClawQL's TypeScript-native inference gateway and model-improvement platform — a LiteLLM-class layer with ClawQL's trust model: WORM-auditable routing, semantic cache, model tier escalation, agent coordination hooks, verdict-filtered export, and fine-tuning flywheel. It is designed as a drop-in OpenAI replacement (OPENAI_BASE_URL=http://127.0.0.1:8080/v1) while closing the production loop that generic proxies leave open.

Related docs: Inference provider plugins · Token efficiency (Layer 5 cache) · Ouroboros library


What it does

CapabilitySummary
GatewayOpenAI-compatible REST (/v1/chat/completions, /v1/models, SSE streaming)
ProvidersBuilt-in OpenAI, Anthropic, Ollama; extensible plugin registry
RoutingFrugal → standard → frontier tier escalation with kill switches
CacheEmbedding similarity semantic cache (cosine threshold + TTL)
ResiliencePer-tier / per-model fallback chains before hard failure
AuthVirtual keys (per-team budgets, rate limits)
EntitlementsOptional plan limits via clawql-payments
ObservabilityDurable call store, logs / trace / spend CLI
FlywheelVerdict-filtered export → fine-tune → register custom model in tier map
AutomationScheduled pipeline worker (cron export when sample threshold met)
Ouroborosmodel_escalation + agent_coordination audit events in lineage store

Architecture overview

flowchart TB
  subgraph clients [Clients]
    SDK[OpenAI SDK / curl]
    CLI[clawql inference complete]
    OB[Ouroboros EvolutionaryLoop]
  end

  subgraph http [HTTP layer]
    AUTH[Virtual key auth middleware]
    OAI[OpenAI-compat router]
  end

  subgraph gateway [Gateway decorator stack — inner to outer]
    CFG[ConfiguredInferenceGateway]
    FB[FallbackChainGateway]
    CACHE[SemanticCachedGateway]
    ENT[EntitlementEnforcedGateway]
    OBS[ObservedInferenceGateway]
  end

  subgraph backends [Backends]
    PLG[Provider plugins openai / anthropic / ollama]
    STORE[(Inference store memory / jsonl / postgres)]
  end

  SDK --> AUTH --> OAI --> OBS
  CLI --> OBS
  OB --> CFG
  OBS --> ENT --> CACHE --> FB --> CFG --> PLG
  OBS --> STORE

Every successful complete() call flows outward through decorators and ends in the call store. HTTP clients additionally pass through virtual-key auth before the OpenAI router invokes the same gateway.


Gateway decorator stack

createInferenceGateway() composes decorators in this order (inner → outer):

LayerModuleWhen activeBehavior
1ConfiguredInferenceGatewayAlwaysResolves provider/model, calls provider adapter
2FallbackChainGatewayCLAWQL_INFERENCE_FALLBACK_ENABLED=1 or chains fileTries alternates on primary failure; sets response.fallback
3SemanticCachedGatewayCLAWQL_INFERENCE_SEMANTIC_CACHE=1Embedding similarity lookup; sets cacheHit
4EntitlementEnforcedGatewayCLAWQL_PAYMENTS_ENFORCE_INFERENCE=1Checks plan limits, records usage
5ObservedInferenceGatewayStore not offAppends InferenceRecord to call store
import { createInferenceGateway } from 'clawql-inference'

const gateway = createInferenceGateway({ env: process.env })
const result = await gateway.complete({
  model: 'anthropic/claude-sonnet-4',
  messages: [{ role: 'user', content: 'Summarize this spec' }],
  correlationId: 'seed_abc_gen_2',
  team: 'eng',
})

Disable layers via options: \{ semanticCache: false \}, \{ fallback: false \}, \{ store: null \}.


HTTP API layer

Entry points

CommandBinaryNotes
clawql inference serveclawql CLIWired via src/onboarding/inference-cli.ts
npx clawql-inferencepackages/clawql-inference/binStandalone sidecar

createInferenceHttpApp() (packages/clawql-inference/src/api/server.ts):

  1. express.json() — 2 MB body limit
  2. GET /healthz — liveness (no auth)
  3. GET /v1 — capability discovery
  4. createVirtualKeyAuthMiddleware — Bearer / x-api-key when keys enabled
  5. createOpenAiCompatRouter — models list + chat completions

OpenAI-compatible endpoints

MethodPathNotes
GET/healthzLiveness
GET/v1/modelsTier map + env models + Ollama tags
GET/v1/models/:idSingle model
POST/v1/chat/completionsBare gpt-4o or provider/model; stream: true SSE

Request headers

HeaderPurpose
Authorization: Bearer <key>Virtual key or upstream-style auth
x-api-key / x-clawql-api-keyAlternative key header
x-correlation-id / x-clawql-correlation-idWORM lineage; echoed on response
x-clawql-tenant-idPlan entitlement tenant override

Drop-in OpenAI client

export OPENAI_BASE_URL=http://127.0.0.1:8080/v1
export OPENAI_API_KEY=<virtual-key-or-upstream-key>
npx clawql-inference
# or: clawql inference serve --port 8080

Provider plugins

Built-ins register via composeDefaultProviderPlugins() unless allow/denylisted:

Plugin idAdapterCredentials
openaiChat completionsOPENAI_API_KEY, CLAWQL_OPENAI_BASE_URL
anthropicMessages APIANTHROPIC_API_KEY, CLAWQL_ANTHROPIC_BASE_URL
ollamaLocal /api/chatOLLAMA_BASE_URL (default http://127.0.0.1:11434)

Model ids use provider/model (e.g. ollama/phi4, anthropic/claude-sonnet-4). Bare public ids like gpt-4o resolve through the registry when a matching provider is configured.

Third-party plugins use the same InferenceProviderPlugin contract — see Inference provider plugins. Subpath export: clawql-inference/plugin.

EnvEffect
CLAWQL_INFERENCE_PROVIDERS=openai,anthropicAllowlist
CLAWQL_INFERENCE_DISABLE_PROVIDERS=ollamaDenylist

Model tier escalation

TierEscalationRouter implements AdaptiveRouter with three tiers:

TierDefault model (env override)Role
frugalCLAWQL_INFERENCE_MODEL_FRUGALollama/phi4Cheapest / custom fine-tuned
standardCLAWQL_INFERENCE_MODEL_STANDARDgroq/llama-3.3-70bBalanced
frontierCLAWQL_INFERENCE_MODEL_FRONTIERanthropic/claude-sonnet-4Highest capability

Kill switches:

  • Escalation is off by default unless CLAWQL_INFERENCE_ROUTING_ENABLED=1 or CLAWQL_INFERENCE_MODEL_PIN is set
  • CLAWQL_INFERENCE_MODEL_PIN=<modelId> bypasses the ladder

Tier map overrides persist at $CLAWQL_HOME/Inference/tier-map.json (written by clawql inference finetune register or escalation set-tier).

clawql inference escalation show
clawql inference escalation set-tier --tier frugal --model ollama/phi4-custom

Ouroboros integration

When EvolutionaryLoop runs with an AdaptiveRouter:

  1. router.initialTier() picks starting tier per seed / decomposed-child context
  2. On generation failure (AC fail, low eval score, drift exceeded), router.escalate() moves one notch up
  3. model_escalation audit events append to the Ouroboros Postgres / in-memory event store
  4. Correlation id: \{seedId\}_gen_\{n\}

See Agent coordination for the Hermes tripwire path.


Semantic cache

Layer 5 in token efficiency. Enabled with CLAWQL_INFERENCE_SEMANTIC_CACHE=1.

SettingDefaultPurpose
CLAWQL_INFERENCE_CACHE_THRESHOLD0.92Cosine similarity floor
CLAWQL_INFERENCE_CACHE_TTL24hEntry TTL
CLAWQL_INFERENCE_CACHE_MAX_ENTRIES1000In-memory cap
CLAWQL_EMBEDDING_MODELtext-embedding-3-smallEmbedding model

Cache hits return stored responses with cacheHit: true on inference records. Embedding failures fail open to live inference.

clawql inference cache   # show active config

Fallback chains

When the primary provider/model fails, try configured alternates before surfacing an error.

export CLAWQL_INFERENCE_FALLBACK_ENABLED=1
export CLAWQL_INFERENCE_FALLBACK_FRUGAL=ollama/phi4,openai/gpt-4o-mini
export CLAWQL_INFERENCE_FALLBACK_STANDARD=groq/llama-3.3-70b,anthropic/claude-haiku-4

Chains also persist at $CLAWQL_HOME/Inference/fallback-chains.json (byTier / byModel). Responses include fallback.attempted and fallback.succeeded.

clawql inference fallback

Virtual keys and HTTP auth

Per-team API keys with optional USD budgets and rate limits (100rpm, 10rps).

export CLAWQL_INFERENCE_KEYS_ENABLED=1
clawql inference keys create --team eng --budget-usd 500 --rate-limit 100rpm
clawql inference keys list
clawql inference keys revoke --id vk_abc123

Keys persist at $CLAWQL_HOME/Inference/virtual-keys.json (secrets stored as SHA-256 hashes only). When enforcement is active, /v1/* requires a valid key; /healthz stays open.

team and virtualKeyId are stamped on inference records; spend rollups support --group-by team.


Plan entitlements (clawql-payments)

When CLAWQL_PAYMENTS_ENFORCE_INFERENCE=1, the gateway checks plan limits before each completion and increments inference_calls usage after success. Tenant resolution order:

  1. x-clawql-tenant-id header
  2. Virtual key team
  3. $CLAWQL_HOME/Payments config default tenant

Limit breaches throw EntitlementLimitError (HTTP 402-shaped OpenAI error) and append a WORM payment audit entry. Configure plans via clawql payments — see packages/clawql-payments.


Inference call store

Every successful completion writes an InferenceRecord used by observability and export.

Backends

CLAWQL_INFERENCE_STOREBehavior
offNo persistence
memoryIn-process (tests)
jsonlAppend-only file (default when CLAWQL_HOME set)
postgresclawql_inference_calls table (JSONB records)

Postgres: CLAWQL_INFERENCE_DATABASE_URL or split CLAWQL_INFERENCE_DB_* vars. Default JSONL path: $CLAWQL_HOME/Inference/calls.jsonl.

Record fields

FieldPurpose
id, correlation_idLink to WORM / Ouroboros generation
timestampExport date-range filters
model_id, provider, tierModel and escalation tier at call time
team, virtual_key_idVirtual key attribution
messages, responseFine-tuning message pairs
usageToken counts
latency_msQuality filtering
cache_hitCost attribution
routingModelEscalationDecision snapshot
evaluator_verdictpassed / failed / noneprimary export filter
evaluator_scoreConfidence floor filters
policy_versionManifest Merkle anchor (when set)

Observability CLI

clawql inference logs [--model M] [--tier T] [--since 24h] [--limit 50]
clawql inference spend [--group-by model|tier|team|provider] [--since 7d]
clawql inference trace --correlation-id <id>

Export and fine-tuning flywheel

Production traffic
  → WORM-logged inference (prompt, response, tier, verdict, correlation_id)
  → Evaluator verdicts + quality filters
  → PII-scrubbed dataset export (JSONL)
  → Fine-tuning job (Anthropic / OpenAI)
  → Custom model registered in ModelTierMap
  → Deployed to Frugal tier
  → Better cheap-tier results → better verdicts → better training data

LiteLLM routes inference. ClawQL closes the loop: infer → observe → evaluate → export → fine-tune → redeploy.

Export

clawql inference export \
  --output ./training-data/export.jsonl \
  --verdict passed \
  --tier frugal \
  --format openai-jsonl \
  --min-score 0.8
FormatTarget
openai-jsonlOpenAI fine-tuning
anthropic-jsonlAnthropic fine-tuning
raw-jsonlFull inference records
sharegptCommunity tooling interop

PII scrubbing (Presidio) is on by default. Every export writes a WORM dataset manifest (sample hashes, filter criteria, Merkle root, policy version).

Fine-tune and register

clawql inference finetune \
  --dataset ./training-data/export.jsonl \
  --base-model gpt-4o-mini \
  --provider openai

clawql inference finetune status --job-id ftjob_abc123
clawql inference finetune register --job-id ftjob_abc123 --tier frugal --alias ollama/phi4-production-v3

Pipeline automation

Scheduled auto-export when sample thresholds are met.

clawql inference pipeline enable \
  --schedule "0 2 * * 0" \
  --min-samples 500 \
  --verdict passed \
  --target-tier frugal \
  --base-model gpt-4o-mini

clawql inference pipeline status
clawql inference pipeline run          # manual trigger
clawql inference pipeline worker       # cron sidecar

Config persists at $CLAWQL_HOME/Inference/pipeline.json. Cron worker:

  • CLAWQL_INFERENCE_PIPELINE_WORKER=1 — starts with inference serve
  • CLAWQL_INFERENCE_PIPELINE_POLL_MS — poll interval (default 60s)
  • Tracks lastRunAt, lastRunStatus, lastRunDetail on each tick

Agent coordination (#562)

TierEscalationRouter.shouldTriggerAgentCoordination() fires when:

  • Combined drift exceeds 0.3, or
  • Standard-tier exhaustion with active failure signals

When CLAWQL_INFERENCE_AGENT_COORDINATION_ENABLED=1:

  1. evaluateAgentCoordination() builds an agent_coordination audit entry
  2. Hermes stub runs when HERMES_BASE_URL is unset; live MoA when configured
  3. Ouroboros appends the event to the lineage store alongside model_escalation

Policy

clawql inference policy show [--json]

resolveInferencePolicy() aggregates the effective view from environment: escalation, cache, fallback, keys, store backend, export defaults, pipeline worker, and agent coordination. Manifest YAML overrides are planned; today the source is env.


Persistence layout

All operator state under $CLAWQL_HOME/Inference/:

FileWritten by
calls.jsonlCall store (jsonl backend)
tier-map.jsonfinetune register, escalation set-tier
fallback-chains.jsonFallback config merge
virtual-keys.jsonkeys create / revoke
pipeline.jsonpipeline enable / worker ticks

Postgres store uses clawql_inference_calls (separate from CLAWQL_INFERENCE_DATABASE_URL).


CLI wiring

The clawql binary dispatches inference subcommands in src/onboarding/cli.ts → thin wrappers in src/onboarding/inference-cli.tspackages/clawql-inference/src/cli/*.

clawql inference <subcommand>
├── serve              HTTP gateway (+ optional pipeline worker)
├── complete           One-shot completion
├── logs | trace | spend
├── export | finetune [status|register]
├── escalation [show|set-tier]
├── pipeline [enable|status|disable|run|worker]
├── cache | fallback | policy
└── keys [create|list|revoke]

Environment variables

VariableDefaultPurpose
OPENAI_API_KEYOpenAI provider
ANTHROPIC_API_KEYAnthropic provider
OLLAMA_BASE_URLhttp://127.0.0.1:11434Ollama runtime
CLAWQL_INFERENCE_PORT8080HTTP listen port
CLAWQL_INFERENCE_HOST0.0.0.0HTTP bind address
CLAWQL_INFERENCE_PROVIDERSall builtinsProvider allowlist
CLAWQL_INFERENCE_DISABLE_PROVIDERSProvider denylist
CLAWQL_INFERENCE_ROUTING_ENABLEDoffTier escalation
CLAWQL_INFERENCE_MODEL_FRUGALollama/phi4Frugal tier model
CLAWQL_INFERENCE_MODEL_STANDARDgroq/llama-3.3-70bStandard tier model
CLAWQL_INFERENCE_MODEL_FRONTIERanthropic/claude-sonnet-4Frontier tier model
CLAWQL_INFERENCE_MODEL_PINPin single model
CLAWQL_INFERENCE_SEMANTIC_CACHEoffSemantic cache
CLAWQL_INFERENCE_CACHE_THRESHOLD0.92Cache similarity floor
CLAWQL_INFERENCE_CACHE_TTL24hCache TTL
CLAWQL_INFERENCE_CACHE_MAX_ENTRIES1000Cache size cap
CLAWQL_EMBEDDING_MODELtext-embedding-3-smallEmbeddings model
CLAWQL_INFERENCE_FALLBACK_ENABLEDoffFallback chains
CLAWQL_INFERENCE_FALLBACK_FRUGALFrugal fallback chain
CLAWQL_INFERENCE_FALLBACK_STANDARDStandard fallback chain
CLAWQL_INFERENCE_FALLBACK_FRONTIERFrontier fallback chain
CLAWQL_INFERENCE_KEYS_ENABLEDoffRequire virtual keys
CLAWQL_INFERENCE_STOREjsonl when CLAWQL_HOMEmemory / jsonl / postgres / off
CLAWQL_INFERENCE_DATABASE_URLPostgres URL
CLAWQL_INFERENCE_STORE_PATH$CLAWQL_HOME/Inference/calls.jsonlJSONL path override
CLAWQL_INFERENCE_PIPELINE_WORKERoffCron worker with serve
CLAWQL_INFERENCE_PIPELINE_POLL_MS60000Worker poll interval
CLAWQL_INFERENCE_AGENT_COORDINATION_ENABLEDoffAgent coordination
HERMES_BASE_URLHermes MoA endpoint
CLAWQL_PAYMENTS_ENFORCE_INFERENCEoffPlan entitlement gate

Package exports

ImportContents
clawql-inferenceGateway, routing, store, CLI runners, HTTP server, audit builders
clawql-inference/routingAdaptiveRouter, tier types, config loaders
clawql-inference/pluginProvider plugin factories, compose helpers
clawql-inference/api/servercreateInferenceHttpApp for embedding

Differentiation vs LiteLLM

ClawQLLiteLLM-class proxies
Outcome-driven tier escalation from agent failure signalsStatic model routing
correlation_id → WORM / Ouroboros lineageGeneric request logs
Verdict-filtered export + PII scrub + dataset manifestAd-hoc dataset dumps
Custom models promoted back into frugal tierOne-off fine-tunes
Manifest / policy-governed tier map and export rulesEnv-only config
TypeScript-native, catalog-mirrored adaptersPython proxy dependency

Implementation phasing

PhaseDeliverableStatus
P0-Drouting/ + Ouroboros hooks (#560)
P0-FGateway MVP: serve, complete, provider adapters
P0-GCall store + logs / trace / spend
P0-HExport + Presidio + dataset manifest
P0-IFine-tune jobs + tier registration
P1Pipeline enable + cron worker
P1Model escalation audit (#561)
P1Agent coordination (#562)
AdoptionOpenAI REST, semantic cache, fallback, virtual keys, Postgres store

Planned (not blockers)

  • Langfuse / OpenTelemetry full wiring (ADR 0005)
  • Manifest YAML inference block overrides for policy show
  • Live Hermes MoA HTTP client (stub ships today)
  • Postgres advisory locks for multi-instance pipeline dedup

References