The Agentic AI Codex
Ch 18 · Enterprise AI Architecture & MLOps
Chapter 18 · Architecture at scale

The Cognitive AI Platform — architecture & MLOps

The bridge from "I built an agent in a notebook" to "my organisation runs AI as a regulated, multi-tenant platform service" — inference gateway, model-serving backends, RAG / knowledge services, fine-tuning pipelines, MCP/agent tooling, model governance, observability, security, multi-tenancy and cost controls, designed cloud-agnostic from day one.

18.1 · Why "platform thinking" beats "another model deployment"

One team can ship one model. A national / enterprise programme has to expose AI as a standardised platform service consumed by dozens of ministries, business units, or vendors. The constraints flip:

Single productPlatform
One tenantDozens of tenants — isolation by design
One modelA catalog of models routed by policy
One SDKOpenAI-compatible APIs so any consumer drops in
Trust the devAudit every prompt, output, and tool call
"It works locally"SLO-backed, observable, rollback-ready
Cloud lock-in OKCloud-agnostic patterns; bring-your-own GPU

18.2 · The reference architecture in one picture

Consumers Ministry app SI agent Internal copilot AI Inference Gateway OpenAI-compatible API Auth · quotas · keys Routing & fallback Prompt cache · batching Safety filters / guardrails Audit / OTel hooks SLA enforcement Model serving Frontier hosted (Claude / GPT / Gemini) Open-weight on vLLM / Triton / NIM Fine-tuned tenant models (LoRA) Embedding & rerank services Knowledge plane Vector DB (pgvector / Weaviate) Document ingestion Object storage (S3) MCP / tool catalog Control plane (cross-cutting) Model registry + cards Eval harness + canary Policy-as-code / OPA OTel / Datadog / Dynatrace Infrastructure Kubernetes (KServe / Ray) GPU pools (A100 / H100) Secrets · KMS · IAM CI/CD · GitOps · SBOM

Read this picture top-down: consumers hit one gateway; the gateway routes to the right serving backend; serving may call the knowledge plane; the control plane governs everything (registry, eval, policy, observability); all of it sits on cloud-agnostic infrastructure.

18.3 · The AI Inference Gateway

Definition. A reverse-proxy + policy engine that all consumers hit instead of calling models directly. Speaks an OpenAI-compatible API (so any SDK works), enforces tenant policy, routes to backends, and emits telemetry.

FeatureDefinitionExample
OpenAI-compatible surfaceEndpoints like POST /v1/chat/completions, /v1/embeddings, /v1/responses.Any client written for OpenAI / Anthropic / vLLM drops in with one base-URL change.
Auth & tenancyBearer keys / OIDC tokens carry tenant + scopes; every request is labelled and quota-checked.Ministry A's key cannot read Ministry B's vector store.
RoutingPick the backend by model name, region, cost tier, or capacity.cognitive/general-fast → small model; cognitive/general-deep → frontier.
FallbackIf the primary model 5xx's or times out, retry on a secondary backend within the SLA.Frontier down → fall back to open-weight Llama on vLLM with same schema.
Prompt cacheHash the stable prefix; replay the prefill from cache.50–90% prefill cost cut on long system prompts.
BatchingCoalesce concurrent requests into one GPU batch for throughput.vLLM continuous batching → 5–20× throughput.
Safety filtersInput + output classifiers (PII, toxicity, jailbreak signatures) inline.Llama Guard / Azure Content Safety call at ingress + egress.
SLA enforcementDrop / queue / shed load by tenant priority when capacity is tight.Premium tenant keeps p95 < 2s; free tier gets queued.
Telemetry hookOTel spans for each call: tokens, latency, cost, tenant, model, prompt hash.Datadog / Dynatrace / Tempo dashboards.

18.4 · Model serving backends

Behind the gateway sit one or more serving engines that actually run the forward pass. You choose by model size, throughput needs, latency target, and hardware.

vLLM

