Skip to content
Visual explainer 3h to learn 5 steps

One application interface for model calls

Put every model call behind one adapter with a fake provider for local work and clear boundaries for inputs, outputs and credentials.

By Invicly Tech, , in FastAPI with Python for AI Backends. About 12 minutes to read.

Topic 10 of 29

In short

A model gateway is one small interface that every part of the service uses to call a language model. Behind it sit adapters: a deterministic fake for local work and tests, a remote provider reached through its SDK or HTTP API, and optionally a local model server. Routes never see provider SDKs, API keys or raw responses, only typed requests and results that record which model and prompt version produced them.

Think of it like this: The gateway is a wall socket: appliances plug into the same shape whether the power comes from the grid, a generator or a test bench.

Explained simply

The document Q&A service needs a language model to write answers. There are many ways to get one: a paid cloud API, a model running on your own laptop, or, during development, a fake that returns made-up but predictable text. We want the rest of the code to work the same way with any of them.

So we write one small interface, the model gateway, with a single method: generate. It takes a request we designed and returns a result we designed. Behind it sit adapters. Each adapter knows how to talk to one kind of model and converts its replies into our result type.

We build the fake adapter first. Given the same question, it always returns the same answer, it needs no internet and costs nothing. That means you can build, run and test the whole service on a train with no API key. Later you swap in a real adapter by changing one setting.

Two more rules keep things tidy. API keys live in settings and are given to the adapter once at startup, so no route ever touches a key. And every result records which model and which prompt version produced it, so when an answer looks wrong you can find out exactly what made it.

Press Play on a diagram to walk through it one step at a time.

LayersWho knows what in a model call
  1. 1
    Route and services

    Build a GenerateRequest; know nothing about providers

  2. 2
    ModelGateway protocol

    generate(request) -> GenerateResult

  3. 3
    Adapters

    FakeModel, RemoteModel, LocalModel

  4. 4
    Transport and credentials

    HTTPX client and API key, set up in lifespan

  5. 5
    Provider

    Remote API, local server or nothing at all

CompareRemote API versus local model
Remote provider API
  • Strong models, no hardware to run
  • Paid per token; needs an API key
  • Data leaves your network; check retention terms
  • Rate limits and outages you do not control
Local model server
  • Free to call once installed
  • Needs RAM, ideally a GPU; slower on a laptop
  • Data stays on your machine
  • Smaller models, lower answer quality
MapAdapter choice by environment
settings.model_provider
  • fake
    • Unit tests and CI
    • Local development
    • Failure drills
  • local
    • Offline demos
    • Data must stay on the machine
  • remote
    • Staging and production
    • Needs a key and a budget

In depth

Designing the interface in your own terms

Write the request and result as Pydantic models that describe what your application needs, not what one provider offers. A request holds the system instructions, the conversation messages, retrieved context passages, a maximum output length and the prompt version. A result holds the text, the model ID, the prompt version, input and output token counts and a finish reason such as stop, length or refusal.

Describe the gateway with typing.Protocol. Any class with a matching async generate method satisfies it, so adapters do not need a shared base class and tests can pass a tiny stub. Keep the interface small. Add streaming later as a second method that yields text pieces, rather than adding flags to generate. Provider-specific options, such as a special safety setting, belong in the adapter's own configuration, not in the shared request.

  • Request: system, messages, context, max_output_tokens, prompt_version
  • Result: text, model, prompt_version, input_tokens, output_tokens, finish_reason
  • Protocol, not inheritance
  • Provider options live in adapter config

A deterministic fake provider

The fake takes the request, builds a stable string from it and returns text derived from that string. A common trick is to hash the last user message with SHA-256 and pick a canned answer by the hash, or to echo the question and the first context passage. Count tokens roughly, for example by splitting on spaces, so usage metrics have numbers to show.

Give the fake switches for testing failure paths: a delay in seconds, an error status to raise, or invalid JSON to return. Tests then exercise timeouts, retries and validation without a network. Because nothing is random, a test that passes once passes every time, and a snapshot of an answer stays stable across runs.

