HomeCase studiesHigh-Throughput AI API Development, Prompt Versioning, and...

Case study · London, United Kingdom

High-Throughput AI API Development, Prompt Versioning, and Guardrails Platform

LLM Gateway, Prompt Versioning & Guardrails

Product teams shipping LLM-backed features quickly outgrow hardcoded provider SDK calls scattered across microservices, losing visibility into prompt regressions, latency spikes, and sensitive data leaks. We engineered an AI API development platform combining a high-concurrency Python FastAPI inference gateway with a React prompt studio and evaluation console. Developers version prompt templates with JSON schema contracts, run canary traffic splits, enforce inline PII and policy guardrails, and trace every token with OpenTelemetry.

Industry
LLM Gateway, Prompt Versioning & Guardrails
Solution
An enterprise AI API engineering platform pairing a React prompt and eval studio with a Python FastAPI LLM gateway, semantic cache, and inline guardrail pipeline.
Platforms
Web & API
Stack
Python · FastAPI · React · TypeScript · PostgreSQL · Redis
Location
London, United Kingdom · delivered remotely
Role
Engineering, with the team behind for mobile and QA

Delivered remotely for a business based in London, United Kingdom. Names withheld by agreement.

Project Overview

Teams integrating generative AI into customer-facing APIs quickly discover that calling a model provider SDK directly is the easy part; operating reliable, compliant AI endpoints in production is far harder. Prompt templates drift across services without version history, upstream model outages cascade into user-facing errors, and unguarded payloads risk leaking customer PII or breaking strict JSON parsers.

We built an AI API development platform uniting a Python and FastAPI inference gateway with a React prompt-engineering and evaluation console. Application teams call one unified, low-overhead API endpoint while gaining immutable prompt versioning, automated golden-dataset evaluations, inline safety guardrails, and deep OpenTelemetry observability.

Production AI API Friction

Engineering groups scaling multiple LLM-powered features consistently hit operational barriers that raw vendor wrappers leave unsolved:

  • Coupled deployments for prompt tuning: Adjusting system instructions, temperature, or model targets requires risky code deploys and obscures which version handled past user sessions.
  • Unchecked guardrail blind spots: Without centralized pre-request and post-response checks, user inputs leak sensitive identifiers or slip past brittle formatting instructions.
  • Silent quality regressions: Swapping to a newer or cheaper model checkpoint subtly degrades structured extraction accuracy unless validated systematically against historical baselines.
  • Opaque latency and spend attribution: Standard HTTP logs capture response codes but miss time-to-first-token, cached-token ratios, guardrail overhead, and per-feature burn rates.

Architectural Strategy

We designed the platform around a stateless-hot-path FastAPI proxy coupled with a versioned control plane. Application services integrate once using familiar OpenAI-compatible HTTP contracts or lightweight SDKs, passing a logical endpoint_slug and structured variables rather than raw prompt strings.

FastAPI resolves the active routing policy—including weighted canary splits and cached prompt templates synced from PostgreSQL into Redis—runs parallel PII and injection guardrails, checks tenant-scoped semantic caches, and streams tokens back via async Server-Sent Events. Every request emits structured OpenTelemetry spans consumed by the React workbench for live trace inspection and regression testing.

Core Capabilities

  • Immutable Prompt & Schema Registry: Versioned templates with variable typing, required JSON Schema output validation, and instant rollback across environments.
  • Canary Routing & Multi-Provider Failover: Weighted traffic splitting across model families paired with Redis circuit breakers that divert traffic during upstream provider brownouts.
  • Inline Pre/Post Guardrails: Fast deterministic PII masking, secret detection, topic-boundary classifiers, and automated JSON repair retries before responses reach callers.
  • React Playground & Eval Diffing: Side-by-side prompt editor executing batch comparisons across model candidates against golden evaluation datasets with rubric scoring.
  • Token-Level OpenTelemetry Tracing: Captures prompt version, cache hit status, guardrail latency, upstream time-to-first-token, and tenant cost tags in unified trace waterfalls.

Technical Architecture

Backend callers send typed requests to FastAPI, which authenticates API keys, checks Redis token-bucket rate limits and semantic caches, executes inbound PII scrubbing, resolves canary model weights, and proxies streaming completions upstream. Asynchronous background pipelines flush OpenTelemetry traces and sample production traffic for offline evaluation inside PostgreSQL and React.

Flow: Client API Request → FastAPI Gateway (Auth & Redis Rate Limits) → Inbound PII & Policy Guardrails → Tenant Semantic Cache Check → Canary Router & Failover Proxy → Upstream LLM Providers → Streaming Validation + OpenTelemetry Export → React Studio & Eval Console

Keeping the hot inference path strictly async in Python with in-memory Redis policy caches avoids database round-trips during live token generation while preserving rich control-plane governance.

Technology Stack