Open-source LLM inference engine with PagedAttention and continuous batching. Maximum throughput on GPUs for open-weight LLMs.

NVIDIA Triton

General-purpose inference server (TensorRT, ONNX, PyTorch, Python backends). Mixed model types behind one HTTP/gRPC surface.

NVIDIA NIM

Pre-packaged, optimised inference microservices from NVIDIA for popular models. Zero-tuning, vendor-backed.

KServe

Kubernetes-native model serving CRDs (InferenceService) on top of Knative. Declarative, autoscaling, scale-to-zero.

Ray Serve

Python-first serving on top of Ray. Great for compositional graphs of models + tools.

TGI / TensorRT-LLM

Alternative high-performance LLM serving engines from Hugging Face / NVIDIA.

Performance levers

LeverDefinitionEffect
Continuous batchingAdd new requests into a running batch as soon as a slot frees.5–20× throughput vs static batching.
PagedAttentionManages the KV cache in fixed-size pages like virtual memory.Higher concurrency on the same GPU.
KV / prompt cachingReuse hidden states for repeated prefixes.Slashes prefill cost; lowers TTFT.
Speculative decodingTiny draft model proposes N tokens; big model verifies.1.5–3× faster generation.
QuantizationLower-precision weights and/or activations.Bigger models fit; throughput up.
Tensor / pipeline parallelismSplit a single model across multiple GPUs.Lets you run 70B+ on commodity nodes.
AutoscalingScale replicas on QPS / queue depth / GPU util.Match cost to demand.

18.5 · Multi-tenant AI patterns

PatternDefinitionWhen
Shared pool, soft isolationAll tenants hit the same model replicas; logical separation by API key + quotas.Default for the general-purpose models — cheapest.
Per-tenant endpointDedicated URL / key namespace, still shared compute under the hood.Tenants need their own SLA or vanity URL.
Dedicated GPU poolA pool of GPUs reserved to a tenant.Regulated tenant or noisy-neighbour problems.
Tenant-fine-tuned LoRAOne base model; load per-tenant LoRA adapters per request.Tenant-specific behaviour without forking the base.
Tenant-owned data planeTenant brings their own vector store, S3 bucket, KMS key.Hard data-residency requirements.

Isolation rules you can't break

  1. Every request carries a verified tenant_id claim from auth.
  2. Every vector / SQL / blob query filters on tenant_id at the lowest layer.
  3. Per-tenant quotas (TPM, RPM, $/day) enforced at the gateway.
  4. Per-tenant data boundary — logs and traces also segmented.
  5. Cross-tenant incident drills run quarterly.

18.6 · RAG as a knowledge service

Source (Sharepoint, S3, DB)→ Ingestion (Airflow / Prefect)→ Parse + chunk + embed→ Vector index (per tenant)
Query→ Retrieval policy→ Re-rank→ Grounded LLM (with citations)→ Response + provenance
ConcernPlatform answer
Ingestion at scaleEvent-driven; idempotent jobs; per-source connectors; backfill replay.
Embedding rotationEmbeddings are versioned; re-embedding is a background job with feature flags.
Chunk hygieneHeading-aware splitter; overlap; tagged with source_id, page, section.
Retrieval policyHybrid (dense + BM25) + metadata filter; configurable per knowledge base.
Grounding contractLLM must cite passage IDs; ungrounded answers are rejected.
ProvenanceResponse carries trace: which chunks, which doc versions, which model — for audit.

18.7 · Fine-tuning pipelines — LoRA & PEFT

Definition. Fine-tuning adjusts a pre-trained model on your data. Full fine-tuning updates every weight (expensive, copy-per-tenant). Parameter-Efficient Fine-Tuning (PEFT) trains only a tiny add-on — typically a few million parameters — that plugs onto the frozen base model.

LoRA

Replace a weight update $\Delta W$ with a low-rank product $A B$ where $A, B$ are tiny. 0.1–1% of the parameters; swap-in / swap-out per tenant.

