Provider adapters with explicit credentials and per-call receipts
Optional adapters that call hosted and local language-model routes, record one usage receipt per invocation, and share a single text-generation contract across Codex, Claude, OpenAI, Bedrock, and Ollama.
The recohut_kit.providers package holds optional adapters around explicit, caller-owned authentication. Each adapter turns one text request into a provider-native call and returns the same Generation shape: completed text plus a UsageReceipt. Failed, cancelled, and successful invocations can all append receipts. Payload bodies and credentials are not copied into safe errors or into receipt rows beyond fingerprints and token counters.
The package root exports nothing. Import the submodule you need (recohut_kit.providers.codex, recohut_kit.providers.routes, and so on). The adapters are not imported by other kit modules as a single facade; they are building blocks for applications and for higher kit layers that already own policy, tools, and grounding.
This layer deliberately does not own tool loops, retrieval, guardrail policy authoring, or model-directed orchestration beyond what each native client already exposes. Credentials are not read from the process environment; RECOHUT_LLM_ROUTE only selects the route, and RECOHUT_CLAUDE_ENV_FILE names the file that holds ANTHROPIC_API_KEY. It does not substitute static text when a local generation fails. The Strands companion keeps native Anthropic streaming and adds budget metering, cache replay, events, an optional content sink, and client close.
Purpose
A provider adapter handles one model call and returns its content alongside usage. This common shape lets callers compare and handle results without pretending providers behave identically.
What it owns. A portable TextClient protocol, shared Generation results, receipt observation (observe, provider_failure), route selection between Codex plan credits and Claude API-key billing (routes), Codex plan authorization and login (codex_auth, codex_login), Responses-shaped Codex transport and failure taxonomy (codex, codex_wire), native Anthropic and Claude HTTP clients (anthropic, claude_wire), OpenAI Responses and Chat wrappers (openai, openai_wire), Bedrock Converse text and structured output (bedrock), explicit Bedrock ApplyGuardrail wrapping (bedrock_guardrails), loopback Ollama generation (ollama), Pydantic-validated structured output over formatted clients (structured), schema fingerprints for adapted requests (schema_observation), chat UI catalog helpers for the Codex plan route (codex_chat_models), and an optional metered Strands Anthropic model (strands_anthropic).
What it does not own. Application prompts, safety policy content, tool permissions, evidence grounding, distributed rate limiting, and managed secret stores. OpenAI accepts an injected client or API key; Bedrock accepts only a caller-supplied runtime client. Codex expects a connection directory you maintain. Claude expects a file that holds ANTHROPIC_API_KEY. None of these modules implement a generic agent runtime.
Language-model calls happen inside the adapters (network I/O to provider APIs). Receipt writing, payload fingerprinting, schema relaxation, retry classification helpers, and validation repair loops are plain code around those calls.
Public API
| Name | Kind | What it does |
|---|---|---|
Generation | dataclass | Completed text and a UsageReceipt for every provider. |
TextClient | protocol | One generate(text, instructions, prompt_version) plus unwrap() for the native client. |
observe | function | Context manager that appends a usage receipt on success, failure, or cancellation. |
provider_failure | function | Builds a sanitised ProviderFailure from an SDK or transport error. |
ProviderFailure | exception | Safe failure with coarse category and optional HTTP metadata. |
ObservedCall | dataclass | Mutable counters and completion flag for one observed attempt. |
ReceiptWriteError | exception | Call finished but receipt persistence failed. |
tokens | function | Accepts only nonnegative integer counters; otherwise None. |
selected_route | function | Reads RECOHUT_LLM_ROUTE (codex default, or claude / anthropic). |
text_client | function | Returns the TextClient for Codex or Claude with explicit paths. |
claude_env_file | function | Resolves RECOHUT_CLAUDE_ENV_FILE to the API-key env file. |
ClaudeForCodexTextClient | class | Claude behind the Codex call surface (format, effort, stream). |
claude_tools_client | function | Anthropic tools client standing in for CodexToolsClient. |
CodexAuth | class | Caller-owned ChatGPT plan connection and token refresh under file lock. |
Connection | dataclass | Saved grant state for a Codex connection directory. |
AuthPolicy | dataclass | Timeouts and refresh margin for authorization; no spend ceilings. |
GrantLifetime | dataclass | Parsed grant expiry metadata from the connection file. |
refreshing_connection | function | Returns a CodexAuth that refreshes the shared directory under connection.lock. |
CodexUnavailable | exception | Safe authorization failure without credentials or bodies. |
Login | class | One-use loopback PKCE sign-in for a Codex connection. |
CodexTextClient | class | Synchronous Codex plan text client; redirects to Claude when route is claude. |
plan_payload | function | Adapts a Responses-style payload to what the plan route accepts. |
payload_adapter | function | Returns a callable that strips unsupported top-level fields. |
CodexRequestFailed and subclasses | exceptions | Classified Codex failures (CodexParameterRejected, CodexIncomplete, and others). |
RetryPolicy, call_with_retries, RetryingTextClient | types | Repeat classified transient Codex failures, defaulting to rate limit, server error, transport, and stream. |
sdk_http_client | function | SDK-native Responses HTTP client on Codex credits with terminal receipts. |
prompt_version_override | function | Context manager to label receipts for nested SDK calls. |
chat_model_label, ChatChoice, chat_catalog, resolve_chat_choice | helpers | Chat turn model catalog and validation for the Codex plan. |
Turn | dataclass | One Anthropic turn with native content blocks and receipt. |
cache_details | function | Maps Anthropic usage fields into UsageDetails. |
AnthropicTextClient, AsyncAnthropicTextClient | classes | Native Messages API clients with receipts. |
read_env_file | function | Reads named keys from one explicit env file. |
claude_text_client | function | Constructs AnthropicTextClient from an env file path. |
ClaudeSettings, claude_settings, claude_http_client | types | Settings and observed HTTP client for framework adapters on Claude. |
OpenAITextClient | class | OpenAI Responses or Chat client with per-call receipts. |
observed_chat_completion, observed_chat_completion_with_receipt | functions | Chat completion with native result preserved plus receipt. |
observed_async_http_client | function | Async HTTP client hook that records OpenAI usage receipts. |
converse_output_config | function | Translates Responses json_schema format to Bedrock Converse outputConfig. |
BedrockTextClient | class | Converse text generation through an injected runtime client. |
BedrockGuardrails, GuardedTextClient | classes | Explicit ApplyGuardrail calls and fail-closed wrapped TextClient. |
GuardrailResult, Guardrails, GuardrailIntervention | types | Guardrail outcomes and intervention exception. |
OllamaTextClient, OllamaServer | classes | Loopback Ollama generation and an owned-server recipe. |
OllamaProtocolError | exception | Local-protocol failure, including incomplete or empty text, invalid bodies, pull or catalog failures, and an owned process that exits. |
generate_structured, Structured, StructuredOutputError | API | Pydantic-validated JSON schema output with repair attempts. |
strict_json_schema, schema_name_for | functions | Strict-mode schema preparation and default format names. |
FormattedTextClient | protocol | TextClient that accepts optional text_format. |
SchemaObservation, schema_observation | types | Metadata-only fingerprints of tools and output schema on a request. |
estimated_input, ModelContext, MeteredAnthropicModel | Strands helpers | Reservation heuristic and metered Strands Anthropic streaming. |
How it composes
Adapters pull shared primitives from other recohut_kit packages rather than reimplementing them.
| Kit package | Role in providers |
|---|---|
recohut_kit.usage | UsageReceipt, DetailedUsageReceipt, append_receipt, scoped sinks, and receipt delivery hooks. |
recohut_kit.json | JsonValue, fingerprint, canonical_json, and as_json_value for payloads and schemas. |
recohut_kit.files | atomic_private_json and file_lock for Codex connection and login. |
recohut_kit.streams | SSE parsing for Codex streaming responses. |
recohut_kit.production.retry | provider_failure uses classify_failure; Codex retries classify with codex_error_type and read retry_after_seconds. |
recohut_kit.production.inference_metrics | MeasuredStream for instrumented streaming on Codex and Claude. |
recohut_kit.production.runtime | wait_until waits for the owned Ollama server; process ownership is ManagedProcess from recohut_kit.integrations.langchain_serving.lifecycle. |
recohut_kit.prompt_caching.observation | Prompt prefix observations from Codex and Claude wire clients. |
recohut_kit.latency | LatencyRecorder for streaming entry points. |
recohut_kit.storage.cache_contract | Cache contract for Strands replay. |
recohut_kit.verification.persistent_budget | Call budget type for Strands metering. |
Internal composition stays within recohut_kit.providers: Generation is the shared result; receipts.observe is used by Anthropic, OpenAI, Bedrock, and guardrails, while Codex and Ollama write receipts through recohut_kit.usage. codex_wire calls codex, codex_auth, receipts, and schema_observation; claude_wire calls anthropic, receipts, and routes. structured expects a FormattedTextClient such as CodexTextClient or BedrockTextClient. selected_route returns codex or claude, treating the setting anthropic as claude, and text_client builds the matching client. bedrock_guardrails wraps any TextClient.
Third-party libraries appear at documented boundaries: httpx for Codex and Ollama HTTP, jwt for Codex token handling, pydantic for generate_structured, and strands for MeteredAnthropicModel. The OpenAI and Anthropic text clients import their SDKs when no client is injected; sdk_http_client imports openai whenever it builds the Codex HTTP client. Bedrock text and guardrail types take a caller-supplied runtime client and do not import or configure botocore.
Minimal usage example
Pass an injected Messages client to exercise the text response and usage receipt contract locally. This client returns a fixed response and uses no provider SDK, network, or credentials.
from pathlib import Path
from tempfile import TemporaryDirectory
from types import SimpleNamespace
from recohut_kit.providers.anthropic import AnthropicTextClient
def scripted_response(**request):
assert request["model"] == "reference-model"
return SimpleNamespace(
id="local-response",
stop_reason="end_turn",
content=[SimpleNamespace(type="text", text="The release is ready for review.")],
usage=SimpleNamespace(input_tokens=7, output_tokens=8),
)
with TemporaryDirectory() as directory:
receipt_path = Path(directory) / "receipts.ndjson"
client = AnthropicTextClient(
model="reference-model",
base_url="https://example.invalid",
max_output_tokens=64,
receipts=receipt_path,
client=SimpleNamespace(messages=SimpleNamespace(create=scripted_response)),
)
result = client.generate(
"Summarize the release.", instructions="Use one sentence.", prompt_version="v1",
)
assert result.text == "The release is ready for review."
assert result.receipt.status == "completed" and receipt_path.is_file()For live Anthropic calls, the anthropic extra supplies the SDK for claude_text_client. The factory reads credentials from a file you specify. Calls through that factory are billed to the supplied API key.
Limits and gotchas
- Explicit inputs.
observerequires nonemptymodelandprompt_version. Most clients reject missing models, base URLs, or credentials at construction time rather than at first call. - Route selection. Unset
RECOHUT_LLM_ROUTEkeeps the Codex route. Values other thancodex,claude, oranthropicraiseValueError. When the route isclaude, constructingCodexTextClientredirects toClaudeForCodexTextClientso receipts name the Claude model andapi_keybilling. - Credential isolation. Codex connection reprs and user-facing failures omit credentials. Share a connection directory across processes, not copies of
connection.json, because refresh rotates refresh tokens. Anthropicread_env_filereads only the path you pass. - Safe failures.
provider_failureand Codex failure types strip provider prose and bodies.GuardedTextClienttreats any guardrail intervention, including redaction, as failure and does not forward rewritten prompts or unreviewed model output. Do not layerBedrockGuardrailsover Strands model calls; configure guardrails on the Strands Bedrock model instead. - Structured output.
generate_structuredretries only Pydantic validation failures up tomax_validation_retries.CodexIncompleteand in-call auth failures propagate after a receipt;CodexInputRejectedandCodexModelUnavailablepropagate with nothing sent and no receipt.strict_json_schemareshapes Pydantic JSON Schema for strict Responses mode; Bedrock usesconverse_output_config, which rejectsjson_object, unsupported format keys, non-local$ref, and map-typed fields withoutadditionalProperties: false. - Codex payload surface.
UNSUPPORTED_FIELDSandplan_payloaddocument fields the plan route strips or rejects.CodexTextClientdoes not hide retries at the client level; separateRetryingTextClientopts in. - Streaming receipts.
observed_chat_completionrefusesstream=Truebecause partial streams would record incorrect completion. Use stream-aware transports (generate_stream,MeasuredStream, wire clients) where provided. - Ollama completeness.
OllamaProtocolErrorsignals a failed local protocol exchange, including incomplete or empty text, and there is no substitute completion string. - Token counters.
tokensstores only actual nonnegative integers from provider usage objects; missing counters stayNone, not zero. - Schema observation timing.
schema_observationrequires a generation receipt whose status is notcache_hit. - Optional dependencies.
generate_structuredrequires Pydantic at the consumer. Importingstrands_anthropicimports Strands immediately; the Anthropic SDK is imported when a text client is constructed without an injected client.
Verification
The example checks text and receipt persistence with an injected client. Live provider behavior depends on the configured route and provider. See Verify the examples.
How is this page?
Last updated on