FlowHow the fake turns a request into an answer
  1. 1
    Read the last user message
  2. 2
    Hash it with SHA-256

    Same input, same hash

  3. 3
    Pick a canned reply

    Or echo the question and first context

  4. 4
    Apply test switches

    Delay, error or invalid output

  5. 5
    Return a GenerateResult

    model=fake-1, rough token counts

Remote SDK or local model

A remote adapter calls a hosted API through the vendor's Python SDK or plain HTTPX. You get strong models without hardware, but you pay per token, need an API key, accept the provider's rate limits and send data outside your network, so check its data retention terms. A local adapter calls a model server on your machine. Ollama, for example, is free, listens on http://localhost:11434 and offers a native /api/chat endpoint as well as an OpenAI-compatible endpoint under /v1. It needs several gigabytes of RAM, runs faster with a GPU, and small local models answer less well.

Whichever you use, map its response fields into your GenerateResult inside the adapter, and map its errors into your own exception types with a status code. The rest of the service then never sees a vendor class. Paid APIs are optional in this path: the fake covers every exercise.

Credentials and wiring at startup

Load settings with pydantic-settings, declaring the API key as SecretStr so it does not appear when settings are printed or logged. In the lifespan handler, read settings.model_provider and build one adapter: fake, remote or local. Create a single shared httpx.AsyncClient with timeouts and pass it in, then store the gateway on app.state and close the client on shutdown. A dependency returns request.app.state.gateway, and routes declare gateway: ModelGateway = Depends(get_gateway).

This keeps keys in exactly one place, makes the provider a deployment choice, and lets tests replace the gateway with app.dependency_overrides. If the remote provider is selected but no key is set, fail at startup with a clear message rather than on the first user request.

SequenceWiring the gateway once, using it per request
Lifespan
Settings
Gateway
Route
  1. 1Read provider and SecretStr key
    Lifespan to Settings: Read provider and SecretStr key
  2. 2Build adapter with shared HTTPX client
    Lifespan to Gateway: Build adapter with shared HTTPX client
  3. 3generate(request) via Depends
    Route to Gateway: generate(request) via Depends
  4. 4GenerateResult with model and usage
    Gateway to Route: GenerateResult with model and usage
  5. 5On shutdown: close the client
    Lifespan to Gateway: On shutdown: close the client

Recording model and prompt versions

Store prompt templates in code or files with an explicit version string such as qa-answer@3, and change the version whenever you change the wording. Store the model ID the provider actually reports, not just the alias you asked for, because aliases can move to newer models. Save both on every assistant message row, along with token counts and latency. Include them in cache keys and in logs.

This turns a vague complaint such as answers got worse last week into a query: compare ratings or evaluation scores grouped by model and prompt version. It also lets you roll back a prompt change by setting the version back.

Learn it in 5 short steps

About 35m each. Track them with a timer in your plan.

  1. 1
    Define the adapter interface~35m
  2. 2
    Build a deterministic fake provider~35m
  3. 3
    Compare a remote SDK and a local model~35m
  4. 4
    Keep credentials out of call sites~35m
  5. 5
    Record model and prompt versions~35m

Key points

  • Define the interface in your own terms with typing.Protocol and Pydantic models, not a provider's SDK types.
  • Build the fake first: same input gives the same output, with no network, cost or key.
  • Create adapters and their credentials once in the lifespan handler and inject the gateway with Depends.
  • Every result carries the model ID, prompt version and token usage so answers can be traced and costed.
  • Choose the adapter from settings, so switching provider needs no code change in routes.

Key terms

Tap a card to flip it. 0/5 known

Examples

python
class GenerateRequest(BaseModel):
    system: str
    messages: list[dict[str, str]]
    prompt_version: str
    max_output_tokens: int = 512

class GenerateResult(BaseModel):
    text: str
    model: str
    prompt_version: str
    input_tokens: int = 0
    output_tokens: int = 0

