AI & Machine Learning

Designing an LLM Gateway: One Internal API in Front of Every Model

A minimal LLM gateway built as a policy enforcement point: a neutral request model, tenant keys, budgets that hold under concurrency, adapters for two real SDKs, redacted logs and a usage ledger, with the gateway/application line drawn explicitly.

Khalid Aboubakr
16 min read
Ai EngineeringLlmArchitectureApi Design
AI Engineering Masterclass, part 5 of 50: designing an LLM gateway, beside an architecture diagram of services calling providers through one policy enforcement point

Twenty requests arrive within the same few milliseconds for a tenant whose remaining budget covers five of them. A gateway that checks spend before each call and records it afterwards admits all twenty, because at the moment each check runs nothing has been spent yet. In the test suite behind this article that version spends 42,400 units against a limit of 20,090. Nothing in it is wrong line by line; the design is wrong, and it is the design most internal gateways start with.

An LLM gateway architecture earns its extra network hop only by enforcing rules that must hold no matter which service is calling: who may use which model, how much they may spend, what is allowed into the logs, and what a provider failure looks like to a caller. This article builds that core as a small Python library with an ASGI front, runs it against the real OpenAI and Anthropic SDKs over a local transport, and is strict about what it leaves out, because most gateways fail by accumulating responsibilities, not by lacking them.

A policy enforcement point, not a prompt library

The usual origin of an AI gateway is convenience. Three services call two providers, someone writes a shared client so that keys live in one place, and the shared client grows: a retry helper, a prompt template registry, a response parser, a cache. A year later every prompt change is a platform release and nobody can say which behaviours are policy and which are leftovers.

A more useful starting point is the access-control term policy enforcement point: the one place a request must pass through, where decisions made elsewhere are applied. Two questions sort almost every proposed feature. Must the rule hold regardless of which application is calling? Can it be decided without knowing what the request means? If both answers are yes, it belongs in the gateway. A spend limit qualifies. So does a model allow-list, a cap on output tokens, and the rule that prompts are not written to logs. A prompt template fails the second question; so does output validation, retrieval, tool execution and anything that needs the conversation's meaning. Those stay with the application that understands them, which is why the executor that runs an agent's tool calls sits in the application and not in the proxy.

Architecture diagram: three internal services call one gateway API; inside the gateway a request passes authentication, model routing, budget reservation and a provider adapter, then settlement and logging; the gateway alone holds provider credentials and writes to a ledger and a logFigure 1. The gateway is the only component that holds provider credentials, so every stage in it is unavoidable for callers.

The figure also shows the precondition that makes any of this real. A gateway is a control only if it is the sole holder of provider credentials and the network refuses direct egress to provider hosts from application workloads. If a team can paste a provider key into its own service, every policy below is advisory.

Hosted and open-source products occupy the same position. LiteLLM's proxy offers virtual keys with budgets and spend tracking in front of a long list of providers, and the Envoy-based project now named Agent Router (formerly Envoy AI Gateway) handles upstream authentication, rate limiting and usage quotas at the proxy layer. Reading a small implementation first makes it easier to judge what those systems do on your behalf and where their defaults differ from what you need.

The neutral request model and its escape hatch

The contract between callers and the gateway is deliberately narrow: an alias, messages, an output cap, a temperature and one extension point.

@dataclass(frozen=True) class ChatRequest: model: str # an alias owned by the platform, never a provider model ID messages: tuple[Message, ...] max_output_tokens: int | None = None temperature: float | None = None provider_options: dict = field(default_factory=dict) # allow-listed per adapter, see adapters.py @classmethod def from_json(cls, body: object) -> "ChatRequest": def bad(message: str) -> GatewayError: return GatewayError(400, "invalid_request", message) if not isinstance(body, dict): raise bad("body must be a JSON object") if unknown := sorted(set(body) - FIELDS): raise bad(f"unknown field(s): {', '.join(unknown)}") # reject, never silently drop model, raw = body.get("model"), body.get("messages") if not isinstance(model, str) or not model: raise bad("model must be a non-empty string") if not isinstance(raw, list) or not raw: raise bad("messages must be a non-empty array") messages = [] for i, m in enumerate(raw): if not isinstance(m, dict) or set(m) != {"role", "content"} or m["role"] not in ROLES \ or not isinstance(m["content"], str): raise bad(f"messages[{i}] must be {{role: system|user|assistant, content: string}}") messages.append(Message(m["role"], m["content"])) if messages[-1].role != "user": raise bad("the last message must have role user") max_out, temperature = body.get("max_output_tokens"), body.get("temperature") if max_out is not None and (type(max_out) is not int or max_out < 1): raise bad("max_output_tokens must be a positive integer") if temperature is not None and (isinstance(temperature, bool) or not isinstance(temperature, (int, float))): raise bad("temperature must be a number") options = body.get("provider_options", {}) if not isinstance(options, dict): raise bad("provider_options must be an object") return cls(model, tuple(messages), max_out, temperature, options)

