Adam Bandel


Generative Gateway

Nov 2026
Type: api
Code: 16k lines
Files: 74
Active: Nov 2025 to Nov 2026
Stack:
PythonFastAPITypeScriptNext.jsSQLiteOpenRouterOpenTelemetryDocker
Tags:
aideveloper-toolsapi

Overview

Generative Gateway is an HTTP service that sits between my apps and the models they call. Everything goes upstream through OpenRouter, and the gateway puts one API over all of it: chat with images, PDFs or audio as input, plus embeddings, reranking, speech, transcription, image and video generation, and structured decision models. That came to about 600 models when the catalog sync was fixed in September 2026. On top of that it records the cost of every request, keeps conversation sessions, streams responses, enforces per-project budgets and rate limits, and exports metrics and traces.

Because apps call the gateway instead of a provider, switching models or vendors is a change to the model name, not to how the app makes the call. Every request is logged with its token counts, latency and the cost OpenRouter actually charged for it. My own apps and the coding agents I run call models through it instead of calling a provider directly; Music Analyzer and Personal Media Feed are two of them. It has run on my home server as a Docker Compose stack, the API plus a Next.js dashboard, since July 2026.

Screenshots

Chat Interface

Model Catalog

Usage Dashboard

Problem

An app that calls LLMs usually needs to:

Building all of that again for every app is slow and easy to get wrong.

Approach

Requests come in through one schema per route, and an adapter layer translates them for OpenRouter, which fronts the model vendors. OpenRouter still leaves plenty of differences in place, and those are what the adapters handle: each vendor’s reasoning settings, a different upstream endpoint for each kind of output, and usage reports in different shapes.

Routes

Stack

Challenges

Outcomes

The adapters handled the differences between provider APIs well. Most of the complexity was in normalizing responses, because providers return reasoning, tool calls and multi-modal content in wildly different structures. Several of the fixes since January have been to the cost accounting, and those bugs logged a wrong number instead of failing loudly.

Limits

Implementation Notes

Streaming

A streamed chat sends typed Server-Sent Events: meta with the request ID, model and session, then token, reasoning, tool_calls and images as they arrive, error if the upstream fails mid-stream, and done with the token counts, latency, the provider’s finish_reason, and whether the reply was truncated and why.

Cost Calculation

The cost comes from OpenRouter’s own usage block:

# Authoritative cost: OpenRouter returns the actual amount charged in
# usage.cost (credits == USD) because the adapter sends usage.include=true.
# This reflects the specific upstream provider that served the request,
# which varies per call for multi-provider model slugs (e.g. DeepSeek V4
# Pro served by Novita vs Alibaba vs GMICloud at different prices).
usd = float(usage.get("cost") or 0.0)
provider_returned_cost = usage.get("cost") is not None

Only when provider_returned_cost is false does it fall back to tokens times the cached per-token price, plus the model’s web search price, or $0.01 a search when the catalog has none.

Model Resolution

A request can name a model by its full ID, OpenRouter’s bare slug, or an alias. POST /v1/models/resolve fuzzy-matches a typed name against display names and aliases with rapidfuzz:

best = process.extractOne(q_norm, names, scorer=fuzz.token_sort_ratio) if names else None
if best is None:
    return {"id": None, "confidence": 0.0, "matched_alias": None}
match_name, score, _ = best
return {"id": display_to_id.get(match_name), "confidence": float(score) / 100.0, "matched_alias": match_name}

Hedged Requests

A request can opt into hedging: if the first call has not answered within a set number of milliseconds, an identical second call starts, and whichever finishes first wins.

async def hedged_call(
    call_factory: Callable[[], Awaitable[Tuple[int, Dict[str, Any]]]],
    hedge_after_ms: int = 200,
) -> Tuple[int, Dict[str, Any]]:
    task1 = asyncio.create_task(call_factory())
    try:
        await asyncio.wait_for(asyncio.shield(task1), timeout=hedge_after_ms / 1000.0)
        return await task1
    except asyncio.TimeoutError:
        task2 = asyncio.create_task(call_factory())
        done, pending = await asyncio.wait({task1, task2}, return_when=asyncio.FIRST_COMPLETED)
        for t in pending:
            t.cancel()
        done_task = done.pop()
        return await done_task

Related Posts

No posts yet.