/engineering:ai-model-gatewayfrom engineering
Designs and builds an LLM gateway with provider abstraction, tenant-aware routing, fallbacks, quotas, residency, audit logging, cost capture, and kill switches.
Ships in engineering. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
| Input | Required | Purpose |
|---|---|---|
| Domain evidence | yes | provider inventory, tenant plans, residency constraints, request schema, budgets, fallback policy, and kill-switch owner |
Skill-specific outputs:
saas-admin-backoffice-tooling).Default to read-only analysis. Read only scoped records; redact secrets and regulated data. Writes, execution, network calls, production configuration, customer communication, billing changes, and delegation require explicit authority and an identified owner. Never widen tenant, time-window, or system scope implicitly.
When required telemetry, evidence, execution, network access, or write authority is unavailable, return a partial result with each unassessed item labelled, preserve the safest existing state, and state the evidence or approval needed to continue. Never convert missing evidence into a pass.
| Condition | Action |
|---|---|
| Scope, owner, or threshold is missing | Stop the affected decision and request it |
| Evidence is incomplete but read-only analysis is safe | Produce a qualified partial result and gap list |
| A mutation exceeds authority or tenant boundary | Block it and route for approval |
| Evidence meets the stated threshold | Issue the output with provenance and owner |
Acknowledgement: Shared by Peter Bamuhigire, techguypeter.com, +256 784 464178.
ai-on-saas-architecture.ai-llm-integration is the bare-metal SDK skill.ai-prompt-engineering.tenant_ai_binding schema from ai-on-saas-architecture.When the gateway is part of a wider AI data foundation, load AI data foundation selection and operations for data-product contracts, portability, trust, and session-level operations.
SKILL.md.| Category | Artifact | Format | Example |
|---|---|---|---|
| Correctness | Gateway contract | OpenAPI doc | docs/ai/gateway-api.yaml |
| Correctness | Provider capability matrix | Markdown table | docs/ai/provider-matrix.md |
| Release evidence | Fallback policy per tier | Markdown doc | docs/ai/fallback-policy.md |
| Operability | Gateway SLO + on-call runbook | Markdown runbook | docs/runbooks/llm-gateway.md |
references/llm-gateway-design.md — full design (canonical copy lives in ai-on-saas-architecture/references/).references/token-accounting-pipeline.md — how token-in / token-out / cost rolls up.ai-on-saas-architecture, ai-cost-per-tenant-attribution, ai-usage-metering-and-billing, saas-entitlements-and-plan-gating, ai-prompt-injection-and-tenant-safety, ai-observability-and-debugging, saas-rate-limiting-and-quotas.ai_incident_mitigation_log with (actor, ts, primitive, scope, reason, ticket_id), and be invocable from a back-office UI without writing code or SQL. See ai-incident-response-runbook §3 for the full primitive contract and ai-incident-recovery-and-rollback/references/rollback-patterns.md for the un-pin contract.A single endpoint that feature teams call:
POST /v1/generate
Authorization: Bearer <service-jwt> # signed by internal auth
X-Tenant-Id: 8421 # required
X-Feature-Id: support-copilot.answer # namespaced
X-Trace-Id: trc_01HXY... # propagate
{
"prompt_id": "support.answer",
"prompt_version": "latest", // or pinned e.g. "v17"
"variables": { "user_question": "...", "kb_partition_id": "kb_t8421" },
"retrieval": { // optional; gateway can call KB service
"do_retrieve": true,
"top_k": 6
},
"intent": "answer_question",
"user_id": 990012,
"max_tokens_out": 800,
"temperature": 0.2,
"stream": false
}
Response:
{
"request_id": "ai_req_01HXY...",
"model_used": "claude-3.7-sonnet",
"region": "eu-west-1",
"text": "...",
"tokens_in": 1840,
"tokens_out": 412,
"usd_cost": 0.013824,
"latency_ms": 1923,
"fallback_used": false,
"safety_findings": [],
"grounding_score": 0.91,
"citations": [{"chunk_id": "...", "source": "...", "score": 0.83}],
"eval_sampled": false
}
A streaming variant uses Server-Sent Events. The final SSE event carries the full envelope (cost, latency, model, audit id).
1. Authn (service JWT) — verify signature; resolve calling service
2. Authz (tenant + feature) — service is allowed to act for this tenant on this feature
3. Resolve binding — read tenant_ai_binding for tenant
4. Entitlement check — tenant's plan permits this feature/model
5. Kill-switch check — ai_enabled = false → 403 fast
6. Rate limit — Redis token bucket per tenant per feature
7. Cap check — monthly USD/token cap not exceeded
8. Resolve prompt — prompt registry returns (template, model_hint)
9. Render prompt — template + variables (sanitised)
10. Safety in — prompt-injection classifier on user-supplied variables
11. (optional) Retrieval — call KB service with tenant_id (no other path)
12. Provider call — primary; retry once on transient
13. Safety out — PII scrub, jailbreak detect, grounding check
14. Cost compute — tokens × price table → usd_cost
15. Audit write — synchronous; row in ai_requests
16. Cost event — ai.cost.recorded onto event bus
17. Eval sample — N% of requests written to eval queue
18. Respond — envelope to caller
The pipeline is the gateway. Each stage has a hard timeout; stage failures emit gateway.stage.failed traces.
class Provider(Protocol):
name: str
models: list[ModelDescriptor]
regions: list[str]
async def generate(self, req: NormalizedRequest) -> NormalizedResponse: ...
class AnthropicProvider:
name = "anthropic"
models = [
ModelDescriptor("claude-3.7-sonnet", ctx=200_000,
in_price=3e-6, out_price=15e-6),
ModelDescriptor("claude-3-haiku", ctx=200_000,
in_price=0.25e-6, out_price=1.25e-6),
]
regions = ["us-east-1", "eu-west-1"]
async def generate(self, req): ...
Adapter responsibilities:
Anything else (rate limit, retries with backoff, cost compute, audit) lives in the pipeline, not the adapter.
Per tier, an ordered list of (provider, model, region) candidates.
tiers:
enterprise:
primary: [anthropic, claude-3.7-sonnet, region:tenant]
fallback_1: [bedrock, anthropic.claude-3-5-sonnet, region:tenant]
fallback_2: [openai, gpt-4o, region:tenant_or_us]
pro:
primary: [anthropic, claude-3.7-sonnet, region:tenant]
fallback_1: [anthropic, claude-3-5-haiku, region:tenant]
free:
primary: [anthropic, claude-3-haiku, region:any]
fallback_1: [openai, gpt-4o-mini, region:any]
Triggering fallback:
RateLimitError after one retry on primary.Retry-After > slo_budget.Record fallback_used=true in the audit row; alert when fallback ratio for a tier exceeds threshold.
The gateway enforces caps at the atomic check-and-increment level using Redis (saas-rate-limiting-and-quotas algorithms). Three ceilings:
tenant_ai_binding.monthly_usd_cap). On hit: 429 + quota:ai_usd. Upgrade path link in response.quota:ai_tokens_day.ai.budget.threshold event for in-product banner and sales-assist email; no enforcement.For enterprise tenants on a true-up model, replace the hard cap with a paging threshold instead.
tenant_ai_binding.region drives:
When a region's preferred model is unavailable, the gateway consults a region policy:
strict: 503 if the region cannot serve. Used for sovereignty.degraded: allow cross-region with a region_breach=true flag in audit; emit alert.permissive: allow cross-region silently (default for low-sensitivity tenants).Synchronous, in-pipeline, atomic with the response. The gateway returns ONLY after the ai_requests row is committed and the ai.cost.recorded event has been published (or rolled back).
Two writes:
ai_requests row (the legal/compliance record).A reconciliation job nightly compares Postgres rollups vs Redis to detect drift.
See references/token-accounting-pipeline.md.
The gateway reads tenant_ai_binding.ai_enabled from a Redis-cached binding (TTL 30s; invalidated by ai.kill_switched event).
On ai_enabled = false:
{
"error": {
"code": "AI_DISABLED",
"message": "AI features are disabled for this tenant. Contact support.",
"kill_switch_reason": "tenant requested temporary disable"
}
}
The back-office UI (saas-admin-backoffice-tooling) exposes the toggle plus a feature-scoped variant (tenant_ai_feature_disable table).
| Metric | Target |
|---|---|
| Gateway availability | 99.95% |
| Hot-path overhead | < 50ms p95 |
| Audit-write success | 100% (any failure = reject request) |
| Time to roll a new provider | < 1 week from contract to traffic |
| Time to flip kill-switch | < 60 seconds |
| Fallback ratio (enterprise tier) | < 1% sustained |
Dashboards: gateway QPS, p50/p95/p99 latency by stage, error rate by stage, fallback ratio by tier, cost burn by tenant top-20.
if anthropic: ... branches).ai-on-saas-architecture — broader context.ai-cost-per-tenant-attribution — what the gateway feeds.ai-usage-metering-and-billing — how the ledger turns into invoices.ai-prompt-injection-and-tenant-safety — the safety-in/safety-out logic the pipeline runs.ai-observability-and-debugging — traces, replays, debugging.saas-rate-limiting-and-quotas — algorithms the gateway uses.What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
llm-gateway, multi-tenant, provider-routing, fallback, cost-tracking
npx claudepluginhub peterbamuhigire/chwezi-dev-engine --plugin engineering169 skills in this plugin
/accounting-engineUse when designing or implementing double-entry accounting policy and an embedded ledger engine for invoices, payments, stock, balanced postings, mapped accounts, idempotency, reversals, period locks, audit trails, and financial statements./accounting-finance-controllerUse when coordinating accounting and finance implementation reviews, doctrine routing, control evidence, remediation priorities, and release decisions across a software system./advanced-testing-strategyUse when designing or reviewing test strategy for production systems, APIs, mobile apps, SaaS platforms, ERP workflows, and AI-enabled systems. Covers unit, integration, contract, end-to-end, regression, release-gate, and risk-based testing decisions.Other plugins' skills for the same job