Three decisions in this class matter more than its size suggests.

Callers name an alias, never a provider model. chat-default is resolved by a route table the platform owns, so a model can be replaced without redeploying eight services. That power cuts both ways. A silent swap changes the behaviour of every prompt tuned against the old model, so a change of route is a release that deserves an evaluation run before it ships, and the response always reports the provider model that actually answered.

Unknown fields are rejected, not dropped. A caller that sends tools to a gateway that does not support tools should get a 400 naming the field. Dropping it produces a successful response to a different question, which is the worst available outcome.

provider_options is an allow-list per adapter. A neutral model that exposes only what all providers share becomes the reason teams bypass the gateway the day they need a provider-specific feature. The opposite mistake, a free-form passthrough, lets a caller override model or anything else the gateway decided. In the tests, {"openai": {"seed": 7}} reaches the provider and {"openai": {"model": "something-expensive"}} is refused before any upstream call.

Authentication uses keys of the form gw_<key id>_<secret>. The store keeps a SHA-256 digest of the secret, finds the record by key id and compares digests in constant time; the key id is safe to put in logs and the key never is. The reasoning is the same as for any service credential and is covered in the guide to authentication and authorization in production. One detail is specific to gateways: an alias the tenant may not use and an alias that does not exist return the same 403 model_not_allowed, so the error cannot be used to enumerate the route table.

Budgets that survive concurrency

The opening failure has a standard cure, borrowed from payment authorisation: reserve the worst case before the call, then settle to the actual amount. The worst case is computable in advance because the gateway controls both terms: an estimate of input tokens and the clamped output cap, each multiplied by the route's price. The input estimate (one token per three UTF-8 bytes plus a per-message allowance) is a heuristic that errs high for ordinary prose, not a bound. Text that tokenises more densely than that can settle above its reservation, and the overshoot is limited to that estimation error; a gateway that needs a hard bound has to count with the provider's own tokeniser or token-counting endpoint.

The reservation must be a single conditional write. Reading the balance and then updating it reintroduces the race one level down.

RESERVE = """ UPDATE budgets SET reserved_micro = reserved_micro + :amount WHERE tenant = :tenant AND period = :period AND spent_micro + reserved_micro + :amount <= :limit """
def reserve(self, tenant: str, period: str, limit_micro: int, amount: int) -> Reservation: """Admit the request only if its worst-case cost still fits. One conditional UPDATE, no read-then-write.""" self.db.execute("INSERT OR IGNORE INTO budgets (tenant, period) VALUES (?, ?)", (tenant, period)) done = self.db.execute(RESERVE, {"tenant": tenant, "period": period, "amount": amount, "limit": limit_micro}) if done.rowcount == 1: return Reservation(tenant, period, amount) spent, _ = self.balance(tenant, period) if spent + amount > limit_micro: # permanent for this period: retrying cannot help raise GatewayError(403, "budget_exhausted", f"budget for {period} cannot cover this request") # only in-flight reservations are in the way; they shrink when those requests settle raise GatewayError(429, "budget_in_flight", "budget is held by requests in progress", retry_after=1)

The UPDATE succeeds only if spent plus reserved plus the new amount still fits, and the database evaluates that condition and the write atomically. The same SQL is valid on PostgreSQL and MySQL, which is what lets the design hold across several gateway processes; an in-memory counter guarded by a lock holds for exactly one.

The two error branches exist because of what the burst test shows. With reservations, five of twenty concurrent requests are admitted and fifteen refused, but when the five settle at their real cost (2,120 units each, against a reserved 4,018) almost half the budget is free again. Telling those fifteen callers that the budget is exhausted would be false, and a client that treats exhaustion as final would give up for the rest of the month. So the ledger distinguishes the cases: 403 budget_exhausted when the amount cannot fit even with nothing in flight, and 429 budget_in_flight with Retry-After when only reservations are in the way. The status codes are chosen for what clients do with them. Retry middleware and both provider SDKs treat a 429 as retryable; a spent budget answered with 429 would be retried until someone noticed the traffic.

