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.