QLoRA

Quantise the frozen base to 4-bit, train LoRA on top. Fine-tunes 65B models on a single 48 GB GPU.

Adapter / IA³ / Prefix tuning

Other PEFT variants — bottleneck adapters, scaling vectors, learned prefixes.

Continued pre-training

More self-supervised training of the base on your domain corpus before any SFT.

SFT (instruction tuning)

Train on (prompt, ideal answer) pairs. Shapes format, tone, task adherence.

DPO / KTO / ORPO

Preference optimisation from ranked (chosen, rejected) pairs.

The pipeline, end to end

Curated dataset→ Dataset card→ Train (LoRA / SFT / DPO)→ Eval gate→ Registry (MLflow / HF)→ Canary→ Production adapter

18.8 · Model registry & lifecycle

A model registry is the source of truth for every model artefact, version, and approval.

ConceptDefinition
Model cardDocument for each model: intended use, training data summary, evals, limitations.
Dataset cardSame idea for the training/eval dataset: source, licence, demographics.
ArtefactImmutable blob (weights, tokenizer, config) referenced by SHA.
Stagestaging → canary → production → archived.
ProvenanceTraining run, code commit, dataset version, evaluator used.
AttestationSigned metadata proving who built the model.
RollbackPromotion is reversible in one command; previous stage is always warm.

Common tools: MLflow Model Registry, Weights & Biases Artefacts, Hugging Face Hub (private), Vertex AI Model Registry, SageMaker Model Registry.

18.9 · MLOps on Kubernetes

LayerTool examplesWhat it does
OrchestrationAirflow, Prefect, Dagster, Argo WorkflowsSchedule + version pipelines.
Distributed trainingRay Train, PyTorch DDP / FSDP, DeepSpeedScale training across GPUs.
Distributed computeRay, Spark, DaskETL, embedding generation, batch inference.
ServingKServe, Ray Serve, vLLM, Triton, NIMDeploy + autoscale models.
Experiment trackingMLflow, W&B, CometLog runs, params, metrics, artefacts.
Feature storeFeast, TectonConsistent feature serving for ML.
CI/CD & GitOpsGitHub Actions, ArgoCD, FluxPromote artefacts and configs by PR.
Secrets / KMSVault, AWS KMS, GCP KMSManage keys, tokens, encryption.

18.10 · Observability — five pillars

PillarWhat you captureTools
MetricsLatency p50/p95/p99, TPM, $/req, GPU util, KV-cache hit, queue depth.Prometheus, OTel metrics, Datadog.
LogsStructured request/response logs with tenant + prompt hash.Loki, Splunk, ELK.
TracesEnd-to-end spans across gateway → model → tools → DB.OpenTelemetry, Tempo, Jaeger, Langfuse.
AuditsAppend-only record of every action.Object storage + tamper-evident hash chain.
HLEMHuman-in-the-Loop Eval / Monitoring — human review of sampled outputs.Argilla, Label Studio, custom queues.

Anomaly & drift signals to alert on

  • Eval score drop > 3% on canary vs baseline.
  • Refusal rate spike (jailbreak attempt or guardrail mis-fire).
  • Tool error rate > 1%.
  • Cost / request > 2× moving average.
  • Hallucination flag rate climbing week over week.
  • Latency p95 above SLO for 5 minutes.

18.11 · Safety, governance & policy-as-code

ControlDefinition
Prompt governanceReviewed library of system prompts with owners, versions, change history.
PII redactionInline regex / NER pipeline that masks emails, IDs, phones before the LLM.
Content filtersClassifier-based input/output checks (Llama Guard, Azure Content Safety).
Policy-as-codeRules expressed as code (OPA / Rego) enforced at the gateway and CI gates.
SBOM & attestationSoftware Bill of Materials for the model + serving stack; signed.
Approval workflowModel promotion needs sign-off from a risk owner, evaluator, and security.
Incident responsePlaybook for: prompt injection, jailbreak, data leak, biased output.