class ModelGateway(Protocol):
    async def generate(self, req: GenerateRequest) -> GenerateResult: ...

Imports: Protocol from typing, BaseModel from pydantic. This is the application's own contract; each adapter implements generate().

Write the fake adapter

Step 1: implement generate with the same signature as the protocol. Step 2: derive the answer from a hash of the question so it is stable. Step 3: estimate tokens by word count. Step 4: add an optional delay for timeout tests. Evidence: calling it twice with the same request gives identical results, and a type checker such as mypy accepts it wherever ModelGateway is expected.

python
import asyncio, hashlib

class FakeModel:
    def __init__(self, delay_s: float = 0.0):
        self.delay_s = delay_s

    async def generate(self, req: GenerateRequest) -> GenerateResult:
        await asyncio.sleep(self.delay_s)
        q = req.messages[-1]["content"]
        tag = hashlib.sha256(q.encode()).hexdigest()[:8]
        text = f"[fake {tag}] You asked: {q}"
        return GenerateResult(text=text, model="fake-1",
            prompt_version=req.prompt_version,
            input_tokens=len(q.split()), output_tokens=len(text.split()))

Try a local model with Ollama (optional)

Prerequisites: Ollama installed and about 4 GB of free RAM; no API key or payment. Step 1: pull a small model. Step 2: call the native chat endpoint with streaming turned off. Evidence: the JSON reply contains message.content plus prompt_eval_count and eval_count, which your adapter maps to input and output tokens. Step 3: set MODEL_PROVIDER=local and restart the API. Cleanup: ollama rm removes the model. If your machine is too small, stay on the fake.

bash
ollama pull llama3.2
curl -s http://localhost:11434/api/chat -d '{
  "model": "llama3.2",
  "messages": [{"role": "user", "content": "Say hello in five words."}],
  "stream": false
}'
# expect: message.content, prompt_eval_count, eval_count
ollama rm llama3.2

Quick reference

  • Routes depend on ModelGateway, never on a provider SDK
  • Build the fake first: deterministic, offline, free
  • class ModelGateway(Protocol): async def generate(self, req) -> GenerateResult
  • API keys as SecretStr in pydantic-settings; build adapters in lifespan
  • Store model ID, prompt version and token counts with every answer
  • Override the gateway in tests with app.dependency_overrides
  • Ollama serves on localhost:11434; /api/chat with "stream": false

Common mistakes

  • Importing a provider SDK in route code, so a provider change touches every endpoint.
  • A fake that returns random text, which makes tests flaky and hides bugs.
  • Reading the API key from the environment inside each call instead of injecting it once from settings.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1What is the main reason to keep provider SDK types out of route code?

Question 2

2Which property matters most for the fake provider?

Question 3

3Where should the remote adapter's API key be read?

Question 4

4Users say answers changed yesterday. Which stored fields help most?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write a get_gateway dependency and a POST /ask route that sends the question to the gateway and returns the text, model and prompt version.

  2. Exercise 2medium

    Write a lifespan handler that builds the fake, local or remote adapter from settings and closes the shared HTTPX client on shutdown. Fail at startup if remote is chosen without a key.

  3. Exercise 3hard

    Write a LocalModel adapter that calls Ollama's /api/chat with streaming off and maps the reply into GenerateResult, raising your own ProviderError on HTTP errors.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Do I need a paid API key for this path?
No. Every exercise works with the fake provider. A local model through Ollama is a free optional step, and a paid API is only needed if you want to try a hosted model.
Should I use a library such as LiteLLM or LangChain instead of my own adapter?
You can put such a library behind your own adapter. Keeping your own small interface on top still lets you swap the library later and keeps tests simple.
Why use Protocol instead of an abstract base class?
Protocol checks structure: any class with the right methods fits, including test stubs, without inheriting from anything. An abstract base class also works if you prefer explicit inheritance.

Go deeper

ShareXLinkedInWhatsApp