A typed first model call with a deterministic stub
Call a model through one typed interface that swaps between a fake, a hosted and a local model and records identity, usage and cost.
By Invicly Tech, , in Generative AI, Agentic AI and RAG. About 11 minutes to read.
In short
Your application should call models through one small typed interface, not scatter provider SDK calls through the code. Behind that interface you can plug in a deterministic fake for tests, a hosted model or a local model. Every call records which model answered, how many tokens it used and what you assume it cost, so later comparisons are fair.
Think of it like this: The interface is like a wall socket: the kettle does not care whether the power comes from the grid or a generator, as long as the plug fits.
Explained simply
Your first model call should not be a quick script that pastes an API key into the code. Instead, write a small interface that says what any model must do: take a prompt and return a result. The rest of your program only knows about that interface.
The first thing you plug in is a fake model. It does not use AI at all. It returns fixed answers, the same every time. That sounds silly, but it lets you build and test the whole program offline, for free, with results you can predict.
Later you can plug in a hosted model, run by a provider over the internet, or a local model running on your own computer. Both are optional for this path. Because they follow the same interface, swapping them takes one line, and your tests keep running on the fake.
Every call should record which model answered, how many tokens went in and out, how long it took and what you assume it costs. Without these records you cannot compare models or explain a surprising bill.
Press Play on a diagram to walk through it one step at a time.
- 1Application code
Triage, RAG, agent loop
- 2ChatModel protocol
generate(prompt) -> ModelResult
- 3Adapters
FakeModel, HostedModel, LocalModel
- 4Providers
In-process stub, hosted API, local server
- Free and offline
- Same output every run
- Ideal for unit tests
- Proves wiring, not quality
- Strong quality, no hardware
- Paid per token
- Needs an API key and network
- Data leaves your machine
- Runs on your hardware
- No per-token fee
- Needs RAM or a GPU for speed
- Usually smaller and weaker
- Triage code to ChatModel adapter: generate(prompt, temperature=0)1generate(prompt, temperature=0)
- ChatModel adapter to Provider: Provider-specific request2Provider-specific request
- Provider to ChatModel adapter: Text, model ID, usage3Text, model ID, usage
- ChatModel adapter to Call log: Record ID, tokens, latency, cost4Record ID, tokens, latency, cost
- ChatModel adapter to Triage code: ModelResult5ModelResult
In depth
Designing the interface with typing.Protocol
A Protocol from Python's typing module describes the shape an object must have. Any class with a matching generate method satisfies it, with no base class needed. Keep the interface narrow: one method that takes the prompt and a few settings, and returns a frozen dataclass or Pydantic model with the text, the model ID, input tokens, output tokens and latency. Narrow interfaces are easy to fake and easy to adapt. Resist adding every provider feature; when you need streaming or tool calls later, add a second method rather than widening the first. A type checker such as mypy or pyright will tell you if an adapter's method signature drifts from the Protocol.
- One method, a few typed parameters
- Return a frozen result object, not a raw dict
- Include model ID and usage in the result
- Let the type checker verify adapters
A deterministic fake that is actually useful
A good fake is more than return 'ok'. Give it a dictionary that maps known prompts, or a keyword in the prompt, to canned replies, and a default reply for everything else. Make it count tokens with the same rough rule every time, so usage numbers are stable. Give it a model ID such as fake-v1 so logs show clearly that no real model ran. You can also make variants: one that returns malformed JSON, one that returns a refusal, one that sleeps to simulate latency. These variants let you test error handling in later modules without paying for or waiting on a real model.
- Happy path
- Canned replies by keyword
- Malformed
- Broken JSON
- Missing fields
- Refusal
- Returns a polite decline
- Slow
- Sleeps to test deadlines
Hosted versus local models at design level
A hosted model runs on a provider's servers. You send HTTPS requests with an API key, pay per token, and get strong quality without owning hardware. Your data leaves your machine, so check the provider's data handling terms before sending anything real. A local model runs on your machine through a server such as Ollama, which listens on localhost port 11434 by default. There is no per-token fee and data stays local, but you need enough memory, ideally a GPU, and local models are usually smaller and less capable. For this path both are optional. If you try one, keep the API key in an environment variable, never in code, and keep the fake as the default for tests.
- Hosted: paid per token, needs a key and network
- Local: free per call, needs RAM or GPU
- Keys go in environment variables, never in Git
- Tests always use the fake
Logging identity, usage and cost assumptions
Log one structured record per call. Include a request ID, the adapter name, the model ID the provider returned, any sampling settings, input and output tokens, latency in milliseconds and an estimated cost. Store prices in a small config table with the date you copied them, because prices change. Compute cost as input tokens times the input price plus output tokens times the output price. Do not log full prompts if they may contain personal data; log a hash or a truncated preview instead. These records become the baseline you compare against in the next module and after adding retrieval.
Learn it in 4 short steps
About 45m each. Track them with a timer in your plan.
- 1Define a typed model interface~45m
- 2Build a deterministic fake model~45m
- 3Compare hosted and local options~45m
- 4Log model ID, usage and cost assumptions~45m
Key points
- Define a Protocol with one method and a typed result; the rest of the code depends only on that.
- The fake model returns canned answers keyed by input, so tests are fast, free and repeatable.
- Record the exact model ID and version string the provider returns, not just a friendly name.
- Store input and output token counts per call; cost is an assumption you write down with a date.
- Hosted and local models are optional for this path; every lab runs on the fake.
Key terms
Tap a card to flip it. 0/5 known
Examples
from dataclasses import dataclass
from typing import Protocol
@dataclass(frozen=True)
class ModelResult:
text: str
model_id: str
input_tokens: int
output_tokens: int
class ChatModel(Protocol):
def generate(self, prompt: str) -> ModelResult: ...
class FakeModel:
def generate(self, prompt: str) -> ModelResult:
return ModelResult("category: login", "fake-v1", len(prompt) // 4, 3)A typed interface and a deterministic fake. Hosted and local adapters return the same ModelResult.
A keyword fake with stable usage numbers
This fake returns canned replies based on keywords and computes usage the same way every time. Tests can assert exact values. Step 1: create it. Step 2: call it with a password ticket. Step 3: check that model_id is fake-v1 and the text is the expected label. Expected evidence: the same result on every run, with no network access.
from dataclasses import dataclass
@dataclass(frozen=True)
class ModelResult:
text: str
model_id: str
input_tokens: int
output_tokens: int
class FakeModel:
replies = {"password": "access", "invoice": "billing"}
def generate(self, prompt: str, temperature: float = 0.0) -> ModelResult:
text = next((v for k, v in self.replies.items() if k in prompt.lower()), "other")
return ModelResult(text, "fake-v1", max(1, len(prompt) // 4), 1)An optional local adapter for Ollama
Prerequisites: Ollama installed and a model pulled, for example with ollama pull followed by a model name. Step 1: the adapter posts to the local chat endpoint with streaming off. Step 2: it maps Ollama's prompt_eval_count and eval_count fields to the same ModelResult. Expected evidence: a reply and non-zero token counts. Cleanup: stop the Ollama server and remove the model with ollama rm if you no longer need it.
import httpx
class OllamaModel:
def __init__(self, model: str, base: str = "http://localhost:11434"):
self.model, self.base = model, base
def generate(self, prompt: str, temperature: float = 0.0) -> ModelResult:
body = {"model": self.model, "stream": False,
"messages": [{"role": "user", "content": prompt}],
"options": {"temperature": temperature}}
data = httpx.post(f"{self.base}/api/chat", json=body, timeout=60).json()
return ModelResult(data["message"]["content"], data["model"],
data.get("prompt_eval_count", 0), data.get("eval_count", 0))Quick reference
- Depend on a ChatModel Protocol, never on a provider SDK, in business code
- Default to the deterministic fake in tests: offline, free, repeatable
- Return a typed result with text, model ID, input tokens and output tokens
- Cost = input tokens x input price + output tokens x output price
- Keep prices in config with the date you copied them
- Ollama listens on http://localhost:11434 by default
- API keys live in environment variables, never in code or Git
Common mistakes
- Calling a provider SDK directly from business logic, so tests need a network and a key.
- Logging only the reply text and losing which model and settings produced it.
- Hard-coding a price and forgetting that it was an assumption from a specific date.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write a ModelResult dataclass and a FakeModel that always returns 'other' with model ID fake-v1.
- Exercise 2medium
Write a cost function that takes a ModelResult and a price table keyed by model ID, with prices per million tokens, and returns the cost.
- Exercise 3hard
Write a LoggedModel wrapper that satisfies the same Protocol, times each call, and appends a dict with model ID, tokens, latency and cost to a list.
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 lab runs on the deterministic fake. A hosted model is optional and usually paid per token; a local model through Ollama is a free alternative if your computer has enough memory.
- Why not just use the provider's SDK directly?
- Calling it directly ties your code and tests to one provider and a network connection. A small interface lets you test offline and switch providers with one change.
- Where should I keep my API key?
- In an environment variable or a local secrets file that Git ignores. Never put it in code, commits or logs.