Conversational AI (artificial intelligence) · 09 / 22

Development with the AI Gateway

How an engineer builds the booking assistant against an enterprise AI gateway: aliases, keys, budgets, guardrails, errors and tests.

What the gateway gives a developer

The enterprise AI gateway is the one front door to models. A developer does not hold a provider key, pick a vendor or write retry logic. They call an OpenAI-compatible endpoint with a project key and a model alias, and the platform team owns routing, fallback, budgets, guardrails and logging behind it. The gateway in this example sits in front of Prisma AIRS scanning; the same developer experience applies whichever product provides the gateway, such as Portkey or the Databricks AI Gateway.

Header names, paths and configuration keys below are illustrative. Use the names your gateway documents.

Model aliases

booking-fast and booking-reasoner, never a vendor model name. The platform team repoints an alias after the evaluation set passes.

Project keys

One key per service and environment, with its own budget and rate limit. Keys are issued and rotated by the platform team.

Default guardrails

The security profile attached to the key scans every request. Developers do not call the scanner themselves.

Metadata

Each call carries an application name, session identifier, channel and trace identifier, so cost and incidents can be traced to a turn.

The developer workflow

  1. Request a project

    Raise a request with the service name, channels and data classes. The platform team creates the dev, test and prod keys, budgets and a security profile.

  2. Call the sandbox

    Develop against the sandbox gateway, which runs the same scanning with small budgets and synthetic data only.

  3. Use aliases and tools

    Call booking-fast for slot extraction and phrasing, booking-reasoner for hard turns. Tools are declared in the request; execution stays in your service.

  4. Handle gateway errors

    Treat a guardrail block, a budget stop and a provider failure as different outcomes with different replies.

  5. Run the evaluation set

    Run the shared evaluation set against your branch. Thresholds gate the merge.

  6. Promote

    The prod key is bound to the production profile. Nothing in the code changes between environments except configuration.

Calling the gateway

A turn that extracts booking details uses the standard OpenAI-compatible SDK (Software Development Kit) with the base URL (Uniform Resource Locator) pointed at the gateway. The service passes metadata as headers and asks for a structured result.

booking/llm.py · extraction through the gateway
import os
from openai import OpenAI

client = OpenAI(
    base_url=os.environ["AI_GATEWAY_URL"],          # the gateway, not a provider
    api_key=os.environ["AI_GATEWAY_KEY"],           # project key with a budget
    default_headers={"x-app": "booking-assistant", "x-channel": "web-chat"},
)

def extract_request(message: str, session_id: str, trace_id: str) -> dict:
    resp = client.chat.completions.create(
        model="booking-fast",                       # alias, repointed by the platform team
        messages=[
            {"role": "system", "content": SYSTEM_PROMPT},
            {"role": "user", "content": message},
        ],
        response_format={"type": "json_schema", "json_schema": BOOKING_SLOTS_SCHEMA},
        temperature=0,
        extra_headers={"x-session-id": session_id, "x-trace-id": trace_id},
    )
    return json.loads(resp.choices[0].message.content)

The code never names a vendor or a model version. A repoint of the booking-fast alias is a configuration change, tested by the evaluation set first.

Gateway configuration as code

The platform team keeps routes, budgets and guardrail attachments in version control and reviews changes like any other code. This is the shape of a route for the booking service.

gateway/booking.yaml · illustrative
routes:
  - alias: booking-fast
    primary:   { provider: provider-a, model: small-model }
    fallbacks: [ { provider: provider-b, model: small-model } ]
    retries:   { attempts: 2, on: [429, 500, 503], backoff_ms: 250 }
    timeout_ms: 8000
    guardrails: [ prisma-airs:booking-chat-prod ]
  - alias: booking-reasoner
    primary:   { provider: provider-a, model: large-model }
    fallbacks: [ { provider: provider-b, model: large-model } ]
    timeout_ms: 30000
    guardrails: [ prisma-airs:booking-chat-prod ]

keys:
  booking-assistant-prod:
    routes: [ booking-fast, booking-reasoner ]
    budget:     { usd_per_day: 1500, alert_at: 0.8 }
    rate_limit: { requests_per_minute: 1200 }
    metadata_required: [ x-app, x-session-id, x-trace-id ]

Errors and what the guest sees

A booking assistant must tell a blocked message from a failed provider, because the right behaviour differs.

Gateway outcomeMeaningService behaviourGuest sees
200 with contentNormal reply, scans passedContinue the state machineThe reply
Guardrail blockPrompt or reply failed a scanLog a security event, do not retry the same text, never echo the blocked contentA short, neutral refusal and an offer of a person
429 rate or budgetKey limit reachedBack off, then degrade to a static menu if the limit persistsPlease try again shortly, or call the line desk
5xx or timeoutProvider failure after fallbacksKeep the booking state, retry once, then hand offAn apology and a handoff with the conversation attached
Schema failureModel returned an invalid structureRetry once with the validation error, then ask a clarifying questionA clarifying question

Sequence: a call with retry and fallback

A gateway call with retry and fallback The service calls the gateway with an alias. The gateway checks the key, scans the prompt, tries the primary provider, retries, fails over to the second provider, scans the reply and returns the answer with usage and cost. Service AI gateway Prisma AIRS Provider A Provider B completion, alias booking-fast check key, budget, rate limit scan prompt allow route to primary 503 retry after 250 ms retry 503 fallback route completion scan reply allow 200, usage, cost, fallback flag
A gateway call with retry and fallback

The service sees one call and one answer. Which provider answered shows only in the metadata, so cost and fallback rates can be watched without changing application code.

Sequence: a blocked prompt and a budget stop

Guardrail block and budget stop at the gateway A guardrail block returns an error body and never reaches a provider. A key that has used its daily budget gets a rate error before any scan or provider call. Service AI gateway Prisma AIRS completion with injected text scan prompt block: injection guardrail error, no provider call log event, send safe reply next request daily budget used: 100% 429 budget_exceeded static menu or try later
Guardrail block and budget stop at the gateway

The two errors need different handling in the service, which is why the error table above separates them.

Testing without surprises

  1. Unit tests

    Mock the gateway client and test the state machine, slot validation and error handling with fixed replies.

  2. Record and replay

    Record sandbox responses for a set of conversations and replay them in CI (continuous integration), so tests are fast and free.

  3. Contract tests

    Check that every alias the service uses exists, returns the structure expected and carries the required metadata.

  4. Adversarial tests

    Include prompt injection, personal-data and tool-abuse cases and assert that the gateway blocks them and the service handles the block.

  5. Cost tests

    Assert a token budget per turn and fail the build if a prompt change doubles it.

Developer checklist

Build this for your business

This example is a booking assistant for a ground-handling network, but the same pattern, a governed gateway, runtime security, grounded knowledge, deterministic commits and measured quality, fits any customer-facing assistant that takes actions. We can scope a pilot on your own systems.

Book a discovery call