SkilVaultSign inStart free

Catalogue / production-llm-blueprint

production-llm-blueprint

Older skill: source not recordedSignedDesigns layered production architectures for LLM applications, covering an API gateway with rate limiting and auth, cost-aware model routing with fallback chains, retrieval-based context assembly, observability with traces and per-model metrics, and tiered caching. Use when planning, reviewing, or s…
---
name: production-llm-blueprint
description: >
  Designs layered production architectures for LLM applications, covering an API gateway with rate limiting and auth, cost-aware model routing with fallback chains, retrieval-based context assembly, observability with traces and per-model metrics, and tiered caching. Use when planning, reviewing, or scaling a production AI service, deciding how to split requests across models, or adding resilience and monitoring to an existing LLM backend. Not for model training or fine-tuning, prompt copywriting, or throwaway single-script prototypes.
license: MIT
---

Production LLM Blueprint

Use this skill whenever the user asks you to design, extend, or audit an application that calls language models in production. Treat the work as five decisions taken in order — shape, routing, context, measurement, guardrails — because each decision constrains the ones after it. Finish with a worked example sized to the user's real traffic so the numbers land in their world, not the abstract.

Decision 1 — Set the shape with five layers

Before writing any code, lay the system out as five layers and adapt the labels to the user's product as you go. The ordering principle is simple: cheap, protective work sits in front of expensive work, so a paid model call happens only after validation, screening, and caching have had their chance to absorb or reject the request.

| Layer | Owns | Why it sits here | | --- | --- | --- | | Edge | Web, mobile, CLI, and partner API clients | Holds nothing but authentication material and transport | | Gateway | Key validation, per-tenant rate limits, payload size caps, input screening | Stops abuse and runaway spend before a paid model is touched | | Orchestration | Model router, response caches, context assembly, agent loops, output screening | The single home for all request-shaping logic | | Model | Primary LLM, fallback LLMs, specialists such as embedders, rerankers, and a small complexity classifier | Isolates provider choices behind one swappable interface | | Data | Vector store for retrieved passages, relational store, shared cache | Keeps retrieval state separate from request handling |

Do not pause for approval on naming. Pick reasonable, consistent names — renaming the layers to match the user's domain vocabulary where it is obvious — and move straight to routing. A later rename is a find-and-replace, not a redesign, but a stalled design delivers nothing.

Decision 2 — Decide who answers each request

Routing is the main cost lever, because most traffic does not need frontier quality. Classify each request as simple or deep, weigh any constraint the caller attached, and only then choose a model. Explicit constraints override the classifier: a quality-critical flag forces the strong model even on short input, while a cost-sensitive flag pins the cheap one.

| Request profile | Constraint | Target | Reasoning | | --- | --- | --- | --- | | Short factual or lookup-style question | Cost-sensitive | atlas-mini | Roughly 82% of top quality at about 4% of the price | | Multi-step reasoning or long input | Quality-critical | atlas-pro | Cheap models lose coherence over long chains | | Classifier unsure or errored | Default | atlas-mini, escalate on low confidence | A cheap default protects the budget during failures |

Wrap every call in a fallback chain: on timeout, provider error, or failed output validation, try the next model in the chain, cap attempts at three, and fail with a distinct error when the chain is exhausted. The runner returns the winning model's name together with the reply so later traces can attribute outcomes correctly.

class Router:
    CATALOG = {
        "atlas-pro":  {"per_1k_tokens": 0.021, "quality": 0.96, "p50_latency": 1.8},
        "atlas-mini": {"per_1k_tokens": 0.0008, "quality": 0.82, "p50_latency": 0.4},
    }

    def pick(self, task):
        if (task.constraint == "quality_critical"
                or task.depth == "deep"
                or task.tokens_in > 6000):
            return "atlas-pro"
        return "atlas-mini"

    def run(self, task, chain=("atlas-pro", "atlas-mini")):
        for name in chain[:3]:
            try:
                reply = self.invoke(name, task)
                if self.output_passes(task, reply):
                    return name, reply
            except ProviderError:
                continue
        raise AllModelsFailed(chain)

Decision 3 — Decide what the model sees

Assemble the prompt's context in four fixed stages instead of dumping everything you can find:

  1. Retrieve the top 8 passages from the vector store.
  2. Rerank them and keep the top 4; ordering matters more than volume.
  3. Compress: if the joined context exceeds 3,500 characters, summarize it before insertion.
  4. Append only the last 6 conversation turns as history, and record the final token count so budgets stay enforceable.

State each stage's cutoffs in your design so the user can tune them later against real traces rather than guesses.

Decision 4 — Decide what you measure

You cannot tune routing rules without per-model cost and latency data, so wrap the model client exactly once, at the boundary between orchestration and the model layer, and emit four signals from that single wrapper: a request counter split by model and outcome, a latency histogram per model, token counters split input and output, and one trace span per generation carrying the model name and the reason it was chosen. The wrapper must return the provider's reply unchanged — metrics are a side effect, never a transformation — and it must stay free of business logic so every code path is measured identically.

class MeteredClient:
    def generate(self, prompt, model, route_reason):
        with tracer.span("llm.generate") as span:
            span.set("model", model)
            span.set("route_reason", route_reason)
            started = time.monotonic()
            try:
                reply = self.inner.generate(prompt, model)
            except Exception:
                REQUESTS.labels(model=model, outcome="error").inc()
                raise
            LATENCY.labels(model=model).observe(time.monotonic() - started)
            TOKENS.labels(model=model, direction="in").inc(count(prompt))
            TOKENS.labels(model=model, direction="out").inc(count(reply))
            REQUESTS.labels(model=model, outcome="ok").inc()
            return reply

Decision 5 — Set the guardrails

  • Cache twice: an exact-match response cache at the gateway and a semantic cache keyed on embeddings in orchestration; state a hit-rate target, for example 30%, so it can be verified against the metrics from Decision 4.
  • Set hard budget caps per API key and per day; on breach, downgrade the model rather than silently continuing.
  • Screen input at the gateway for injection attempts and screen output before it leaves orchestration.
  • Keep provider SDKs behind your own client interface so a fallback swap never touches business code.

Worked example: MiraDesk support copilot

MiraDesk answers 12,000 support tickets per day: 8,400 order-status lookups, 3,000 how-to questions, 600 billing disputes. Route status and how-to traffic to atlas-mini at roughly 900 tokens each (about $6 per day total) and disputes to atlas-pro at roughly 3,000 tokens each (about $38 per day), giving roughly $44 per day. Sending everything to atlas-pro would cost roughly $378 per day, so routing alone cuts spend by about 88%. A 35% exact-match cache hit rate on status questions saves a further $2 per day. If atlas-pro times out twice on a dispute, degrade to atlas-mini and flag the reply as unverified.

What not to do

  • Never place real API keys, customer records, or production credentials in any diagram, sample config, or code you produce; refer to a secrets manager by name and leave the value as a placeholder.
  • Never retry a failing provider without a bound; cap fallback attempts at three and surface a distinct error when the chain is exhausted.

Scope and attribution

This skill produces designs, code, and review notes only; it does not provision cloud resources, create accounts, or call live model APIs, and it does not cover model training or fine-tuning, since routing treats models as fixed building blocks. The workflow is adapted and rewritten from an MIT-licensed skill in the doanchienthangdev/omgkit repository; the full license text ships in the package's THIRD_PARTY_NOTICES.md.