Lab: One Client for Hosted, Local and Mock Models
Build a small provider-neutral client: a typing.Protocol interface, adapters for the Anthropic API and for any OpenAI-compatible server such as Ollama or vLLM, a mock for offline tests, and contract tests that catch the differences between "compatible" servers.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: Define the interface and a mock
- Step 2: Test business code against the mock
- Step 3: Wrap the hosted provider and any OpenAI-compatible server
- Step 4: Choose the implementation from configuration
- Step 5: Check each adapter with tests
- Troubleshooting
- Check your understanding
- Apply it: stretch task
- Review prompt
Lessons of LLM API Integration
- Anatomy of a Request: Messages, Parameters and Media Concept · 15 min
- First Calls: Parameters, Usage, Images and Audio Worked example · 25 min
- Lab: Retries, Backoff and Timeouts Lab · 25 min
- Streaming and Cancellation Worked example · 20 min
- Lab: One Client for Hosted, Local and Mock Models Lab · 30 min
- Check: Diagnose Failing API Calls Knowledge check · 10 questions
What you will learn
- Wrap hosted providers and a locally served open-weight model (through an OpenAI-compatible endpoint) behind one interface, with a mock implementation so tests run without network access or API keys.
Prerequisites: Python Foundations, HTTP & APIs
01. Goal and setup
So far each script has called an SDK directly. That is fine for experiments, but in an application it spreads provider details everywhere: message formats, stop reasons, exception classes, model names. In this lab you put them behind one small interface, ChatModel, with three implementations:
AnthropicChat, for a hosted model through the Messages API;OpenAICompatibleChat, for OpenAI or any server that speaks its chat completions API, including a local open-weight model in Ollama or vLLM;MockChat, which returns scripted replies, so that tests run without a network, keys or cost.
Business code receives a ChatModel and never imports an SDK. Configuration picks the implementation. Contract tests, run on demand against real endpoints, check that every adapter behaves the same way. When you finish, the folder looks like this (the scripts from earlier lessons stay where they are):
llm-client/
fake_provider.py the stand-in from lesson 2 (hosted provider)
pyproject.toml pytest settings
llmclient/
__init__.py from_env(): choose an implementation
base.py Message, Reply, LLMError, ChatModel
mock.py MockChat
anthropic_chat.py AnthropicChat
openai_chat.py OpenAICompatibleChat
try_adapters.py both adapters side by side
support.py business code that uses a ChatModel
chat.py a command-line client
tests/
test_support.py business code against the mock
test_adapters.py translation of provider responses
test_live.py contract tests against real endpointsKeep the stand-in running in terminal 1 as the hosted provider, with the environment variables from lesson 2 set in terminal 2. For the local model you need Ollama, an open-weight model runtime that exposes an OpenAI-compatible API at http://localhost:11434/v1. Install the app from ollama.com and run ollama pull qwen2.5:1.5b, or use Docker as below. qwen2.5:1.5b is a 1 GB instruction-tuned model that answers short questions on a laptop CPU; any small chat model works. The lab was tested with Ollama 0.40.6 and pytest 9.2.
python -m pip install pytest
docker run -d --name ollama -p 11434:11434 -v ollama:/root/.ollama ollama/ollama
docker exec ollama ollama pull qwen2.5:1.5b
curl -s http://localhost:11434/v1/models | python -m json.tool{
"object": "list",
"data": [
{
"id": "qwen2.5:1.5b",
"object": "model",
"created": 1792314779,
"owned_by": "library"
}
]
}vLLM is the other common choice, built for serving many requests on a GPU: vllm serve Qwen/Qwen2.5-1.5B-Instruct starts an OpenAI-compatible server, by default at http://localhost:8000/v1. Everything below works with it by changing LOCAL_BASE_URL and LOCAL_MODEL.
02. Step 1: Define the interface and a mock
Create the llmclient folder and save base.py:
from collections.abc import Callable
from dataclasses import dataclass
from typing import Literal, Protocol
Stop = Literal['end', 'max_tokens', 'stop_sequence', 'other']
@dataclass(frozen=True)
class Message:
role: Literal['user', 'assistant']
content: str
@dataclass(frozen=True)
class Reply:
text: str
stop: Stop
input_tokens: int
output_tokens: int
model: str
class LLMError(Exception):
"""A model call failed, after the client's own retries."""
@classmethod
def wrap(cls, name: str, exc: Exception) -> 'LLMError':
status = getattr(exc, 'status_code', None)
detail = f' (HTTP {status})' if status else ''
return cls(f'{name}: {type(exc).__name__}{detail}')
class ChatModel(Protocol):
"""What the rest of the application may use. Nothing provider-specific."""
name: str
def complete(self, messages: list[Message], *, system: str = '',
max_tokens: int = 1024, stop: list[str] | None = None) -> Reply: ...
def stream(self, messages: list[Message], *, on_text: Callable[[str], None],
system: str = '', max_tokens: int = 1024) -> Reply: ...ChatModelis atyping.Protocol: any class with anameand these two methods counts as aChatModel, without inheriting from anything. A type checker such as mypy checks that each implementation matches.Replyholds only what the application needs, in the application's words.stopis reduced to four values, so callers never compare provider strings such asend_turnorlength;othercovers everything else, such as a refusal or a tool call, and should be treated as not a normal answer.streamtakes anon_textcallback and still returns a completeReply, so streaming callers get the stop reason and usage too.LLMErroris the one exception business code catches. Its message keeps the exception type and HTTP status, never the request body.
Keep the interface this small: every method you add must be implemented by every adapter and the mock.
The mock returns scripted replies and records every call, so a test can check what the code under test sent:
from collections.abc import Callable
from .base import Message, Reply, Stop
class MockChat:
"""A scripted ChatModel for tests: no network, no keys, no cost."""
name = 'mock'
def __init__(self, *replies: str, stop: Stop = 'end',
error: Exception | None = None) -> None:
self.replies = list(replies) or ['mock reply']
self.stop = stop
self.error = error
self.calls: list[dict] = [] # what the code under test sent
def complete(self, messages: list[Message], *, system: str = '',
max_tokens: int = 1024, stop: list[str] | None = None) -> Reply:
self.calls.append({'messages': messages, 'system': system,
'max_tokens': max_tokens, 'stop': stop})
if self.error:
raise self.error
text = self.replies.pop(0) if len(self.replies) > 1 else self.replies[0]
words = sum(len(m.content.split()) for m in messages)
return Reply(text, self.stop, words, len(text.split()), self.name)
def stream(self, messages: list[Message], *, on_text: Callable[[str], None],
system: str = '', max_tokens: int = 1024) -> Reply:
reply = self.complete(messages, system=system, max_tokens=max_tokens)
for i, word in enumerate(reply.text.split(' ')):
on_text(word if i == 0 else ' ' + word)
return replyFor now, llmclient/__init__.py only exports the names; step 4 completes it. Save this first version and try the mock:
from .base import ChatModel, LLMError, Message, Reply
from .mock import MockChat
__all__ = ['ChatModel', 'LLMError', 'Message', 'MockChat', 'Reply']python - <<'EOF'
from llmclient import Message, MockChat
print(MockChat('Hi there.').complete([Message('user', 'Hello')]))
EOFReply(text='Hi there.', stop='end', input_tokens=1, output_tokens=2, model='mock')03. Step 2: Test business code against the mock
The business code depends on the protocol only. Its max_tokens of 4,000 looks large for one sentence, but max_tokens caps thinking and answer text together, and current Claude models think by default: effort: low, set in step 4, means less thinking, not none. A cap sized for the sentence alone can stop a live call at max_tokens, and summarise_ticket would then report a cut-off summary.
"""Business code: it depends on the ChatModel protocol, not on a provider."""
from llmclient import ChatModel, Message
SYSTEM = 'Summarise the support ticket in one sentence for an on-call engineer.'
def summarise_ticket(model: ChatModel, ticket: str) -> str:
reply = model.complete([Message('user', ticket)], system=SYSTEM, max_tokens=4000)
if reply.stop == 'max_tokens':
raise ValueError('the summary was cut off; raise max_tokens or shorten it')
return reply.text.strip()A pyproject.toml lets pytest import the project, and the tests use the mock:
[tool.pytest.ini_options]
pythonpath = ["."] # lets tests import support and llmclient
testpaths = ["tests"]import pytest
from llmclient import LLMError, MockChat
from support import SYSTEM, summarise_ticket
def test_returns_the_trimmed_summary():
model = MockChat(' Export fails with 413: the payload is too large. ')
assert summarise_ticket(model, 'Export broke') == (
'Export fails with 413: the payload is too large.')
def test_sends_the_ticket_and_instructions():
model = MockChat()
summarise_ticket(model, 'Login page returns 500')
call = model.calls[0]
assert call['system'] == SYSTEM
assert call['messages'][0].content == 'Login page returns 500'
def test_refuses_a_cut_off_summary():
with pytest.raises(ValueError, match='cut off'):
summarise_ticket(MockChat('The export', stop='max_tokens'), 'Export broke')
def test_provider_errors_reach_the_caller():
with pytest.raises(LLMError):
summarise_ticket(MockChat(error=LLMError('429 after 3 retries')), 'x')pytest -q tests/test_support.py.... [100%]
4 passed in 0.06sThese tests run in milliseconds, need no network or key, and always give the same result, so they can run on every commit. Notice what they test: that the summary is trimmed, that the ticket and instructions are sent, that a cut-off answer is refused and that provider errors reach the caller. None of that depends on what a real model would say.
04. Step 3: Wrap the hosted provider and any OpenAI-compatible server
from collections.abc import Callable
import anthropic
from .base import LLMError, Message, Reply, Stop
STOPS: dict[str | None, Stop] = {
'end_turn': 'end', 'max_tokens': 'max_tokens', 'stop_sequence': 'stop_sequence'}
def to_reply(message: anthropic.types.Message) -> Reply:
text = ''.join(b.text for b in message.content if b.type == 'text')
return Reply(text, STOPS.get(message.stop_reason, 'other'),
message.usage.input_tokens, message.usage.output_tokens, message.model)
class AnthropicChat:
def __init__(self, model: str, *, params: dict | None = None,
timeout: float = 30.0, max_retries: int = 3) -> None:
self.name = f'anthropic:{model}'
self.model = model
self.params = params or {} # model-specific settings, e.g. output_config
self.client = anthropic.Anthropic(timeout=timeout, max_retries=max_retries)
def _request(self, messages: list[Message], system: str, max_tokens: int) -> dict:
wire = [{'role': m.role, 'content': m.content} for m in messages]
request = {'model': self.model, 'max_tokens': max_tokens, 'messages': wire,
**self.params}
if system:
request['system'] = system
return request
def complete(self, messages: list[Message], *, system: str = '',
max_tokens: int = 1024, stop: list[str] | None = None) -> Reply:
request = self._request(messages, system, max_tokens)
if stop:
request['stop_sequences'] = stop
try:
return to_reply(self.client.messages.create(**request))
except anthropic.APIError as exc:
raise LLMError.wrap(self.name, exc) from exc
def stream(self, messages: list[Message], *, on_text: Callable[[str], None],
system: str = '', max_tokens: int = 1024) -> Reply:
try:
with self.client.messages.stream(
**self._request(messages, system, max_tokens)) as stream:
for text in stream.text_stream:
on_text(text)
return to_reply(stream.get_final_message())
except anthropic.APIError as exc:
raise LLMError.wrap(self.name, exc) from excto_replyis the only place that knows the shape of an Anthropic response. Keeping it a plain function makes it easy to test.paramscarries model-specific settings, such asoutput_configfor effort, so they live in configuration rather than in business code.- The client uses the SDK's own retries, three of them, and a 30-second timeout, as the practice project requires. The retry policy from lesson 3 would work too, with
max_retries=0here; just do not use both. - SDK exceptions are caught here and turned into
LLMError, so no other module has to importanthropic.
from collections.abc import Callable
import openai
from .base import LLMError, Message, Reply, Stop
STOPS: dict[str | None, Stop] = {'stop': 'end', 'length': 'max_tokens'}
def to_reply(response: openai.types.chat.ChatCompletion) -> Reply:
choice, usage = response.choices[0], response.usage
return Reply(choice.message.content or '', STOPS.get(choice.finish_reason, 'other'),
usage.prompt_tokens if usage else 0,
usage.completion_tokens if usage else 0, response.model)
class OpenAICompatibleChat:
"""OpenAI itself, or any server that speaks its chat completions API."""
def __init__(self, model: str, *, base_url: str | None = None,
api_key: str | None = None, params: dict | None = None,
token_param: str = 'max_completion_tokens',
timeout: float = 30.0, max_retries: int = 3) -> None:
self.name = f'openai-compatible:{model}'
self.model = model
self.params = params or {} # e.g. {'temperature': 0, 'seed': 7}
self.token_param = token_param # some local servers only honour max_tokens
self.client = openai.OpenAI(base_url=base_url, api_key=api_key,
timeout=timeout, max_retries=max_retries)
def _request(self, messages: list[Message], system: str, max_tokens: int) -> dict:
wire = [{'role': m.role, 'content': m.content} for m in messages]
if system:
wire.insert(0, {'role': 'system', 'content': system})
return {'model': self.model, 'messages': wire, self.token_param: max_tokens,
**self.params}
def complete(self, messages: list[Message], *, system: str = '',
max_tokens: int = 1024, stop: list[str] | None = None) -> Reply:
request = self._request(messages, system, max_tokens)
if stop:
request['stop'] = stop
try:
return to_reply(self.client.chat.completions.create(**request))
except openai.APIError as exc:
raise LLMError.wrap(self.name, exc) from exc
def stream(self, messages: list[Message], *, on_text: Callable[[str], None],
system: str = '', max_tokens: int = 1024) -> Reply:
request = self._request(messages, system, max_tokens)
request.update(stream=True, stream_options={'include_usage': True})
parts, finish, usage = [], None, None
try:
with self.client.chat.completions.create(**request) as stream:
for chunk in stream:
usage = chunk.usage or usage
if chunk.choices:
text = chunk.choices[0].delta.content or ''
parts.append(text)
on_text(text)
finish = chunk.choices[0].finish_reason or finish
except openai.APIError as exc:
raise LLMError.wrap(self.name, exc) from exc
return Reply(''.join(parts), STOPS.get(finish, 'other'),
usage.prompt_tokens if usage else 0,
usage.completion_tokens if usage else 0, self.model)One class serves OpenAI, Ollama, vLLM and most gateways, because they share the request and response shapes. What differs goes into the constructor: the base URL, the key, the model name, sampling settings in params, and token_param, the name of the output-limit field. OpenAI uses max_completion_tokens, while some compatible servers only honour max_tokens; step 5 shows how to find out which. Try both adapters with an eight-token limit:
import os
from llmclient import Message
from llmclient.anthropic_chat import AnthropicChat
from llmclient.openai_chat import OpenAICompatibleChat
hosted = AnthropicChat(os.environ['ANTHROPIC_MODEL'])
local = OpenAICompatibleChat(
'qwen2.5:1.5b',
base_url=os.environ.get('LOCAL_BASE_URL', 'http://localhost:11434/v1'),
api_key='unused',
params={'temperature': 0, 'seed': 7},
token_param='max_tokens',
)
question = [Message('user', 'What does HTTP 429 mean?')]
for model in (hosted, local):
reply = model.complete(question, max_tokens=8)
print(f'{model.name}: stop={reply.stop} output_tokens={reply.output_tokens}')
print(f' {reply.text!r}')python try_adapters.pyanthropic:claude-sonnet-5-5: stop=max_tokens output_tokens=8
'Fake reply to: What does HTTP 429'
openai-compatible:qwen2.5:1.5b: stop=max_tokens output_tokens=8
'HTTP 429 is a status'Two different APIs, one shape of answer: both replies report stop=max_tokens, translated from max_tokens and length respectively.
05. Step 4: Choose the implementation from configuration
Replace llmclient/__init__.py with the full version, which adds from_env(). The LLM_PROVIDER environment variable decides which implementation the application gets:
import os
from .anthropic_chat import AnthropicChat
from .base import ChatModel, LLMError, Message, Reply
from .mock import MockChat
from .openai_chat import OpenAICompatibleChat
__all__ = ['ChatModel', 'LLMError', 'Message', 'MockChat', 'Reply', 'from_env']
def from_env() -> ChatModel:
"""Choose the model from configuration, so code never names a provider."""
provider = os.environ.get('LLM_PROVIDER', 'anthropic')
if provider == 'anthropic': # hosted; reads ANTHROPIC_API_KEY
return AnthropicChat(os.environ['ANTHROPIC_MODEL'],
params={'output_config': {'effort': 'low'}})
if provider == 'openai': # hosted; reads OPENAI_API_KEY
return OpenAICompatibleChat(os.environ['OPENAI_MODEL'])
if provider == 'local': # Ollama, vLLM or another OpenAI-compatible server
return OpenAICompatibleChat(
os.environ['LOCAL_MODEL'],
base_url=os.environ.get('LOCAL_BASE_URL', 'http://localhost:11434/v1'),
api_key='unused', # local servers ignore it, but the SDK needs one
params={'temperature': 0, 'seed': 7},
token_param='max_tokens',
)
if provider == 'mock':
return MockChat('This is a mock reply.')
raise ValueError(f'unknown LLM_PROVIDER: {provider}')Save chat.py, a small command-line client that streams the answer to the terminal and logs one line of usage per call. Its max_tokens leaves room for thinking, as in step 2:
import logging
import sys
from llmclient import LLMError, Message, from_env
logging.basicConfig(level=logging.INFO, format='%(levelname)s %(message)s')
logging.getLogger('httpx2').setLevel(logging.WARNING) # hide per-request lines
log = logging.getLogger('chat')
model = from_env()
question = ' '.join(sys.argv[1:]) or 'What does HTTP 429 mean?'
try:
reply = model.stream([Message('user', question)], max_tokens=4000,
system='Answer in one short sentence.',
on_text=lambda text: print(text, end='', flush=True))
except LLMError as exc:
sys.exit(f'model call failed: {exc}')
print(flush=True)
log.info('model=%s stop=%s input_tokens=%d output_tokens=%d',
model.name, reply.stop, reply.input_tokens, reply.output_tokens)export LOCAL_MODEL=qwen2.5:1.5b
LLM_PROVIDER=anthropic python chat.py What does HTTP 429 mean?
LLM_PROVIDER=local python chat.py What does HTTP 429 mean?
LLM_PROVIDER=mock python chat.py What does HTTP 429 mean?Fake reply to: What does HTTP 429 mean?
Received 1 message(s), 0 image(s), 0 document(s).
There is no model here; a real provider would answer the question.
INFO model=anthropic:claude-sonnet-5-5 stop=end input_tokens=12 output_tokens=43
HTTP 429 means "Too Many Requests."
INFO model=openai-compatible:qwen2.5:1.5b stop=end input_tokens=28 output_tokens=12
This is a mock reply.
INFO model=mock stop=end input_tokens=5 output_tokens=5The same code ran against the hosted stand-in, a real open-weight model on your machine and the mock. Only the configuration changed. The local answer is real: qwen2.5 runs on your CPU, nothing leaves the machine, and there is no per-token bill. Small local models are less capable than hosted ones, though, so check their answers for your task before you rely on them.
Now let the hosted provider fail. With four 429 responses scripted, the SDK makes its three retries, honouring Retry-After, and the client then reports a clean error:
curl -s http://127.0.0.1:8100/_fake/plan -H "Content-Type: application/json" \
-d '{"fail": [429, 429, 429, 429], "retry_after": 1}' > /dev/null
LLM_PROVIDER=anthropic python chat.py What does HTTP 429 mean?INFO Retrying request to /v1/messages in 1.000000 seconds
INFO Retrying request to /v1/messages in 1.000000 seconds
INFO Retrying request to /v1/messages in 1.000000 seconds
model call failed: anthropic:claude-sonnet-5-5: RateLimitError (HTTP 429)06. Step 5: Check each adapter with tests
First, test the translation code offline. The SDKs' response classes are Pydantic models, so you can build one from JSON copied from a real response:
"""Check each adapter's translation, using response JSON as providers send it."""
import anthropic
import openai
from llmclient.anthropic_chat import to_reply as from_anthropic
from llmclient.openai_chat import to_reply as from_openai
def test_anthropic_cut_off_answer():
message = anthropic.types.Message.model_validate({
'id': 'msg_1', 'type': 'message', 'role': 'assistant', 'model': 'm',
'content': [{'type': 'text', 'text': 'Export fails'}],
'stop_reason': 'max_tokens', 'stop_sequence': None,
'usage': {'input_tokens': 30, 'output_tokens': 2}})
reply = from_anthropic(message)
assert (reply.text, reply.stop, reply.output_tokens) == ('Export fails',
'max_tokens', 2)
def test_openai_cut_off_answer():
completion = openai.types.chat.ChatCompletion.model_validate({
'id': 'c1', 'object': 'chat.completion', 'created': 0, 'model': 'm',
'choices': [{'index': 0, 'finish_reason': 'length',
'message': {'role': 'assistant', 'content': 'Export fails'}}],
'usage': {'prompt_tokens': 30, 'completion_tokens': 2, 'total_tokens': 32}})
reply = from_openai(completion)
assert (reply.text, reply.stop, reply.output_tokens) == ('Export fails',
'max_tokens', 2)Second, write a contract test: one behaviour that every real endpoint must show, run against each configured provider. It is skipped unless you name providers in LIVE_PROVIDERS, so the normal test run stays offline:
"""Contract tests against real endpoints. Skipped unless LIVE_PROVIDERS is set."""
import os
import pytest
from llmclient import Message, from_env
PROVIDERS = [p for p in os.environ.get('LIVE_PROVIDERS', '').split(',') if p]
live = pytest.mark.skipif(not PROVIDERS, reason='set LIVE_PROVIDERS=anthropic,local')
@live
@pytest.mark.parametrize('provider', PROVIDERS)
def test_max_tokens_is_honoured(provider, monkeypatch):
monkeypatch.setenv('LLM_PROVIDER', provider)
reply = from_env().complete([Message('user', 'Count from 1 to 20.')],
max_tokens=5)
assert reply.stop == 'max_tokens'
assert 0 < reply.output_tokens <= 5curl -s http://127.0.0.1:8100/_fake/plan -H "Content-Type: application/json" -d "{}"
echo
pytest -q
LIVE_PROVIDERS=anthropic,local pytest -q tests/test_live.py{"fail":[],"retry_after":null,"delay":0.0}
..s.... [100%]
6 passed, 1 skipped in 4.98s
.. [100%]
2 passed in 6.39sNow see why the contract test exists. In from_env, change the local adapter's token_param='max_tokens' to token_param='max_completion_tokens', the OpenAI name, and run the local contract test again:
LIVE_PROVIDERS=local pytest -q tests/test_live.py reply = from_env().complete([Message('user', 'Count from 1 to 20.')],
max_tokens=5)
> assert reply.stop == 'max_tokens'
E AssertionError: assert 'end' == 'max_tokens'
E
E - max_tokens
E + end
tests/test_live.py:18: AssertionError
=========================== short test summary info ============================
FAILED tests/test_live.py::test_max_tokens_is_honoured[local] - AssertionErro...
1 failed in 17.80sOllama 0.40.6 accepts the request but ignores max_completion_tokens, so the model counted to twenty and stop came back as end. Nothing failed loudly: in production this would show up as longer answers and a higher bill. "OpenAI-compatible" means the common requests work, not that every field is honoured, so a short contract test against each real endpoint is worth its few seconds. Change the setting back to max_tokens before you continue.
07. Troubleshooting
08. Check your understanding
09. Apply it: stretch task
Finish the skill's practice project by extending this client:
- Add attachments: let
Messagecarry optional image and PDF paths, and have each adapter turn them into its own content blocks, reusingimage_blockandpdf_blockfrom lesson 2. TeachMockChatto count them, and test thatsupport.pypasses an attachment through. - Add
transcribe(path) -> stras a second small protocol with two implementations, one calling the hosted endpoint and one using faster-whisper, and a mock for tests. - Add a contract test for streaming: every provider must deliver the text in more than one piece and report usage at the end. Run it against the stand-in, Ollama and, if you have a key, a real hosted model.
- Optional: point
OpenAICompatibleChatat a model gateway such as LiteLLM or OpenRouter, and use the contract tests to find which fields it honours.
10. Review prompt
Without looking back, write the ChatModel protocol and the Reply dataclass, and list what each adapter is responsible for. Then explain why the normal test run uses a mock while a separate, opt-in run uses real endpoints, and describe one difference between "compatible" servers that only the second kind of test can find.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.