The test keeps the naive ledger next to the real one so the difference stays measured:

class CheckThenCharge(Ledger): """The obvious budget check: compare what has been SPENT with the limit, charge after the call.""" def reserve(self, tenant, period, limit_micro, amount): if self.balance(tenant, period)[0] + amount > limit_micro: raise GatewayError(403, "budget_exhausted", "over budget") self.db.execute("INSERT OR IGNORE INTO budgets (tenant, period) VALUES (?, ?)", (tenant, period)) return Reservation(tenant, period, 0) WORST = 18 + 4 * 1000 # 18 estimated input tokens at 1, 1000 output tokens at 4: 4,018 micro-units def burst(ledger, n=20): gateway, key, logs, *_ = build(ledger, budget_micro=5 * WORST) # the budget fits five worst cases ask = {**ASK, "max_output_tokens": 1000} async def go(): return await asyncio.gather(*(gateway.handle(key, ask) for _ in range(n)), return_exceptions=True) results = run(go()) admitted = sum(not isinstance(r, Exception) for r in results) return admitted, gateway, key, results def test_concurrent_burst_overspends_with_check_then_charge_and_not_with_reservations(): admitted, gateway, _, _ = burst(CheckThenCharge()) assert admitted == 20 and gateway.ledger.balance("acme", PERIOD) == (20 * 2120, 0) # 42,400 against 20,090 admitted, gateway, key, results = burst(Ledger()) assert admitted == 5 and gateway.ledger.balance("acme", PERIOD) == (5 * 2120, 0) refused = [r for r in results if isinstance(r, GatewayError)] # the fifteen were refused by reservations, not by spend: that is retryable, and says so assert len(refused) == 15 and {(r.status, r.code, r.retry_after) for r in refused} == {(429, "budget_in_flight", 1)} # once the five settle at their real cost, three more fit; then the refusal becomes permanent outcomes = [] for _ in range(4): try: run(gateway.handle(key, {**ASK, "max_output_tokens": 1000})) outcomes.append("ok") except GatewayError as e: outcomes.append(e.code) assert outcomes == ["ok", "ok", "ok", "budget_exhausted"] assert gateway.ledger.balance("acme", PERIOD) == (8 * 2120, 0) # 16,960 of 20,090: never over

On this fixture the check-then-charge ledger admits all 20 requests and spends 42,400; the reserving ledger admits 5, then 3 more once the first wave settles, and stops at 16,960 of 20,090. The last 3,130 units are unreachable for a request with a 1,000-token output cap and reachable for one that asks for less, which is the right incentive.

The request lifecycle

Every stage of the pipeline is a decision the calling application does not get to make, and their order is part of the design.

