Skip to Content
Recodocs

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.

8 min read

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

NameKindWhat it does
GenerationdataclassCompleted text and a UsageReceipt for every provider.
TextClientprotocolOne generate(text, instructions, prompt_version) plus unwrap() for the native client.
observefunctionContext manager that appends a usage receipt on success, failure, or cancellation.
provider_failurefunctionBuilds a sanitised ProviderFailure from an SDK or transport error.
ProviderFailureexceptionSafe failure with coarse category and optional HTTP metadata.
ObservedCalldataclassMutable counters and completion flag for one observed attempt.
ReceiptWriteErrorexceptionCall finished but receipt persistence failed.
tokensfunctionAccepts only nonnegative integer counters; otherwise None.
selected_routefunctionReads RECOHUT_LLM_ROUTE (codex default, or claude / anthropic).
text_clientfunctionReturns the TextClient for Codex or Claude with explicit paths.
claude_env_filefunctionResolves RECOHUT_CLAUDE_ENV_FILE to the API-key env file.
ClaudeForCodexTextClientclassClaude behind the Codex call surface (format, effort, stream).
claude_tools_clientfunctionAnthropic tools client standing in for CodexToolsClient.
CodexAuthclassCaller-owned ChatGPT plan connection and token refresh under file lock.
ConnectiondataclassSaved grant state for a Codex connection directory.
AuthPolicydataclassTimeouts and refresh margin for authorization; no spend ceilings.
GrantLifetimedataclassParsed grant expiry metadata from the connection file.
refreshing_connectionfunctionReturns a CodexAuth that refreshes the shared directory under connection.lock.
CodexUnavailableexceptionSafe authorization failure without credentials or bodies.
LoginclassOne-use loopback PKCE sign-in for a Codex connection.
CodexTextClientclassSynchronous Codex plan text client; redirects to Claude when route is claude.
plan_payloadfunctionAdapts a Responses-style payload to what the plan route accepts.
payload_adapterfunctionReturns a callable that strips unsupported top-level fields.
CodexRequestFailed and subclassesexceptionsClassified Codex failures (CodexParameterRejected, CodexIncomplete, and others).
RetryPolicy, call_with_retries, RetryingTextClienttypesRepeat classified transient Codex failures, defaulting to rate limit, server error, transport, and stream.
sdk_http_clientfunctionSDK-native Responses HTTP client on Codex credits with terminal receipts.
prompt_version_overridefunctionContext manager to label receipts for nested SDK calls.
chat_model_label, ChatChoice, chat_catalog, resolve_chat_choicehelpersChat turn model catalog and validation for the Codex plan.
TurndataclassOne Anthropic turn with native content blocks and receipt.
cache_detailsfunctionMaps Anthropic usage fields into UsageDetails.
AnthropicTextClient, AsyncAnthropicTextClientclassesNative Messages API clients with receipts.
read_env_filefunctionReads named keys from one explicit env file.
claude_text_clientfunctionConstructs AnthropicTextClient from an env file path.
ClaudeSettings, claude_settings, claude_http_clienttypesSettings and observed HTTP client for framework adapters on Claude.
OpenAITextClientclassOpenAI Responses or Chat client with per-call receipts.
observed_chat_completion, observed_chat_completion_with_receiptfunctionsChat completion with native result preserved plus receipt.
observed_async_http_clientfunctionAsync HTTP client hook that records OpenAI usage receipts.
converse_output_configfunctionTranslates Responses json_schema format to Bedrock Converse outputConfig.
BedrockTextClientclassConverse text generation through an injected runtime client.
BedrockGuardrails, GuardedTextClientclassesExplicit ApplyGuardrail calls and fail-closed wrapped TextClient.
GuardrailResult, Guardrails, GuardrailInterventiontypesGuardrail outcomes and intervention exception.
OllamaTextClient, OllamaServerclassesLoopback Ollama generation and an owned-server recipe.
OllamaProtocolErrorexceptionLocal-protocol failure, including incomplete or empty text, invalid bodies, pull or catalog failures, and an owned process that exits.
generate_structured, Structured, StructuredOutputErrorAPIPydantic-validated JSON schema output with repair attempts.
strict_json_schema, schema_name_forfunctionsStrict-mode schema preparation and default format names.
FormattedTextClientprotocolTextClient that accepts optional text_format.
SchemaObservation, schema_observationtypesMetadata-only fingerprints of tools and output schema on a request.
estimated_input, ModelContext, MeteredAnthropicModelStrands helpersReservation heuristic and metered Strands Anthropic streaming.