Category Technology detail
Prompt & Eval Workbench React and TypeScript powering prompt diffs, side-by-side model testing, and trace views
LLM Gateway Runtime Python and FastAPI handling async SSE streaming, retries, and provider abstraction
Registry & Eval Store PostgreSQL storing immutable prompt versions, schema contracts, and dataset runs
Cache & Rate Limiter Redis powering semantic response caching, token buckets, and circuit-breaker state
Guardrail Pipeline Low-latency PII redaction, prompt-injection classifiers, and JSON schema validators
Observability Layer OpenTelemetry exporting latency spans, time-to-first-token, and token cost tags
Traffic Router Weighted canary and failover policy engine spanning multiple foundation model APIs
SDK & Contract Layer Typed OpenAI-compatible HTTP endpoints and versioned TypeScript/Python client SDKs

Engineering Trade-offs & Solutions

Engineering Challenge Solution & Trade-off
Running PII and policy checks without stalling streaming time-to-first-token Executed regex and compact local classifiers concurrently on ingress and buffered short sliding windows on SSE output rather than waiting for full completions; adds slight stream complexity while protecting responsiveness.
Ensuring prompt updates never wait on PostgreSQL reads during traffic spikes Pushed compiled prompt bundles and routing tables into Redis via pub/sub invalidation on publish; introduces brief eventual-consistency windows in exchange for fast in-memory lookups.
Preventing semantic caches from leaking context across tenants or prompt versions Included tenant namespace, exact prompt version hash, and model settings inside every vector/exact cache key; lowers cross-tenant hit rates intentionally to guarantee strict isolation.
Auditing production outputs without choking gateway throughput Buffered OpenTelemetry span payloads in memory and shipped traces asynchronously to collection queues; risks dropping rare un-flushed traces on hard pod kills while keeping p99 gateway latency low.

Security & Reliability

As the central conduit for enterprise AI traffic, the gateway enforces tenant-scoped API keys, mTLS upstream options, and zero-retention provider headers. Inbound redaction replaces detected payment tokens, national identifiers, and private keys with reversible session placeholders before prompts leave the VPC—re-hydrating authorized fields strictly on return when workflows permit.

To protect downstream application stability, FastAPI isolates upstream connections behind configurable timeouts, bounded connection pools, and automatic fallback chains. If a streaming response violates its declared JSON Schema contract, the gateway either triggers a constrained repair pass or returns a deterministic validation error rather than passing malformed payloads to calling services.

Performance & Scale

FastAPI leverages Python asyncio and pooled HTTP/2 transports so a single stateless gateway replica sustains thousands of concurrent open SSE streams waiting on upstream model tokens. Redis tracks per-tenant token-per-minute and request-per-minute buckets atomically, shielding shared provider quotas from runaway client loops.

Inside the React evaluation console, large batch dataset runs stream progress asynchronously via worker queues, letting engineers inspect failing rows, compare token footprints, and promote winning prompt versions without browser timeouts.

Operational Outcomes

Standardizing generative AI traffic through a dedicated FastAPI gateway and React engineering studio brought discipline to rapid AI product delivery:

  • Decoupled release velocity: Product teams iterate on prompts, test against regression datasets, and roll out canary splits without scheduling backend code deploys.
  • Consistent safety posture: Centralized PII redaction and schema enforcement apply uniformly across every internal service calling foundation models.
  • Resilient multi-provider uptime: Automated health checks and failover routing shield end users when individual model APIs degrade.
  • Actionable cost and latency clarity: OpenTelemetry attribution ties every token and millisecond directly to specific prompt versions and product endpoints.

01 — Questions

asked about this kind of project

How does the FastAPI gateway enforce PII and safety guardrails without ruining streaming time-to-first-token?

Inbound request checks run deterministic regex and lightweight local ONNX/classifier passes concurrently inside FastAPI before dispatching upstream. For outbound SSE streams, a sliding token-window buffer validates policy boundaries with minimal holdback while structured-output endpoints validate full JSON payloads before release.

Why decouple prompt templates and model parameters from application code releases?

Hardcoding prompts inside application repositories forces full CI builds for minor wording tweaks or provider switches. Storing immutable prompt versions and fallback routing rules in PostgreSQL lets teams test against golden datasets in React and shift canary weights instantly.

How do you prevent semantic caching from returning stale or cross-tenant responses?

Cache keys in Redis are strictly namespaced by tenant ID, prompt version hash, model parameters, and user permission tags—never shared globally—with configurable TTLs and explicit bypass headers for non-cacheable queries.

What happens when a primary foundation model provider experiences elevated HTTP 429s or regional downtime?

Redis-backed sliding-window health trackers trip circuit breakers automatically when error rates or tail latencies breach policy thresholds, transparently failing over to pre-mapped secondary model endpoints that satisfy the request's schema and capability tier.

How does the platform verify that a prompt edit does not break downstream JSON consumers?

Every prompt version binds to an explicit JSON Schema contract. Before promoting a draft from staging to production traffic, FastAPI runs automated batch evaluations over curated test suites in React and flags any schema mismatch or regression score.

03 — Similar project?

describe what is different about yours

Build yours.

Tell me what exists, what you need and the deadline. Fixed price for a defined scope, or $55/day (8–9 hours work) with a written plan first.

Solitaire Corporate Park, Makarba, Ahmedabad, Gujarat 380015, India · IST (UTC+5:30) · --:-- IST · Mon–Fri 09:00–18:00 IST · US & EU overlap daily

No newsletter, no CRM. Just a reply.