async def handle(self, api_key: str | None, body: object) -> tuple[str, ChatResponse]: request_id = f"req_{secrets.token_hex(8)}" # unique across restarts and processes record: dict = {"request_id": request_id, "outcome": "error"} started = time.monotonic() try: # 1. Who is calling? Nothing else runs for an unauthenticated request. key_id, tenant = self.keys.authenticate(api_key) record |= {"tenant": tenant.id, "key_id": key_id} # 2. Is the request well-formed in the neutral contract? req = ChatRequest.from_json(body) # 3. May this tenant use this alias? Unknown and forbidden aliases get the same answer. route = self.routes.get(req.model) if route is None or req.model not in tenant.models: raise GatewayError(403, "model_not_allowed", f"model '{req.model}' is not available to this key") record |= {"alias": req.model, "provider": route.provider, "model": route.model} # 4. Clamp the output, then reserve the worst case this call can cost. max_out = min(req.max_output_tokens or route.default_max_output_tokens, tenant.max_output_tokens) worst = route.cost(Usage(estimate_input_tokens(req), max_out)) reservation = self.ledger.reserve(tenant.id, self.period(), tenant.budget_micro, worst) meter = dict(request_id=request_id, alias=req.model, provider=route.provider, model=route.model) # 5. Call the provider under the gateway's deadline, and settle whatever happens. try: async with asyncio.timeout(route.timeout_s): response = await self.adapters[route.provider].complete(route.model, req, max_out) except BaseException as exc: rejected = isinstance(exc, GatewayError) and exc.code not in AMBIGUOUS if rejected: # the provider answered with an error: nothing was billed self.ledger.release(reservation) else: # timeout, disconnect, cancellation: it may have billed it all self.ledger.settle(reservation, **meter, input_tokens=0, output_tokens=0, cost_micro=worst, estimated=True) record |= {"cost_micro": worst, "estimated": True} if isinstance(exc, TimeoutError): raise GatewayError(504, "provider_timeout", "the model provider did not answer in time") from exc raise cost = route.cost(response.usage) self.ledger.settle(reservation, **meter | {"model": response.model}, input_tokens=response.usage.input_tokens, output_tokens=response.usage.output_tokens, cost_micro=cost) record |= {"outcome": "ok", "finish": response.finish, "model": response.model, "cost_micro": cost, "input_tokens": response.usage.input_tokens, "output_tokens": response.usage.output_tokens} if tenant.log_content: # opt-in, and never unredacted prompt, found = redact("\n".join(m.content for m in req.messages)) completion, found_out = redact(response.text) record |= {"prompt": prompt, "completion": completion, "redactions": {k: found.get(k, 0) + found_out.get(k, 0) for k in found | found_out}} return request_id, response except GatewayError as exc: record |= {"status": exc.status, "error": exc.code} exc.request_id = request_id raise finally: record["latency_ms"] = round((time.monotonic() - started) * 1000) self.log(record) # exactly one record per request, on every path

Inside handle, authentication comes before validation of the request against the contract, so an anonymous caller learns nothing about fields, aliases or budgets. The ASGI front does two things earlier, for its own protection: it enforces the body size limit and rejects bytes that are not JSON. The output cap is clamped before the reservation because the reservation is computed from it. The log record is written in finally, so there is exactly one per request whatever happened.

The settlement block deserves the closest reading. A provider failure has two different meanings for money. If the provider answered with an error status, it reported no usage; the gateway treats that as unbilled and releases the reservation. If the gateway stopped waiting (a timeout, a dropped connection, a cancelled task because the caller disconnected) the provider may have generated every token and will bill for them. The gateway cannot know, so it keeps the worst case as spent and marks the usage event estimated, to be corrected later against the provider's usage export. The alternative, releasing on timeout, means a provider brown-out lets a tenant exceed its budget by exactly the amount nobody measured. It is the same ambiguity that idempotency keys exist to resolve for payments, with the difference that a completion cannot be made idempotent.

Sequence diagram of one request: the caller sends a request, the gateway authenticates it, reserves the worst-case cost in the ledger, calls the provider through an adapter, settles the reservation to the reported usage, writes one log record and returns the response; a timeout branch keeps the reservation as an estimated chargeFigure 2. One request through the policy stages. Money moves twice: a reservation before the call and a settlement after it.

Adapters: where providers stop looking alike

Each adapter turns the neutral request into one SDK call and the SDK's response back into a ChatResponse. The mechanical differences are small, and each one has broken somebody's model provider abstraction: the Messages API takes the system prompt as a top-level field and requires max_tokens, while Chat Completions takes system messages inline and names the cap max_completion_tokens. The test suite asserts the exact JSON body each SDK sends.

Two differences are less visible. The first is token accounting. Anthropic's input_tokens excludes tokens read from or written to the prompt cache, and its documentation gives total input as the sum of three fields; OpenAI reports cached tokens as a breakdown inside the prompt total. An adapter that copies input_tokens from both will under-count one provider by whatever fraction of the prompt was cached, and the budget will drift from the invoice. The adapters here normalise both to total input. They do not price cached tokens differently, which a production ledger must.

The second is the error surface, where a naive proxy leaks the wrong facts:

def translate(exc: Exception) -> GatewayError: """Map either SDK's exception to what the CALLER should see. Both SDKs share these class names.""" kind = type(exc).__name__ if kind == "APITimeoutError": return GatewayError(504, "provider_timeout", "the model provider did not answer in time") if kind == "APIConnectionError": return GatewayError(502, "provider_unreachable", "could not reach the model provider") status = getattr(exc, "status_code", None) if status == 429: header = exc.response.headers.get("retry-after", "") retry_after = float(header) if header.replace(".", "", 1).isdigit() else None return GatewayError(429, "provider_rate_limited", "the model provider is rate limiting", retry_after) if status in (401, 403): # the GATEWAY's credential failed; the caller's key was fine return GatewayError(502, "provider_auth", "gateway misconfiguration; the platform team has been notified") if status in (400, 413, 422): return GatewayError(400, "provider_rejected", "the model provider rejected the request") return GatewayError(502, "provider_error", "the model provider failed")

