Model route
The model-route layer owns provider clients, credentials, structured output, retries and the per-call usage receipt, so every model call looks the same to the code above it.
When an application switches from one model provider to another, the surrounding workflow should not have to learn a new response format. The model-route layer owns the provider client, credential, structured-response validation and usage receipt. Above it, the caller sees a Generation containing text and a UsageReceipt for token accounting. Provider-specific behaviour remains below that common contract.
The layer stops at the provider boundary. It does not choose the next tool, hold run state or decide what the model may be asked. A client makes one explicit call. It does not loop, retry or fall back to another credential on its own. Those behaviours are opt-in wrappers, listed below.
Where the boundary is
| This layer owns | This layer does not own |
|---|---|
| Provider clients: Codex, OpenAI, Anthropic, Bedrock, Ollama | The tool loop that calls a client many times (agent loop) |
| Credentials passed in by the caller, and the Codex sign-in grant | Where the application keeps secrets |
generate_structured: strict JSON schema plus bounded repair | What the validated value means to the business |
One UsageReceipt per call, including failed calls | Dashboards and cost reports (observability) |
| Opt-in retry, admission limits, exact cache keys, cascade routing | Input and output policy checks (guardrails) |
Owners and tiers
The golden path names a pair as the owner. recohut_kit.providers owns credentials, transport and the call record. The PydanticAI adapter builds the native model object that a PydanticAI Agent needs, using the same credentials and receipt stream.
| Import path | Tier | What it is for |
|---|---|---|
recohut_kit.providers.codex.CodexTextClient | core | One text call on a ChatGPT-plan grant. No hidden loop, retry or API-key fallback. Accepts text_format, reasoning_effort and max_output_tokens. |
recohut_kit.providers.codex_auth.CodexAuth | core | Reads and refreshes one caller-owned grant directory under a file lock. |
recohut_kit.providers.codex_login.Login | core | Runs the sign-in callback listener and returns the login URL. |
recohut_kit.providers.openai.OpenAITextClient | core | Responses or Chat Completions through the OpenAI SDK, with a receipt per call. Also serves OpenAI-compatible bases, such as a local server or Databricks. |
recohut_kit.providers.anthropic.AnthropicTextClient | core | Claude through the Anthropic SDK. An async twin, AsyncAnthropicTextClient, has agenerate. |
recohut_kit.providers.bedrock.BedrockTextClient | core | Bedrock Converse through a boto3 client you pass in. Supports text_format as a Converse output config. |
recohut_kit.providers.bedrock_guardrails.BedrockGuardrails | core | Standalone ApplyGuardrail checks. GuardedTextClient wraps any client with input and output checks. |
recohut_kit.providers.ollama.OllamaTextClient | core | A local Ollama server. The base URL must be plain HTTP on loopback. |
recohut_kit.providers.structured.generate_structured | core | Strict JSON-schema output with bounded validation repair and one receipt per attempt. |
recohut_kit.providers.routes.text_client | core | Picks the Codex or Claude client from the RECOHUT_LLM_ROUTE setting. |
recohut_kit_pydantic_ai.integrations.pydantic_ai.lifecycle.codex_responses_model | core | Application-lifetime native PydanticAI model on the Codex route, with receipts and an owned client. |
recohut_kit_pydantic_ai.integrations.pydantic_ai.codex.codex_model | core | The same model as an async context manager that closes its client on exit. |
recohut_kit.production (retry, limits, semantic_cache) | supported | Opt-in retries with attempt evidence, local request and token admission, a semantic cache, and export to OpenTelemetry, Phoenix, MLflow and Prometheus. |
recohut_kit.caching.exact_key | supported | A pure function that builds an exact cache key for a model request. |
recohut_kit_databricks.providers | supported | The Databricks Model Serving client and auth. The old recohut_kit.providers.databricks path is a deprecated shim. |
recohut_kit.model_routing | catalog | A deterministic cost cascade: a RouteTable of tiers per task, a residency policy and a scorer. No model chooses the route. |
recohut_kit.decision_models, prompt_caching, kv_cache, optimization, finetune, cloud_ml | catalog | Decision-question adapters, cache measurement, efficiency policies, local LoRA tuning and managed-training contracts. |
Framework bindings for CrewAI, LangChain, the OpenAI Agents SDK and Strands also live under recohut_kit.integrations and the adapter packages. They hand the same Codex grant and receipts to those SDKs.
How the pieces fit
Every client appends a receipt to the JSONL file you give it. generate_structured sits on top of a client and adds validation. codex_responses_model is the path for a PydanticAI agent: the agent runs its own loop, and each model request still writes a receipt.
The contract every client shares
Model providers differ, but consumers need the same distinction between the generated content and the receipt that describes the call.
TextClient is a runtime-checkable protocol with two methods: generate(text, *, instructions, prompt_version) and unwrap(). unwrap() returns the underlying SDK object. Generation is a frozen dataclass of text and receipt.
UsageReceipt carries the request id, model, billing route (codex, api_key, aws, local or databricks), prompt version, a SHA-256 of the request, status, token counts and elapsed milliseconds. A counter the provider does not report stays None. It is never turned into zero.
Worked examples
Structured output with a stand-in client
generate_structured needs a client whose generate accepts text_format. The stand-in below has the same surface as CodexTextClient, so the example runs without a network. The first reply misses a required field, so the helper makes one repair attempt and records a second receipt under the #repair-1 prompt version.
import tempfile
from pathlib import Path
from pydantic import BaseModel
from recohut_kit.providers.contracts import Generation
from recohut_kit.providers.structured import StructuredOutputError, generate_structured
from recohut_kit.usage import UsageReceipt, append_receipt
receipts = Path(tempfile.mkdtemp()) / "receipts.jsonl"
class Verdict(BaseModel):
ok: bool
reason: str
class ScriptedClient:
"""Same generate() surface as CodexTextClient, with canned replies."""
def __init__(self, replies):
self.replies, self.calls = list(replies), 0
def unwrap(self):
return self
def generate(self, text, *, instructions, prompt_version, text_format=None, **knobs):
self.calls += 1
receipt = UsageReceipt(
request_id=f"r{self.calls}", model="scripted", billing_route="local",
prompt_version=prompt_version, request_sha256="0" * 64, status="completed",
input_tokens=10, output_tokens=5, elapsed_ms=1,
)
append_receipt(receipts, receipt)
return Generation(self.replies.pop(0), receipt)
client = ScriptedClient(['{"ok": true}', '{"ok": true, "reason": "carry-over allowed"}'])
result = generate_structured(
client, Verdict, text="Is 5 days carry-over allowed?",
instructions="Judge the claim.", prompt_version="judge-v1",
)
print(result.value) # ok=True reason='carry-over allowed'
print([r.prompt_version for r in result.receipts]) # ['judge-v1', 'judge-v1#repair-1']
try:
generate_structured(ScriptedClient(["nope", "nope"]), Verdict, text="x",
instructions="y", prompt_version="v")
except StructuredOutputError as error:
print(error.problems) # locations and messages, not model textWith a real client, replace ScriptedClient with CodexTextClient or BedrockTextClient. The default is one repair attempt (max_validation_retries=1). When every attempt fails, StructuredOutputError carries the attempts and the error locations.
A Codex client and a native PydanticAI model
Both halves read the same CodexAuth directory. This example needs a signed-in grant, so it only constructs objects. The model name must come from the connection's recorded catalog.
from pathlib import Path
from pydantic_ai import Agent
from recohut_kit.providers.codex import CodexTextClient
from recohut_kit.providers.codex_auth import CodexAuth
from recohut_kit.providers.structured import generate_structured
from recohut_kit_pydantic_ai.integrations.pydantic_ai.lifecycle import codex_responses_model
auth = CodexAuth(Path("data/local/codex-auth")) # one directory, shared by every process
receipts = Path("data/receipts.jsonl")
model_name = auth.available_models()[0] # an empty tuple means: sign in again
# One-shot calls: extraction, classification, grading.
client = CodexTextClient(auth, model=model_name, receipts=receipts)
# verdict = generate_structured(client, Verdict, text="...", instructions="Judge.",
# prompt_version="judge-v1").value
# A PydanticAI agent: the agent runs its own loop, each request writes a receipt.
handle = codex_responses_model(
auth, model=model_name, namespace="app_tools", receipts=receipts, prompt_version="v1",
)
agent = Agent(handle.model, instructions="Answer from the tools.")codex_responses_model raises CodexUnavailable before any request when the model is not in the grant's catalog or the grant is missing. Use codex_model instead when you want an async context manager that closes the client on exit.
Opt-in retries
Clients never retry. RetryingClient wraps one and records every attempt. The flaky client below fails twice with a 429, then succeeds. Attempts are visible on last_receipt.
from recohut_kit.production.retry import CallFailure, RetryPolicy, RetryingClient
class Flaky:
def __init__(self, inner):
self.inner, self.calls = inner, 0
def unwrap(self):
return self
def generate(self, text, *, instructions, prompt_version, **options):
self.calls += 1
if self.calls < 3:
raise CallFailure(429, "rate_limit")
return self.inner.generate(text, instructions=instructions, prompt_version=prompt_version)
# inner: any TextClient, for example the ScriptedClient from the first example
client = RetryingClient(Flaky(ScriptedClient(["ok"])), RetryPolicy(max_attempts=4, sleeper=lambda s: None))
generation = client.generate("hi", instructions="i", prompt_version="v1")
print(client.last_receipt.terminal_reason) # completed
print([a.status for a in client.last_receipt.attempts]) # ['failed', 'failed', 'completed']RetryPolicy defaults to four attempts, a 0.2 second first delay, a 5 second cap per delay and a 60 second deadline. A provider Retry-After value is treated as a minimum wait. Pass sleeper=lambda s: None in tests so no real time passes.
Choosing between owners
| You need | Use |
|---|---|
| A ChatGPT-plan grant, no API key | CodexTextClient with CodexAuth |
| A paid API key, OpenAI or an OpenAI-compatible server | OpenAITextClient |
| Claude with an API key | AnthropicTextClient, or text_client(route="claude", ...) |
| AWS, with your own boto3 client and region | BedrockTextClient, optionally wrapped in GuardedTextClient |
| A local model with no network egress | OllamaTextClient |
| A PydanticAI agent on Codex | codex_responses_model, not CodexTextClient |
| A one-shot typed answer | generate_structured over CodexTextClient or BedrockTextClient |
| Cheap tiers first, escalating on a low score | model_routing.Router (catalog) |
| Retries, local rate limits | production.retry and production.limits, added by you |
Use the PydanticAI model for a loop and generate_structured for a single typed answer. Do not wire a native loop through CodexTextClient.
Failure behaviour, limits and gotchas
- Failed calls still write a receipt. Provider failures are reduced to a safe status, a coarse category (
rate_limit,auth,server,timeout,bad_request,unknown) andRetry-After. The SDK message and body are never copied into the exception or the receipt. - Codex failures are classified.
CodexRequestFailedcarrieserror_typeandhttp_status.CodexIncompleteis raised when the output cap is hit, andgenerate_structureddoes not retry it. Reasoning tokens count towardmax_output_tokens. - No API-key fallback on Codex. A missing or expired grant raises
CodexUnavailable. The grant file must be mode 0600 and not a symlink, or it reads as disconnected. - Share the grant directory, never a copy of
connection.json. A refresh rotates the refresh token, so a copied file goes stale. Refresh runs under a file lock and re-reads the file inside it. RECOHUT_LLM_ROUTE=clauderedirectsCodexTextClient(...)to a Claude client. Receipts name the Claude model and theapi_keybilling route. The Claude route needs an env file holdingANTHROPIC_API_KEY; there is no ambient credential lookup.generate_structuredaccepts clients whosegeneratetakestext_format.CodexTextClientandBedrockTextClientdo. The OpenAI, Anthropic and Ollama clients in the source do not take it, so passing one raises aTypeError.TextClientdoes not includetext_format. The protocol covers plain text only.- OpenAI and Anthropic clients are built with
max_retries=0. The SDK does not retry behind your back. - Ollama needs a loopback URL. Anything other than plain HTTP on
127.0.0.1,localhostor::1raisesValueError. - Bedrock needs explicit inputs. The constructor requires a boto3 client, model, region, output limit and receipts path. It does no region or credential discovery.
- Token counts are what the provider reports. Nothing is estimated. A missing counter is
None. - Optional SDKs load inside constructors. Importing
providers.codexorproviders.structuredloads none ofopenai,anthropic,boto3orpydantic. Install the extra you need:codex,openai,anthropic,bedrockorollama.
Spend control lives next door
The spend_guard package prices receipts with a table you supply and trips a circuit breaker on loops and spikes. It is classed under observability, not here. It is a rules engine around your client and makes no model call.
How is this page?
Last updated on