18.12 · GPU / accelerator infrastructure

AcceleratorNotesTypical role
NVIDIA A100 / H100 / H200 / B200FP16 / FP8 / NVLink; most LLM kernels target these.Training + serving anything from 7B to 700B.
NVIDIA L40S / L4Lower TDP; great inference / cost.High-throughput serving for < 70B models.
AMD MI300XBig HBM; ROCm-supported.Cost-effective alternative to H100.
Google TPU v5e / v5pPod-scale training; XLA toolchain.Frontier training; GCP-only.
AWS Trainium / InferentiaCustom silicon, AWS-native.AWS-locked workloads with strong $/token.

Capacity terms you'll be quoted on

  • GPU-hour — one GPU running for one hour.
  • vRAM — accelerator memory; hard ceiling on model size at a given precision.
  • NVLink / NVSwitch — high-bandwidth GPU-GPU interconnect; required for tensor-parallel serving.
  • MIG — Multi-Instance GPU; split one A100/H100 into smaller slices for many small tenants.

18.13 · Cost engineering

  • Right-size the model. Cascade: small first, big on low-confidence.
  • Prompt caching — the cheapest single lever.
  • Batch API — for offline jobs, 50% provider discount.
  • Quantisation — same GPU serves a bigger model or more replicas.
  • Reserved capacity for floor demand, spot/on-demand for bursts.
  • Per-tenant budgets at the gateway — hard caps avoid horror stories.
  • Showback / chargeback dashboards — tenants who see their cost optimise voluntarily.

18.14 · SLAs / SLOs / production-readiness gates

ConceptDefinitionExample
SLIA measurable signal of service quality.p95 TTFT, success rate, RAG faithfulness.
SLOThe target value of an SLI over a window.p95 TTFT < 1.5s over 30 days.
SLAThe customer-facing contract with consequences if SLO is missed.Credits if availability < 99.5%.
Error budget1 − SLO. The bad-time allowance before deploys are frozen.0.5% per month → ~3.6 hours.

The production-readiness checklist

  1. Eval suite green; safety eval green; both reproducible.
  2. Model + dataset cards published; risk sign-off recorded.
  3. Canary plan + auto-rollback wired.
  4. Per-tenant quotas, budgets, and isolation tested.
  5. Observability: metrics, logs, traces, audit, HLEM all live.
  6. Runbooks: outage, drift, incident, data deletion.
  7. Capacity plan and cost model approved.
  8. Compliance review (residency, privacy, sector rules) signed.

18.15 · Vendor & design assurance

  • Publish reference architectures; vendors map their design to them.
  • Run design reviews at three gates: concept, detailed, pre-launch.
  • Define acceptance criteria: functional, performance, safety, observability, security.
  • Demand performance test plans (load, soak, chaos) before sign-off.
  • Use PoCs to de-risk: 2-week timeboxed, scored against a rubric.

18.16 · The "golden path" developer experience

  • SDKs wrapping the OpenAI-compatible API + retries + tenancy headers.
  • Templates / starters: "RAG service", "agent with tools", "fine-tune job".
  • Sample apps showing best practices end-to-end.
  • Onboarding docs: setup → first call → first eval → first deploy → first alert.
  • Office hours + a public roadmap.
A measurable goal
A new developer should go from "given an API key" to "first successful call" in < 10 minutes, and to "first deployed sample app" in < 1 day.

18.17 · Self-check

Q1 · Why is an OpenAI-compatible gateway surface a strategic choice?
It is the fastest protocol
Existing SDKs and new backends slot in without client changes
It is mandated by ISO
It removes the need for auth
Q2 · You need to serve a different fine-tuned behaviour per tenant without duplicating the base model. Best pattern?
Full fine-tune per tenant
Per-tenant LoRA adapters on one shared base model
Different vendor per tenant
Increase context window