A 401 from the provider means the gateway's own credential is wrong. Passing it through tells a caller with a perfectly valid key to go and rotate it. It becomes a 502 and an alert. A provider 429 stays a 429 and carries Retry-After through, because the caller's correct reaction is to wait. Raw provider error bodies are never forwarded; they can contain organisation identifiers and request fragments.

Both SDK clients are constructed with max_retries=0. The installed versions default to two automatic retries, which is reasonable for a script and wrong beneath a gateway: every hidden retry stretches the caller's latency, multiplies load on a provider that is already refusing work, and makes the gateway's own retry policy a guess. The test asserts one upstream call per failed request.

Logging, redaction and the usage ledger

The gateway produces two records per request and they are not interchangeable. The usage event is written in the same transaction that settles the budget; it is the billing record and must be complete. The request log is for debugging and may be sampled, shipped late or dropped. Deriving invoices from logs works until the day the log pipeline loses an hour.

By default the log contains no prompt and no completion, only metadata. A tenant can opt in to content logging, and content then passes through redaction first:

def redact(text: str) -> tuple[str, dict[str, int]]: """Replace what the patterns recognise and report how many of each kind were removed.""" counts: dict[str, int] = {} def swap(kind: str, keep=lambda match: True): def repl(match: re.Match) -> str: if not keep(match.group()): return match.group() counts[kind] = counts.get(kind, 0) + 1 return f"[{kind}]" return repl text = SECRET.sub(swap("secret"), text) text = EMAIL.sub(swap("email"), text) text = CARD.sub(swap("card", luhn), text) # a 16-digit order number that fails Luhn stays readable return text, counts

This is the record produced for an opted-in tenant by demo.py in the examples directory (the request id, key id and latency vary between runs and are fixed in the script):

{ "request_id": "req_5b1e09c47a2d3f60", "outcome": "ok", "tenant": "acme", "key_id": "9f2c41aa", "alias": "chat-careful", "provider": "anthropic", "model": "fixture-large", "finish": "length", "cost_micro": 1320, "input_tokens": 120, "output_tokens": 64, "prompt": "Reply to [email] about invoice [card].", "completion": "ok from anthropic", "redactions": { "email": 1, "card": 1 }, "latency_ms": 3 }

Card numbers are replaced only when they pass the Luhn check, so a sixteen-digit order number stays readable for whoever is debugging. That refinement should not create confidence in the approach. Pattern redaction recognises shapes, and most personal data has no shape: the last assertion in the redaction test feeds it a full name, a street address and a diagnosis and confirms that nothing is removed. That is why the default is to log no content at all, and why OWASP lists sensitive information disclosure among its top risks for LLM applications. Note also what this redaction protects: the log. The prompt still goes to the provider unmodified. Deciding which data may leave for which provider is a separate policy with different owners.

What this LLM gateway architecture leaves out, and what production adds

The core is under five hundred lines and makes no claim to be a platform. The omissions fall into two groups: things a production gateway needs, and things it should refuse to take on.

Two-column figure: on the left, responsibilities that belong in the gateway such as credentials, authentication, model allow-list, budgets, limits, metering and redacted logs; on the right, responsibilities that stay in the application such as prompts, retrieval, tool execution, output validation, conversation state and evaluationFigure 3. The dividing test: a rule that must hold for every caller and needs no knowledge of the request's meaning goes left.

Needed and missing. Streaming changes settlement: usage arrives in the final event, the reservation stays open for the whole stream, and a client that disconnects mid-stream is the ambiguous case again. Reservation expiry: a process that dies between reserve and settle leaves reserved_micro raised forever; production needs reservations as rows with a deadline and a sweeper that converts expired ones into estimated charges. Rate limiting against provider quotas is a scheduling problem of its own and is the subject of a later article in this series. Hot rows: one budget row per tenant per period serialises that tenant's requests through one row lock; at high request rates, instances lease a slice of budget and reserve against it locally. Price history: cost is computed from the route's current price, so a price change mid-period needs versioned prices on the usage event. Availability: the gateway is now on the path of every model call, so it needs the same care as any shared dependency, including a decision about whether it fails open or closed when the ledger is unreachable. For spend limits the defensible answer is closed.