How it composes

Adapters pull shared primitives from other recohut_kit packages rather than reimplementing them.

Kit packageRole in providers
recohut_kit.usageUsageReceipt, DetailedUsageReceipt, append_receipt, scoped sinks, and receipt delivery hooks.
recohut_kit.jsonJsonValue, fingerprint, canonical_json, and as_json_value for payloads and schemas.
recohut_kit.filesatomic_private_json and file_lock for Codex connection and login.
recohut_kit.streamsSSE parsing for Codex streaming responses.
recohut_kit.production.retryprovider_failure uses classify_failure; Codex retries classify with codex_error_type and read retry_after_seconds.
recohut_kit.production.inference_metricsMeasuredStream for instrumented streaming on Codex and Claude.
recohut_kit.production.runtimewait_until waits for the owned Ollama server; process ownership is ManagedProcess from recohut_kit.integrations.langchain_serving.lifecycle.
recohut_kit.prompt_caching.observationPrompt prefix observations from Codex and Claude wire clients.
recohut_kit.latencyLatencyRecorder for streaming entry points.
recohut_kit.storage.cache_contractCache contract for Strands replay.
recohut_kit.verification.persistent_budgetCall 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. observe requires nonempty model and prompt_version. Most clients reject missing models, base URLs, or credentials at construction time rather than at first call.
  • Route selection. Unset RECOHUT_LLM_ROUTE keeps the Codex route. Values other than codex, claude, or anthropic raise ValueError. When the route is claude, constructing CodexTextClient redirects to ClaudeForCodexTextClient so receipts name the Claude model and api_key billing.
  • 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. Anthropic read_env_file reads only the path you pass.
  • Safe failures. provider_failure and Codex failure types strip provider prose and bodies. GuardedTextClient treats any guardrail intervention, including redaction, as failure and does not forward rewritten prompts or unreviewed model output. Do not layer BedrockGuardrails over Strands model calls; configure guardrails on the Strands Bedrock model instead.
  • Structured output. generate_structured retries only Pydantic validation failures up to max_validation_retries. CodexIncomplete and in-call auth failures propagate after a receipt; CodexInputRejected and CodexModelUnavailable propagate with nothing sent and no receipt. strict_json_schema reshapes Pydantic JSON Schema for strict Responses mode; Bedrock uses converse_output_config, which rejects json_object, unsupported format keys, non-local $ref, and map-typed fields without additionalProperties: false.
  • Codex payload surface. UNSUPPORTED_FIELDS and plan_payload document fields the plan route strips or rejects. CodexTextClient does not hide retries at the client level; separate RetryingTextClient opts in.
  • Streaming receipts. observed_chat_completion refuses stream=True because partial streams would record incorrect completion. Use stream-aware transports (generate_stream, MeasuredStream, wire clients) where provided.
  • Ollama completeness. OllamaProtocolError signals a failed local protocol exchange, including incomplete or empty text, and there is no substitute completion string.
  • Token counters. tokens stores only actual nonnegative integers from provider usage objects; missing counters stay None, not zero.
  • Schema observation timing. schema_observation requires a generation receipt whose status is not cache_hit.
  • Optional dependencies. generate_structured requires Pydantic at the consumer. Importing strands_anthropic imports 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