Deliberately absent. Prompt templates, retrieval, tool execution, output parsing and conversation memory need the meaning of the request and change at the pace of the product. Semantic caching looks like infrastructure, but whether two prompts are "the same question" is an application judgement, and a cache shared across tenants is a data leak. Content guardrails are a boundary case: a coarse, uniform filter can live at the gateway, while anything that depends on the task belongs with the task. The run-level budgets inside an agent loop are also not replaced by tenant budgets: one bounds a single run, the other bounds everyone, and each catches failures the other cannot see.

On the security side the gateway is an API like any other and inherits the usual obligations: a body size limit applied before parsing (1 MB here, answered with 413), TLS, key rotation and revocation, and audit of administrative changes to routes and tenants. The general API security hardening guide applies without modification. OWASP's Unbounded Consumption entry is the LLM-specific addition, and three of the mitigations it lists (quotas, input size limits, timeouts) are stages of this gateway.

Testing the gateway without a provider

The adapters call the real openai and anthropic clients; only the transport is replaced, by a local handler that plays both provider APIs and records each request body. That choice tests what a mock of the adapter cannot: the wire format the SDK actually emits, the SDK's own response validation, and its exception classes on scripted 400, 401, 429 and 500 responses.

The suite has ten tests. They cover the two wire formats and usage normalisation; authentication order, digest storage and revocation; indistinguishable model errors and rejected unknown fields; the output clamp and the options allow-list; the concurrent burst against both ledgers; settlement and metering; error translation with reservation release and no SDK retries; the timeout path with its estimated charge; default-off content logging and redaction, including what redaction misses; and the ASGI front end to end through httpx.ASGITransport, covering 200, 400, 401, 404, 413 and 429.

Verification. All ten tests pass with ./run.sh on Python 3.13.18 with openai 3.49.0, anthropic 2.8.0, httpx 0.28.1 and pytest 9.2.0 on Linux (November 2026). Every number in this article comes from those tests and their fixture prices, which are arbitrary integers and not any provider's prices. Not verified: any call to a live provider, streaming, behaviour across several gateway processes (the conditional update was run on in-memory SQLite only, on one connection), and performance under load.

Common mistakes

Checking the budget against spend only. Any check that ignores in-flight requests is a limit on sequential traffic. Concurrency is where budgets are broken.

Answering a spent budget with 429. Retry logic everywhere treats 429 as "try again soon". Reserve it for conditions that waiting will fix.

Forwarding provider errors verbatim. The caller receives a 401 about a key it has never seen and a body that describes someone else's account.

Letting the SDK retry underneath the gateway. Latency, load and cost become functions of a default nobody chose.

Logging prompts "temporarily" for debugging. The log system has wider access and longer retention than the application database, and redaction only removes what has a recognisable shape.

Growing the neutral model one provider feature at a time. Each addition is cheap; the sum is a second, worse SDK. Use the allow-listed extension point and promote a field to the contract only when two providers support it with the same meaning.

Putting prompts in the gateway. It turns a control point into a deployment bottleneck and makes platform engineers the owners of product behaviour.

Engineering verdict

Build or adopt a gateway when more than one team calls models, when spend has an owner who needs a limit that actually holds, or when a regulator or customer will ask where prompts are stored. At that point the alternative is the same policy implemented slightly differently in every service.

Do not build one for a single service with a single provider. A hop that enforces nothing is latency and an outage surface; an SDK and a spending alert are enough until a second caller appears.

If the choice is between writing one and running an existing LLM proxy, running one is usually right, and this article is then a checklist for evaluating it: does its budget check reserve or merely compare, what does it return when a budget is spent, does it retry underneath you, what does it log by default, and how does it count cached tokens. To take the code here toward production, change the store to a shared database with expiring reservation rows first, add streaming settlement second, and keep the contract small throughout. A gateway stays valuable in proportion to how little it knows about what the requests mean.

References

Related Articles

AI & Machine Learning14 min read

The Agent Loop Is Forty Lines. The Guards Around It Are the Engineering

A framework-free agent loop in Python, written as a state machine with five explicit exits: validated tool calls, errors returned as observations, step, token and time budgets, and stall detection, all tested with a scripted model and the real SDK.