Ir para o conteúdo

tempest_fastapi_sdk.genai

IA generativa self-hosted: geração de texto, embeddings, VLM, moderação, cache, métricas e router.

« IA e visão computacional


A superfície de topo do genai — geração de texto, embeddings, VLM, moderação, cache, métricas e router. Os submódulos que exigem outra disciplina (hub, image, inventory, rag, audio) têm página própria.

genai

Self-hosted generative AI — run HuggingFace models on your own hardware.

The first slice ships the capacity check: before you download and load a model, ask whether the host can actually run it. Everything here imports without the [genai] extra; torch / transformers are only needed to probe real GPUs and (later) run inference.

ANTHROPIC_STOP_REASONS module-attribute

ANTHROPIC_STOP_REASONS: dict[str, StopReason] = {
    "end_turn": "end",
    "stop_sequence": "end",
    "max_tokens": "max_tokens",
    "refusal": "refusal",
    "tool_use": "tool_use",
}

Messages API stop_reason values to the normalized :data:StopReason.

From the stop-reason table of https://platform.claude.com/docs/en/api/messages (end_turn, max_tokens, stop_sequence, tool_use, pause_turn, refusal). pause_turn and any value added later map to other.

ANTHROPIC_VERSION module-attribute

ANTHROPIC_VERSION: str = '2023-06-01'

The anthropic-version header value.

The example value of the required header at https://platform.claude.com/docs/en/api/overview.

ChatStreamEvent module-attribute

ChatStreamEvent = StreamTextDelta | StreamToolCalls

One event of :meth:ToolStreamingBackend.stream_chat_with_tools.

DEFAULT_ANTHROPIC_MAX_TOKENS module-attribute

DEFAULT_ANTHROPIC_MAX_TOKENS: int = 16000

max_tokens sent when the call sets no max_new_tokens.

The Messages API requires max_tokens on every request (https://platform.claude.com/docs/en/api/messages), unlike the OpenAI and Ollama formats, where it is optional.

DEFAULT_ANTHROPIC_MODEL module-attribute

DEFAULT_ANTHROPIC_MODEL: str = 'claude-opus-5-5'

The model used when none is given.

The current Opus model id on the models table (https://platform.claude.com/docs/en/models/overview) when this was written. Pass model to choose another; model ids are never guessed from a date.

DEFAULT_ANTHROPIC_URL module-attribute

DEFAULT_ANTHROPIC_URL: str = 'https://api.anthropic.com'

API root; requests go to {base_url}/v1/messages.

From https://platform.claude.com/docs/en/api/overview.

DEFAULT_DEEPSEEK_MODEL module-attribute

DEFAULT_DEEPSEEK_MODEL: str = 'deepseek-flash'

DeepSeek's default model id.

The model field of https://api-docs.deepseek.com/api/create-chat-completion accepts deepseek-flash or deepseek-v4-pro when this was written.

DEFAULT_DEEPSEEK_URL module-attribute

DEFAULT_DEEPSEEK_URL: str = 'https://api.deepseek.com'

DeepSeek's OpenAI-format API root.

From https://api-docs.deepseek.com/, which posts to https://api.deepseek.com/chat/completions.

DEFAULT_DOCUMENT_FILENAME module-attribute

DEFAULT_DOCUMENT_FILENAME: Final[str] = 'document.pdf'

The filename :func:document_part sends when the caller gives none.

Every base64 example of the OpenAI PDF guide passes a filename next to file_data, so the part always carries one.

DEFAULT_GOOGLE_OPENAI_URL module-attribute

DEFAULT_GOOGLE_OPENAI_URL: Final[str] = (
    "https://generativelanguage.googleapis.com/v1beta/openai"
)

Gemini's OpenAI-compatible API root; /chat/completions is appended.

From https://ai.google.dev/gemini-api/docs/openai, whose base_url is https://generativelanguage.googleapis.com/v1beta/openai/. Stored without the trailing slash because the generator joins /chat/completions itself.

DEFAULT_OPENAI_URL module-attribute

DEFAULT_OPENAI_URL: str = 'https://api.openai.com/v1'

Where the wire format originates; override for any other provider.

The servers entry of the official OpenAPI document (https://github.com/openai/openai-openapi).

DEFAULT_SPEECH_MODEL module-attribute

DEFAULT_SPEECH_MODEL: str = 'default'

The speech model sent when the constructor names none.

tempest-ai reads default as "the TTS model this machine serves"; an OpenAI account needs a real id (tts-1, gpt-4o-mini-tts), passed as speech_model.

DOCUMENT_MEDIA_TYPES module-attribute

DOCUMENT_MEDIA_TYPES: Final[frozenset[str]] = frozenset({PDF_MEDIA_TYPE})

Media types :func:document_part accepts.

Only PDF. The OpenAI PDF guide (https://developers.openai.com/api/docs/guides/pdf-files) says Chat Completions "supports only .pdf (application/pdf)" for file_data, and the base64 document source of the Anthropic PDF guide (https://platform.claude.com/docs/en/build-with-claude/pdf-support) is application/pdf. Plain text goes in a text part instead.

DOCUMENT_PROVIDERS module-attribute

DOCUMENT_PROVIDERS: Final[frozenset[HostedProvider]] = frozenset(
    {"anthropic", "openai"}
)

Hosted providers whose documentation describes PDF input.

Read on 2026-11-04:

Left out, because their documentation does not describe it:

The SDK's tests pin the request built for each provider, not a provider's answer: membership here is what the documentation says, not a live call.

Effort module-attribute

Effort = Literal['low', 'medium', 'high', 'xhigh', 'max']

How much reasoning a call asks for, from cheapest to most thorough.

The Anthropic spelling (output_config.effort). The OpenAI-compatible generator forwards it under its effort_field, translated through its effort_values when the provider documents a narrower set.

GOOGLE_EFFORT_VALUES module-attribute

GOOGLE_EFFORT_VALUES: Final[MappingProxyType[str, str]] = MappingProxyType(
    {"low": "low", "medium": "medium", "high": "high", "xhigh": "high", "max": "high"}
)

Effort values translated to Gemini's reasoning_effort.

https://ai.google.dev/gemini-api/docs/openai documents minimal, low, medium and high for reasoning_effort; xhigh and max have no Gemini spelling, so they ask for the highest one it has.

HOSTED_PROVIDERS module-attribute

HOSTED_PROVIDERS: Final[tuple[HostedProvider, ...]] = (
    "anthropic",
    "openai",
    "google",
    "deepseek",
)

The values of :data:HostedProvider, for checking a provider at runtime.

HostedProvider module-attribute

HostedProvider = Literal['anthropic', 'openai', 'google', 'deepseek']

The hosted providers :func:hosted_generator knows how to build.

MODEL_PREFIXES module-attribute

MODEL_PREFIXES: Final[tuple[tuple[str, HostedProvider], ...]] = (
    ("claude-", "anthropic"),
    ("gpt-", "openai"),
    ("chatgpt-", "openai"),
    ("o1", "openai"),
    ("o3", "openai"),
    ("o4", "openai"),
    ("gemini-", "google"),
    ("deepseek-", "deepseek"),
)

Model-id prefixes and the provider each one belongs to, checked in order.

The prefixes the providers use for their model families. A model id outside them (a fine-tune, a self-hosted model behind an OpenAI-compatible server) is not guessed: pass provider= explicitly.

MULTILINGUAL_E5_PREFIXES module-attribute

MULTILINGUAL_E5_PREFIXES: Final[EmbeddingPrefixes] = {
    "query_prefix": "query: ",
    "passage_prefix": "passage: ",
}

Prefixes of the intfloat/multilingual-e5-* and intfloat/e5-* family.

NOMIC_EMBED_TEXT_PREFIXES module-attribute

NOMIC_EMBED_TEXT_PREFIXES: Final[EmbeddingPrefixes] = {
    "query_prefix": "search_query: ",
    "passage_prefix": "search_document: ",
}

Prefixes of nomic-embed-text (Ollama tag and the nomic-ai weights).

Strings published on the model card for the retrieval task.

OPENAI_FINISH_REASONS module-attribute

OPENAI_FINISH_REASONS: dict[str, StopReason] = {
    "stop": "end",
    "length": "max_tokens",
    "content_filter": "refusal",
    "tool_calls": "tool_use",
}

choices[].finish_reason values to the normalized :data:StopReason.

The values documented for finish_reason in the official OpenAPI document (https://github.com/openai/openai-openapi, openapi.yaml): stop for a natural stop or a stop sequence, length for the token budget, content_filter for content omitted by a filter, tool_calls for a tool call. Anything else (the deprecated function_call, a provider's own value) maps to other.

OPENAI_MAX_TOKENS_FIELD module-attribute

OPENAI_MAX_TOKENS_FIELD: Final[str] = 'max_completion_tokens'

Where the output budget goes on OpenAI.

The official OpenAPI document (https://github.com/openai/openai-openapi, branch main) marks max_tokens deprecated in favor of max_completion_tokens. The same value HostedGenAISettings.openai_kwargs() selects.

PDF_MEDIA_TYPE module-attribute

PDF_MEDIA_TYPE: Final[str] = 'application/pdf'

The media type of a PDF, the default of :func:document_part.

SPEECH_RESPONSE_FORMAT module-attribute

SPEECH_RESPONSE_FORMAT: str = 'wav'

The response_format a synthesis asks for when the caller names none.

STREAM_FORMAT module-attribute

STREAM_FORMAT: str = 'audio'

stream_format asking the server to stream the audio bytes as made.

STREAM_RESPONSE_FORMAT module-attribute

STREAM_RESPONSE_FORMAT: str = 'pcm'

response_format of a streamed synthesis: raw 24 kHz 16-bit mono PCM.

StopReason module-attribute

StopReason = Literal['end', 'max_tokens', 'refusal', 'tool_use', 'other']

Why a call stopped, normalized across providers.

end is a natural stop (Anthropic end_turn / stop_sequence, OpenAI stop); max_tokens is a reply cut at the budget (max_tokens / length); refusal is a declined request (Anthropic refusal, OpenAI content_filter or a non-null message.refusal); tool_use is a tool call; other is anything the mapping does not name — the raw value is kept in :attr:StructuredCompletion.provider_stop_reason.

StreamModeration module-attribute

StreamModeration = Literal['incremental', 'buffered']

How :meth:AIChatPipeline.stream screens the reply when a moderator is set.

  • "incremental" — every piece is checked (together with everything generated before it) before it is sent; the first flagged check stops the stream and sends blocked_message. Pieces already sent stay sent.
  • "buffered" — the whole reply is generated and checked first, then sent as a single piece; nothing reaches the client before the verdict.

StructuredOutputMode module-attribute

StructuredOutputMode = Literal['json_schema', 'json_object']

How :meth:OpenAICompatGenerator.chat_structured asks for JSON.

"json_schema" sends the schema as response_format (the ResponseFormatJsonSchema of the OpenAI spec). "json_object" asks only for some JSON object and states the schema in a system turn — for a provider whose response_format has no json_schema type, like DeepSeek (https://api-docs.deepseek.com/guides/json_mode).

TRANSCRIPTION_RESPONSE_FORMAT module-attribute

TRANSCRIPTION_RESPONSE_FORMAT: str = 'verbose_json'

The response_format every transcription asks for.

verbose_json is the one format of the OpenAI spec whose body carries duration, language and segments; json carries only text.

ThinkLevel module-attribute

ThinkLevel = bool | Literal['low', 'medium', 'high']

The Ollama think field: on/off, or a reasoning level.

Sent at the top level of /api/chat and /api/generate (inside options the daemon ignores it). True/False switch reasoning on or off on a model with the thinking capability; "low"/"medium"/ "high" pick a level on the models that support levels (gpt-oss).

ImageSource

ImageSource = str | Path | bytes | bytearray | Image | NDArray[Any]

Supported input image forms accepted by :meth:ImageGenerator.edit.

PrefixAllowedTokensFn

PrefixAllowedTokensFn = Callable[[int, TokenIdSequence], list[int]]

Callback shape transformers.GenerationMixin.generate expects.

AIChatPipeline

AIChatPipeline(
    generator: TextBackend,
    *,
    memory: ChatMemory | PgChatMemory | None = None,
    web_search: WebSearch | None = None,
    tts: TextToSpeech | None = None,
    tools: list[Tool] | None = None,
    base_system_prompt: str = "",
    max_tool_iterations: int = 5,
    tokenizer: Any = None,
    max_context_tokens: int | None = None,
    moderator: ModerationBackend | None = None,
    blocked_message: str = "Sorry, I can't help with that request.",
    stream_moderation: StreamModeration = "incremental",
    parse_text_tool_calls: bool = True,
)

Compose a text backend with memory, web search, TTS and tools.

The pipeline owns no persistence and no model lifecycle — you inject ready objects and it orchestrates them per turn. Only the pieces you provide are wired: pass just a generator and you get plain chat; add a memory and every turn recalls + indexes; add tools and (when the backend supports chat_with_tools) a bounded tool loop runs.

Example:

>>> pipeline = AIChatPipeline(
...     OllamaGenerator("llama3.2"),
...     memory=chat_memory,
...     web_search=web_search,
... )
>>> result = await pipeline.respond(
...     user_id="u1", chat_id="c1", content="What is PIX?",
... )
>>> result.reply

Attributes:

Name Type Description
generator TextBackend

The LLM backend.

memory ChatMemory | PgChatMemory | None

Optional long-term chat memory (ChromaDB or pgvector).

web_search WebSearch | None

Optional web-search augmenter.

tts TextToSpeech | None

Optional text-to-speech backend.

tools list[Tool]

Tools available to the model (may be empty).

base_system_prompt str

System prompt prepended to every turn.

max_tool_iterations int

Upper bound on tool-loop rounds.

parse_text_tool_calls bool

Whether a tool call written as JSON in the reply text is run like a native one.

Configure the pipeline.

Parameters:

Name Type Description Default
generator TextBackend

The text-generation backend (required).

required
memory ChatMemory | PgChatMemory | None

Long-term memory for recall + indexing, or None to disable.

None
web_search WebSearch | None

Web-search augmenter, or None.

None
tts TextToSpeech | None

Text-to-speech backend, or None.

None
tools list[Tool] | None

Tools the model may call, or None.

None
base_system_prompt str

System prompt prepended every turn.

''
max_tool_iterations int

Max tool-loop rounds before giving up.

5
tokenizer Any

Tokenizer (encode) used with max_context_tokens to trim old turns before generating; None disables truncation.

None
max_context_tokens int | None

Token budget for the built message list; oldest turns are dropped to fit (needs tokenizer).

None
moderator ModerationBackend | None

Screens the user input and every history turn before generating, and the reply after — in :meth:respond and in :meth:stream (see stream_moderation). A flagged turn is answered with blocked_message instead. None disables.

None
blocked_message str

The reply returned when moderation flags the input or the generated output.

"Sorry, I can't help with that request."
stream_moderation StreamModeration

How :meth:stream screens the reply — "incremental" (default) checks the accumulated text before sending each piece, so pieces keep flowing but a flagged reply is cut where it tripped; "buffered" checks the whole reply before sending anything, trading streaming for zero leakage. Ignored without a moderator.

'incremental'
parse_text_tool_calls bool

When a tool-loop reply has no native tool_calls, read its text as a call: one JSON object {"name", "arguments"} (or a list of them), optionally in a single markdown fence, whose name is a registered tool. Some models choose the right tool and arguments but write the call in content; without this the JSON becomes the reply. Turn it off when a legitimate reply can be a JSON object whose name matches a tool name.

True

Raises:

Type Description
ValueError

When stream_moderation is not one of the :data:StreamModeration values.

respond async

respond(
    *,
    user_id: str | UUID | None,
    chat_id: str | UUID,
    content: str,
    history: list[dict[str, Any]] | None = None,
    images: list[str] | None = None,
    use_web_search: bool = False,
    speak: bool = False,
) -> AIChatResult

Produce a grounded reply for a single chat turn.

Recalls relevant memory, optionally augments with web context, builds the message list, generates a reply (running the tool loop when tools + a tool-capable backend are present), optionally synthesizes audio, and indexes both sides of the turn into memory (best-effort — indexing failures are logged, never raised).

Parameters:

Name Type Description Default
user_id str | UUID | None

Owner of the conversation — the key memory is recalled and indexed under. None skips memory for this turn (no recall, no indexing), which is what an unauthenticated caller gets: never recall under an id the caller merely claimed.

required
chat_id str | UUID

The active chat.

required
content str

The user's message.

required
history list[dict[str, Any]] | None

Prior turns, each {"role": ..., "content": ...}. Defaults to empty. Passed to the backend as-is (any role), so only hand it roles you trust; the router restricts them to user/assistant. Screened by the moderator like content.

None
images list[str] | None

Base64 images for a multimodal model; placed on the user message when truthy.

None
use_web_search bool

Augment the prompt with web context.

False
speak bool

Synthesize the reply to audio when a TTS backend is configured.

False

Returns:

Name Type Description
AIChatResult AIChatResult

The reply plus any sources, memory hits, tool

AIChatResult

names and audio produced.

stream async

stream(
    *,
    user_id: str | UUID | None,
    chat_id: str | UUID,
    content: str,
    history: list[dict[str, Any]] | None = None,
    images: list[str] | None = None,
    use_web_search: bool = False,
) -> AsyncIterator[str]

Stream a reply piece by piece for a single chat turn.

With tools and a generator implementing :class:~tempest_fastapi_sdk.genai.ToolStreamingBackend, the turn is one streamed generation per step: the tool specs go out with it, text is passed on as it arrives, and when the model asks for tools they run (same dispatch as :meth:respond's loop) and the next step streams on, up to max_tool_iterations. Text the model writes before asking for a tool ("let me look that up…") reaches the client and is part of the reply. A reply that opens with { or a code fence is held back until its step ends, so that a tool call written as JSON text (parse_text_tool_calls) is run instead of being shown. Otherwise the same recall + augment + (non-streamed) tool loop as :meth:respond resolves any tool calls, then the final answer is streamed — a second generation. When the generator implements :class:~tempest_fastapi_sdk.genai.text.ChatStreamingBackend, the built message list is streamed as it is (stream_chat), so the system turn, the history, the tool results and the user's images keep their roles exactly as in :meth:respond. A generator with only :meth:TextBackend.stream gets the list flattened into one prompt string (system + turns), which loses the roles — the fallback for engines that cannot stream a conversation. The intermediate tool-call steps are not streamed either way. The final answer is indexed into memory after the stream completes (best-effort).

With a moderator, the input and history are screened first (a flagged input yields only blocked_message), and the reply is screened per stream_moderation:

  • "incremental" — before each piece is yielded, the text generated so far, including that piece, is checked. The first flagged check stops generation and yields blocked_message as the last piece. Pieces yielded before it cannot be recalled: the client keeps them. What the check guarantees is that the piece which makes the text flaggable is never sent — with :class:~tempest_fastapi_sdk.genai.RuleModerator, a block-listed term is never emitted whole, though a prefix of it may be.
  • "buffered" — the reply is generated in full and checked once; the client receives either the whole reply as one piece or blocked_message, and nothing before the verdict.

A blocked reply is not indexed into memory, matching :meth:respond.

Parameters:

Name Type Description Default
user_id str | UUID | None

Owner of the conversation; None skips memory recall and indexing.

required
chat_id str | UUID

The active chat.

required
content str

The user's message.

required
history list[dict[str, Any]] | None

Prior turns.

None
images list[str] | None

Base64 images (placed on the user message; only a ChatStreamingBackend receives them — the flattened fallback carries text only).

None
use_web_search bool

Augment the prompt with web context.

False

Yields:

Name Type Description
str AsyncIterator[str]

Text pieces of the reply as the backend produces them, or

AsyncIterator[str]

blocked_message when moderation flags the turn.

AIChatResult

Bases: BaseSchema

The outcome of one :meth:AIChatPipeline.respond turn.

Attributes:

Name Type Description
reply str

The assistant's final text reply.

sources list[SearchResult]

Web sources used to augment the prompt (empty unless web search ran).

memory_hits list[MemoryHit]

Past messages recalled from memory and injected into the system prompt (empty when no memory).

tool_calls_made list[str]

Names of the tools invoked, in order (empty when no tool loop ran).

audio_base64 str | None

Base64-encoded WAV of the reply when speak=True and a TTS backend is configured, else None.

AIUsageStore

AIUsageStore(
    db: AsyncDatabaseManager,
    *,
    model: type[UsageT],
    price_input_per_1k: float = 0.0,
    price_output_per_1k: float = 0.0,
    price_cache_hit_per_1k: float | None = None,
)

Bases: Generic[UsageT]

Record and aggregate AI consumption.

Every method opens its own short session, like :class:~tempest_fastapi_sdk.tasks.JobStore — the recording call runs inside a worker as often as inside a request.

Example:

>>> store = AIUsageStore(db, model=UsageModel, price_input_per_1k=0.00014)
>>> text, usage = await gen.generate_with_usage(prompt)
>>> await store.record(subject_id=user.id, service="summary", usage=usage)

Initialize the store.

Parameters:

Name Type Description Default
db AsyncDatabaseManager

The database manager.

required
model type[UsageT]

The concrete usage model.

required
price_input_per_1k float

Cost of 1000 prompt tokens, in whatever currency you report. Left at 0.0, cost comes back as None.

0.0
price_output_per_1k float

Cost of 1000 generated tokens.

0.0
price_cache_hit_per_1k float | None

Cost of 1000 prompt tokens served from a cached prefix, when the provider bills those cheaper. None — the default — means "no separate cached rate", and prices the cached slice at price_input_per_1k like every other prompt token.

None rather than 0.0 on purpose: 0.0 is a price, and defaulting to it would make an unconfigured store report cached tokens as free, understating every discounted call. An unconfigured price should never move a number.

None

Raises:

Type Description
ValueError

When a price is negative.

by_service async

by_service(
    since: datetime | timedelta | None = None, *, subject_id: UUID | None = None
) -> list[ServiceUsage]

Split a window by capability, heaviest first.

Duration-only rows are excluded: they carry no tokens, so including them would add a slice worth 0% to every chart.

Parameters:

Name Type Description Default
since datetime | timedelta | None

Lower bound.

None
subject_id UUID | None

Restrict to one subject.

None

Returns:

Type Description
list[ServiceUsage]

list[ServiceUsage]: One entry per service, with its share of

list[ServiceUsage]

the window's tokens. Empty when nothing matched.

estimate_cost

estimate_cost(
    input_tokens: int, output_tokens: int, *, cache_hit_tokens: int = 0
) -> float | None

Price a set of token counts.

Deliberately not stored on the row: a price correction then applies to the whole history at once, instead of leaving old rows priced with a number nobody remembers setting.

Not rounded. Any fixed precision is wrong at some scale here: token prices live around 0.0001 per 1000, so rounding to cents reports zero for almost every single call, and even six decimals zeroes a one-token call — while a monthly total wants cents. The library therefore returns the number and leaves formatting to the boundary, which knows whether it is showing one call or a month.

Parameters:

Name Type Description Default
input_tokens int

Prompt tokens, cached ones included — that is how providers report the field, so subtracting them here would double-discount.

required
output_tokens int

Generated tokens.

required
cache_hit_tokens int

How many of input_tokens came from a cached prefix. Priced at price_cache_hit_per_1k when one is configured; otherwise it changes nothing. Clamped to input_tokens: a provider reporting more cached tokens than prompt tokens is nonsense, and letting it through would produce a negative full-rate term.

0

Returns:

Type Description
float | None

float | None: The estimate, or None when neither price is

float | None

configured — which the interface should read as "do not show a

float | None

cost", never as zero.

per_day async

per_day(
    since: datetime | timedelta | None = None,
    *,
    subject_id: UUID | None = None,
    by_service: bool = True,
) -> list[DailyUsage]

Bucket a window by UTC day, oldest first.

Parameters:

Name Type Description Default
since datetime | timedelta | None

Lower bound.

None
subject_id UUID | None

Restrict to one subject.

None
by_service bool

Split each day by capability — what a stacked bar chart wants. False gives one row per day with service=None.

True

Returns:

Type Description
list[DailyUsage]

list[DailyUsage]: The buckets, oldest first.

record async

record(
    *,
    subject_id: UUID | None,
    service: str,
    usage: TokenUsage | None,
    model: str | None = None,
) -> UsageT | None

Record one paid call.

Parameters:

Name Type Description Default
subject_id UUID | None

Who to bill.

required
service str

Which capability spent it.

required
usage TokenUsage | None

What the provider reported.

required
model str | None

Which model answered.

None

Returns:

Type Description
UsageT | None

UsageT | None: The stored row, or None when nothing was

UsageT | None

recorded — either the provider reported no usage, or it

UsageT | None

reported zero tokens, which is what a short-circuit that never

UsageT | None

called the model looks like. Writing either would inflate the

UsageT | None

call count with calls that did not happen.

record_duration async

record_duration(
    *, subject_id: UUID | None, seconds: float, model: str | None = None
) -> UsageT

Record local inference, which costs time rather than tokens.

service stays NULL so these rows never land in a token sum or a per-service share: they belong to a different unit.

Parameters:

Name Type Description Default
subject_id UUID | None

Who to attribute it to.

required
seconds float

Wall-clock the work took, or the media duration processed — pick one and stay consistent.

required
model str | None

Which local model ran.

None

Returns:

Name Type Description
UsageT UsageT

The stored row.

top_subjects async

top_subjects(
    since: datetime | timedelta | None = None, *, limit: int = 20
) -> list[SubjectUsage]

Who spent the most in a window.

Parameters:

Name Type Description Default
since datetime | timedelta | None

Lower bound.

None
limit int

How many to return.

20

Returns:

Type Description
list[SubjectUsage]

list[SubjectUsage]: Subjects ordered by tokens, heaviest first.

Raises:

Type Description
ValueError

When limit is below 1.

totals async

totals(
    since: datetime | timedelta | None = None, *, subject_id: UUID | None = None
) -> UsageTotals

Sum a window.

Parameters:

Name Type Description Default
since datetime | timedelta | None

Lower bound.

None
subject_id UUID | None

Restrict to one subject.

None

Returns:

Name Type Description
UsageTotals UsageTotals

The sums, with cost priced on the fly. An

UsageTotals

empty window returns zeros, not None — "nobody used it" is

UsageTotals

an answer.

AnthropicGenerator

AnthropicGenerator(
    model: str = DEFAULT_ANTHROPIC_MODEL,
    *,
    api_key: str,
    base_url: str = DEFAULT_ANTHROPIC_URL,
    timeout: float = 120.0,
    max_tokens: int = DEFAULT_ANTHROPIC_MAX_TOKENS,
    config: GenerationConfig | None = None,
    extra_body: dict[str, Any] | None = None,
    extra_headers: dict[str, str] | None = None,
    anthropic_version: str = ANTHROPIC_VERSION,
    http_client: HTTPClient | None = None,
    transport: AsyncBaseTransport | None = None,
    retry_policy: RetryPolicy | None = None,
)

Text generation, tool calling and structured output on Claude.

Attributes:

Name Type Description
model str

The model id.

base_url str

API root, without a trailing slash.

max_tokens int

max_tokens used when a call sets no max_new_tokens.

config GenerationConfig | None

Default generation parameters, layered under every call's own.

Configure the client. No network call happens here.

Parameters:

Name Type Description Default
model str

Model id ("claude-opus-5-5", "claude-sonnet-5-5", ...).

DEFAULT_ANTHROPIC_MODEL
api_key str

The API key, sent as x-api-key. Empty raises here, where the configuration is read, instead of as a 401 from inside the first background job.

required
base_url str

API root; /v1/messages is appended.

DEFAULT_ANTHROPIC_URL
timeout float

Per-request HTTP timeout in seconds. A long non-streaming generation can outlive it; prefer :meth:stream for long outputs, as the streaming guide recommends.

120.0
max_tokens int

Default max_tokens, required by the API on every call. max_new_tokens in a config or keyword wins.

DEFAULT_ANTHROPIC_MAX_TOKENS
config GenerationConfig | None

Default generation parameters for every call. A call's own config is layered over it field by field, and keyword overrides win over both.

None
extra_body dict[str, Any] | None

Fields merged into every request body, under the computed ones — the place for thinking, output_config.effort or metadata.

None
extra_headers dict[str, str] | None

Headers added to every request (anthropic-beta, anthropic-workspace-id). x-api-key and anthropic-version always come from the arguments above.

None
anthropic_version str

The anthropic-version header.

ANTHROPIC_VERSION
http_client HTTPClient | None

An injected client for connection reuse. When None one is created lazily and owned by this instance, with retry, backoff, a per-host circuit-breaker and X-Request-ID propagation.

None
transport AsyncBaseTransport | None

Transport for the lazily-created client — an httpx.MockTransport in tests. Ignored with http_client.

None
retry_policy RetryPolicy | None

Retry configuration for the lazily-created client. None retries 429, the common 5xx and 529 (Anthropic's overloaded_error), but not a read timeout: the provider stops the generation when the client gives up, so a retry starts it again from zero. Ignored with http_client.

None

Raises:

Type Description
ValueError

When api_key is empty or max_tokens is not positive.

is_loaded property

is_loaded: bool

Return True — the provider owns model residency.

Returns:

Name Type Description
bool bool

Always True.

url property

url: str

Return the Messages endpoint.

Returns:

Name Type Description
str str

{base_url}/v1/messages.

aclose async

aclose() -> None

Close the HTTP client when this instance owns it.

chat async

chat(
    messages: list[dict[str, Any]],
    *,
    config: GenerationConfig | None = None,
    **kwargs: Any,
) -> str

Continue a chat and return the reply (the TextBackend method).

Parameters:

Name Type Description Default
messages list[dict[str, Any]]

The chat turns, oldest first.

required
config GenerationConfig | None

Typed generation parameters.

None
**kwargs Any

Per-call parameters, winning over config.

{}

Returns:

Name Type Description
str str

The reply.

chat_structured async

chat_structured(
    messages: list[dict[str, Any]],
    schema: type[StructuredT],
    *,
    config: GenerationConfig | None = None,
    **kwargs: Any,
) -> StructuredT

Generate a reply constrained to a Pydantic schema.

The schema goes out as output_config.format (json_schema), adapted by :func:~tempest_fastapi_sdk.genai.hosted.strict_json_schema to what the API accepts; the reply is validated against the original model, constraints the adaptation removed included. An output_config in extra_body (an effort, say) is kept and only its format is set.

Parameters:

Name Type Description Default
messages list[dict[str, Any]]

Chat turns; put the instruction in a system turn and the content in user.

required
schema type[StructuredT]

The Pydantic model to produce.

required
config GenerationConfig | None

Typed generation parameters.

None
**kwargs Any

Per-call parameters, winning over config.

{}

Returns:

Name Type Description
StructuredT StructuredT

The validated instance.

Raises:

Type Description
TypeError

When output_config is passed as a keyword — the schema argument is what sets its format.

ValueError

When the reply carries no JSON object (a refusal, or a reply cut at max_tokens).

ValidationError

When the JSON fails schema.

chat_with_tools async

chat_with_tools(
    messages: list[dict[str, Any]],
    tools: list[dict[str, Any]],
    *,
    config: GenerationConfig | None = None,
    **kwargs: Any,
) -> dict[str, Any]

Generate a reply that may call tools (the ToolCallingBackend method).

Tools go out in the Messages API shape and tool_use blocks come back as OpenAI-style tool_calls — the shape the :class:~tempest_fastapi_sdk.agents.Agent loop reads and appends back to the conversation, which :func:to_anthropic_messages translates again on the next call. Each call keeps the tool_use id, so its result is matched by id.

Parameters:

Name Type Description Default
messages list[dict[str, Any]]

The conversation so far, including assistant turns with tool_calls and role: tool results.

required
tools list[dict[str, Any]]

{"type": "function", ...} specs (or Messages API tools, passed through).

required
config GenerationConfig | None

Typed generation parameters.

None
**kwargs Any

Per-call parameters, winning over config (tool_choice, for one).

{}

Returns:

Type Description
dict[str, Any]

dict[str, Any]: ``{"role": "assistant", "content": ,

dict[str, Any]

"tool_calls": [...]}``, each call being

dict[str, Any]

{"id", "type": "function", "function": {"name", "arguments"}}

dict[str, Any]

with arguments as a dict.

chat_with_usage async

chat_with_usage(
    messages: list[dict[str, Any]],
    *,
    config: GenerationConfig | None = None,
    **kwargs: Any,
) -> tuple[str, TokenUsage | None]

Continue a chat and report what it cost.

Parameters:

Name Type Description Default
messages list[dict[str, Any]]

The chat turns, oldest first. system turns become the top-level system field.

required
config GenerationConfig | None

Typed generation parameters.

None
**kwargs Any

Per-call parameters, winning over config.

{}

Returns:

Type Description
str

tuple[str, TokenUsage | None]: The reply, and the usage the API

TokenUsage | None

reported (cache reads and writes included in input_tokens).

complete_structured async

complete_structured(
    messages: list[dict[str, Any]],
    schema: type[StructuredT],
    *,
    effort: Effort | None = None,
    cache_system: bool = False,
    max_tokens: int | None = None,
    config: GenerationConfig | None = None,
    **kwargs: Any,
) -> StructuredCompletion[StructuredT]

Generate a reply constrained to schema and report the outcome.

Builds the request as :meth:chat_structured does (output_config.format), and returns a :class:~tempest_fastapi_sdk.genai.StructuredCompletion instead of raising for an outcome the model produced: a refusal, a reply cut at max_tokens or a reply that fails schema come back with the usage the call was billed for. stop_reason is normalized through :data:ANTHROPIC_STOP_REASONS, and the reply is parsed only after a natural stop.

Parameters:

Name Type Description Default
messages list[dict[str, Any]]

Chat turns; images as :func:~tempest_fastapi_sdk.genai.image_part parts.

required
schema type[StructuredT]

The Pydantic model to produce.

required
effort Effort | None

Sent as output_config.effort. None keeps whatever extra_body sets, or nothing.

None
cache_system bool

Send the system prompt as one text block marked cache_control: {"type": "ephemeral"} (https://platform.claude.com/docs/en/build-with-claude/prompt-caching). Ignored when the conversation has no system turn.

False
max_tokens int | None

max_tokens of this call, replacing the instance default.

None
config GenerationConfig | None

Typed generation parameters.

None
**kwargs Any

Per-call body fields, winning over config.

{}

Returns:

Type Description
StructuredCompletion[StructuredT]

StructuredCompletion[StructuredT]: The outcome.

Raises:

Type Description
TypeError

When output_config is passed as a keyword.

HostedAPIError

A typed subclass for an error status.

generate async

generate(prompt: str, *, config: GenerationConfig | None = None, **kwargs: Any) -> str

Generate a completion for prompt (the TextBackend method).

Parameters:

Name Type Description Default
prompt str

The input text.

required
config GenerationConfig | None

Typed generation parameters.

None
**kwargs Any

Per-call parameters, winning over config.

{}

Returns:

Name Type Description
str str

The generated text.

generate_with_usage async

generate_with_usage(
    prompt: str,
    *,
    config: GenerationConfig | None = None,
    system: str | None = None,
    **kwargs: Any,
) -> tuple[str, TokenUsage | None]

Generate a completion and report what it cost.

Parameters:

Name Type Description Default
prompt str

The input text.

required
config GenerationConfig | None

Typed generation parameters.

None
system str | None

System prompt, sent as the top-level system field.

None
**kwargs Any

Per-call parameters, winning over config.

{}

Returns:

Type Description
tuple[str, TokenUsage | None]

tuple[str, TokenUsage | None]: The text and its usage.

load

load() -> None

No-op load hook, for surface-compatibility with TextGenerator.

stream async

stream(
    prompt: str, *, config: GenerationConfig | None = None, **kwargs: Any
) -> AsyncIterator[str]

Stream a completion (the TextBackend method).

Reads the server-sent events of the streaming guide: text arrives as content_block_delta events with a text_delta; ping and the other event types carry no text and are skipped.

Parameters:

Name Type Description Default
prompt str

The input text.

required
config GenerationConfig | None

Typed generation parameters.

None
**kwargs Any

Per-call parameters, winning over config.

{}

Yields:

Name Type Description
str AsyncIterator[str]

Text deltas, in order.

Raises:

Type Description
HostedAPIError

A typed subclass when the stream cannot be opened, or when an error event arrives mid-stream (overloaded_error raises :class:HostedServerError with status_code 529). Text already yielded stays yielded.

stream_chat async

stream_chat(
    messages: list[dict[str, Any]],
    *,
    config: GenerationConfig | None = None,
    **kwargs: Any,
) -> AsyncIterator[str]

Stream the reply to a chat messages list piece by piece.

The streaming counterpart of :meth:chat: the conversation goes out as the Messages API body :meth:chat builds (system lifted to the top-level field), so the system prompt keeps its role.

Parameters:

Name Type Description Default
messages list[dict[str, Any]]

The chat turns, oldest first.

required
config GenerationConfig | None

Typed generation parameters.

None
**kwargs Any

Per-call parameters, winning over config.

{}

Yields:

Name Type Description
str AsyncIterator[str]

Text deltas, in order.

Raises:

Type Description
HostedAPIError

A typed subclass when the stream cannot be opened, or when an error event arrives mid-stream. Text already yielded stays yielded.

unload

unload() -> None

No-op unload hook, for the registry's Unloadable protocol.

AsyncEmbeddingCache

Bases: Protocol

An asynchronous per-text vector cache (e.g. a Redis wrapper).

:class:Embedder accepts either cache flavor — it awaits get / set when they return an awaitable and calls them plainly otherwise — so a single-process app can start with :class:InMemoryEmbeddingCache and switch to :class:RedisEmbeddingCache for multi-worker reuse with no call-site change.

get async

get(key: str) -> list[float] | None

Return the cached vector for key, or None on a miss.

Parameters:

Name Type Description Default
key str

Cache key for the embedded text.

required

Returns:

Type Description
list[float] | None

list[float] | None: The cached vector, or None on a miss.

set async

set(key: str, value: list[float]) -> None

Store value under key.

Parameters:

Name Type Description Default
key str

Cache key for the embedded text.

required
value list[float]

The vector to store.

required

AsyncGenerationCache

Bases: Protocol

An asynchronous prompt→completion cache (e.g. Redis-backed).

get async

get(key: str) -> str | None

Return the cached completion for key or None.

Parameters:

Name Type Description Default
key str

Cache key derived from the prompt and generation settings.

required

Returns:

Type Description
str | None

str | None: The cached completion, or None on a miss.

set async

set(key: str, value: str) -> None

Store value under key.

Parameters:

Name Type Description Default
key str

Cache key derived from the prompt and generation settings.

required
value str

The completion to store.

required

AudioDiffusionPipeline

Bases: Protocol

Minimal surface of a loaded diffusers audio pipeline.

AudioGenerationConfig

Bases: BaseSchema

Typed parameters for local text-to-audio generation.

Passed to :class:~tempest_fastapi_sdk.genai.AudioGenerator. Only the fields you set reach the pipeline, so a partial config layers on top of the model's own defaults. Those differ a lot: read from diffusers 0.39, AudioLDMPipeline defaults to 10 steps and guidance 2.5, MusicLDMPipeline to 200 steps and guidance 2.0.

Example:

>>> cfg = AudioGenerationConfig(seconds=10.0, steps=50, seed=0)
>>> clips = await generator.generate("rain on a tin roof", config=cfg)

Attributes:

Name Type Description
negative_prompt str | None

What to steer the sound away from.

seconds float | None

Length of each clip, at most 120.

steps int | None

Denoising steps, at most 1000.

guidance_scale float | None

How hard to follow the prompt.

seed int | None

RNG seed, 0 to 2**64 - 1 -- the range torch.manual_seed accepts (2**64 raised ValueError: Overflow when unpacking long long on torch 2.14). Set it and the same prompt gives the same waveform on the same hardware.

num_waveforms int

Clips per call, at most 8. These ceilings are the schema's absolute bounds; make_genai_router enforces tighter per-request limits from :class:GenAIRequestLimits on top.

to_pipeline_kwargs

to_pipeline_kwargs() -> dict[str, Any]

Return the explicitly-set pipeline keywords, in diffusers names.

seed is excluded (it binds a torch.Generator), and seconds / steps / num_waveforms become audio_length_in_s / num_inference_steps / num_waveforms_per_prompt.

Returns:

Type Description
dict[str, Any]

dict[str, Any]: Keywords to splat into the pipeline call.

AudioGenerator

AudioGenerator(
    model_id: str,
    *,
    device: str = "auto",
    dtype: str | ModelDtypeEnum = "auto",
    cache_dir: str | None = None,
    hf_token: str | None = None,
    revision: str | None = None,
    local_files_only: bool | None = None,
    trust_remote_code: bool = False,
    pipeline_kwargs: dict[str, Any] | None = None,
    max_concurrent: int = 1,
    idle_unload_seconds: float | None = None,
    hardware: HardwareInfo | None = None,
    metrics: GenAIMetrics | None = None,
)

A lazily-loaded local text-to-audio pipeline with idle unload.

Example:

>>> gen = AudioGenerator("cvssp/audioldm-s-full-v2")
>>> clips = await gen.generate(
...     "thunderstorm with heavy rain on a tin roof",
...     config=AudioGenerationConfig(seconds=10.0, steps=50),
... )
>>> Path("storm.wav").write_bytes(clips[0].data)

Attributes:

Name Type Description
model_id str

The HuggingFace model id.

device str

The resolved device (cuda / mps / cpu).

dtype ModelDtypeEnum

The resolved compute precision.

source ModelRef

The resolved weight identity forwarded to from_pretrained.

pipeline_kwargs dict[str, Any]

Extra from_pretrained keywords, applied last so they override what the SDK computes.

idle_unload_seconds float | None

Idle threshold used by :meth:unload_if_idle.

Configure the generator (does not load weights yet).

Parameters:

Name Type Description Default
model_id str

HuggingFace model id of an AudioLDM-family pipeline (cvssp/audioldm-s-full-v2, ucsd-reach/musicldm).

required
device str

"auto" / "cuda" / "mps" / "cpu".

'auto'
dtype str | ModelDtypeEnum

Compute precision, or "auto" (bf16 on GPU, fp32 on CPU).

'auto'
cache_dir str | None

Where weights are downloaded and read back; None uses the huggingface_hub default.

None
hf_token str | None

Hub token for gated or private repositories; None falls back to HF_TOKEN.

None
revision str | None

Branch, tag or commit sha to load.

None
local_files_only bool | None

Load from the cache without the network; None takes GENAI_OFFLINE from the environment.

None
trust_remote_code bool

Allow the repository's own Python to run at load time.

False
pipeline_kwargs dict[str, Any] | None

Extra keywords for from_pretrained; they win over what the SDK computes.

None
max_concurrent int

Simultaneous renders. Defaults to 1, since one diffusion call already saturates the GPU.

1
idle_unload_seconds float | None

When set, :meth:unload_if_idle frees the pipeline after this many idle seconds.

None
hardware HardwareInfo | None

Injected snapshot for device resolution (tests); probed when None.

None
metrics GenAIMetrics | None

Optional Prometheus metrics; :meth:generate records request count and latency under op "audio".

None

Raises:

Type Description
ValueError

When max_concurrent is not positive.

is_loaded property

is_loaded: bool

Return True once the pipeline is in memory.

Returns:

Name Type Description
bool bool

Whether :meth:load has run without a later

bool

meth:unload.

pipeline property

Return the underlying diffusers pipeline (escape hatch).

Loads on first access, which blocks for the download and build.

Returns:

Name Type Description
AudioDiffusionPipeline AudioDiffusionPipeline

The loaded pipeline.

seconds_idle property

seconds_idle: float

Return seconds since the pipeline was last in use.

Returns:

Name Type Description
float float

Idle time in seconds; 0.0 while a render runs.

generate async

generate(
    prompt: str, *, config: AudioGenerationConfig | None = None
) -> list[GeneratedAudio]

Generate one or more clips from a text prompt.

Parameters:

Name Type Description Default
prompt str

The sound or music to generate.

required
config AudioGenerationConfig | None

Length, steps, guidance, seed and count. Unset fields fall through to the model's defaults.

None

Returns:

Type Description
list[GeneratedAudio]

list[GeneratedAudio]: The clips. Every clip carries the call's

list[GeneratedAudio]

seed; with num_waveforms above 1 they differ from each other,

list[GeneratedAudio]

so reproducing clip i takes the same seed, the same

list[GeneratedAudio]

num_waveforms and index i. Without a seed in config

list[GeneratedAudio]

one is drawn.

Raises:

Type Description
ImportError

When the extras are missing.

ValueError

When the model is not supported.

load

load() -> None

Download (if needed) and load the pipeline.

Idempotent, and safe to call from several threads at once.

Raises:

Type Description
ImportError

When the extras are missing.

ValueError

When the model is not a supported AudioLDM-family pipeline (see :func:check_audio_pipeline).

unload

unload() -> None

Free the pipeline and its memory; waits for renders in flight.

unload_if_idle

unload_if_idle() -> bool

Free the pipeline when it has been idle past the threshold.

Returns:

Name Type Description
bool bool

True when this call unloaded the pipeline.

AudioPipelineOutput

Bases: Protocol

Output object returned by a diffusers audio pipeline.

audios property

audios: Sequence[Any]

Generated waveforms, one per requested clip.

BaseAIUsageModel

Bases: BaseModel

Abstract usage table — one row per recorded AI call.

Inherits id / is_active / created_at / updated_at from :class:~tempest_fastapi_sdk.db.model.BaseModel, so created_at is when the call happened and is what every aggregation buckets on.

Attributes:

Name Type Description
subject_id UUID | None

Who the call is billed to — a user, a tenant, whatever the application charges. None for calls with no owner (a scheduled sweep, a system prompt), which is why the aggregations treat it as a real bucket rather than dropping it.

service str | None

Which capability spent it ("summary", "suggest_tasks"). None marks a row that carries duration instead of tokens, so the two never contaminate each other's sums.

model str | None

Which model answered, so a price change or a model swap stays attributable afterwards.

input_tokens int

Prompt tokens, as the provider reported them.

output_tokens int

Generated tokens.

total_tokens int

What the provider counts for the call — carried rather than summed, because cached-prefix discounts make the two disagree.

duration_seconds float | None

Wall-clock, for local inference that has no token bill.

cache_hit_tokens int | None

The slice of input_tokens the provider served from a cached prefix and billed cheaper — a subset, not an addition. Nullable rather than defaulted to zero on the column, because rows written before this column existed genuinely do not know their split, and claiming zero for them would price a discounted call at full rate.

BatchScheduler

BatchScheduler(
    handler: Callable[[list[ItemT]], Awaitable[list[ResultT]]],
    *,
    max_batch: int = 32,
    max_wait_ms: float = 10.0,
)

Bases: Generic[ItemT, ResultT]

Merge concurrent :meth:submit calls into batched handler calls.

A background loop drains a queue, forming a batch once either max_batch items are waiting or max_wait seconds have elapsed since the first queued item, then calls handler(batch) once and hands each caller its matching result by position.

The handler is awaited, so it must be a coroutine function taking the whole batch. :meth:Embedder.embed is that shape already; its private _embed_many is not — it is synchronous, and awaiting it raises TypeError: object list can't be used in 'await' expression.

Example:

>>> async def embed_batch(texts: list[str]) -> list[list[float]]:
...     return await embedder.embed(texts)
>>> sched = BatchScheduler(embed_batch, max_batch=32, max_wait_ms=10)
>>> vec = await sched.submit("hello")   # coalesced with concurrent calls
>>> await sched.aclose()

Attributes:

Name Type Description
max_batch int

Max items per handler call.

max_wait float

Max seconds to wait forming a batch.

Initialize the scheduler.

Parameters:

Name Type Description Default
handler Callable[[list[ItemT]], Awaitable[list[ResultT]]]

Async batch function. Must return one output per input, in order.

required
max_batch int

Max items per batch.

32
max_wait_ms float

Max milliseconds to wait for a batch to fill before flushing what's queued.

10.0

Raises:

Type Description
ValueError

When max_batch is not positive.

aclose async

aclose() -> None

Stop the worker after the current batch; reject new submits.

submit async

submit(item: ItemT) -> ResultT

Submit one item and await its result.

The item is batched with others submitted around the same time.

Parameters:

Name Type Description Default
item I

The input to process.

required

Returns:

Name Type Description
O ResultT

The handler's output for item.

Raises:

Type Description
RuntimeError

When the scheduler has been closed.

CachedModel

Bases: BaseSchema

One model repository present in the local cache.

Attributes:

Name Type Description
model_id str

The Hub model id.

size_bytes int

Total bytes the repository occupies, counting every cached revision once (blobs shared between revisions are not double-counted).

path str

The repository directory inside the cache.

revisions list[CachedRevision]

The cached revisions, largest first.

CachedRevision

Bases: BaseSchema

One revision of a model present in the local cache.

Attributes:

Name Type Description
revision str

The commit sha the snapshot belongs to.

refs list[str]

Branch/tag names pointing at this commit.

size_bytes int

Bytes this revision occupies on disk.

path str

The snapshot directory.

last_modified float | None

Unix timestamp of the last change, or None when the cache does not report one.

CapacityReport

Bases: BaseSchema

The verdict of whether the host can run a given model.

When the memory of device could not be measured (memory_measured=False, e.g. CPU on macOS without psutil), the verdict is unknown rather than negative: fits is False because nothing was verified, available_bytes and headroom_pct are 0 and carry no information, and reason/suggestion say what to install to measure it.

Attributes:

Name Type Description
fits bool

Whether the model is expected to fit on device. Only True when the free memory was measured and covers the estimate.

device str

The chosen device — "cuda", "mps" or "cpu".

dtype ModelDtypeEnum

The precision the estimate assumes.

estimated_bytes int

Estimated memory the model needs (weights + inference overhead).

available_bytes int

Memory available on device; 0 when memory_measured is False.

headroom_pct float

(available - estimated) / available * 100; negative when it doesn't fit, 0.0 when memory_measured is False.

reason str

Human-readable explanation of the verdict.

suggestion str | None

A concrete next step when it doesn't fit (e.g. quantize, offload to CPU) or when the memory could not be measured, or None when it fits.

memory_measured bool

Whether the free memory of device was read. False means the report is a "could not check", not a "does not fit".

ChatStreamingBackend

Bases: Protocol

A backend that streams the reply to a whole conversation.

:meth:TextBackend.stream takes a single prompt, so a caller holding a message list had to flatten it, and the model lost the system role and the turn structure. A backend implementing stream_chat streams the conversation as it is; :class:~tempest_fastapi_sdk.genai.AIChatPipeline uses it when the generator has it and falls back to the flattened prompt otherwise. Implemented by :class:~tempest_fastapi_sdk.genai.ollama.OllamaGenerator (/api/chat), :class:~tempest_fastapi_sdk.genai.OpenAICompatGenerator, :class:~tempest_fastapi_sdk.genai.AnthropicGenerator, :class:TextGenerator and the testing FakeTextBackend.

stream_chat

stream_chat(
    messages: list[dict[str, Any]],
    *,
    config: GenerationConfig | None = ...,
    **kwargs: Any,
) -> AsyncIterator[str]

Stream the reply to messages piece by piece.

Parameters:

Name Type Description Default
messages list[dict[str, Any]]

The chat turns, oldest first, in the shape the backend's chat accepts (images included).

required
config GenerationConfig | None

Generation parameters; None uses the defaults.

...
**kwargs Any

Extra generation parameters, overriding config.

{}

Returns:

Type Description
AsyncIterator[str]

AsyncIterator[str]: The reply, in pieces.

ClassifierModerator

ClassifierModerator(
    model_id: str,
    *,
    flagged_labels: list[str] | None = None,
    threshold: float = 0.5,
    device: str = "auto",
    cache_dir: str | None = None,
    hf_token: str | None = None,
    revision: str | None = None,
    local_files_only: bool | None = None,
    trust_remote_code: bool = False,
    idle_unload_seconds: float | None = None,
    hardware: HardwareInfo | None = None,
    activation: _Activation = "auto",
    window_tokens: int | None = 64,
    window_overlap: int = 16,
)

A local text-classification moderator over transformers.

Runs a sequence-classification model (e.g. a toxicity classifier), maps its labels via the model config, and flags the text when a configured label's score crosses threshold. Lazy-loaded; inference runs in a worker thread. Best-effort — validate the model on your language before relying on it. Needs the [genai] extra.

Scores come from a sigmoid per label when the model is multi-label (config.problem_type == "multi_label_classification", as in unitary/toxic-bert) or has a single output, and from a softmax otherwise; activation= forces either. A softmax over independent labels splits the mass between them, so a text that is both toxic and insulting can score under the threshold on both.

Text is never truncated: it is cut into short overlapping windows (64 tokens by default), every window is classified, and each label keeps its highest score across windows — so content placed after a long harmless prefix is still screened. The windows are short on purpose: a classifier such as unitary/toxic-bert dilutes one toxic sentence inside a few hundred benign tokens below the threshold, so a window as wide as the model's context (512) still lets that sentence through. Cost grows with the number of windows.

Attributes:

Name Type Description
model_id str

The HuggingFace classifier id.

threshold float

Score above which a label flags the text.

activation str

"auto", "sigmoid" or "softmax".

window_tokens int | None

Tokens per window, special tokens included; None uses the model's whole context.

window_overlap int

Tokens shared by consecutive windows.

Configure the moderator (does not load weights yet).

Parameters:

Name Type Description Default
model_id str

HuggingFace sequence-classification model id.

required
flagged_labels list[str] | None

Label names that flag the text (case-insensitive); None flags any non-"neutral"/"ok" label.

None
threshold float

Minimum probability for a label to flag.

0.5
device str

"auto" / "cuda" / "mps" / "cpu".

'auto'
cache_dir str | None

Where the downloaded weights are written and read back from. None uses the huggingface_hub default — $HF_HOME/hub, or ~/.cache/huggingface/hub when HF_HOME is unset — which is why the second run of a script starts instantly instead of downloading again. Point it at a mounted volume when the process is a container, so the layer does not re-download the model on every restart.

None
hf_token str | None

Hub token for gated or private repositories. None falls back to HF_TOKEN in the environment; without either, anonymous downloads work but are rate-limited (the Hub says so on stderr).

None
revision str | None

Branch, tag or commit sha to load; None follows the moving Hub default.

None
local_files_only bool | None

Load from the cache without touching the network — what an air-gapped or deploy-frozen host wants. None (the default) takes GENAI_OFFLINE from the environment; passing the argument overrides it.

None
trust_remote_code bool

Allow the repository's own Python to run at load time.

False
idle_unload_seconds float | None

When set, :meth:unload_if_idle frees the classifier after this many idle seconds.

None
hardware HardwareInfo | None

Injected snapshot (tests).

None
activation str

"auto" reads the model config — sigmoid for problem_type="multi_label_classification" or a single output, softmax otherwise. "sigmoid" / "softmax" force one, for a checkpoint whose config does not declare its problem type.

'auto'
window_tokens int | None

Tokens per classified window, special tokens included, capped at the model's context (the tokenizer's model_max_length and the config's max_position_embeddings, 512 for BERT). None uses that whole context — fewer forward passes, but a short violation diluted by the text around it scores lower.

64
window_overlap int

Tokens shared by consecutive windows, so a phrase of up to window_overlap + 1 tokens cut by one window boundary lands whole in the next.

16

Raises:

Type Description
ValueError

On an unknown activation, a negative window_overlap, or a window_tokens that leaves no room to advance past window_overlap.

is_loaded property

is_loaded: bool

Return True once the weights are in memory.

seconds_idle property

seconds_idle: float

Return seconds since the classifier was last in use.

Reads 0.0 while a check is in flight.

Returns:

Name Type Description
float float

Idle time in seconds.

check async

check(text: str) -> ModerationResult

Classify text and flag it per the label/threshold policy.

Parameters:

Name Type Description Default
text str

The text to screen.

required

Returns:

Name Type Description
ModerationResult ModerationResult

The verdict with the matched categories + score.

load

load() -> None

Load the classifier + tokenizer. Idempotent.

Safe to call from several threads at once: concurrent callers on a cold instance wait for one build.

Raises:

Type Description
ImportError

When the [genai] extra is missing.

unload

unload() -> None

Free the classifier and its memory. Safe when not loaded.

While a check is in flight the release waits for it: the last call to finish drops the weights.

unload_if_idle

unload_if_idle() -> bool

Free the classifier when idle past its configured threshold.

Returns:

Name Type Description
bool bool

True when this call unloaded the model, False

bool

when it was already free, still in use, or no

bool

idle_unload_seconds was configured.

DailyUsage dataclass

DailyUsage(day: date, service: str | None, total_tokens: int)

One day of one service.

Attributes:

Name Type Description
day date

The UTC day.

service str | None

The capability, or None when the query did not split by service.

total_tokens int

Tokens spent that day.

Embedder

Embedder(
    model_id: str,
    *,
    device: str = "auto",
    dtype: str | ModelDtypeEnum = "auto",
    cache: EmbeddingCache | AsyncEmbeddingCache | None = None,
    normalize: bool = False,
    cache_dir: str | None = None,
    hf_token: str | None = None,
    revision: str | None = None,
    local_files_only: bool | None = None,
    trust_remote_code: bool = False,
    idle_unload_seconds: float | None = None,
    hardware: HardwareInfo | None = None,
    metrics: GenAIMetrics | None = None,
    query_prefix: str = "",
    passage_prefix: str = "",
)

A lazily-loaded local text-embedding model with optional caching.

Example:

>>> emb = Embedder("sentence-transformers/all-MiniLM-L6-v2")
>>> vectors = await emb.embed(["hello", "world"])
>>> emb.unload()

Attributes:

Name Type Description
model_id str

The HuggingFace model id.

device str

Resolved device.

dtype ModelDtypeEnum

Resolved compute precision.

idle_unload_seconds float | None

Idle threshold for :meth:unload_if_idle.

query_prefix str

Prepended by :meth:embed_query.

passage_prefix str

Prepended by :meth:embed_passages.

Configure the embedder (does not load weights yet).

Parameters:

Name Type Description Default
model_id str

HuggingFace model id.

required
device str

"auto" / "cuda" / "mps" / "cpu".

'auto'
dtype str | ModelDtypeEnum

Compute precision or "auto".

'auto'
cache EmbeddingCache | AsyncEmbeddingCache | None

Optional per-text vector cache (sync like :class:InMemoryEmbeddingCache, or async like :class:RedisEmbeddingCache); a cache hit skips loading the model entirely.

None
normalize bool

When True, L2-normalize every returned vector so cosine similarity is a plain dot product.

False
cache_dir str | None

Where the downloaded weights are written and read back from. None uses the huggingface_hub default — $HF_HOME/hub, or ~/.cache/huggingface/hub when HF_HOME is unset — which is why the second run of a script starts instantly instead of downloading again. Point it at a mounted volume when the process is a container, so the layer does not re-download the model on every restart.

None
hf_token str | None

Hub token for gated or private repositories. None falls back to HF_TOKEN in the environment; without either, anonymous downloads work but are rate-limited (the Hub says so on stderr).

None
revision str | None

Branch, tag or commit sha to load; None follows the moving Hub default.

None
local_files_only bool | None

Load from the cache without touching the network — what an air-gapped or deploy-frozen host wants. None (the default) takes GENAI_OFFLINE from the environment; passing the argument overrides it.

None
trust_remote_code bool

Allow the repository's own Python to run at load time.

False
idle_unload_seconds float | None

Idle threshold for :meth:unload_if_idle.

None
hardware HardwareInfo | None

Injected snapshot for device resolution (tests); probed when None.

None
metrics GenAIMetrics | None

Optional Prometheus metrics; when set, :meth:embed records request count + latency (op "embed").

None
query_prefix str

Text prepended to every input of :meth:embed_query. Asymmetric models were trained with a role marker on each side — the multilingual-e5 family wants "query: " here and "passage: " in passage_prefix. :meth:embed never applies it.

''
passage_prefix str

Text prepended to every input of :meth:embed_passages (the corpus side).

''

is_loaded property

is_loaded: bool

Return True once the weights are in memory.

seconds_idle property

seconds_idle: float

Return seconds since the model was last in use.

Reads 0.0 while an embedding batch is in flight.

Returns:

Name Type Description
float float

Idle time in seconds.

embed async

embed(texts: str | list[str], *, batch_size: int = 32) -> list[list[float]]

Embed one or many texts, recording metrics when configured.

Parameters:

Name Type Description Default
texts str | list[str]

A single text or a list of texts.

required
batch_size int

Max texts per model forward pass.

32

Returns:

Type Description
list[list[float]]

list[list[float]]: One vector per input text, in input order.

embed_passages async

embed_passages(texts: str | list[str], *, batch_size: int = 32) -> list[list[float]]

Embed corpus passages, prepending passage_prefix to each one.

:class:~tempest_fastapi_sdk.genai.rag.Retriever calls this when it indexes chunks, so the stored vectors and the query vectors carry the role markers the model was trained with.

Parameters:

Name Type Description Default
texts str | list[str]

A single passage or a list of passages.

required
batch_size int

Max texts per model forward pass.

32

Returns:

Type Description
list[list[float]]

list[list[float]]: One vector per input passage, in input order.

embed_query async

embed_query(texts: str | list[str], *, batch_size: int = 32) -> list[list[float]]

Embed search queries, prepending query_prefix to each one.

:class:~tempest_fastapi_sdk.genai.rag.Retriever calls this for the query when the embedder has it, so an asymmetric model gets its role marker without the caller writing it.

Parameters:

Name Type Description Default
texts str | list[str]

A single query or a list of queries.

required
batch_size int

Max texts per model forward pass.

32

Returns:

Type Description
list[list[float]]

list[list[float]]: One vector per input query, in input order.

load

load() -> None

Load the embedding model + tokenizer into memory (idempotent).

Safe to call from several threads at once: concurrent callers on a cold instance wait for one build.

Raises:

Type Description
ImportError

When the [genai] extra is missing.

unload

unload() -> None

Free the model and its memory. Safe when not loaded.

While an embedding batch is in flight the release waits for it: the last call to finish drops the weights.

unload_if_idle

unload_if_idle() -> bool

Unload the model once idle past idle_unload_seconds.

Returns:

Name Type Description
bool bool

True when it unloaded, False otherwise — including

bool

while a batch is in flight.

EmbeddingCache

Bases: Protocol

A synchronous per-text vector cache (e.g. a dict wrapper).

get

get(key: str) -> list[float] | None

Return the cached vector for key, or None on a miss.

Parameters:

Name Type Description Default
key str

Cache key for the embedded text.

required

Returns:

Type Description
list[float] | None

list[float] | None: The cached vector, or None on a miss.

set

set(key: str, value: list[float]) -> None

Store value under key.

Parameters:

Name Type Description Default
key str

Cache key for the embedded text.

required
value list[float]

The vector to store.

required

EmbeddingModelEnum

Bases: StrEnum

Sentence embedders for Embedder, RAG and semantic search.

Member Dim Use it when
ALL_MINILM_L6_V2 384 English only, fastest, RAG default
PARAPHRASE_MULTILINGUAL_MINILM_L12_V2 384 Cheap PT-BR
MULTILINGUAL_E5_LARGE 1024 Best PT-BR retrieval
BGE_M3 1024 Multilingual, 8k context, dense+sparse

MULTILINGUAL_E5_LARGE expects the query: / passage: prefixes on every text — without them retrieval quality drops to roughly the MiniLM level it was chosen to beat.

EmbeddingPrefixes

Bases: TypedDict

The two role markers of an asymmetric embedding model.

Splat into an embedder constructor: OllamaEmbedder(model, **prefixes).

Attributes:

Name Type Description
query_prefix str

Prepended to every search query by embed_query.

passage_prefix str

Prepended to every corpus passage by embed_passages.

GPUInfo

Bases: BaseSchema

One CUDA device's memory picture.

Attributes:

Name Type Description
index int

The CUDA device index.

name str

The device name (e.g. "NVIDIA RTX 4090").

vram_total_bytes int

Total VRAM on the device.

vram_free_bytes int

Currently free VRAM.

GenAIMetrics

GenAIMetrics(*, namespace: str = 'genai', registry: Any = None)

Prometheus counters + histogram for genai inference.

Example:

>>> metrics = GenAIMetrics()
>>> async with metrics.track("Qwen/Qwen2.5-7B", "generate") as span:
...     span.tokens_out = 128
...     ...  # run the model

Attributes:

Name Type Description
namespace str

Metric name prefix.

Build the metric objects.

Parameters:

Name Type Description Default
namespace str

Prefix for every metric name.

'genai'
registry Any

A prometheus_client.CollectorRegistry to register on; None uses the client's default registry.

None

observe_inventory

observe_inventory(report: ModelRuntimeReport) -> None

Publish a runtime inventory as gauge values.

Counters answer "how much work went through"; these answer "what is resident now", which is the question that explains an OOM. Feed it from a periodic task:

>>> metrics.observe_inventory(registry.inventory(probe=False))

The labelled gauges are cleared first, because they describe a snapshot: a model that unloaded between two calls must stop being reported, and an unlabelled leftover would read as still resident. Cleared-then-empty is the correct picture for a service holding nothing.

Parameters:

Name Type Description Default
report ModelRuntimeReport

A :class:~tempest_fastapi_sdk.genai.ModelRuntimeReport.

required

record

record(
    model: str,
    op: str,
    duration_seconds: float,
    *,
    tokens_in: int | None = None,
    tokens_out: int | None = None,
    status: str = "ok",
) -> None

Record one finished inference.

Parameters:

Name Type Description Default
model str

The model id label.

required
op str

The operation label ("generate" / "chat" / …).

required
duration_seconds float

Wall-clock duration.

required
tokens_in int | None

Input tokens, when known.

None
tokens_out int | None

Output tokens, when known.

None
status str

The outcome label — "ok" for a call that returned, "error" for one that raised. Without it a failing backend reads as healthy traffic on the request counter.

'ok'

record_tokens

record_tokens(
    model: str, *, tokens_in: int | None = None, tokens_out: int | None = None
) -> None

Add to the input/output token counters (no-op for None).

Parameters:

Name Type Description Default
model str

The model id label.

required
tokens_in int | None

Input tokens to add.

None
tokens_out int | None

Output tokens to add.

None

track

track(model: str, op: str = 'generate') -> _Span

Return an async context manager that times and records a call.

Set span.tokens_in / span.tokens_out inside the block to record token counts alongside the latency.

Parameters:

Name Type Description Default
model str

The model id label.

required
op str

The operation label.

'generate'

Returns:

Name Type Description
_Span _Span

The timing span (async context manager).

GenAIRequestLimits

Bases: BaseSchema

Per-request ceilings :func:make_genai_router enforces.

Every GenAI endpoint turns request size into GPU time or memory: a 2 MB prompt with max_new_tokens=10**9, a 100 000-item /embed batch or a 100 000 x 100 000 image are each a way for one caller to hold the worker. The router checks the request against these limits before calling the model and answers 422 with the offending field and its limit in details. The defaults suit a small self-hosted deployment; pass your own instance to raise or lower any of them.

max_new_tokens caps only the value a caller sends. A request that leaves it unset falls through to the generator's own default, which the operator — not the caller — chose.

Example:

>>> limits = GenAIRequestLimits(max_prompt_chars=8_000, max_top_k=20)
>>> router = make_genai_router(text_generator=gen, limits=limits)

Attributes:

Name Type Description
max_prompt_chars int

Largest prompt, in characters. Applies to the /generate prompt, the sum of every /chat message, the /rag query, each /embed text and the /image prompt and negative prompt.

max_chat_messages int

Most messages one /chat request may carry.

max_new_tokens int

Largest config.max_new_tokens accepted.

max_embed_texts int

Most texts one /embed request may carry.

max_top_k int

Largest top_k accepted by /rag.

max_tts_chars int

Largest /tts text, in characters.

max_image_side int

Largest config.width / config.height accepted by /image, in pixels.

max_image_steps int

Largest config.steps accepted by /image.

max_audio_seconds float

Largest config.seconds accepted by /audio.

max_audio_steps int

Largest config.steps accepted by /audio. The default admits MusicLDM's own default of 200.

max_upload_bytes int

Largest /transcribe upload, in bytes. The default equals DEFAULT_MAX_UPLOAD_BYTES (25 MiB), the ceiling make_voice_router uses.

GeneratedAudio

Bases: BaseSchema

One generated clip plus what it takes to generate it again.

Attributes:

Name Type Description
data bytes

The clip as a 16-bit PCM WAV.

sample_rate int

Samples per second (16 000 for AudioLDM and MusicLDM, read from the pipeline's vocoder).

channels int

Channel count of the WAV.

seconds float

Duration of the clip.

seed int

The seed of the call that generated this clip. A call with num_waveforms above 1 gives every clip the same seed, so reproducing one also takes the same num_waveforms and its position in the result.

GeneratedImage

Bases: BaseSchema

One rendered image plus what it takes to render it again.

The seed travels with the image on purpose. Diffusion is deterministic given a seed, so returning the seed the run actually used is the difference between "nice image, gone forever" and "nice image, here is how to get it back" — and when the caller passes no seed, only the generator knows which one was drawn.

Attributes:

Name Type Description
data bytes

The encoded image (PNG unless image_format says otherwise).

image_format str

The encoding, lowercase ("png").

seed int

The seed this image was rendered with.

width int

Pixel width of the result.

height int

Pixel height of the result.

GenerationCache

Bases: Protocol

A synchronous prompt→completion cache (e.g. in-memory).

get

get(key: str) -> str | None

Return the cached completion for key or None.

Parameters:

Name Type Description Default
key str

Cache key derived from the prompt and generation settings.

required

Returns:

Type Description
str | None

str | None: The cached completion, or None on a miss.

set

set(key: str, value: str) -> None

Store value under key.

Parameters:

Name Type Description Default
key str

Cache key derived from the prompt and generation settings.

required
value str

The completion to store.

required

GenerationConfig

Bases: BaseSchema

Typed generation parameters for the local text generators.

Passed to :class:~tempest_fastapi_sdk.genai.TextGenerator and :class:~tempest_fastapi_sdk.genai.VisionTextGenerator, which apply every field the same way (tests/genai/test_vision_text_config.py fails when a field reaches one and not the other). Replaces loose **kwargs at the call site with a validated, self-describing, reusable object — build one config and pass it to generate / chat / stream. Only the fields you set are forwarded to model.generate (unset fields fall through to the generator's own defaults), so a partial config layers cleanly on top.

Example:

>>> cfg = GenerationConfig(max_new_tokens=512, temperature=0.2)
>>> await gen.generate("Explain PIX.", config=cfg)

Attributes:

Name Type Description
max_new_tokens int | None

Maximum tokens to generate (> 0).

temperature float | None

Sampling temperature (0..2); lower is more deterministic.

top_p float | None

Nucleus sampling probability mass (0..1).

top_k int | None

Top-k sampling cutoff (>= 0); 0 disables.

repetition_penalty float | None

Penalty for repeated tokens (> 0, 1.0 = no penalty).

do_sample bool | None

Sample (True) or use greedy decoding (False).

seed int | None

RNG seed for reproducible sampling.

stop list[str]

Stop strings that end generation early.

to_generate_kwargs

to_generate_kwargs() -> dict[str, Any]

Return only the set fields as model.generate keyword args.

seed and stop are dropped from the mapping — they are not transformers generate kwargs. Both generators reapply them themselves: seed through a per-call torch.Generator and stop via the stop_strings generation argument (see :func:~tempest_fastapi_sdk.genai.text._resolve_control).

Returns:

Type Description
dict[str, Any]

dict[str, Any]: The explicitly-set generation kwargs.

GenerationStoppedError

Bases: RuntimeError

Raised when a generation was stopped through its stop_event.

Local generation runs in a worker thread, and a thread cannot be cancelled from outside — so cancelling the awaiting coroutine leaves the GPU producing tokens for a reply nobody will read. The stop_event is how the decision reaches the thread, and this is what the thread raises once it has honoured it: the work stopped because it was told to, not because it went wrong.

HardwareInfo

Bases: BaseSchema

A snapshot of the host's compute resources.

A byte field that could not be read stays 0 so arithmetic on it keeps working, and its *_measured flag turns False: read the flag before treating 0 as "nothing free". Both flags default to True, so a snapshot built by hand (tests, a cached probe) means what its numbers say.

Attributes:

Name Type Description
cpu_cores int

Logical CPU cores.

ram_total_bytes int

Total RAM this process can use: the host's, or the cgroup memory limit when ram_cgroup_limited is True; 0 when ram_measured is False.

ram_available_bytes int

Currently available RAM, bounded by the cgroup when ram_cgroup_limited is True; 0 when ram_measured is False.

ram_measured bool

Whether the two RAM fields were read. :func:~tempest_fastapi_sdk.genai.probe_hardware sets it to False when neither psutil (the [metrics] extra) nor, on Linux, /proc/meminfo could be read — in practice, Windows or macOS without psutil.

ram_cgroup_limited bool

Whether the RAM fields come from a Linux cgroup memory limit (a container's --memory) that is below the host's RAM, rather than from the host. Defaults to False.

has_cuda bool

Whether a CUDA GPU is usable via torch.

gpus list[GPUInfo]

Per-CUDA-device memory (empty without CUDA).

has_mps bool

Whether Apple Metal (MPS) is available.

disk_free_bytes int

Free space on the model cache filesystem; 0 when disk_measured is False.

disk_measured bool

Whether disk_free_bytes was read. False when the filesystem query raised OSError (e.g. the directory does not exist).

warnings list[str]

Environment problems the probe detected that will make a later model load fail, each a sentence that names the cause and the fix. Empty when nothing was detected, which is not a guarantee that every load succeeds. Today the only one is a CUDA 13 torch next to ctranslate2 (faster-whisper), whose wheels link against CUDA 12.

HostedAPIError

HostedAPIError(
    message: str,
    *,
    request: Request,
    response: Response,
    provider: str,
    error_type: str | None = None,
    detail: str = "",
    request_id: str | None = None,
    retry_after: float | None = None,
)

Bases: HTTPStatusError

A hosted provider answered with an error status.

Subclass of :class:httpx.HTTPStatusError, so existing handlers keep working; the attributes below are what that base class made the caller dig out of the response by hand.

Attributes:

Name Type Description
provider str

Which backend raised it ("anthropic", "openai", "deepseek", or "openai-compatible").

status_code int

The HTTP status. For an error that arrived inside a stream it is the status the provider documents for that error type.

error_type str | None

The provider's own error type ("rate_limit_error", "invalid_request_error", ...), when the body carried one.

detail str

The provider's error message, or the response text when the body was not the documented JSON.

request_id str | None

The provider's request id, for a support ticket. Read from the request-id header or the body's request_id.

retry_after float | None

Seconds the provider asked to wait, from a numeric retry-after header. None when absent or given as an HTTP date.

Build the error.

Parameters:

Name Type Description Default
message str

The exception message.

required
request Request

The request that failed.

required
response Response

The error response.

required
provider str

Which backend raised it.

required
error_type str | None

The provider's error type.

None
detail str

The provider's error message.

''
request_id str | None

The provider's request id.

None
retry_after float | None

Seconds to wait before retrying.

None

HostedAuthenticationError

HostedAuthenticationError(
    message: str,
    *,
    request: Request,
    response: Response,
    provider: str,
    error_type: str | None = None,
    detail: str = "",
    request_id: str | None = None,
    retry_after: float | None = None,
)

Bases: HostedAPIError

The key was rejected (401) or lacks permission (403).

Not worth retrying: the same key fails the same way.

HostedRateLimitError

HostedRateLimitError(
    message: str,
    *,
    request: Request,
    response: Response,
    provider: str,
    error_type: str | None = None,
    detail: str = "",
    request_id: str | None = None,
    retry_after: float | None = None,
)

Bases: HostedAPIError

The account is being throttled (429).

Retry after :attr:retry_after seconds when it is set. Anthropic notes that a 429 caused by the monthly spend cap carries no retry-after and keeps failing until access resumes (https://platform.claude.com/docs/en/api/errors).

HostedServerError

HostedServerError(
    message: str,
    *,
    request: Request,
    response: Response,
    provider: str,
    error_type: str | None = None,
    detail: str = "",
    request_id: str | None = None,
    retry_after: float | None = None,
)

Bases: HostedAPIError

The provider failed or is overloaded (5xx, including 529).

Retryable later, or a reason to fail over to another backend.

ImageDiffusionPipeline

Bases: Protocol

Minimal surface of a loaded diffusers image pipeline.

ImageGenerationConfig

Bases: BaseSchema

Typed parameters for local image generation.

Passed to :class:~tempest_fastapi_sdk.genai.ImageGenerator. Only the fields you set are forwarded to the diffusion pipeline, so a partial config layers on top of the model's own defaults — which matters here more than for text, because the right step count and guidance scale differ by an order of magnitude between a distilled turbo model and a full SDXL.

Example:

>>> cfg = ImageGenerationConfig(steps=4, guidance_scale=0.0, seed=7)
>>> images = await generator.generate("a red bicycle", config=cfg)

Attributes:

Name Type Description
negative_prompt str | None

What to steer away from. Ignored by models that do not implement classifier-free guidance.

width int | None

Output width in pixels; must suit the model (multiples of 8, and SDXL expects ~1024). At most 4096.

height int | None

Output height in pixels. At most 4096.

steps int | None

Denoising steps. Distilled/turbo models want 1-8; full models want 20-50. At most 500.

guidance_scale float | None

How hard to follow the prompt. Turbo models want 0.0; full models want 5-9.

seed int | None

RNG seed. Set it and the same prompt gives the same image on the same hardware.

num_images int

How many images to generate per call, at most 16. These ceilings are the schema's absolute bounds, far above any model's useful range, so an unbounded value cannot reach the pipeline; make_genai_router enforces the tighter per-request limits of :class:GenAIRequestLimits on top.

to_pipeline_kwargs

to_pipeline_kwargs() -> dict[str, Any]

Return the explicitly-set pipeline keywords.

seed is excluded: diffusers takes reproducibility through a torch.Generator, not a keyword, so the generator builds one from it. steps and num_images are renamed to the diffusers spellings (num_inference_steps / num_images_per_prompt) — the SDK keeps the short names because they are what the parameter actually is.

Returns:

Type Description
dict[str, Any]

dict[str, Any]: Keywords to splat into the pipeline call.

ImageGenerator

ImageGenerator(
    model_id: str,
    *,
    device: str = "auto",
    dtype: str | ModelDtypeEnum = "auto",
    cache_dir: str | None = None,
    hf_token: str | None = None,
    revision: str | None = None,
    local_files_only: bool | None = None,
    trust_remote_code: bool = False,
    image_format: str = "png",
    pipeline_kwargs: dict[str, Any] | None = None,
    max_concurrent: int = 1,
    idle_unload_seconds: float | None = None,
    hardware: HardwareInfo | None = None,
    metrics: GenAIMetrics | None = None,
)

A lazily-loaded local diffusion pipeline with idle unload.

Example:

>>> gen = ImageGenerator("stabilityai/sdxl-turbo")
>>> images = await gen.generate(
...     "a lighthouse at dawn",
...     config=ImageGenerationConfig(steps=4, guidance_scale=0.0),
... )
>>> Path("out.png").write_bytes(images[0].data)
>>> gen.unload()

Attributes:

Name Type Description
model_id str

The HuggingFace model id.

device str

The resolved device (cuda / mps / cpu).

dtype ModelDtypeEnum

The resolved compute precision.

source ModelRef

The resolved weight identity forwarded to from_pretrained.

image_format str

Encoding of the returned bytes.

pipeline_kwargs dict[str, Any]

Extra from_pretrained keywords, applied last so they override what the SDK computes.

idle_unload_seconds float | None

Idle threshold used by :meth:unload_if_idle.

Configure the generator (does not load weights yet).

Parameters:

Name Type Description Default
model_id str

HuggingFace diffusion model id.

required
device str

"auto" / "cuda" / "mps" / "cpu".

'auto'
dtype str | ModelDtypeEnum

Compute precision, or "auto" (bf16 on GPU, fp32 on CPU).

'auto'
cache_dir str | None

Where the downloaded weights are written and read back from. None uses the huggingface_hub default — $HF_HOME/hub, or ~/.cache/huggingface/hub when HF_HOME is unset — which is why the second run of a script starts instantly instead of downloading again. Point it at a mounted volume when the process is a container, so the layer does not re-download the model on every restart.

None
hf_token str | None

Hub token for gated or private repositories. None falls back to HF_TOKEN in the environment; without either, anonymous downloads work but are rate-limited (the Hub says so on stderr).

None
revision str | None

Branch, tag or commit sha to load; None follows the moving Hub default.

None
local_files_only bool | None

Load from the cache without touching the network — what an air-gapped or deploy-frozen host wants. None (the default) takes GENAI_OFFLINE from the environment; passing the argument overrides it.

None
trust_remote_code bool

Allow the repository's own Python to run at load time.

False
image_format str

Encoding of the returned bytes — "png" (lossless, the default), "jpeg" or "webp".

'png'
pipeline_kwargs dict[str, Any] | None

Extra keywords for from_pretrained, for the load-time decisions the SDK does not model. The three that come up constantly: {"safety_checker": None} skips the extra CLIP that Stable Diffusion 1.x repositories bundle (it costs memory and can blank an image); {"variant": "fp16"} fetches the half-precision weights, roughly halving the download; {"use_safetensors": True} refuses a pickle checkpoint. Keys here win over the ones the SDK computes, so this is also the way to override torch_dtype.

None
max_concurrent int

Simultaneous renders. Defaults to 1 because one diffusion call already saturates the GPU.

1
idle_unload_seconds float | None

When set, :meth:unload_if_idle frees the pipeline after this many idle seconds.

None
hardware HardwareInfo | None

Injected snapshot for device resolution (tests); probed when None.

None
metrics GenAIMetrics | None

Optional Prometheus metrics; when set, :meth:generate / :meth:edit record request count and latency (op "image" / "image_edit").

None

Raises:

Type Description
ValueError

When max_concurrent is not positive.

is_loaded property

is_loaded: bool

Return True once the pipeline is in memory.

Returns:

Name Type Description
bool bool

Whether :meth:load has run without a later

bool

meth:unload.

pipeline property

Return the underlying diffusers pipeline (escape hatch).

Use it to swap the scheduler, attach a LoRA or enable a memory optimization the SDK does not wrap. Loads on first access, which blocks for the whole download and build.

Returns:

Name Type Description
ImageDiffusionPipeline ImageDiffusionPipeline

The loaded AutoPipelineForText2Image.

seconds_idle property

seconds_idle: float

Return seconds since the pipeline was last in use.

A render in flight counts as use for its whole duration, so this reads 0.0 while one runs.

Returns:

Name Type Description
float float

Idle time in seconds.

edit async

edit(
    prompt: str,
    image: ImageSource,
    *,
    strength: float = 0.8,
    config: ImageGenerationConfig | None = None,
) -> list[GeneratedImage]

Redraw an existing image under a new prompt (image-to-image).

The load, the image-to-image pipeline build and the decoding of image all run on the worker thread with the render, so none of them blocks the event loop.

Example:

>>> edited = await generator.edit(
...     "the same room, at night",
...     "room.png",
...     strength=0.6,
... )

Parameters:

Name Type Description Default
prompt str

What the result should depict.

required
image ImageSource

The starting image — a path, bytes, a PIL.Image or a NumPy array.

required
strength float

How far to move from the input, 0..1. Low values keep the composition; 1.0 ignores the input almost entirely.

0.8
config ImageGenerationConfig | None

Steps, guidance, seed and count. width/height are usually left unset here — the input image sets the size.

None

Returns:

Type Description
list[GeneratedImage]

list[GeneratedImage]: The redrawn images.

Raises:

Type Description
ImportError

When the [genai-image] extra is missing.

TypeError

When image is not a supported source type.

ValueError

When strength is outside 0..1.

generate async

generate(
    prompt: str, *, config: ImageGenerationConfig | None = None
) -> list[GeneratedImage]

Render one or more images from a text prompt.

Runs the blocking pipeline — including the first-call load — in a worker thread, capped by the concurrency semaphore, so it never blocks the event loop.

Example:

>>> images = await generator.generate("a red bicycle")
>>> images[0].seed
418223901

Parameters:

Name Type Description Default
prompt str

What to draw.

required
config ImageGenerationConfig | None

Size, steps, guidance, seed and count. Unset fields fall through to the model's own defaults, which differ by an order of magnitude between a turbo model and a full one.

None

Returns:

Type Description
list[GeneratedImage]

list[GeneratedImage]: The rendered images, each carrying the

list[GeneratedImage]

seed that reproduces it.

Raises:

Type Description
ImportError

When the [genai-image] extra is missing.

load

load() -> None

Download (if needed) and load the diffusion pipeline.

Idempotent — a no-op once loaded. Called automatically by :meth:generate / :meth:edit, on their worker thread. Safe to call from several threads at once: concurrent callers on a cold instance wait for one build.

Raises:

Type Description
ImportError

When the [genai-image] extra is missing.

unload

unload() -> None

Free the pipeline and its memory (VRAM/RAM).

Safe to call when not loaded. After this, the next render reloads the weights. While renders are in flight the release waits for them: the last one to finish drops the pipeline.

unload_if_idle

unload_if_idle() -> bool

Free the pipeline when it has been idle past the threshold.

Returns:

Name Type Description
bool bool

True when this call unloaded the pipeline, False

bool

when it was already free, still in use, or no

bool

idle_unload_seconds was configured.

ImageModelEnum

Bases: StrEnum

Diffusion checkpoints for ImageGenerator.

Step counts differ by an order of magnitude between these — a turbo checkpoint wants ~4 steps and a full one ~30, so pass default_steps on the tool rather than letting a model guess.

Member Steps Use it when
SDXL_TURBO ~4 Fast previews, agent loops, CPU-tolerable.
SDXL_BASE_1_0 ~30 Final quality at 1024², 10+ GB VRAM.
FLUX_1_SCHNELL ~4 Best prompt adherence of the fast ones; 16+ GB VRAM.

ImagePipelineOutput

Bases: Protocol

Output object returned by a diffusers text-to-image pipeline.

images property

images: Sequence[Any]

Generated images, one per requested sample.

InMemoryEmbeddingCache

InMemoryEmbeddingCache(*, max_entries: int | None = _DEFAULT_MAX_ENTRIES)

An in-process LRU embedding cache.

Fine for a single process; for multi-worker reuse, pass a Redis-backed object satisfying :class:EmbeddingCache instead. Bounded by max_entries: once full, storing a new key evicts the least-recently-used vector (a read counts as a use), so a long-lived worker that embeds an open-ended stream of texts does not grow forever.

Attributes:

Name Type Description
max_entries int | None

Capacity before eviction, or None for an unbounded store.

Initialize an empty cache.

Parameters:

Name Type Description Default
max_entries int | None

Maximum number of vectors kept. None disables eviction (the pre-bound behaviour).

_DEFAULT_MAX_ENTRIES

Raises:

Type Description
ValueError

When max_entries is lower than 1.

get

get(key: str) -> list[float] | None

Return the cached vector for key or None.

A hit marks the entry as most recently used.

Parameters:

Name Type Description Default
key str

Cache key for the embedded text.

required

Returns:

Type Description
list[float] | None

list[float] | None: The cached vector, or None on a miss.

set

set(key: str, value: list[float]) -> None

Store value under key, evicting the LRU entry when full.

Parameters:

Name Type Description Default
key str

Cache key for the embedded text.

required
value list[float]

The vector to store.

required

InMemoryGenerationCache

InMemoryGenerationCache(*, max_entries: int | None = _DEFAULT_MAX_ENTRIES)

A process-local LRU cache. Not shared across workers.

Bounded by max_entries: once full, storing a new key evicts the least-recently-used one (a read counts as a use). Without the bound a long-lived worker that sees distinct deterministic prompts grows the store forever.

Attributes:

Name Type Description
max_entries int | None

Capacity before eviction, or None for an unbounded store.

Initialize the empty cache.

Parameters:

Name Type Description Default
max_entries int | None

Maximum number of completions kept. None disables eviction (the pre-bound behaviour).

_DEFAULT_MAX_ENTRIES

Raises:

Type Description
ValueError

When max_entries is lower than 1.

get

get(key: str) -> str | None

Return the cached completion for key or None.

A hit marks the entry as most recently used.

Parameters:

Name Type Description Default
key str

Cache key derived from the prompt and generation settings.

required

Returns:

Type Description
str | None

str | None: The cached completion, or None on a miss.

set

set(key: str, value: str) -> None

Store value under key, evicting the LRU entry when full.

Parameters:

Name Type Description Default
key str

Cache key derived from the prompt and generation settings.

required
value str

The completion to store.

required

LoadedModel

Bases: BaseSchema

One model handle, as it stands right now.

Every field except kind and loaded is optional, because the inventory reports what a handle actually exposes. A third-party object that only implements is_loaded still appears — with the rest None — which beats omitting it from a memory audit.

Attributes:

Name Type Description
key str | None

The registry key, when it came from one.

kind str

The handle's class name ("TextGenerator"). The SDK reports the class rather than inventing a taxonomy over it.

model_id str | None

Hub id, Whisper size or graph path.

device str | None

Where it is resident (cuda / cpu).

dtype str | None

Compute precision, when the handle resolves one.

loaded bool

Whether the weights are in memory now.

seconds_idle float | None

Time since the last use, when the handle tracks it.

idle_unload_seconds float | None

The handle's configured idle threshold, when it has one.

unloadable bool

Whether the handle exposes unload().

idle_past_threshold property

idle_past_threshold: bool

Return whether this handle is due to be unloaded.

Returns:

Name Type Description
bool bool

True only when the handle is loaded, tracks its idle

bool

time, has a threshold configured, and has crossed it. Any

bool

missing piece answers False — an unknown is not a reason to

bool

free someone's VRAM.

ModelDtypeEnum

Bases: BaseStrEnum

Weight precision a model is loaded in.

Fewer bytes per parameter → smaller memory footprint, at some quality cost. int8 / int4 require quantization (the [genai-quant] extra).

  • FLOAT32 — 4 bytes/param (full precision).
  • FLOAT16 / BFLOAT16 — 2 bytes/param (the usual GPU default).
  • INT8 — 1 byte/param (quantized).
  • INT4 — ~0.5 byte/param (quantized).

ModelRef

Bases: BaseSchema

Everything needed to resolve one set of weights, reproducibly.

A bare model id names a moving target: the author pushes to main and the next restart loads different weights. Pinning revision to a commit sha (see :func:resolve_revision) makes a deployment reproducible and removes a supply-chain surface — the weights a service runs stop depending on when it happened to boot.

Example:

>>> ref = ModelRef(
...     model_id="Qwen/Qwen2.5-0.5B-Instruct",
...     revision="a8b602d",
...     local_files_only=True,
... )
>>> ref.loader_kwargs()
{'revision': 'a8b602d', 'local_files_only': True}

Attributes:

Name Type Description
model_id str

The Hub model id ("org/name") or a local path.

revision str | None

Branch, tag or commit sha. None means the Hub default (main) — convenient, not reproducible.

cache_dir str | None

Where weights are cached. None takes GENAI_CACHE_DIR from the environment, falling back to the HF_HUB_CACHE default.

token str | None

Hub token for gated or private repositories. None takes GENAI_HF_TOKEN.

local_files_only bool | None

When True, never touch the network: load from the cache or fail — what an air-gapped or deploy-frozen production host wants. None takes GENAI_OFFLINE, falling back to False.

trust_remote_code bool

When True, allow the repository's own Python to run at load time. Some architectures require it; it also executes code you did not review, so it stays opt-in and per-model.

download_kwargs

download_kwargs() -> dict[str, Any]

Return the snapshot_download keywords this ref implies.

Same values as :meth:loader_kwargs minus trust_remote_code, which is a load-time decision and means nothing while fetching files.

Returns:

Type Description
dict[str, Any]

dict[str, Any]: Keywords to splat into snapshot_download.

loader_kwargs

loader_kwargs() -> dict[str, Any]

Return the from_pretrained keywords this ref implies.

Only non-default values are emitted. That keeps the call byte-identical to what the loaders sent before this ref existed when nothing was pinned, and it keeps the same dictionary usable with narrower loaders (tokenizers.Tokenizer.from_pretrained accepts revision but not trust_remote_code).

model_id is not included — it is the positional argument.

Returns:

Type Description
dict[str, Any]

dict[str, Any]: Keywords to splat into from_pretrained.

ModelRegistry

ModelRegistry(max_models: int = 2)

An LRU cache of loaded models keyed by a string id.

Each held object must expose unload() (TextGenerator and Embedder do), called on eviction.

Eviction never frees weights under a running call: the SDK loaders defer an unload() that arrives while calls are in flight until the last one finishes.

A handle kept after its eviction (model = registry.get(...) at startup, used for every request) does not reload behind the registry. Its next call re-registers it under its key — replacing whatever object a later :meth:get built there — and evicts the least-recently-used entry to make room, then waits for that entry's in-flight calls to finish before building. So max_models keeps holding for SDK loaders however the handle was obtained.

The same wait applies to a model :meth:get just built: when the entry it pushed out still has calls running, the new model's first call blocks until they finish, so the two are never resident together. One allowance remains — a call made from inside another model's call does not wait, since the outer call could be what the evicted model is waiting on; there the ceiling is exceeded until that outer call ends. A third-party object exposing only unload() has no hook for any of this; hold those through :meth:get per request.

Attributes:

Name Type Description
max_models int

How many models may be live at once before the least-recently-used is evicted.

Initialize the registry.

Parameters:

Name Type Description Default
max_models int

Live-model ceiling before LRU eviction.

2

Raises:

Type Description
ValueError

When max_models is not positive.

evict

evict(key: str) -> bool

Evict one model by key, calling its unload().

Parameters:

Name Type Description Default
key str

The entry to remove.

required

An SDK loader evicted this way still counts if a kept handle uses it again: the call re-registers it (see the class docstring).

Returns:

Name Type Description
bool bool

True when an entry was evicted, False otherwise.

evict_all

evict_all() -> None

Evict every model, calling each unload().

get

get(key: str, factory: Callable[[], T]) -> T

Return the model for key, creating it via factory on miss.

A hit marks the entry most-recently-used. A miss builds the model, stores it, and evicts the LRU entry when over capacity.

Parameters:

Name Type Description Default
key str

The model identity (e.g. the model id + config).

required
factory Callable[[], T]

Zero-arg builder called on a miss.

required

Returns:

Name Type Description
T T

The cached or freshly built model.

inventory

inventory(
    *, hardware: HardwareInfo | None = None, probe: bool = True
) -> ModelRuntimeReport

Report what this registry is holding in memory right now.

The capacity ceiling says how many models may be live; this says which ones are, on what device, and how long each has been idle — the question an operator actually asks when a card fills up.

Parameters:

Name Type Description Default
hardware HardwareInfo | None

A HardwareInfo snapshot to reuse instead of probing the host again.

None
probe bool

When no snapshot is given, probe the host. False skips it, which makes this call pure bookkeeping.

True

Returns:

Name Type Description
ModelRuntimeReport ModelRuntimeReport

The held handles plus, optionally, the

ModelRuntimeReport

host's memory picture.

items

items() -> dict[str, Unloadable]

Return the live entries, most-recently-used last.

A copy, so iterating it while evicting is safe.

Returns:

Type Description
dict[str, Unloadable]

dict[str, Unloadable]: Key to model, in LRU order — the first

dict[str, Unloadable]

entry is the next one eviction would take.

unload_idle

unload_idle() -> list[str]

Free every held model that has sat idle past its own threshold.

Entries stay in the registry — a TextGenerator that unloaded its weights is still the right object to hand out, and it reloads on next use. This frees memory without losing the configuration, so it is what a periodic task should call; :meth:evict and :meth:evict_all are for forgetting the entry entirely.

A handle that does not implement unload_if_idle is skipped: without an idle clock there is no basis to decide, and unloading someone's model on a guess is worse than leaving it.

Returns:

Type Description
list[str]

list[str]: The keys whose models this call unloaded.

ModelRuntimeReport

Bases: BaseSchema

The models resident right now, next to the host's memory picture.

Attributes:

Name Type Description
models list[LoadedModel]

Every known handle, loaded first and then by longest idle — the order an operator reads when looking for what to free.

loaded_count int

How many are resident.

total_count int

How many handles are known, loaded or not.

hardware HardwareInfo | None

The host snapshot, when probed.

ModelSnapshot

Bases: BaseSchema

The result of materializing one revision on local disk.

Attributes:

Name Type Description
model_id str

The Hub model id that was downloaded.

revision str | None

The revision asked for (None for the Hub default).

path str

Local directory holding the snapshot.

size_bytes int

Total size of the downloaded files.

file_count int

Number of files in the snapshot.

ModerationBackend

Bases: Protocol

Anything that screens a piece of text.

check async

check(text: str) -> ModerationResult

Return the moderation verdict for text.

Parameters:

Name Type Description Default
text str

The content to screen.

required

Returns:

Name Type Description
ModerationResult ModerationResult

The verdict, with the matched categories.

ModerationResult

Bases: BaseSchema

The verdict of a moderation check.

Attributes:

Name Type Description
flagged bool

Whether the text violates policy.

categories list[str]

Matched category labels (empty when clean).

score float

Confidence of the strongest match in 0..1.

MusicGenerator

MusicGenerator(
    model_id: str,
    *,
    device: str = "auto",
    dtype: str | ModelDtypeEnum = "auto",
    cache_dir: str | None = None,
    hf_token: str | None = None,
    revision: str | None = None,
    local_files_only: bool | None = None,
    max_concurrent: int = 1,
    idle_unload_seconds: float | None = None,
    hardware: HardwareInfo | None = None,
    metrics: GenAIMetrics | None = None,
)

A lazily-loaded local MusicGen model with idle unload.

Example:

>>> gen = MusicGenerator("facebook/musicgen-small")
>>> clips = await gen.generate(
...     "calm lo-fi hip hop beat with soft piano",
...     config=AudioGenerationConfig(seconds=10.0, seed=0),
... )
>>> Path("lofi.wav").write_bytes(clips[0].data)

Attributes:

Name Type Description
model_id str

The HuggingFace model id.

device str

The resolved device (cuda / mps / cpu).

dtype ModelDtypeEnum

The resolved compute precision.

source ModelRef

The resolved weight identity.

idle_unload_seconds float | None

Idle threshold used by :meth:unload_if_idle.

Configure the generator (does not load weights yet).

Parameters:

Name Type Description Default
model_id str

HuggingFace id of a MusicGen checkpoint.

required
device str

"auto" / "cuda" / "mps" / "cpu".

'auto'
dtype str | ModelDtypeEnum

Compute precision, or "auto" (bf16 on GPU, fp32 on CPU). Measured on the RTX 4070 Ti SUPER, 10 s took about 9.2 s in bf16, 9.3 s in fp16 and 10 s in fp32.

'auto'
cache_dir str | None

Where weights are downloaded and read back; None uses the huggingface_hub default.

None
hf_token str | None

Hub token; None falls back to HF_TOKEN.

None
revision str | None

Branch, tag or commit sha to load.

None
local_files_only bool | None

Load from the cache without the network; None takes GENAI_OFFLINE.

None
max_concurrent int

Simultaneous renders. Defaults to 1; it also keeps two calls from interleaving their seeds on the process-wide RNG.

1
idle_unload_seconds float | None

When set, :meth:unload_if_idle frees the model after this many idle seconds.

None
hardware HardwareInfo | None

Injected snapshot for device resolution (tests); probed when None.

None
metrics GenAIMetrics | None

Optional Prometheus metrics; :meth:generate records under op "audio".

None

Raises:

Type Description
ValueError

When max_concurrent is not positive.

accepts_melody property

accepts_melody: bool

Return whether the checkpoint conditions on a reference melody.

Loads the model on first access, which blocks.

Returns:

Name Type Description
bool bool

True for a musicgen_melody checkpoint.

is_loaded property

is_loaded: bool

Return True once the model is in memory.

Returns:

Name Type Description
bool bool

Whether :meth:load has run without a later :meth:unload.

max_seconds property

max_seconds: float

Return the longest clip the decoder window allows.

Loads the model on first access (it reads the model config), which blocks for the whole download and load: from a coroutine, read it through await asyncio.to_thread(lambda: generator.max_seconds) or after an awaited :meth:generate.

Returns:

Name Type Description
float float

max_position_embeddings / frame_rate (40.96 s for the

float

MusicGen checkpoints measured).

seconds_idle property

seconds_idle: float

Return seconds since the model was last in use.

Returns:

Name Type Description
float float

Idle time in seconds; 0.0 while a render runs.

generate async

generate(
    prompt: str,
    *,
    config: AudioGenerationConfig | None = None,
    melody: str | Path | bytes | None = None,
) -> list[GeneratedAudio]

Generate one or more music clips from a text prompt.

Parameters:

Name Type Description Default
prompt str

The music to generate.

required
config AudioGenerationConfig | None

seconds, guidance_scale, seed and num_waveforms. steps and negative_prompt are refused.

None
melody str | Path | bytes | None

A reference clip (path or bytes) whose melody the music follows; only a musicgen-melody checkpoint takes one. It is decoded with :func:~tempest_fastapi_sdk.genai.audio.load_audio (a 16-bit WAV needs nothing else; other formats need PyAV, from [genai-audio]), mixed to mono at the model's rate, and its input features are cast to the model's precision -- in bf16 they otherwise fail with mat1 and mat2 must have the same dtype. A string is always a path, never fetched; a missing file is refused before the model loads, and a clip longer than :data:MAX_MELODY_SECONDS is refused when decoded.

None

Returns:

Type Description
list[GeneratedAudio]

list[GeneratedAudio]: The clips, mono or stereo as the checkpoint

list[GeneratedAudio]

produces them. Every clip carries the call's seed; with

list[GeneratedAudio]

num_waveforms above 1 they differ, so reproducing clip i

list[GeneratedAudio]

takes the same seed, the same num_waveforms and index i.

Reproducibility holds while nothing else draws from torch's process-wide RNG during the render: keep max_concurrent=1 and do not run other torch sampling in the same process concurrently.

Raises:

Type Description
ImportError

When the [genai] extra is missing.

ValidationException

When the config cannot be honoured; steps and negative_prompt are refused before the model loads, a melody for a checkpoint without melody support after.

FileNotFoundError

When melody is a path that does not exist.

load

load() -> None

Download (if needed) and load the processor and model.

Idempotent, and safe to call from several threads at once.

Raises:

Type Description
ImportError

When the [genai] extra is missing.

OSError

When the checkpoint cannot be downloaded or read.

ValueError

When the checkpoint is not a MusicGen model (raised by from_pretrained).

unload

unload() -> None

Free the model and its memory; waits for renders in flight.

unload_if_idle

unload_if_idle() -> bool

Free the model when it has been idle past the threshold.

Returns:

Name Type Description
bool bool

True when this call unloaded the model.

OllamaContextExceededError

OllamaContextExceededError(
    model: str,
    detail: str,
    *,
    prompt_tokens: int | None = None,
    context_window: int | None = None,
)

Bases: OllamaError

The prompt does not fit the context window and truncate was False.

By default the daemon cuts an overflowing prompt to about half the window and answers 200. With truncate=False it refuses instead: 400 with an exceed_context_size_error that carries the prompt size and the window (reproduced on Ollama 0.30.11 on /api/chat and /api/generate, streamed or not, before any line is streamed). Raise num_ctx or shorten the prompt.

Attributes:

Name Type Description
model str

The model tag the request targeted.

detail str

The daemon's error message.

prompt_tokens int | None

The prompt size the daemon counted (n_prompt_tokens), when it reported one.

context_window int | None

The window the request ran with (n_ctx), when the daemon reported one.

Build the error from the daemon message and the sizes it reported.

Parameters:

Name Type Description Default
model str

The model tag the request targeted.

required
detail str

The daemon's error message.

required
prompt_tokens int | None

The prompt size in tokens, if known.

None
context_window int | None

The context window in tokens, if known.

None

OllamaEmbedder

OllamaEmbedder(
    model: str,
    *,
    base_url: str = DEFAULT_OLLAMA_URL,
    timeout: float = 120.0,
    keep_alive: str | float | None = None,
    http_client: HTTPClient | None = None,
    transport: AsyncBaseTransport | None = None,
    retry_policy: RetryPolicy | None = None,
    metrics: GenAIMetrics | None = None,
    generation_cache: GenerationCache | AsyncGenerationCache | None = None,
    query_prefix: str = "",
    passage_prefix: str = "",
)

Bases: _OllamaClientMixin

Embeddings backed by an Ollama daemon.

Satisfies :class:~tempest_fastapi_sdk.genai.rag.SupportsEmbed, so it plugs into :class:~tempest_fastapi_sdk.genai.rag.Retriever and the /embed endpoint of :func:~tempest_fastapi_sdk.genai.make_genai_router in place of the torch-backed :class:~tempest_fastapi_sdk.genai.Embedder. Pull an embedding model first (e.g. ollama pull nomic-embed-text).

Asymmetric models such as nomic-embed-text were trained with a task prefix on each side; pass them as query_prefix / passage_prefix (or splat a preset such as :data:~tempest_fastapi_sdk.genai.NOMIC_EMBED_TEXT_PREFIXES) and the Retriever applies each one through :meth:embed_query and :meth:embed_passages. Changing the prefixes changes every vector, so an existing index has to be rebuilt.

Attributes:

Name Type Description
model str

The Ollama embedding model tag.

base_url str

The daemon base URL.

query_prefix str

Prepended by :meth:embed_query.

passage_prefix str

Prepended by :meth:embed_passages.

Configure the daemon connection and the task prefixes.

Parameters:

Name Type Description Default
model str

The Ollama embedding model tag (must already be pulled, e.g. "nomic-embed-text").

required
base_url str

Base URL of the Ollama daemon.

DEFAULT_OLLAMA_URL
timeout float

Per-request HTTP timeout in seconds.

120.0
keep_alive str | float | None

Ollama keep_alive value; None uses the daemon default.

None
http_client HTTPClient | None

An injected client; when None one is created lazily and owned by this instance.

None
transport AsyncBaseTransport | None

Explicit transport for the lazily-created client (httpx.MockTransport in tests). Ignored when http_client is given.

None
retry_policy RetryPolicy | None

Retry configuration for the lazily-created client. Ignored when http_client is given.

None
metrics GenAIMetrics | None

Optional Prometheus metrics.

None
generation_cache GenerationCache | AsyncGenerationCache | None

Accepted for signature compatibility with the shared client base; embeddings never read it.

None
query_prefix str

Text prepended to every input of :meth:embed_query. nomic-embed-text wants "search_query: ". :meth:embed never applies it.

''
passage_prefix str

Text prepended to every input of :meth:embed_passages (the corpus side); nomic-embed-text wants "search_document: ".

''

embed async

embed(texts: str | list[str], *, batch_size: int = 32) -> list[list[float]]

Embed one or many texts into vectors.

Parameters:

Name Type Description Default
texts str | list[str]

A single text or a list of texts.

required
batch_size int

Max texts sent to the daemon per request.

32

Returns:

Type Description
list[list[float]]

list[list[float]]: One vector per input text, in input order. Returns an empty list for empty input.

embed_passages async

embed_passages(texts: str | list[str], *, batch_size: int = 32) -> list[list[float]]

Embed corpus passages, prepending passage_prefix to each one.

:class:~tempest_fastapi_sdk.genai.rag.Retriever calls this when it indexes chunks, so stored vectors and query vectors carry the role markers the model was trained with.

Parameters:

Name Type Description Default
texts str | list[str]

A single passage or a list of passages.

required
batch_size int

Max texts sent to the daemon per request.

32

Returns:

Type Description
list[list[float]]

list[list[float]]: One vector per input passage, in input order.

embed_query async

embed_query(texts: str | list[str], *, batch_size: int = 32) -> list[list[float]]

Embed search queries, prepending query_prefix to each one.

:class:~tempest_fastapi_sdk.genai.rag.Retriever calls this for the query when the embedder has it.

Parameters:

Name Type Description Default
texts str | list[str]

A single query or a list of queries.

required
batch_size int

Max texts sent to the daemon per request.

32

Returns:

Type Description
list[list[float]]

list[list[float]]: One vector per input query, in input order.

OllamaError

OllamaError(model: str, detail: str)

Bases: RuntimeError

The Ollama daemon answered with an {"error": ...} body.

The daemon reports some failures (model not pulled, out of memory, a runner crash mid-stream) as a JSON object with an error key — on a 200 response or as one line of an NDJSON stream. Treating that object as a normal reply yields an empty completion, or a stream that ends as if it had finished. This exception surfaces it instead.

Attributes:

Name Type Description
model str

The model tag the request targeted.

detail str

The daemon's error message.

Build the error from the daemon message.

Parameters:

Name Type Description Default
model str

The model tag the request targeted.

required
detail str

The daemon's error string.

required

OllamaFormatIgnoredError

OllamaFormatIgnoredError(model: str, content: str, think: ThinkLevel | None)

Bases: OllamaError, ValueError

A structured call came back as free text instead of the JSON asked for.

The request carried the schema as format and the reply holds no JSON object, so the daemon did not constrain the decoder. Reproduced on Ollama 0.30.11: ornith:35b with think=false answered **Nome:** Ana Costa ... with 200 in 3 of 3 calls, while the same request with think omitted or true returned the object 3 of 3. ornith-1.5:9b, gpt-oss:20b and ministral-3:14b honoured format with think=false (3 of 3 each).

Subclasses ValueError, which is what a reply without a JSON object raised before, so code already catching that keeps working.

Attributes:

Name Type Description
model str

The model tag the request targeted.

detail str

What went wrong.

content str

The start of the reply (first 500 characters).

think ThinkLevel | None

The think value the request carried.

Build the error from the reply.

Parameters:

Name Type Description Default
model str

The model tag the request targeted.

required
content str

The reply content.

required
think ThinkLevel | None

The think value sent, if any.

required

OllamaGenerator

OllamaGenerator(
    model: str,
    *,
    base_url: str = DEFAULT_OLLAMA_URL,
    timeout: float = 120.0,
    keep_alive: str | float | None = None,
    http_client: HTTPClient | None = None,
    transport: AsyncBaseTransport | None = None,
    retry_policy: RetryPolicy | None = None,
    metrics: GenAIMetrics | None = None,
    generation_cache: GenerationCache | AsyncGenerationCache | None = None,
    config: GenerationConfig | None = None,
    num_ctx: int | None = None,
    options: dict[str, Any] | None = None,
    think: ThinkLevel | None = None,
    truncate: bool | None = None,
)

Bases: _OllamaRequestMixin

Text generation backed by an Ollama daemon.

A drop-in alternative to :class:~tempest_fastapi_sdk.genai.text.TextGenerator: it exposes the same generate / chat / stream surface (so it slots into :func:~tempest_fastapi_sdk.genai.make_genai_router) but delegates inference to Ollama over HTTP. No torch, no local weights, no load() — the daemon must be running and the model pulled.

Attributes:

Name Type Description
model str

The Ollama model tag.

base_url str

The daemon base URL.

config GenerationConfig | None

Default generation parameters, layered under every call's own.

options dict[str, Any]

Raw Ollama options sent with every request, num_ctx included when set.

think ThinkLevel | None

Default top-level think field, or None to send none.

truncate bool | None

Default top-level truncate field, or None to send none.

Configure the daemon connection and the per-request defaults.

The connection arguments are the ones every Ollama client takes; the last three exist because some callers pass no options at all. The :class:~tempest_fastapi_sdk.agents.Agent loop calls chat_with_tools(messages, tools) and nothing else, so before these a generator driving an agent always ran on the daemon's defaults — including its context window, which truncates the prompt silently. Measured on Ollama 0.30.11 with lfm2.5-thinking:1.2b: a 35,018-token chat came back with prompt_eval_count 2,051 and no error under the default, and 35,018 with num_ctx=65536. An agent's prompt is the system turn, every tool spec and every tool result so far, so it reaches that ceiling within a few steps.

Parameters:

Name Type Description Default
model str

The Ollama model tag (must already be pulled).

required
base_url str

Base URL of the Ollama daemon.

DEFAULT_OLLAMA_URL
timeout float

Per-request HTTP timeout in seconds.

120.0
keep_alive str | float | None

Ollama keep_alive value; None uses the daemon default.

None
http_client HTTPClient | None

An injected client; one is created lazily and owned by this instance when None.

None
transport AsyncBaseTransport | None

Transport for the lazily-created client (tests). Ignored with http_client.

None
retry_policy RetryPolicy | None

Retry configuration for the lazily-created client. None keeps the HTTPClient defaults but does not retry a read timeout: the daemon aborts the generation when the client gives up, so a retry redoes it from zero and the failure would arrive after three timeouts instead of one. Ignored with http_client.

None
metrics GenAIMetrics | None

Optional Prometheus metrics.

None
generation_cache GenerationCache | AsyncGenerationCache | None

Optional prompt→completion cache for deterministic calls.

None
config GenerationConfig | None

Default generation parameters for every call. A call's own config is layered over it field by field, and its keyword overrides win over both.

None
num_ctx int | None

Context window in tokens, sent as the num_ctx option on every request. None leaves the daemon's default (4096 without OLLAMA_CONTEXT_LENGTH). Either way, a reply whose prompt_eval_count shows the daemon truncated the prompt logs a WARNING on the tempest_fastapi_sdk.genai.ollama logger.

None
options dict[str, Any] | None

Raw Ollama options sent on every request (num_thread, num_gpu, …), under the ones a call's config or overrides produce.

None
think ThinkLevel | None

Default think field for every request, sent at the top level of the body (inside options the daemon ignores it). None sends nothing and leaves the model's default; a call's own think wins over it. Measured in the 2026-11-26/27 local-LLM study (Ollama 0.30.11, temperature 0): gpt-oss:20b with "low" solved 97.1% of 34 tool tasks at p50 1.44 s, against 94.1% at 1.68 s for its default (medium) and 97.1% at 3.59 s for "high"; ornith-1.5:9b with False scored 93.3 per field on 33 extraction cases at p50 1.34 s, against 95.0 at 5.60 s with True.

None
truncate bool | None

Default truncate field for every request, sent at the top level of the body. False makes a prompt longer than the context window fail with :class:OllamaContextExceededError instead of being cut to about half the window; True is the daemon's own default (measured on Ollama 0.30.11: the same prompt_eval_count as omitting it). None sends nothing; a call's own truncate wins over it.

None

Raises:

Type Description
ValueError

When num_ctx is not positive, is given both as an argument and inside options, think is not a bool or one of "low", "medium", "high", or truncate is not a bool.

is_loaded property

is_loaded: bool

Return True — the daemon owns model residency.

Provided for surface-compatibility with TextGenerator; Ollama loads/unloads models on demand, so from the caller's perspective the backend is always ready.

Returns:

Name Type Description
bool bool

Always True.

chat async

chat(
    messages: list[dict[str, Any]],
    *,
    config: GenerationConfig | None = None,
    think: ThinkLevel | None = None,
    truncate: bool | None = None,
    **kwargs: Any,
) -> str

Generate a reply for a chat messages list.

Parameters:

Name Type Description Default
messages list[dict[str, Any]]

Chat turns, each {"role": ..., "content": ...}. A turn may also carry an "images": [<base64>, ...] key for multimodal models — it is forwarded verbatim to Ollama.

required
config GenerationConfig | None

Typed generation parameters.

None
think ThinkLevel | None

Top-level think for this call; None uses the generator's default.

None
truncate bool | None

Top-level truncate for this call; None uses the generator's default.

None
**kwargs Any

Per-call generation overrides (win over config).

{}

Honors generation_cache (deterministic calls only, keyed apart from :meth:generate so a prompt that equals the serialized messages never collides) and records metrics like :meth:generate, matching :meth:~tempest_fastapi_sdk.genai.text.TextGenerator.chat.

Returns:

Name Type Description
str str

The assistant reply.

Raises:

Type Description
OllamaThinkingUnsupportedError

When think is set and the model has no thinking capability.

OllamaContextExceededError

When truncate is False and the prompt does not fit the context window.

OllamaError

When the daemon answers with an error body.

HTTPStatusError

When the daemon answers a non-success status.

chat_structured async

chat_structured(
    messages: list[dict[str, Any]],
    schema: type[StructuredT],
    *,
    config: GenerationConfig | None = None,
    think: ThinkLevel | None = None,
    truncate: bool | None = None,
    **kwargs: Any,
) -> StructuredT

Generate a chat reply constrained to a Pydantic schema.

The messages list is what makes a system instruction separable from the payload being read. That separation helps, but it is the smaller half of the story: the first thing a long document needs is a context window that fits it. Ollama defaults num_ctx to 4096 tokens and truncates the rest silently, and under truncation both shapes degrade — the concatenated one worse, because the instruction competes for room with the document. Measured over a 24,086-character document with 20 extractable items, three runs each: at num_ctx=4096 the system turn returned 0, 6 and 5 items against 1 and 2 (and one empty reply) concatenated; at num_ctx=16384 both returned all 20, every run. Size the window first, then keep the instruction in its own turn.

format is posted at the top level of the request body, which is where the daemon reads it. Sending it inside options — what happens when a schema is passed as a keyword to :meth:chat — is ignored silently: the call returns 200 with free text, and the caller finds out at validation time, or worse, at a parse that happens to succeed.

As in :meth:generate_structured, the posted schema lists every property in required at every level; optional fields stay nullable and the reply is validated against schema itself.

Parameters:

Name Type Description Default
messages list[dict[str, Any]]

Chat turns, each {"role": ..., "content": ...}. Put the instruction in a system turn and the content being read in user.

required
schema type[StructuredT]

The Pydantic model to produce.

required
config GenerationConfig | None

Typed generation parameters.

None
think ThinkLevel | None

Top-level think for this call; None uses the generator's default. False makes some models ignore format (see :class:OllamaFormatIgnoredError).

None
truncate bool | None

Top-level truncate for this call; None uses the generator's default.

None
**kwargs Any

Per-call generation overrides (win over config).

{}

Returns:

Name Type Description
StructuredT StructuredT

The validated instance.

Raises:

Type Description
TypeError

When format is passed as a keyword — the schema argument is what sets it, and a keyword would be dropped into options and ignored.

OllamaFormatIgnoredError

When the reply holds no JSON object, so the daemon did not apply the format constraint.

OllamaThinkingUnsupportedError

When think is set and the model has no thinking capability.

OllamaContextExceededError

When truncate is False and the prompt does not fit the context window.

ValidationError

When the JSON fails schema validation.

Example
from pydantic import BaseModel

from tempest_fastapi_sdk.genai import OllamaGenerator


class Invoice(BaseModel):
    number: str
    total_cents: int


async def read(document: str) -> Invoice:
    "Extract the invoice fields from a document."
    generator = OllamaGenerator(model="gpt-oss:20b")
    return await generator.chat_structured(
        [
            {"role": "system", "content": "Extract the invoice fields."},
            {"role": "user", "content": document},
        ],
        Invoice,
    )

chat_with_tools async

chat_with_tools(
    messages: list[dict[str, Any]],
    tools: list[dict[str, Any]],
    *,
    config: GenerationConfig | None = None,
    think: ThinkLevel | None = None,
    truncate: bool | None = None,
    **kwargs: Any,
) -> dict[str, Any]

Generate a chat reply with tool-calling enabled.

Posts to /api/chat with the same payload as :meth:chat plus a tools field (OpenAI-style function specs) and returns the whole response message dict — so the caller can inspect both its content and any tool_calls the model emitted.

Parameters:

Name Type Description Default
messages list[dict[str, Any]]

Chat turns, each {"role": ..., "content": ...} (a turn may carry tool_calls or be a {"role": "tool", ...} result).

required
tools list[dict[str, Any]]

Tool specifications in the Ollama / OpenAI {"type": "function", "function": {...}} shape.

required
config GenerationConfig | None

Typed generation parameters.

None
think ThinkLevel | None

Top-level think for this call; None uses the generator's default.

None
truncate bool | None

Top-level truncate for this call; None uses the generator's default.

None
**kwargs Any

Per-call generation overrides (win over config).

{}

Returns:

Type Description
dict[str, Any]

dict[str, Any]: The full response message dict (with

dict[str, Any]

content and an optional tool_calls list), or an empty

dict[str, Any]

dict when the daemon returns no message.

Raises:

Type Description
OllamaThinkingUnsupportedError

When think is set and the model has no thinking capability.

OllamaContextExceededError

When truncate is False and the prompt does not fit the context window.

OllamaError

When the daemon answers with an error body.

generate async

generate(
    prompt: str,
    *,
    config: GenerationConfig | None = None,
    images: list[str] | None = None,
    think: ThinkLevel | None = None,
    truncate: bool | None = None,
    **kwargs: Any,
) -> str

Generate a completion for prompt.

Parameters:

Name Type Description Default
prompt str

The input text.

required
config GenerationConfig | None

Typed generation parameters; its set fields are mapped to Ollama options.

None
images list[str] | None

Base64-encoded images for a multimodal model (e.g. llava, llama3.2-vision); forwarded as the Ollama images field. None for a text-only prompt.

None
think ThinkLevel | None

Top-level think for this call; None uses the generator's default.

None
truncate bool | None

Top-level truncate for this call; None uses the generator's default.

None
**kwargs Any

Per-call generation overrides (HuggingFace-style names such as max_new_tokens / temperature); these win over config.

{}

Returns:

Name Type Description
str str

The generated text.

Raises:

Type Description
OllamaThinkingUnsupportedError

When think is set and the model has no thinking capability.

OllamaContextExceededError

When truncate is False and the prompt does not fit the context window.

OllamaError

When the daemon answers with an error body (e.g. the model is not pulled), even on a 200.

HTTPStatusError

When the daemon answers a non-success status.

generate_structured async

generate_structured(
    prompt: str,
    schema: type[StructuredT],
    *,
    system: str | None = None,
    config: GenerationConfig | None = None,
    think: ThinkLevel | None = None,
    truncate: bool | None = None,
    **kwargs: Any,
) -> StructuredT

Generate a completion constrained to a Pydantic schema.

Passes the schema as the Ollama format field (the daemon enforces JSON-schema-valid output natively) and parses the reply into an instance of schema. No [genai-structured] extra needed — the constraint lives in the daemon. The posted schema lists every property in required at every level, defaulted ones included, so the model cannot skip a field and let its default stand in for the answer; optional fields stay nullable.

The request goes to /api/chat, not /api/generate. That is not a style choice: on a harmony/reasoning model such as gpt-oss, /api/generate with a format constraint answers 200 OK with a non-zero eval_count and an empty response — the reply lands in a reasoning channel the endpoint does not surface. Measured against gpt-oss:20b: /api/generate without format works, /api/generate with format returns empty, /api/chat with format returns the JSON in message.content. Non-reasoning models behave the same on either endpoint, so /api/chat is correct for both.

Parameters:

Name Type Description Default
prompt str

The input text. With a schema in hand the model does not need to be told to answer as JSON — the daemon constrains the decoder.

required
schema type[StructuredT]

The Pydantic model to produce.

required
system str | None

Instruction sent as its own system turn ahead of prompt. Prefer it over prefixing the instruction to a long document: a several-thousand-token prompt buries an instruction placed above it, and the model answers about the document while ignoring the ask.

None
config GenerationConfig | None

Typed generation parameters.

None
think ThinkLevel | None

Top-level think for this call; None uses the generator's default. False makes some models ignore format (see :class:OllamaFormatIgnoredError).

None
truncate bool | None

Top-level truncate for this call; None uses the generator's default.

None
**kwargs Any

Per-call generation overrides (win over config).

{}

Returns:

Name Type Description
StructuredT StructuredT

The validated instance.

Raises:

Type Description
OllamaFormatIgnoredError

When the reply holds no JSON object, so the daemon did not apply the format constraint.

OllamaThinkingUnsupportedError

When think is set and the model has no thinking capability.

OllamaContextExceededError

When truncate is False and the prompt does not fit the context window.

ValueError

When the daemon answers with no content.

ValidationError

When the JSON fails schema validation.

load

load() -> None

No-op load hook.

TextGenerator loads weights here; Ollama does it lazily on the first request, so there is nothing to do.

stream async

stream(
    prompt: str,
    *,
    config: GenerationConfig | None = None,
    think: ThinkLevel | None = None,
    truncate: bool | None = None,
    **kwargs: Any,
) -> AsyncIterator[str]

Stream the completion piece by piece.

Parameters:

Name Type Description Default
prompt str

The input text.

required
config GenerationConfig | None

Typed generation parameters.

None
think ThinkLevel | None

Top-level think for this call; None uses the generator's default.

None
truncate bool | None

Top-level truncate for this call; None uses the generator's default.

None
**kwargs Any

Per-call generation overrides (win over config).

{}

Yields:

Name Type Description
str AsyncIterator[str]

Text pieces as the daemon produces them.

Raises:

Type Description
OllamaThinkingUnsupportedError

When think is set and the model has no thinking capability.

OllamaContextExceededError

When truncate is False and the prompt does not fit the context window.

OllamaError

When a stream line is an {"error": ...} object — the daemon's way of failing mid-generation. Pieces already yielded stay yielded; the stream does not end as if done.

stream_chat async

stream_chat(
    messages: list[dict[str, Any]],
    *,
    config: GenerationConfig | None = None,
    think: ThinkLevel | None = None,
    truncate: bool | None = None,
    **kwargs: Any,
) -> AsyncIterator[str]

Stream the reply to a chat messages list piece by piece.

The streaming counterpart of :meth:chat: POST /api/chat with stream: true, so the system turn and the conversation keep their roles, where :meth:stream sends one flattened prompt to /api/generate. Only message.content is yielded; a thinking model's message.thinking stays out of the reply, as in :meth:chat. Like :meth:stream, it bypasses generation_cache.

Parameters:

Name Type Description Default
messages list[dict[str, Any]]

Chat turns, each {"role": ..., "content": ...}; a turn may carry "images": [<base64>, ...] for multimodal models.

required
config GenerationConfig | None

Typed generation parameters.

None
think ThinkLevel | None

Top-level think for this call; None uses the generator's default.

None
truncate bool | None

Top-level truncate for this call; None uses the generator's default.

None
**kwargs Any

Per-call generation overrides (win over config).

{}

Yields:

Name Type Description
str AsyncIterator[str]

Reply pieces as the daemon produces them.

Raises:

Type Description
OllamaThinkingUnsupportedError

When think is set and the model has no thinking capability.

OllamaContextExceededError

When truncate is False and the prompt does not fit the context window.

OllamaError

When a stream line is an {"error": ...} object. Pieces already yielded stay yielded.

stream_chat_with_tools async

stream_chat_with_tools(
    messages: list[dict[str, Any]],
    tools: list[Any],
    *,
    config: GenerationConfig | None = None,
    think: ThinkLevel | None = None,
    truncate: bool | None = None,
    **kwargs: Any,
) -> AsyncIterator[ChatStreamEvent]

Stream one generation with tools attached (ToolStreamingBackend).

POST /api/chat with stream: true and tools: the payload :meth:chat_with_tools sends, streamed. message.content pieces are yielded as :class:~tempest_fastapi_sdk.genai.StreamTextDelta as they arrive (message.thinking stays out, as in :meth:chat); every message.tool_calls the daemon sends is collected and, when there is any, yielded once at the end as :class:~tempest_fastapi_sdk.genai.StreamToolCalls — the calls in the shape :meth:chat_with_tools returns them (arguments a dict). Sending the tools on the streamed call is what lets a model that wants one ask for it, instead of writing a call the daemon then fails to parse.

Parameters:

Name Type Description Default
messages list[dict[str, Any]]

Chat turns, as :meth:chat_with_tools takes them.

required
tools list[Any]

Tool specifications in the Ollama / OpenAI {"type": "function", "function": {...}} shape.

required
config GenerationConfig | None

Typed generation parameters.

None
think ThinkLevel | None

Top-level think for this call; None uses the generator's default.

None
truncate bool | None

Top-level truncate for this call; None uses the generator's default.

None
**kwargs Any

Per-call generation overrides (win over config).

{}

Yields:

Name Type Description
ChatStreamEvent AsyncIterator[ChatStreamEvent]

Text deltas, then the tool calls when the model

AsyncIterator[ChatStreamEvent]

asked for any.

Raises:

Type Description
OllamaThinkingUnsupportedError

When think is set and the model has no thinking capability.

OllamaContextExceededError

When truncate is False and the prompt does not fit the context window.

OllamaError

When a stream line is an {"error": ...} object. Events already yielded stay yielded.

OllamaSpeech

OllamaSpeech(
    model: str,
    *,
    base_url: str = DEFAULT_OLLAMA_URL,
    timeout: float = 120.0,
    http_client: HTTPClient | None = None,
    transport: AsyncBaseTransport | None = None,
    retry_policy: RetryPolicy | None = None,
)

Bases: _OllamaClientMixin

Text-to-speech and speech-to-text backed by an Ollama daemon.

Pull the model first (ollama pull phonon for English speech, ollama pull lfm3-audio for 18 languages and transcription). A request the daemon refuses with 400 (a model without the speech or audio capability, an unknown voice, bad input) raises :class:~tempest_fastapi_sdk.exceptions.ValidationException with the daemon's message; a model that is not pulled, or a daemon failure, raises :class:~tempest_fastapi_sdk.genai.OllamaError. It satisfies :class:~tempest_fastapi_sdk.genai.audio.SpeechTranscriber and :class:~tempest_fastapi_sdk.genai.audio.SpeechSynthesizer, so it backs /transcribe and /tts in :func:~tempest_fastapi_sdk.genai.make_genai_router.

keep_alive, metrics and generation_cache from the shared Ollama client stay None: the speech endpoints ignore keep_alive, and there is no text generation to meter or cache.

Attributes:

Name Type Description
model str

The Ollama model tag.

base_url str

The daemon base URL.

timeout float

Per-request HTTP timeout in seconds.

Configure the connection to the Ollama daemon.

Parameters:

Name Type Description Default
model str

The Ollama model tag (e.g. "phonon" or "lfm3-audio").

required
base_url str

Base URL of the Ollama daemon.

DEFAULT_OLLAMA_URL
timeout float

Per-request HTTP timeout in seconds. The first request after a pull loads the model and can be slow: measured at 116 s for phonon and 55 s for lfm3-audio on an RTX 4070 Ti SUPER, against 1.4 s for a later reload.

120.0
http_client HTTPClient | None

An injected client (connection reuse). When None, one is created lazily and owned here.

None
transport AsyncBaseTransport | None

Explicit transport for the lazily-created client, such as an httpx.MockTransport in tests.

None
retry_policy RetryPolicy | None

Retry configuration for the lazily-created client; None keeps the Ollama default of not retrying a read timeout. A retryable status (5xx) is still retried, and each retry redoes the whole synthesis or transcription.

None

speech_response async

speech_response(
    text: str,
    /,
    *,
    voice: str | None = None,
    speaker: str | None = None,
    language: str | None = None,
    response_format: SpeechFormat = "pcm",
) -> StreamingResponse

Return a StreamingResponse that fails as 422 when it should.

A StreamingResponse sends its status and headers before reading the first chunk, so an error raised by :meth:stream_speech on its first chunk (an unknown voice) reaches the client as 200 with an empty body, and Starlette logs Caught handled exception, but response already started -- measured. This method pulls the first chunk before building the response: a refusal raises here, where :func:~tempest_fastapi_sdk.register_exception_handlers turns it into the SDK's 422, and the audio that follows still streams.

Parameters:

Name Type Description Default
text str

The text to speak.

required
voice str | None

A voice name from :meth:voices.

None
speaker str | None

The same as voice.

None
language str | None

Must stay None.

None
response_format SpeechFormat

"pcm" (served as audio/L16; rate=24000; channels=1) or "wav" (audio/wav).

'pcm'

Returns:

Name Type Description
StreamingResponse StreamingResponse

The audio, streamed.

Raises:

Type Description
ValidationException

When the request or the daemon refuses (see :meth:stream_speech).

OllamaError

When the model is not pulled or the daemon fails.

stream_speech async

stream_speech(
    text: str,
    /,
    *,
    voice: str | None = None,
    speaker: str | None = None,
    language: str | None = None,
    response_format: SpeechFormat = "pcm",
) -> AsyncGenerator[bytes, None]

Yield the speech audio as the daemon generates it.

Where :meth:synthesize waits for the whole clip, this yields each chunk as the daemon flushes it, so a player (or a StreamingResponse) starts before synthesis ends. "pcm" (the default here) is raw 16-bit mono 24 kHz with no header, the format a streaming player wants; "wav" starts with a header whose sizes are the streamed 0xFFFFFFFF placeholder, since the length is not known up front.

Parameters:

Name Type Description Default
text str

The text to speak.

required
voice str | None

A voice name from :meth:voices.

None
speaker str | None

The same as voice.

None
language str | None

Must stay None; the voice decides the language.

None
response_format SpeechFormat

"pcm" or "wav".

'pcm'

Closing the iterator early (a client that disconnects from a StreamingResponse) closes the daemon connection right away. There is no tracing span here, unlike :meth:synthesize: a span held across yield is closed by whoever finalizes the generator, and a consumer that breaks out of the loop without closing it leaves that to the event loop, in another context -- measured with OpenTelemetry installed, every such stream logged Failed to detach context. A "wav" stream is passed through as the daemon sends it; only :meth:synthesize, which holds the whole clip, can rewrite the header sizes.

Yields:

Name Type Description
bytes AsyncGenerator[bytes, None]

The audio, chunk by chunk.

Raises:

Type Description
ValidationException

Before any request when language is given or voice and speaker disagree; before the first chunk when the daemon refuses with 400.

OllamaError

When the model is not pulled or the daemon fails.

HTTPError

When the daemon cannot be reached or does not answer in time.

synthesize async

synthesize(
    text: str,
    /,
    *,
    voice: str | None = None,
    speaker: str | None = None,
    language: str | None = None,
    response_format: SpeechFormat = "wav",
    out_path: str | Path | None = None,
) -> bytes

Generate speech audio from text.

Parameters:

Name Type Description Default
text str

The text to speak. The daemon rejects empty or blank input and input over 4096 characters with 400.

required
voice str | None

A voice name from :meth:voices (case-insensitive on the daemon). None uses the model's default voice.

None
speaker str | None

The same as voice, under the name :class:~tempest_fastapi_sdk.genai.audio.TextToSpeech and the /tts route use, so this class satisfies :class:~tempest_fastapi_sdk.genai.audio.SpeechSynthesizer.

None
language str | None

Must stay None; the voice decides the language.

None
response_format SpeechFormat

"wav" (16-bit mono 24 kHz with real header sizes) or "pcm" (the same samples, raw little-endian, no header). The daemon refuses other formats.

'wav'
out_path str | Path | None

When given, also write the audio there (exactly the returned bytes, so raw samples for "pcm"); the parent directory must exist. The bytes are returned either way.

None

Returns:

Name Type Description
bytes bytes

The synthesized audio.

Raises:

Type Description
ValidationException

When language is given, when voice and speaker name different voices, or when the daemon refuses the request with 400 (unknown voice, model without speech, empty input or input over 4096 characters).

OllamaError

When the model is not pulled or the daemon fails.

HTTPError

When the daemon cannot be reached or does not answer in time.

transcribe async

transcribe(
    audio: str | Path | bytes,
    /,
    *,
    language: str | None = None,
    prompt: str | None = None,
    temperature: float | None = None,
) -> Transcription

Transcribe speech with a model that has the audio capability.

The daemon sniffs the container itself: MP3 bytes uploaded under a .wav name, and a WAV uploaded with no extension, were both transcribed. Ollama 0.40.13 returns a single segment spanning the whole clip, and no language is reported (see the module docstring).

Parameters:

Name Type Description Default
audio str | Path | bytes

A local file path or the audio bytes. A string is always a path; it is never fetched.

required
language str | None

Must stay None; present so this class satisfies :class:~tempest_fastapi_sdk.genai.audio.SpeechTranscriber.

None
prompt str | None

Must stay None, for the same reason.

None
temperature float | None

Must stay None, for the same reason.

None

Returns:

Name Type Description
Transcription Transcription

The text, the duration the daemon measured, and its segments.

Raises:

Type Description
ValidationException

When language, prompt or temperature is given, or when the daemon refuses the request with 400 (audio that does not decode, model without audio input).

FileNotFoundError

When audio is not an existing regular file. The message carries the file name only, never the full path, since the string may come from a form field.

OllamaError

When the model is not pulled, the daemon fails, or it answers with something other than a JSON object.

HTTPError

When the daemon cannot be reached or does not answer in time.

voices async

voices() -> list[str]

List the voices the model offers, as /api/show reports them.

Returns:

Type Description
list[str]

list[str]: The voice names, in the daemon's order; empty for a model without voices.

Raises:

Type Description
OllamaError

When the daemon rejects the request (model not pulled) or answers with something other than a JSON object.

HTTPError

When the daemon cannot be reached or does not answer in time.

OllamaThinkingUnsupportedError

OllamaThinkingUnsupportedError(model: str, detail: str)

Bases: OllamaError

The model has no thinking capability and the request set think.

The daemon refuses the request with 400 and an error saying the model does not support thinking (reproduced on Ollama 0.30.11 with ministral-3:14b). Leave think as None for that model.

Attributes:

Name Type Description
model str

The model tag the request targeted.

detail str

The daemon's error message.

Build the error from the daemon message.

Parameters:

Name Type Description Default
model str

The model tag the request targeted.

required
detail str

The daemon's error string.

required

OnnxEmbedder

OnnxEmbedder(
    model_path: str,
    *,
    tokenizer: str,
    tokenizer_revision: str | None = None,
    hf_token: str | None = None,
    normalize: bool = False,
    max_length: int = 512,
    providers: list[str] | None = None,
    pooling: Literal["mean", "cls"] = "mean",
    idle_unload_seconds: float | None = None,
)

Torch-free text embedder over ONNX Runtime.

Example:

>>> from tempest_fastapi_sdk.genai import OnnxEmbedder
>>> emb = OnnxEmbedder(
...     "model.onnx",
...     tokenizer="sentence-transformers/all-MiniLM-L6-v2",
...     normalize=True,
... )
>>> vectors = await emb.embed(["hello", "world"])

Attributes:

Name Type Description
model_path str

Path to the exported ONNX model.

normalize bool

Whether embeddings are L2-normalized.

max_length int

Max tokens per text.

pooling Literal['mean', 'cls']

"mean" or "cls".

idle_unload_seconds float | None

Idle threshold for :meth:unload_if_idle.

Configure the embedder (does not load the model yet).

The ONNX graph is already on local disk, so only the tokenizer can come from the Hub — the pinning keywords apply to it alone. tokenizers.Tokenizer.from_pretrained accepts revision and token and nothing else, so there is no offline flag to forward here; point tokenizer at a local tokenizer.json when the host must not reach the network.

Parameters:

Name Type Description Default
model_path str

Path to the ONNX model file.

required
tokenizer str

A HuggingFace tokenizer id (loaded via tokenizers.Tokenizer.from_pretrained) or a path to a tokenizer.json (loaded via from_file).

required
tokenizer_revision str | None

Branch, tag or commit sha for the Hub tokenizer; ignored for a local tokenizer.json.

None
hf_token str | None

Hub token for a gated/private tokenizer.

None
normalize bool

L2-normalize the output vectors.

False
max_length int

Truncate/pad tokenization to this length.

512
providers list[str] | None

ONNX Runtime execution providers; None uses the runtime default (CPU).

None
pooling Literal['mean', 'cls']

How token embeddings become a sentence vector — "mean" (masked mean, what sentence-transformers models such as MiniLM are trained with) or "cls" (the first token, what BGE-style models are trained with). Match the model card; ignored when the graph already outputs a pooled (batch, dim) embedding.

'mean'
idle_unload_seconds float | None

When set, :meth:unload_if_idle drops the session after this many idle seconds, so ModelRegistry.unload_idle frees it like the torch loaders.

None

Raises:

Type Description
ValueError

When pooling is not "mean" or "cls".

is_loaded property

is_loaded: bool

Return True once the session and tokenizer are ready.

seconds_idle property

seconds_idle: float

Return seconds since the session was last in use.

Reads 0.0 while an embedding batch is in flight.

Returns:

Name Type Description
float float

Idle time in seconds.

embed async

embed(texts: str | list[str], *, batch_size: int = 32) -> list[list[float]]

Embed one or many texts into vectors.

Parameters:

Name Type Description Default
texts str | list[str]

A single text or a list.

required
batch_size int

Max texts per ONNX run.

32

Returns:

Type Description
list[list[float]]

list[list[float]]: One vector per input text; empty list for empty

list[list[float]]

input.

load

load() -> None

Load the ONNX session and tokenizer. Idempotent and thread-safe.

unload

unload() -> None

Drop the ONNX session and tokenizer. Safe when not loaded.

Present so the embedder can live in a :class:~tempest_fastapi_sdk.genai.ModelRegistry and be reported by the runtime inventory alongside the torch loaders. The session holds far less than a torch model, but "far less" is not "nothing" on a box running several. While a batch is in flight the release waits for it.

unload_if_idle

unload_if_idle() -> bool

Drop the session when it has been idle past the threshold.

Returns:

Name Type Description
bool bool

True when this call unloaded it, False when it was

bool

already free, still in use, or no idle_unload_seconds was

bool

configured.

OpenAICompatEmbedder

OpenAICompatEmbedder(
    model: str,
    *,
    api_key: str,
    base_url: str = DEFAULT_OPENAI_URL,
    timeout: float = 60.0,
    dimensions: int | None = None,
    extra_headers: dict[str, str] | None = None,
    http_client: HTTPClient | None = None,
    transport: AsyncBaseTransport | None = None,
    retry_policy: RetryPolicy | None = None,
    provider: str = "openai-compatible",
    query_prefix: str = "",
    passage_prefix: str = "",
)

Embeddings over an OpenAI-compatible /embeddings endpoint.

Satisfies :class:~tempest_fastapi_sdk.genai.rag.SupportsEmbed, so it takes the place of :class:~tempest_fastapi_sdk.genai.OllamaEmbedder in a :class:~tempest_fastapi_sdk.genai.rag.Retriever. The request and response shapes are the CreateEmbeddingRequest / CreateEmbeddingResponse schemas of the official OpenAPI document (https://github.com/openai/openai-openapi): input is a list of at most 2048 strings, and each returned item carries its index.

Models trained with task prefixes (nomic-embed-text, the e5 family) embed better when queries and corpus passages are marked apart; pass the model's prefixes (**NOMIC_EMBED_TEXT_PREFIXES) and the RAG stores route queries through :meth:embed_query and indexed text through :meth:embed_passages, exactly as with :class:~tempest_fastapi_sdk.genai.OllamaEmbedder. With the default empty prefixes both are :meth:embed, so nothing changes.

Attributes:

Name Type Description
model str

The embedding model id.

base_url str

API root, without a trailing slash.

dimensions int | None

Requested vector size, for models that accept one.

query_prefix str

Prepended by :meth:embed_query.

passage_prefix str

Prepended by :meth:embed_passages.

Configure the client. No network call happens here.

Parameters:

Name Type Description Default
model str

Embedding model id, e.g. "text-embedding-3-small" (the example the OpenAI spec uses).

required
api_key str

Bearer token. Empty raises here.

required
base_url str

API root; /embeddings is appended.

DEFAULT_OPENAI_URL
timeout float

Per-request HTTP timeout in seconds.

60.0
dimensions int | None

Sent as dimensions when set.

None
extra_headers dict[str, str] | None

Headers added to every request; Authorization always comes from api_key.

None
http_client HTTPClient | None

An injected client; one is created lazily and owned by this instance when None.

None
transport AsyncBaseTransport | None

Transport for the lazily-created client (tests). Ignored with http_client.

None
retry_policy RetryPolicy | None

Retry configuration for the lazily-created client; None uses the HTTPClient defaults.

None
provider str

Label carried by the errors this raises.

'openai-compatible'
query_prefix str

Text prepended to every input of :meth:embed_query; nomic-embed-text wants "search_query: ". :meth:embed never applies it.

''
passage_prefix str

Text prepended to every input of :meth:embed_passages; nomic-embed-text wants "search_document: ".

''

Raises:

Type Description
ValueError

When api_key is empty.

aclose async

aclose() -> None

Close the HTTP client when this instance owns it.

embed async

embed(texts: str | list[str], *, batch_size: int = 256) -> list[list[float]]

Embed one or many texts into vectors.

Parameters:

Name Type Description Default
texts str | list[str]

A single text or a list of texts.

required
batch_size int

Texts per request, at most 2048 (the spec's maxItems for input).

256

Returns:

Type Description
list[list[float]]

list[list[float]]: One vector per input text, in input order —

list[list[float]]

ordered by the returned index, not by arrival. [] for

list[list[float]]

empty input.

Raises:

Type Description
ValueError

When batch_size is outside 1..2048.

HostedAPIError

A typed subclass for any error status.

embed_passages async

embed_passages(texts: str | list[str], *, batch_size: int = 256) -> list[list[float]]

Embed corpus passages, prepending passage_prefix to each one.

The RAG stores call this for the text they index when the embedder has it.

Parameters:

Name Type Description Default
texts str | list[str]

A single passage or a list of passages.

required
batch_size int

Texts per request (see :meth:embed).

256

Returns:

Type Description
list[list[float]]

list[list[float]]: One vector per passage, in input order.

embed_query async

embed_query(texts: str | list[str], *, batch_size: int = 256) -> list[list[float]]

Embed search queries, prepending query_prefix to each one.

The RAG stores call this for the query side when the embedder has it.

Parameters:

Name Type Description Default
texts str | list[str]

A single query or a list of queries.

required
batch_size int

Texts per request (see :meth:embed).

256

Returns:

Type Description
list[list[float]]

list[list[float]]: One vector per query, in input order.

unload

unload() -> None

No-op unload hook, for the registry's Unloadable protocol.

OpenAICompatGenerator

OpenAICompatGenerator(
    model: str,
    *,
    api_key: str,
    base_url: str = DEFAULT_OPENAI_URL,
    timeout: float = 120.0,
    extra_body: dict[str, Any] | None = None,
    extra_headers: dict[str, str] | None = None,
    http_client: HTTPClient | None = None,
    transport: AsyncBaseTransport | None = None,
    retry_policy: RetryPolicy | None = None,
    metrics: GenAIMetrics | None = None,
    forward_params: Iterable[str] = (),
    provider: str = "openai-compatible",
    max_tokens_field: str = "max_tokens",
    structured_output: StructuredOutputMode = "json_schema",
    effort_field: str | None = "reasoning_effort",
    effort_values: Mapping[str, str] | None = None,
    accepts_documents: bool = True,
)

Text generation against any OpenAI-compatible /chat/completions.

Attributes:

Name Type Description
model str

The model name as the provider spells it.

base_url str

API root, without a trailing slash.

Configure the client. No network call happens here.

Parameters:

Name Type Description Default
model str

Model name as the provider spells it ("deepseek-flash", ...).

required
api_key str

Bearer token. Empty raises immediately rather than deferring to a 401 from inside whatever background job makes the first call — the failure is a configuration mistake, and it should surface where the configuration is read.

required
base_url str

API root. Provider-specific; the default points at OpenAI.

DEFAULT_OPENAI_URL
timeout float

Per-request HTTP timeout in seconds.

120.0
extra_body dict[str, Any] | None

Fields merged into every request body, for provider extensions the wire format does not standardize. Merged under the fields this class computes, so it cannot silently replace model or messages.

None
extra_headers dict[str, str] | None

Headers added to every request (an OpenRouter HTTP-Referer, an Azure api-key). Authorization is always set from api_key and cannot be overridden here.

None
http_client HTTPClient | None

An injected client for connection reuse. When None, one is created lazily and owned by this instance, which brings retry with exponential backoff, a per-host circuit-breaker and X-Request-ID propagation.

None
transport AsyncBaseTransport | None

Explicit transport for the lazily-created client — pass an httpx.MockTransport in tests. Ignored when http_client is given.

None
retry_policy RetryPolicy | None

Retry configuration for the lazily-created client. None keeps the HTTPClient defaults but does not retry a read timeout: a retry is a new request, so the provider starts the generation that outlived the timeout again from zero, and the failure would arrive after three timeouts instead of one. A connection error and a retryable status (429, 5xx) are still retried. Ignored when http_client is given.

None
metrics GenAIMetrics | None

Optional Prometheus recorder.

None
forward_params Iterable[str]

HuggingFace-only generation fields (top_k, repetition_penalty, do_sample) this provider accepts under the same name — vLLM's server, for one, documents top_k and repetition_penalty. Empty by default: those fields are dropped, because a strict provider (OpenAI, as reported) refuses the body.

()
provider str

Label carried by the errors this instance raises ("openai", "deepseek", ...), so a log line says which account failed.

'openai-compatible'
max_tokens_field str

Body field that max_new_tokens maps to. "max_tokens" by default, which DeepSeek and most compatible servers read; the OpenAI spec marks max_tokens deprecated in favor of max_completion_tokens, which HostedGenAISettings.openai_kwargs() selects.

'max_tokens'
structured_output StructuredOutputMode

How :meth:chat_structured asks for JSON — "json_schema" (OpenAI) or "json_object" (DeepSeek).

'json_schema'
effort_field str | None

Body field that the effort of :meth:complete_structured goes to. "reasoning_effort" by default, the field the OpenAI spec defines; None drops effort instead of sending it, for a provider that documents no such field (DeepSeek's kwargs in :func:~tempest_fastapi_sdk.genai.hosted_generator).

'reasoning_effort'
effort_values Mapping[str, str] | None

Translation of :data:~tempest_fastapi_sdk.genai.Effort values into the provider's own, for a provider that documents a narrower set (Gemini's GOOGLE_EFFORT_VALUES). None sends the value as given. A value missing from the mapping is sent as given.

None
accepts_documents bool

Whether this provider takes the file content part that :func:~tempest_fastapi_sdk.genai.document_part builds. True by default: the part is sent as is, and a provider that refuses it answers with its own error. False makes every call carrying one raise ValueError before the request is sent — what :func:~tempest_fastapi_sdk.genai.hosted_generator sets for a provider whose documentation describes no PDF input (:func:~tempest_fastapi_sdk.genai.supports_documents).

True

Raises:

Type Description
ValueError

When api_key is empty.

is_loaded property

is_loaded: bool

Return True — the provider owns model residency.

Present for surface-compatibility with TextGenerator.

Returns:

Name Type Description
bool bool

Always True.

aclose async

aclose() -> None

Close the HTTP client when this instance owns it.

An injected client is left open for whoever injected it.

chat async

chat(
    messages: list[dict[str, Any]],
    *,
    config: GenerationConfig | None = None,
    **kwargs: Any,
) -> str

Continue a chat and return the reply.

Parameters:

Name Type Description Default
messages list[dict[str, Any]]

The chat turns, oldest first.

required
config GenerationConfig | None

Typed generation parameters.

None
**kwargs Any

Per-call parameters, winning over config.

{}

Returns:

Name Type Description
str str

The generated reply.

chat_structured async

chat_structured(
    messages: list[dict[str, Any]],
    schema: type[StructuredT],
    *,
    config: GenerationConfig | None = None,
    **kwargs: Any,
) -> StructuredT

Generate a reply constrained to a Pydantic schema.

With structured_output="json_schema" the schema goes out as response_format ({"type": "json_schema", "json_schema": {"name", "schema"}}), named after the model class. strict is left at the spec's default (false): strict mode accepts only a subset of JSON Schema, and a Pydantic model with defaults can fall outside it. With "json_object" the provider is asked for a JSON object and the schema is stated in a trailing system turn — DeepSeek's JSON mode requires the word "json" in the prompt (https://api-docs.deepseek.com/guides/json_mode). Either way the reply is validated here against schema.

Parameters:

Name Type Description Default
messages list[dict[str, Any]]

Chat turns; put the instruction in a system turn and the content in user.

required
schema type[StructuredT]

The Pydantic model to produce.

required
config GenerationConfig | None

Typed generation parameters.

None
**kwargs Any

Per-call parameters, winning over config.

{}

Returns:

Name Type Description
StructuredT StructuredT

The validated instance.

Raises:

Type Description
TypeError

When response_format is passed as a keyword — the schema argument is what sets it.

ValueError

When the reply carries no JSON object (DeepSeek documents that JSON mode can return empty content).

ValidationError

When the JSON fails schema.

chat_with_tools async

chat_with_tools(
    messages: list[dict[str, Any]],
    tools: list[dict[str, Any]],
    *,
    config: GenerationConfig | None = None,
    **kwargs: Any,
) -> dict[str, Any]

Generate a reply that may call tools (the ToolCallingBackend method).

tools is the {"type": "function", "function": {...}} list the :class:~tempest_fastapi_sdk.agents.Agent builds, which is already the wire shape. The reply's tool_calls come back as the provider sent them — arguments a JSON string, per the ChatCompletionMessageToolCall schema of the OpenAI spec — so the assistant turn the agent appends is replayed unchanged on the next call.

Parameters:

Name Type Description Default
messages list[dict[str, Any]]

The conversation so far, including assistant turns with tool_calls and role: tool results.

required
tools list[dict[str, Any]]

Function specs.

required
config GenerationConfig | None

Typed generation parameters.

None
**kwargs Any

Per-call parameters, winning over config (tool_choice, for one).

{}

Returns:

Type Description
dict[str, Any]

dict[str, Any]: ``{"role": "assistant", "content": ,

dict[str, Any]

"tool_calls": [...]}—contentis""`` when the provider

dict[str, Any]

sent null, and tool_calls is [] when it asked for none.

chat_with_usage async

chat_with_usage(
    messages: list[dict[str, Any]],
    *,
    config: GenerationConfig | None = None,
    **kwargs: Any,
) -> tuple[str, TokenUsage | None]

Continue a chat and report what it cost.

Parameters:

Name Type Description Default
messages list[dict[str, Any]]

The chat turns, oldest first.

required
config GenerationConfig | None

Typed generation parameters.

None
**kwargs Any

Per-call parameters, winning over config.

{}

Returns:

Type Description
str

tuple[str, TokenUsage | None]: The reply, and the provider's

TokenUsage | None

reported usage.

complete_structured async

complete_structured(
    messages: list[dict[str, Any]],
    schema: type[StructuredT],
    *,
    effort: Effort | None = None,
    cache_system: bool = False,
    max_tokens: int | None = None,
    config: GenerationConfig | None = None,
    **kwargs: Any,
) -> StructuredCompletion[StructuredT]

Generate a reply constrained to schema and report the outcome.

Builds the request as :meth:chat_structured does, and returns a :class:~tempest_fastapi_sdk.genai.StructuredCompletion instead of raising for an outcome the model produced: a refusal, a reply cut at the budget or a reply that fails schema come back with the usage the call was billed for.

finish_reason is normalized through :data:OPENAI_FINISH_REASONS; a non-null message.refusal (the OpenAI spec's refusal message) is a refusal whatever the finish_reason says.

Parameters:

Name Type Description Default
messages list[dict[str, Any]]

Chat turns; images as :func:~tempest_fastapi_sdk.genai.image_part parts, which go out unchanged.

required
schema type[StructuredT]

The Pydantic model to produce.

required
effort Effort | None

Reasoning effort, sent as effort_field after the effort_values translation; dropped when effort_field is None. None sends nothing.

None
cache_system bool

Accepted for interchangeability with :class:~tempest_fastapi_sdk.genai.AnthropicGenerator and not sent: the OpenAI wire format has no per-message cache marker, and what the provider caches is decided on its side.

False
max_tokens int | None

Output budget, sent as max_tokens_field. None leaves the body without it unless config sets max_new_tokens.

None
config GenerationConfig | None

Typed generation parameters.

None
**kwargs Any

Per-call body fields, winning over config.

{}

Returns:

Type Description
StructuredCompletion[StructuredT]

StructuredCompletion[StructuredT]: The outcome.

Raises:

Type Description
TypeError

When response_format is passed as a keyword.

HostedAPIError

A typed subclass for an error status.

generate async

generate(prompt: str, *, config: GenerationConfig | None = None, **kwargs: Any) -> str

Generate a completion for prompt.

The :class:~tempest_fastapi_sdk.genai.text.TextBackend signature. Use :meth:generate_with_usage when the token counts matter.

Parameters:

Name Type Description Default
prompt str

The input text.

required
config GenerationConfig | None

Typed generation parameters.

None
**kwargs Any

Per-call parameters, winning over config.

{}

Returns:

Name Type Description
str str

The generated text.

generate_with_usage async

generate_with_usage(
    prompt: str,
    *,
    config: GenerationConfig | None = None,
    system: str | None = None,
    **kwargs: Any,
) -> tuple[str, TokenUsage | None]

Generate a completion and report what it cost.

Parameters:

Name Type Description Default
prompt str

The input text.

required
config GenerationConfig | None

Typed generation parameters.

None
system str | None

A system turn placed before the prompt. Worth using for long instructions: an instruction pasted on top of a long document competes with it for attention, while a system turn does not.

None
**kwargs Any

Per-call parameters, winning over config.

{}

Returns:

Type Description
str

tuple[str, TokenUsage | None]: The text, and the provider's

TokenUsage | None

reported usage — None when the response carried none.

load

load() -> None

No-op load hook, for surface-compatibility with TextGenerator.

stream async

stream(
    prompt: str, *, config: GenerationConfig | None = None, **kwargs: Any
) -> AsyncIterator[str]

Stream a completion piece by piece.

Parameters:

Name Type Description Default
prompt str

The input text.

required
config GenerationConfig | None

Typed generation parameters.

None
**kwargs Any

Per-call parameters, winning over config.

{}

Yields:

Name Type Description
str AsyncIterator[str]

Content deltas, in order.

Raises:

Type Description
HostedAPIError

A typed subclass when the stream cannot be opened (bad key, rate limit, outage).

stream_chat async

stream_chat(
    messages: list[dict[str, Any]],
    *,
    config: GenerationConfig | None = None,
    **kwargs: Any,
) -> AsyncIterator[str]

Stream the reply to a chat messages list piece by piece.

The streaming counterpart of :meth:chat: the whole conversation goes out as messages with stream: true, so the system turn keeps its role. Turns are normalized like :meth:chat's (tool-call history, document parts).

Parameters:

Name Type Description Default
messages list[dict[str, Any]]

The chat turns, oldest first.

required
config GenerationConfig | None

Typed generation parameters.

None
**kwargs Any

Per-call parameters, winning over config.

{}

Yields:

Name Type Description
str AsyncIterator[str]

Content deltas, in order.

Raises:

Type Description
HostedAPIError

A typed subclass when the stream cannot be opened (bad key, rate limit, outage).

stream_chat_with_tools async

stream_chat_with_tools(
    messages: list[dict[str, Any]],
    tools: list[Any],
    *,
    config: GenerationConfig | None = None,
    **kwargs: Any,
) -> AsyncIterator[ChatStreamEvent]

Stream one generation with tools attached (ToolStreamingBackend).

chat/completions with stream: true and tools. Each delta.content is yielded as a :class:~tempest_fastapi_sdk.genai.StreamTextDelta; the delta.tool_calls fragments are merged by index — id, type and function.name taken from the first fragment that carries them, function.arguments concatenated, as the OpenAI spec streams them — and yielded once at the end as :class:~tempest_fastapi_sdk.genai.StreamToolCalls, in the shape :meth:chat_with_tools returns (arguments a JSON string).

Parameters:

Name Type Description Default
messages list[dict[str, Any]]

The conversation so far, normalized like :meth:chat_with_tools's.

required
tools list[Any]

Function specs.

required
config GenerationConfig | None

Typed generation parameters.

None
**kwargs Any

Per-call parameters, winning over config.

{}

Yields:

Name Type Description
ChatStreamEvent AsyncIterator[ChatStreamEvent]

Text deltas, then the tool calls when the model

AsyncIterator[ChatStreamEvent]

asked for any.

Raises:

Type Description
HostedAPIError

A typed subclass when the stream cannot be opened (bad key, rate limit, outage).

OpenAICompatSpeech

OpenAICompatSpeech(
    model: str,
    *,
    api_key: str,
    base_url: str = DEFAULT_OPENAI_URL,
    speech_model: str = DEFAULT_SPEECH_MODEL,
    timeout: float = 300.0,
    extra_headers: dict[str, str] | None = None,
    http_client: HTTPClient | None = None,
    transport: AsyncBaseTransport | None = None,
    retry_policy: RetryPolicy | None = None,
    provider: str = "openai-compatible",
)

Speech against any OpenAI-compatible /audio endpoints.

Satisfies :class:~tempest_fastapi_sdk.genai.audio.SpeechTranscriber and :class:~tempest_fastapi_sdk.genai.audio.SpeechSynthesizer, so it backs /transcribe and /tts in :func:~tempest_fastapi_sdk.genai.make_genai_router and replaces a local :class:~tempest_fastapi_sdk.genai.audio.SpeechToText or :class:~tempest_fastapi_sdk.genai.audio.TextToSpeech.

Attributes:

Name Type Description
model str

The transcription model id the server serves.

speech_model str

The speech (TTS) model id sent by :meth:synthesize.

base_url str

API root, without a trailing slash.

timeout float

Per-request HTTP timeout in seconds.

provider str

Label carried by the errors this instance raises.

Configure the client. No network call happens here.

Parameters:

Name Type Description Default
model str

Transcription model id. A server that serves one model (tempest-ai lists it on GET {base_url}/models) refuses any other.

required
api_key str

Bearer token. Empty raises immediately, where the configuration is read, instead of as a 401 from the first request.

required
base_url str

API root including the version segment; /audio/transcriptions and /audio/speech are appended. The default points at OpenAI.

DEFAULT_OPENAI_URL
speech_model str

The model :meth:synthesize sends. "default" asks tempest-ai for whatever TTS model it serves; OpenAI needs a real id such as tts-1.

DEFAULT_SPEECH_MODEL
timeout float

Per-request HTTP timeout in seconds. Higher than the generator's default because the server decodes the whole clip before it answers.

300.0
extra_headers dict[str, str] | None

Headers added to every request. Authorization is always set from api_key and cannot be overridden here.

None
http_client HTTPClient | None

An injected client for connection reuse. When None, one is created lazily and owned by this instance.

None
transport AsyncBaseTransport | None

Explicit transport for the lazily-created client — pass an httpx.MockTransport in tests. Ignored when http_client is given.

None
retry_policy RetryPolicy | None

Retry configuration for the lazily-created client. None keeps the HTTPClient defaults but does not retry a read timeout, as in :class:~tempest_fastapi_sdk.genai.OpenAICompatGenerator: a retry uploads the audio again and the server transcribes it again from zero. A connection error and a retryable status (429, 5xx) are still retried. Ignored when http_client is given.

None
provider str

Label carried by the errors this instance raises, so a log line says which account failed.

'openai-compatible'

Raises:

Type Description
ValueError

When api_key is empty.

aclose async

aclose() -> None

Close the HTTP client when this instance owns it.

An injected client is left open for whoever injected it.

synthesize async

synthesize(
    text: str,
    /,
    *,
    voice: str | None = None,
    speaker: str | None = None,
    language: LanguageEnum | str | None = None,
    speaker_wav: str | Path | bytes | None = None,
    response_format: str = SPEECH_RESPONSE_FORMAT,
    out_path: str | Path | None = None,
) -> bytes

Synthesize text on the remote server.

Parameters:

Name Type Description Default
text str

The text to speak. Length limits are the server's.

required
voice str | None

The server's voice or speaker name. None lets the server pick its default (the field is not sent).

None
speaker str | None

The same as voice, under the name :class:~tempest_fastapi_sdk.genai.audio.TextToSpeech uses, so this class satisfies :class:~tempest_fastapi_sdk.genai.audio.SpeechSynthesizer.

None
language LanguageEnum | str | None

Sent as the language extension field: a :class:~tempest_fastapi_sdk.genai.audio.LanguageEnum member resolves to its ISO-639-1 code ("pt", the code XTTS v2 takes too), a raw string ("zh-cn") is sent as given, None leaves the field out. The preset's tts_language is not used: it describes the local single-language default model (None), not a remote multilingual one.

None
speaker_wav str | Path | bytes | None

A clip to clone the voice from — the bytes, or a local file path (a string is always a path; it is never fetched). Sent base64-encoded as the reference_audio extension field; None leaves it out.

None
response_format str

The audio format asked for. tempest-ai serves only "wav".

SPEECH_RESPONSE_FORMAT
out_path str | Path | None

When given, also write the returned bytes there; the parent directory must exist.

None

Returns:

Name Type Description
bytes bytes

The audio the server answered, unchanged.

Raises:

Type Description
ValueError

When voice and speaker are both given and differ, or the success response carries no audio.

FileNotFoundError

When speaker_wav is a path that is not an existing regular file. The message carries the file name only, never the full path.

FileTooLargeException

When the server answers 413.

ValidationException

When the server answers 400 or 422 (blank text, a voice or language it does not serve, a clip it cannot decode).

HostedAPIError

A typed subclass for any other error status.

HTTPError

When the server cannot be reached or does not answer in time.

synthesize_stream async

synthesize_stream(
    text: str,
    /,
    *,
    voice: str | None = None,
    speaker: str | None = None,
    language: LanguageEnum | str | None = None,
    speaker_wav: str | Path | bytes | None = None,
) -> AsyncIterator[bytes]

Stream text from the remote server as 24 kHz 16-bit mono PCM.

Sends the same body as :meth:synthesize with response_format: "pcm" and stream_format: "audio", and hands out the body as the server flushes it -- a player starts on the first piece instead of waiting for the whole clip. Every piece holds whole samples: a byte a read split off a sample is held for the next piece. Satisfies :class:~tempest_fastapi_sdk.genai.audio.StreamingSpeechSynthesizer.

Parameters:

Name Type Description Default
text str

The text to speak.

required
voice str | None

The server's voice or speaker name.

None
speaker str | None

The same as voice.

None
language LanguageEnum | str | None

As in :meth:synthesize.

None
speaker_wav str | Path | bytes | None

As in :meth:synthesize.

None

Yields:

Name Type Description
bytes AsyncIterator[bytes]

PCM pieces, in order.

Raises:

Type Description
ValueError

When voice and speaker differ.

FileNotFoundError

When speaker_wav is a missing path.

FileTooLargeException

When the server answers 413.

ValidationException

When the server answers 400 or 422.

HostedAPIError

A typed subclass for any other error status.

HTTPError

When the server cannot be reached.

All the errors above are raised before the first piece: a status error is read when the stream opens.

transcribe async

transcribe(
    audio: bytes | str | Path,
    /,
    *,
    language: LanguageEnum | str | None = None,
    with_segments: bool = True,
    with_words: bool = False,
    prompt: str | None = None,
    temperature: float | None = None,
) -> Transcription

Transcribe audio on the remote server.

Parameters:

Name Type Description Default
audio bytes | str | Path

The audio bytes, or a local file path. A string is always a path; it is never fetched.

required
language LanguageEnum | str | None

Force the language — a :class:~tempest_fastapi_sdk.genai.audio.LanguageEnum member (resolved to its Whisper code, "pt"), a raw ISO-639-1 code, or None to let the server detect it (the field is then not sent).

None
with_segments bool

Keep the per-span timestamps. False returns segments=[]; duration and language are still filled. Without with_words the request is the same either way.

True
with_words bool

Ask for per-word timestamps. True sends timestamp_granularities[]=word — plus timestamp_granularities[]=segment when with_segments holds, since OpenAI answers only the granularities named and would otherwise leave segments out — and fills words from the response's words. probability is read when the server sends it (tempest-ai does) and None otherwise; word is stripped of surrounding whitespace. False (the default) sends no granularity field and returns words=[]. A server that cannot time words may refuse the field (ValidationException).

False
prompt str | None

Sent as the prompt form field: text the model reads as preceding the audio, the way to hand it the vocabulary of the domain (city names, product names). None leaves the field out. Whisper keeps only the end of a long prompt (the recipe has the numbers), and whether a given server honours the field is up to that server.

None
temperature float | None

Sent as the temperature form field. None leaves the field out and the server picks.

None

Returns:

Name Type Description
Transcription Transcription

text and duration from the response,

Transcription

language from the response's language field (unchanged)

Transcription

or, when the response has none, the requested code ("" when

Transcription

nothing was requested), and the segments. language_probability

Transcription

stays 0.0: the wire format does not carry it.

Raises:

Type Description
FileNotFoundError

When audio is a path that is not an existing regular file. The message carries the file name only, never the full path, since the string may come from a form field.

FileTooLargeException

When the server answers 413.

ValidationException

When the server answers 400 or 422.

HostedAPIError

A typed subclass for any other error status (HostedAuthenticationError for 401/403).

ValueError

When a success response is not a JSON object.

HTTPError

When the server cannot be reached or does not answer in time.

RedisEmbeddingCache

RedisEmbeddingCache(
    redis: Redis, *, prefix: str = "genai:emb:", ttl_seconds: int | None = None
)

A Redis-backed embedding cache shared across workers/processes.

Vectors are stored as JSON under "<prefix><key>". Satisfies :class:AsyncEmbeddingCache, so it drops into :class:Embedder exactly where :class:InMemoryEmbeddingCache goes — the difference is that every worker hits the same store, so a vector computed by one request is reused by the next, on any worker.

Example:

>>> from redis.asyncio import Redis
>>> cache = RedisEmbeddingCache(Redis.from_url("redis://localhost"))
>>> emb = Embedder("sentence-transformers/all-MiniLM-L6-v2", cache=cache)

Attributes:

Name Type Description
prefix str

Key prefix applied to every stored vector.

ttl_seconds int | None

Optional per-entry expiry (seconds).

Initialize the cache over an async Redis client.

Parameters:

Name Type Description Default
redis Redis

An redis.asyncio.Redis client (from the [cache] extra). Injected so the caller owns its lifecycle and configuration.

required
prefix str

Key prefix for stored vectors.

'genai:emb:'
ttl_seconds int | None

Optional expiry per entry; None keeps vectors until evicted by Redis.

None

get async

get(key: str) -> list[float] | None

Return the cached vector for key, or None on a miss.

Parameters:

Name Type Description Default
key str

The cache key.

required

Returns:

Type Description
list[float] | None

list[float] | None: The stored vector, or None.

set async

set(key: str, value: list[float]) -> None

Store value under key (with the optional TTL).

Parameters:

Name Type Description Default
key str

The cache key.

required
value list[float]

The vector to store.

required

RedisGenerationCache

RedisGenerationCache(
    redis: Redis, *, namespace: str = "genai:gen:", ttl_seconds: int | None = None
)

A Redis-backed async cache — completions shared across workers.

Example:

>>> from redis.asyncio import Redis
>>> cache = RedisGenerationCache(Redis.from_url("redis://localhost"))

Attributes:

Name Type Description
namespace str

Key prefix in Redis.

ttl_seconds int | None

Optional expiry per entry.

Initialize the cache.

Parameters:

Name Type Description Default
redis Redis

An redis.asyncio.Redis client.

required
namespace str

Prefix prepended to every key.

'genai:gen:'
ttl_seconds int | None

Per-entry TTL, or None for no expiry.

None

get async

get(key: str) -> str | None

Return the cached completion for key or None.

Parameters:

Name Type Description Default
key str

Cache key derived from the prompt and generation settings.

required

Returns:

Type Description
str | None

str | None: The cached completion, or None on a miss.

set async

set(key: str, value: str) -> None

Store value under key (with the configured TTL).

Parameters:

Name Type Description Default
key str

Cache key derived from the prompt and generation settings.

required
value str

The completion to store.

required

RerankerModelEnum

Bases: StrEnum

Cross-encoders for Reranker, the second stage of retrieval.

Member Use it when
MS_MARCO_MINILM_L6_V2 English, small and fast — the usual pick.
BGE_RERANKER_V2_M3 Multilingual, including PT-BR; heavier and better.

RuleModerator

RuleModerator(blocklist: list[str], *, category: str = 'blocked')

A dependency-free block-list moderator.

Flags text containing any block-listed term as a whole word, case-insensitively. Before matching, both the terms and the text are NFKC-normalized, stripped of format characters (zero-width and bidi controls) and casefolded, so a zero-width space (U+200B) inside the word or its fullwidth spelling (U+FF53 U+FF45 ...) still hits "secret". Whole-word means "not glued to a word character on either side" (lookarounds, not \b), which is what makes terms that start or end with punctuation — "$hit", "c++" — match at all. Predictable and fast — the deterministic default when a classifier's quality (especially in PT-BR) can't be trusted. Homoglyphs from other scripts (Cyrillic U+0435 standing in for Latin "e") are not folded; list those spellings explicitly.

Attributes:

Name Type Description
category str

The category label reported on a match.

Initialize the moderator.

Parameters:

Name Type Description Default
blocklist list[str]

Terms that flag the text (whole-word, case-insensitive, normalized as described on the class). Terms that normalize to an empty string are ignored.

required
category str

The category label reported on a match.

'blocked'

check async

check(text: str) -> ModerationResult

Flag text when it contains a block-listed term.

Parameters:

Name Type Description Default
text str

The text to screen.

required

Returns:

Name Type Description
ModerationResult ModerationResult

flagged=True (score 1.0) on any match.

ServiceUsage dataclass

ServiceUsage(service: str | None, total_tokens: int, share: float)

One service's share of a window.

Attributes:

Name Type Description
service str | None

The capability.

total_tokens int

Tokens it spent.

share float

Percentage of the window's tokens, to one decimal.

SpeechToTextModelEnum

Bases: StrEnum

Whisper sizes for SpeechToText (faster-whisper names, not Hub ids).

Member Use it when
TINY Smoke tests; misses accents and numbers.
BASE The default — usable PT-BR on CPU.
SMALL Noticeably better on noisy audio.
MEDIUM Interviews, calls, where the transcript is the product.
LARGE_V3 Best accuracy; GPU or a lot of patience.

StreamTextDelta dataclass

StreamTextDelta(text: str)

A piece of the reply text, as the model produced it.

Attributes:

Name Type Description
text str

The piece; never empty.

StreamToolCalls dataclass

StreamToolCalls(calls: list[dict[str, Any]] = list())

The tools the model asked for, closing one generation.

Attributes:

Name Type Description
calls list[dict[str, Any]]

The calls in the shape the same backend's chat_with_tools returns in tool_calls: {"function": {"name": str, "arguments": ...}}, plus id and type when the provider sends them. arguments is a dict on Ollama and a JSON string on the OpenAI wire; the pipeline accepts both.

StructuredCompletion dataclass

StructuredCompletion(
    output: StructuredT | None,
    text: str,
    usage: TokenUsage | None,
    stop_reason: StopReason,
    provider_stop_reason: str | None,
    error: ValueError | None = None,
)

Bases: Generic[StructuredT]

The outcome of one complete_structured call.

Attributes:

Name Type Description
output StructuredT | None

The validated instance, or None when the model did not stop naturally or its reply failed the schema.

text str

The reply text as received, "" when there was none.

usage TokenUsage | None

What the provider reported the call cost, present whatever the outcome; None only when the response carried no usage.

stop_reason StopReason

Why the model stopped, normalized.

provider_stop_reason str | None

The provider's own value (end_turn, length...), for logs and for values :data:StopReason folds into other.

error ValueError | None

Why output is None after a natural stop: a reply with no JSON object (ValueError) or one that failed the schema (pydantic.ValidationError, a ValueError subclass). None when the output parsed, and when the stop was not natural — stop_reason already says why.

ok property

ok: bool

Whether the call produced a validated instance.

Returns:

Name Type Description
bool bool

True when :attr:output is set.

StructuredCompletionBackend

Bases: Protocol

A hosted backend that returns a :class:StructuredCompletion.

Both :class:~tempest_fastapi_sdk.genai.AnthropicGenerator and :class:~tempest_fastapi_sdk.genai.OpenAICompatGenerator implement it, and :func:~tempest_fastapi_sdk.genai.hosted_generator returns one of them — so a service typed against this protocol changes provider by changing the model id.

complete_structured async

complete_structured(
    messages: list[dict[str, Any]],
    schema: type[StructuredT],
    *,
    effort: Effort | None = ...,
    cache_system: bool = ...,
    max_tokens: int | None = ...,
    config: GenerationConfig | None = ...,
    **kwargs: Any,
) -> StructuredCompletion[StructuredT]

Generate a reply constrained to schema and report the outcome.

Parameters:

Name Type Description Default
messages list[dict[str, Any]]

Chat turns; images as :func:image_part and PDFs as :func:document_part content parts.

required
schema type[StructuredT]

The Pydantic model to produce.

required
effort Effort | None

Reasoning effort, or None for the provider default.

...
cache_system bool

Ask the provider to cache the system turn.

...
max_tokens int | None

Output budget for this call.

...
config GenerationConfig | None

Typed generation parameters.

...
**kwargs Any

Per-call body fields.

{}

Returns:

Type Description
StructuredCompletion[StructuredT]

StructuredCompletion[StructuredT]: The outcome.

StructuredFormatError

StructuredFormatError(attempts: int, last_output: str)

Bases: ValueError

The model never produced a usable JSON array within the attempt budget.

Subclasses ValueError so code already catching that keeps working.

Attributes:

Name Type Description
attempts int

How many generations were spent.

last_output str

The final raw completion, truncated, so the log line says what the model actually wrote instead of only that it was wrong.

Build the error.

Parameters:

Name Type Description Default
attempts int

Generations spent.

required
last_output str

The final raw completion.

required

StructuredTextBackend

Bases: Protocol

A backend that answers with a validated schema instead of prose.

Both :class:TextGenerator and :class:~tempest_fastapi_sdk.genai.ollama.OllamaGenerator implement it, which is the point: a service that reads documents into schemas can be typed against this and run on a local model or on a daemon without a line changing at the call site. The messages list rather than a prompt string is part of the contract — extraction quality depends on the instruction sitting in its own system turn.

chat_structured async

chat_structured(
    messages: list[dict[str, Any]],
    schema: type[StructuredT],
    *,
    config: GenerationConfig | None = ...,
    **kwargs: Any,
) -> StructuredT

Return a reply validated against schema.

Parameters:

Name Type Description Default
messages list[dict[str, Any]]

Chat turns, each {"role": ..., "content": ...}.

required
schema type[StructuredT]

The Pydantic model to produce.

required
config GenerationConfig | None

Generation parameters.

...
**kwargs Any

Extra generation parameters.

{}

Returns:

Name Type Description
StructuredT StructuredT

The validated instance.

StructuredTokenizer

Bases: Protocol

Minimal tokenizer surface used by :func:build_prefix_allowed_tokens_fn.

Satisfied by HuggingFace PreTrainedTokenizerBase and lightweight test doubles without importing transformers at module load time.

all_special_ids property

all_special_ids: Iterable[int]

Vocabulary ids reserved for special tokens.

eos_token_id property

eos_token_id: int | None

Token id marking end of sequence, or None.

decode

decode(token_ids: list[int]) -> str | Sequence[str]

Decode vocabulary token ids back to text.

encode

encode(text: str) -> Sequence[int]

Encode text into vocabulary token ids.

SubjectUsage dataclass

SubjectUsage(subject_id: UUID | None, total_tokens: int)

One subject's consumption in a window.

Attributes:

Name Type Description
subject_id UUID | None

Who.

total_tokens int

Tokens they spent.

SupportsAudioGeneration

Bases: Protocol

Anything that turns a prompt into :class:GeneratedAudio clips.

The shape POST /audio on make_genai_router calls. Satisfied by :class:AudioGenerator (diffusion) and :class:~tempest_fastapi_sdk.genai.MusicGenerator (MusicGen).

generate

generate(
    prompt: str, /, *, config: AudioGenerationConfig | None = None
) -> Awaitable[list[GeneratedAudio]]

Generate clips for prompt.

Parameters:

Name Type Description Default
prompt str

The sound or music to generate.

required
config AudioGenerationConfig | None

Length, guidance, seed and count; None for the model's defaults.

None

Returns:

Type Description
Awaitable[list[GeneratedAudio]]

Awaitable[list[GeneratedAudio]]: The clips.

TextBackend

Bases: Protocol

The text-generation surface consumers depend on.

Both the torch/transformers :class:~tempest_fastapi_sdk.genai.text.TextGenerator and the :class:~tempest_fastapi_sdk.genai.ollama.OllamaGenerator implement this protocol, so either can be handed to :func:~tempest_fastapi_sdk.genai.make_genai_router as the text backend. Implement these three methods to plug in any other engine (vLLM, TGI, a hosted API, …).

chat async

chat(
    messages: list[dict[str, str]],
    *,
    config: GenerationConfig | None = ...,
    **kwargs: Any,
) -> str

Return a reply for a chat messages list.

Parameters:

Name Type Description Default
messages list[dict[str, str]]

The chat turns, oldest first.

required
config GenerationConfig | None

Generation parameters; None uses the defaults.

...
**kwargs Any

Extra generation parameters, overriding config.

{}

Returns:

Name Type Description
str str

The generated completion.

generate async

generate(prompt: str, *, config: GenerationConfig | None = ..., **kwargs: Any) -> str

Return a completion for prompt.

stream

stream(
    prompt: str, *, config: GenerationConfig | None = ..., **kwargs: Any
) -> AsyncIterator[str]

Stream a completion for prompt piece by piece.

Parameters:

Name Type Description Default
prompt str

The prompt to complete.

required
config GenerationConfig | None

Generation parameters; None uses the defaults.

...
**kwargs Any

Extra generation parameters, overriding config.

{}

Returns:

Type Description
AsyncIterator[str]

AsyncIterator[str]: The completion, streamed token by token.

TextGenerator

TextGenerator(
    model_id: str,
    *,
    device: str = "auto",
    dtype: str | ModelDtypeEnum = "auto",
    quantization: str | ModelDtypeEnum | None = None,
    cache_dir: str | None = None,
    hf_token: str | None = None,
    revision: str | None = None,
    local_files_only: bool | None = None,
    trust_remote_code: bool = False,
    idle_unload_seconds: float | None = None,
    hardware: HardwareInfo | None = None,
    generation_cache: GenerationCache | AsyncGenerationCache | None = None,
    metrics: GenAIMetrics | None = None,
    config: GenerationConfig | None = None,
    max_concurrent: int | None = None,
)

A lazily-loaded local causal LM with streaming and idle unload.

Example:

>>> gen = TextGenerator("Qwen/Qwen2.5-7B-Instruct", quantization="int4")
>>> await gen.generate("Explain PIX in one sentence.")
>>> async for token in gen.stream("..."):
...     ...
>>> gen.unload()   # free VRAM

Attributes:

Name Type Description
model_id str

The HuggingFace model id.

device str

The resolved device (cuda / mps / cpu).

dtype ModelDtypeEnum

The resolved compute precision.

quantization ModelDtypeEnum | None

int8/int4 when quantized.

source ModelRef

The resolved weight identity (id, revision, cache, token, offline/remote-code flags) forwarded to every from_pretrained call.

idle_unload_seconds float | None

Idle threshold used by :meth:unload_if_idle.

config GenerationConfig | None

Default generation parameters, layered under every call's own.

max_concurrent int | None

How many decodings run at once, or None for no limit.

Configure the generator (does not load weights yet).

Parameters:

Name Type Description Default
model_id str

HuggingFace model id.

required
device str

"auto" (default) / "cuda" / "mps" / "cpu".

'auto'
dtype str | ModelDtypeEnum

Compute precision, or "auto" (bf16 on GPU, fp32 on CPU).

'auto'
quantization str | ModelDtypeEnum | None

"int8" / "int4" to quantize (needs [genai-quant]), or None.

None
cache_dir str | None

Where the downloaded weights are written and read back from. None uses the huggingface_hub default — $HF_HOME/hub, or ~/.cache/huggingface/hub when HF_HOME is unset — which is why the second run of a script starts instantly instead of downloading again. Point it at a mounted volume when the process is a container, so the layer does not re-download the model on every restart.

None
hf_token str | None

Hub token for gated or private repositories. None falls back to HF_TOKEN in the environment; without either, anonymous downloads work but are rate-limited (the Hub says so on stderr).

None
revision str | None

Branch, tag or commit sha to load. None follows the Hub default, which moves when the author pushes; pin a sha (see :func:~tempest_fastapi_sdk.genai.resolve_revision) for a reproducible deployment.

None
local_files_only bool | None

Load from the cache without touching the network — what an air-gapped or deploy-frozen host wants. None (the default) takes GENAI_OFFLINE from the environment; passing the argument overrides it.

None
trust_remote_code bool

Allow the repository's own Python to run at load time. Required by some architectures, and it executes code you did not review, so it stays opt-in.

False
idle_unload_seconds float | None

When set, :meth:unload_if_idle frees the model after this many idle seconds.

None
hardware HardwareInfo | None

Injected snapshot for device resolution (tests); probed when None.

None
generation_cache GenerationCache | AsyncGenerationCache | None

Optional prompt→completion cache. Only deterministic generations (do_sample=False / temperature=0) are cached; sampling calls always run the model.

None
metrics GenAIMetrics | None

Optional Prometheus metrics; when set, generate / chat record request count and latency (op "generate" / "chat").

None
config GenerationConfig | None

Default generation parameters for every call. A call's own config is layered over it field by field, and its keyword overrides win over both. This is how a caller that passes no options — the :class:~tempest_fastapi_sdk.agents.Agent loop — still gets a bounded max_new_tokens or greedy decoding.

None
max_concurrent int | None

Decodings this instance runs at once; the rest wait their turn, in arrival order. None (the default) starts every call immediately, each on its own worker thread. On CPU, set 1: one decode already uses every intra-op thread, so concurrent calls only split the cores. Measured with Qwen/Qwen2.5-0.5B-Instruct, four concurrent calls, 128 forced tokens: 22.4 tokens/s and a 22.73 s median latency with no limit, 26.9 tokens/s and 11.91 s with 1. The default stays None because the gain was measured on CPU only. Decoding runs on a pool of this many threads owned by the generator, never on the loop's default executor: torch's OpenMP keeps one worker team per calling thread, and a semaphore over the shared executor measured 18.5 tokens/s on the same load, slower than no limit at all. Process-wide thread count is torch's (torch.set_num_threads) and is deliberately not a knob here.

None

Raises:

Type Description
ValueError

When quantization is not int8/int4, or max_concurrent is not positive.

is_loaded property

is_loaded: bool

Return True once the weights are in memory.

Returns:

Name Type Description
bool bool

Whether :meth:load has run without a later :meth:unload.

seconds_idle property

seconds_idle: float

Return seconds since the model was last in use.

A generation in flight counts as use for its whole duration, so this reads 0.0 while one runs — a long generation is never mistaken for an idle model.

Returns:

Name Type Description
float float

Idle time in seconds.

chat async

chat(
    messages: list[dict[str, str]],
    *,
    config: GenerationConfig | None = None,
    stop_event: Event | None = None,
    **kwargs: Any,
) -> str

Generate a reply for a chat messages list.

Applies the tokenizer's chat template (roles system / user / assistant) before generating. Honors the generation cache (deterministic calls) and metrics like :meth:generate.

Parameters:

Name Type Description Default
messages list[dict[str, str]]

Chat turns, each {"role": ..., "content": ...}.

required
config GenerationConfig | None

Typed generation parameters.

None
stop_event Event | None

Set it to stop decoding at the next token. Cancelling the call sets it too.

None
**kwargs Any

Generation overrides (win over config).

{}

Returns:

Name Type Description
str str

The assistant reply.

Raises:

Type Description
GenerationStoppedError

When stop_event was set mid-flight.

chat_structured async

chat_structured(
    messages: list[dict[str, Any]],
    schema: type[StructuredT],
    *,
    config: GenerationConfig | None = None,
    constrained: bool = True,
    stop_event: Event | None = None,
    **kwargs: Any,
) -> StructuredT

Generate a chat reply constrained to a Pydantic schema.

The same call :meth:~tempest_fastapi_sdk.genai.ollama.OllamaGenerator.chat_structured answers, so a service that reads documents into schemas runs on a local model or on a daemon without a line changing at the call site — see :class:StructuredTextBackend. The turns matter: concatenating a long instruction ahead of a long document makes a model start answering with the document, while the same instruction in its own system turn is respected. Sharing that contract across backends is what makes the two swappable in practice rather than only in type.

Where the two differ is how the schema is enforced. The daemon takes a JSON schema and constrains decoding itself; here the constraint is a lm-format-enforcer token filter ([genai-structured] extra), and both paths end in the same :func:~tempest_fastapi_sdk.genai.structured.parse_structured.

Parameters:

Name Type Description Default
messages list[dict[str, Any]]

Chat turns, each {"role": ..., "content": ...}. Put the instruction in a system turn and the content being read in user.

required
schema type[StructuredT]

The Pydantic model to produce.

required
config GenerationConfig | None

Typed generation parameters.

None
constrained bool

Enforce the schema during decoding (needs the [genai-structured] extra) or only parse afterwards.

True
stop_event Event | None

Set it to stop decoding at the next token. Cancelling the call sets it too.

None
**kwargs Any

Generation overrides (win over config).

{}

Returns:

Name Type Description
StructuredT StructuredT

The validated instance.

Raises:

Type Description
ImportError

When constrained is True and the [genai-structured] extra is missing.

ValueError

When the output carries no JSON object.

GenerationStoppedError

When stop_event was set mid-flight.

ValidationError

When the JSON fails schema validation.

chat_with_tools async

chat_with_tools(
    messages: list[dict[str, Any]],
    tools: list[dict[str, Any]],
    *,
    config: GenerationConfig | None = None,
    stop_event: Event | None = None,
    **kwargs: Any,
) -> dict[str, Any]

Generate a chat reply with tool-calling enabled.

Renders the tokenizer's chat template with the tool specs (transformers

= 4.44 apply_chat_template(tools=...)), generates, then parses any tool call the model emitted out of the completion. The return shape mirrors :meth:OllamaGenerator.chat_with_tools, so the same :class:~tempest_fastapi_sdk.genai.pipeline.AIChatPipeline tool loop drives either backend.

Parameters:

Name Type Description Default
messages list[dict[str, Any]]

Chat turns (a turn may carry tool_calls or be a {"role": "tool", ...} result).

required
tools list[dict[str, Any]]

Tool specs in the {"type": "function", "function": {...}} shape (as produced by :meth:~tempest_fastapi_sdk.genai.pipeline.Tool.to_spec).

required
config GenerationConfig | None

Typed generation parameters.

None
stop_event Event | None

Set it to stop decoding at the next token. Cancelling the call sets it too.

None
**kwargs Any

Generation overrides (win over config).

{}

Returns:

Type Description
dict[str, Any]

dict[str, Any]: {"content": str, "tool_calls": list} where each

dict[str, Any]

call has the {"function": {"name", "arguments"}} shape;

dict[str, Any]

tool_calls is empty when the model returned plain text.

generate async

generate(
    prompt: str,
    *,
    config: GenerationConfig | None = None,
    stop_event: Event | None = None,
    **kwargs: Any,
) -> str

Generate a completion for prompt.

Runs the blocking model in a worker thread so the event loop stays free. A thread cannot be interrupted, so cancelling the coroutine that awaits this (a timeout, a client that went away) sets the stop event the model checks after every token — the caller's stop_event when one was passed — and decoding ends within one token instead of running to max_new_tokens for nobody.

Parameters:

Name Type Description Default
prompt str

The input text.

required
config GenerationConfig | None

Typed generation parameters; its set fields layer over the defaults.

None
stop_event Event | None

Set it to stop decoding at the next token. Cancelling the call sets it too, so a timeout stops the model instead of only the wait.

None
**kwargs Any

Generation overrides (max_new_tokens, temperature, top_p, …) forwarded to model.generate; these win over config.

{}

Returns:

Name Type Description
str str

The generated text (prompt stripped).

Raises:

Type Description
GenerationStoppedError

When stop_event was set mid-flight.

generate_structured async

generate_structured(
    prompt: str,
    schema: type[StructuredT],
    *,
    config: GenerationConfig | None = None,
    constrained: bool = True,
    stop_event: Event | None = None,
    **kwargs: Any,
) -> StructuredT

Generate a completion constrained to a Pydantic schema.

When constrained is True (default) the generation is bound by a lm-format-enforcer token filter ([genai-structured] extra) so the model can only emit schema-valid JSON; the result is then parsed into an instance of schema. Set constrained=False for best-effort parsing without the extra (the model may still stray, in which case parsing raises).

Parameters:

Name Type Description Default
prompt str

The input text (instruct the model to answer as JSON).

required
schema type[StructuredT]

The Pydantic model to produce.

required
config GenerationConfig | None

Typed generation parameters.

None
constrained bool

Enforce the schema during decoding (needs the [genai-structured] extra) or only parse afterwards.

True
stop_event Event | None

Set it to stop decoding at the next token. Cancelling the call sets it too.

None
**kwargs Any

Generation overrides (win over config).

{}

Returns:

Name Type Description
StructuredT StructuredT

The validated instance.

Raises:

Type Description
ImportError

When constrained is True and the [genai-structured] extra is missing.

ValueError

When the output carries no JSON object.

GenerationStoppedError

When stop_event was set mid-flight.

ValidationError

When the JSON fails schema validation.

load

load() -> None

Download (if needed) and load the model + tokenizer into memory.

Idempotent — a no-op once loaded. Called automatically by :meth:generate / :meth:stream / :meth:chat. Safe to call from several threads at once: concurrent callers on a cold instance wait for one build instead of each running from_pretrained. It blocks for the whole download and build, so call it through asyncio.to_thread from async code.

Raises:

Type Description
ImportError

When the [genai] (or [genai-quant]) extra is missing.

stream async

stream(
    prompt: str, *, config: GenerationConfig | None = None, **kwargs: Any
) -> AsyncIterator[str]

Stream the completion token by token.

The generation runs on a worker thread and hands each piece to the event loop through call_soon_threadsafe, so the loop never blocks — not on the first-call load, not while waiting for the next token. Closing the iterator early (a client disconnecting, a break, aclose()) sets an internal stop event that the model checks after every token, so decoding stops within one token instead of running to max_new_tokens for nobody; the close itself returns without waiting for the worker thread.

Measured with Qwen/Qwen2.5-0.5B-Instruct on an RTX 4070 Ti SUPER: the first (cold) stream used to stall the loop for 4190 ms while the weights loaded on it, now 164 to 193 ms over three runs; closing after 5 of 200 tokens used to block for 3532 ms, now about 0.01 ms, with the worker thread done 28 ms later.

With max_concurrent set, the stream holds one of the pool's workers from its first token until that thread returns — after the last token, or one token after the iterator was closed. A stream closed while still queued is dropped from the queue and never runs.

Parameters:

Name Type Description Default
prompt str

The input text.

required
config GenerationConfig | None

Typed generation parameters.

None
**kwargs Any

Generation overrides (win over config).

{}

Yields:

Name Type Description
str AsyncIterator[str]

Text pieces as they are produced.

stream_chat async

stream_chat(
    messages: list[dict[str, Any]],
    *,
    config: GenerationConfig | None = None,
    **kwargs: Any,
) -> AsyncIterator[str]

Stream the reply to a chat messages list token by token.

The streaming counterpart of :meth:chat: the turns go through the tokenizer's chat template, so the system turn keeps its role. Threading, early close and max_concurrent behave as in :meth:stream.

Parameters:

Name Type Description Default
messages list[dict[str, Any]]

Chat turns, each {"role": ..., "content": ...}.

required
config GenerationConfig | None

Typed generation parameters.

None
**kwargs Any

Generation overrides (win over config).

{}

Yields:

Name Type Description
str AsyncIterator[str]

Text pieces as they are produced.

unload

unload() -> None

Free the model and its memory (VRAM/RAM).

Safe to call when not loaded. After this, the next generation call reloads the weights. While generations are in flight the release waits for them: the last one to finish drops the weights, so a running call never has its model freed underneath it.

unload_if_idle

unload_if_idle() -> bool

Unload the model when it has been idle past the threshold.

Call periodically (e.g. from a @tq.interval task) to reclaim VRAM between bursts. A no-op when idle_unload_seconds is unset, the model isn't loaded, a generation is in flight, or it isn't idle enough yet.

Returns:

Name Type Description
bool bool

True when it unloaded, False otherwise.

TextModelEnum

Bases: StrEnum

Chat and instruction models for TextGenerator and agents.

Member Params Use it when
QWEN2_5_0_5B_INSTRUCT 0.5B CI, tests, laptop CPU
QWEN2_5_1_5B_INSTRUCT 1.5B Smallest that tool-calls reliably
QWEN2_5_3B_INSTRUCT 3B Small GPU (6 GB) or patient CPU
QWEN2_5_7B_INSTRUCT 7B Default for real work, 8-16 GB VRAM
QWEN2_5_14B_INSTRUCT 14B 24 GB VRAM, better multi-step goals
QWEN2_5_CODER_7B_INSTRUCT 7B Code generation and review
PHI_3_5_MINI_INSTRUCT 3.8B Best reasoning per gigabyte
MISTRAL_7B_INSTRUCT_V03 7B European multilingual, Apache-2.0
LLAMA_3_1_8B_INSTRUCT 8B Gated: needs licence + Hub token

TextToSpeechModelEnum

Bases: StrEnum

Coqui TTS voices for TextToSpeech.

Member Use it when
XTTS_V2 Multilingual + voice cloning — the default, heaviest.
VITS_PT_BR PT-BR only, fast, no cloning.
VITS_EN English only, fast.

TokenEncoder

Bases: Protocol

Minimal tokenizer interface used by the token-counting helpers.

Satisfied by HuggingFace AutoTokenizer, tiktoken encodings, and lightweight test doubles exposing encode(text) -> Sized.

encode

encode(text: str) -> Sized

Encode text into a sequence of tokens.

TokenIdSequence

Bases: Protocol

Minimal tensor-like token buffer accepted by a prefix token filter.

Matches torch.Tensor (and lightweight test doubles) without importing torch at module load time.

tolist

tolist() -> list[int]

Return the token ids as a plain list of integers.

TokenUsage dataclass

TokenUsage(
    input_tokens: int = 0,
    output_tokens: int = 0,
    total_tokens: int = 0,
    cache_hit_tokens: int = 0,
    cache_write_tokens: int = 0,
)

What one generation call consumed, as the provider reported it.

total is carried rather than recomputed from the two halves. Every provider is free to bill something other than input + output — cached-prefix discounts and reasoning tokens both show up that way — so the reported total is the authority, and :meth:from_payload only falls back to the sum when the field is absent.

Attributes:

Name Type Description
input_tokens int

Tokens in the prompt.

output_tokens int

Tokens generated.

total_tokens int

What the provider counts for the call.

cache_hit_tokens int

The slice of input_tokens the provider served from a cached prefix and billed at a reduced rate — not tokens on top of the prompt. Adding it to input_tokens double-counts. 0 when the provider reported none, which is also what a provider that has no prompt cache reports.

cache_write_tokens int

The slice of input_tokens the provider wrote to its prompt cache on this call, billed at a premium on providers that charge for the write (Anthropic's cache_creation_input_tokens). Like cache_hit_tokens it is already counted in input_tokens. 0 on the OpenAI-compatible wire format, whose usage reports no write.

from_payload classmethod

from_payload(payload: object) -> TokenUsage | None

Build a usage from a provider's usage object.

Reads the OpenAI-compatible spelling (prompt_tokens / completion_tokens / total_tokens), which DeepSeek, vLLM, TGI and the OpenAI API itself all emit.

The cached-prefix count has two spellings in that same family, so both are read: DeepSeek's flat prompt_cache_hit_tokens and OpenAI's nested prompt_tokens_details.cached_tokens. Reading only one of them silently prices a discounted call at full rate on the other provider, which is a wrong number rather than a missing one.

Parameters:

Name Type Description Default
payload object

The usage object from the response, or None when the response carried none.

required

Returns:

Type Description
TokenUsage | None

TokenUsage | None: The parsed usage, or None when payload

TokenUsage | None

is not a mapping — including when it is None. Callers treat

TokenUsage | None

that as "nothing to record", which is honest: a zeroed usage

TokenUsage | None

would claim the call was free.

Tool dataclass

Tool(
    name: str,
    description: str,
    parameters: dict[str, Any],
    handler: Callable[[dict[str, Any]], Awaitable[str]],
)

A callable the LLM can invoke by name during a chat turn.

Attributes:

Name Type Description
name str

The function name the model calls.

description str

What the tool does (shown to the model).

parameters dict[str, Any]

JSON-schema of the tool's arguments.

handler Callable[[dict[str, Any]], Awaitable[str]]

Async function invoked with the parsed arguments; returns the tool result as a string fed back to the model.

to_spec

to_spec() -> dict[str, Any]

Render the tool as an OpenAI / Ollama function specification.

Returns:

Type Description
dict[str, Any]

dict[str, Any]: The {"type": "function", "function": {...}}

dict[str, Any]

spec passed to the backend's chat_with_tools.

ToolStreamingBackend

Bases: Protocol

A backend that streams a reply with tools attached, in one pass.

Implemented by :class:~tempest_fastapi_sdk.genai.ollama.OllamaGenerator (/api/chat with stream and tools), :class:~tempest_fastapi_sdk.genai.OpenAICompatGenerator (chat/completions with stream and tools) and the testing FakeToolStreamingBackend. :class:~tempest_fastapi_sdk.genai.AIChatPipeline uses it whenever it has tools; without it, the pipeline keeps the resolve-then-stream path.

stream_chat_with_tools

stream_chat_with_tools(
    messages: list[dict[str, Any]],
    tools: list[Any],
    *,
    config: GenerationConfig | None = ...,
    **kwargs: Any,
) -> AsyncIterator[ChatStreamEvent]

Stream one generation for messages with tools available.

Parameters:

Name Type Description Default
messages list[dict[str, Any]]

The conversation, oldest first, in the shape chat_with_tools accepts (assistant turns with tool_calls and role: tool results included).

required
tools list[Any]

The tool specs, the same list chat_with_tools takes ({"type": "function", "function": {...}}).

required
config GenerationConfig | None

Generation parameters; None uses the defaults.

...
**kwargs Any

Extra generation parameters, overriding config.

{}

Returns:

Type Description
AsyncIterator[ChatStreamEvent]

AsyncIterator[ChatStreamEvent]: :class:StreamTextDelta pieces

AsyncIterator[ChatStreamEvent]

as they arrive and, when the model asked for tools, one

AsyncIterator[ChatStreamEvent]

class:StreamToolCalls last.

UsageTotals dataclass

UsageTotals(
    input_tokens: int = 0,
    output_tokens: int = 0,
    total_tokens: int = 0,
    duration_seconds: float = 0.0,
    calls: int = 0,
    cost: float | None = None,
    cache_hit_tokens: int = 0,
)

Aggregate consumption over a window.

Attributes:

Name Type Description
input_tokens int

Prompt tokens summed.

output_tokens int

Generated tokens summed.

total_tokens int

Billed tokens summed.

duration_seconds float

Local-inference seconds summed.

calls int

Rows counted.

cost float | None

Estimated spend, or None when no price is configured — which the interface should read as "do not show a cost", not as "it was free".

cache_hit_tokens int

Cached-prefix tokens summed — already part of input_tokens, reported separately so a screen can show how much of the window the cache paid for.

VisionModelEnum

Bases: StrEnum

Vision-language models for VisionTextGenerator.

Member Params Use it when
QWEN2_VL_2B_INSTRUCT 2B Captions, agent self-checks, CPU
QWEN2_VL_7B_INSTRUCT 7B Real visual QA, 16 GB VRAM
LLAVA_1_5_7B 7B The classic, widely documented baseline

VisionTextGenerator

VisionTextGenerator(
    model_id: str,
    *,
    device: str = "auto",
    dtype: str | ModelDtypeEnum = "auto",
    cache_dir: str | None = None,
    hf_token: str | None = None,
    revision: str | None = None,
    local_files_only: bool | None = None,
    trust_remote_code: bool = False,
    idle_unload_seconds: float | None = None,
    hardware: HardwareInfo | None = None,
    max_concurrent: int | None = None,
)

A lazily-loaded local vision-language model with idle unload.

Example:

>>> gen = VisionTextGenerator("llava-hf/llava-1.5-7b-hf")
>>> await gen.generate("Describe this image.", images=["photo.jpg"])

Attributes:

Name Type Description
model_id str

The HuggingFace model id.

device str

The resolved device (cuda / mps / cpu).

dtype ModelDtypeEnum

The resolved compute precision.

idle_unload_seconds float | None

Idle threshold for :meth:unload_if_idle.

max_concurrent int | None

How many decodings run at once, or None for no limit.

Configure the generator (does not load weights yet).

Parameters:

Name Type Description Default
model_id str

HuggingFace vision-language model id.

required
device str

"auto" / "cuda" / "mps" / "cpu".

'auto'
dtype str | ModelDtypeEnum

Compute precision, or "auto".

'auto'
cache_dir str | None

Where the downloaded weights are written and read back from. None uses the huggingface_hub default — $HF_HOME/hub, or ~/.cache/huggingface/hub when HF_HOME is unset — which is why the second run of a script starts instantly instead of downloading again. Point it at a mounted volume when the process is a container, so the layer does not re-download the model on every restart.

None
hf_token str | None

Hub token for gated or private repositories. None falls back to HF_TOKEN in the environment; without either, anonymous downloads work but are rate-limited (the Hub says so on stderr).

None
revision str | None

Branch, tag or commit sha to load; None follows the moving Hub default.

None
local_files_only bool | None

Load from the cache without touching the network — what an air-gapped or deploy-frozen host wants. None (the default) takes GENAI_OFFLINE from the environment; passing the argument overrides it.

None
trust_remote_code bool

Allow the repository's own Python to run at load time — several VLM repositories require it.

False
idle_unload_seconds float | None

When set, :meth:unload_if_idle frees the model after this idle window.

None
hardware HardwareInfo | None

Injected snapshot for device resolution (tests); probed when None.

None
max_concurrent int | None

Decodings this instance runs at once; the rest wait their turn. None (the default) starts every call immediately. Same trade-off as :class:~tempest_fastapi_sdk.genai.TextGenerator's max_concurrent: on CPU, 1 keeps concurrent calls from splitting the cores between them.

None

Raises:

Type Description
ValueError

When max_concurrent is not positive.

is_loaded property

is_loaded: bool

Return True once the weights are in memory.

seconds_idle property

seconds_idle: float

Return seconds since the model was last in use.

Reads 0.0 while a generation is in flight.

Returns:

Name Type Description
float float

Idle time in seconds.

chat async

chat(
    messages: list[dict[str, Any]],
    *,
    images: list[Any] | None = None,
    config: GenerationConfig | None = None,
    stop_event: Event | None = None,
    **kwargs: Any,
) -> str

Generate a reply for a chat messages list with optional images.

Applies the processor's chat template (which inserts the image placeholder tokens) before generating.

Parameters:

Name Type Description Default
messages list[dict[str, Any]]

Chat turns; image content is referenced per the model's template.

required
images list[Any] | None

Images for the turn.

None
config GenerationConfig | None

Typed generation parameters.

None
stop_event Event | None

Set it to stop decoding at the next token. Cancelling the call sets it too.

None
**kwargs Any

Generation overrides (win over config), handled as in :meth:generate.

{}

Returns:

Name Type Description
str str

The assistant reply.

Raises:

Type Description
GenerationStoppedError

When stop_event was set mid-flight.

generate async

generate(
    prompt: str,
    *,
    images: list[Any] | None = None,
    config: GenerationConfig | None = None,
    stop_event: Event | None = None,
    **kwargs: Any,
) -> str

Generate a completion for prompt conditioned on images.

Every :class:GenerationConfig field is applied the way :class:~tempest_fastapi_sdk.genai.TextGenerator applies it: seed through a private per-call generator, stop through the stop_strings generation argument, the rest forwarded to model.generate.

Parameters:

Name Type Description Default
prompt str

The text prompt (include the model's image placeholder token if its processor requires one).

required
images list[Any] | None

Images as path / bytes / PIL / ndarray; None for a text-only call.

None
config GenerationConfig | None

Typed generation parameters.

None
stop_event Event | None

Set it to stop decoding at the next token. Cancelling the call sets it too, so a timeout stops the model instead of only the wait.

None
**kwargs Any

Generation overrides (win over config); seed and stop are applied as above, the rest go to model.generate.

{}

Returns:

Name Type Description
str str

The generated text.

Raises:

Type Description
GenerationStoppedError

When stop_event was set mid-flight.

load

load() -> None

Download (if needed) and load the model + processor into memory.

Idempotent — a no-op once loaded. Called automatically by :meth:generate / :meth:chat. Safe to call from several threads at once: concurrent callers on a cold instance wait for one build.

Raises:

Type Description
ImportError

When the [genai] extra is missing.

unload

unload() -> None

Free the model and its memory (VRAM/RAM). Safe when not loaded.

While a generation is in flight the release waits for it: the last call to finish drops the weights.

unload_if_idle

unload_if_idle() -> bool

Unload the model when idle past idle_unload_seconds.

Returns:

Name Type Description
bool bool

True when it unloaded, False otherwise — including

bool

while a generation is in flight.

genai_span

genai_span(operation: str, model: str, **attributes: Any)

Async context manager emitting one OTel span for a genai call.

Example:

>>> async with genai_span("chat", "Qwen/Qwen2.5-7B") as span:
...     span.tokens_out = 128
...     ...  # run the model

Attributes:

Name Type Description
tokens_in int | None

Set inside the block to record input tokens (gen_ai.usage.input_tokens).

tokens_out int | None

Set inside the block to record output tokens (gen_ai.usage.output_tokens).

Configure the span (no span is started until entry).

Parameters:

Name Type Description Default
operation str

The genai operation name ("generate" / "chat" / "embed" / "retrieve").

required
model str

The model id (gen_ai.request.model).

required
**attributes Any

Extra span attributes; None values are dropped. Keys should already be namespaced (e.g. "gen_ai.request.top_k").

{}

auto_dtype_name

auto_dtype_name(device: str) -> str

Return the default compute precision name for device.

Parameters:

Name Type Description Default
device str

The concrete device.

required

Returns:

Name Type Description
str str

"bfloat16" on CUDA/MPS, "float32" on CPU (which has

str

no fast half-precision path). The capacity planner

str

(:func:~tempest_fastapi_sdk.genai.can_run) sizes an unquantized

str

load from the same rule, so the two cannot drift.

build_prefix_allowed_tokens_fn

build_prefix_allowed_tokens_fn(
    tokenizer: StructuredTokenizer, schema: type[BaseModel]
) -> PrefixAllowedTokensFn

Build a transformers token filter that enforces schema.

Parameters:

Name Type Description Default
tokenizer StructuredTokenizer

The model tokenizer.

required
schema type[BaseModel]

The Pydantic schema the output must satisfy.

required

Returns:

Name Type Description
PrefixAllowedTokensFn PrefixAllowedTokensFn

A prefix_allowed_tokens_fn to pass to

PrefixAllowedTokensFn

model.generate so only schema-valid continuations are allowed.

Raises:

Type Description
ImportError

When the [genai-structured] extra is not installed.

Note

Reimplements lm-format-enforcer's transformers adapter against the library's stable core (JsonSchemaParser + TokenEnforcer + TokenEnforcerTokenizerData). The upstream lmformatenforcer.integrations.transformers module imports PreTrainedTokenizerBase from transformers.tokenization_utils, which moved in transformers 5.x — importing it raises. Building the adapter here from the core avoids that broken import entirely.

build_structured_completion

build_structured_completion(
    text: str,
    schema: type[StructuredT],
    *,
    usage: TokenUsage | None,
    stop_reason: StopReason,
    provider_stop_reason: str | None,
) -> StructuredCompletion[StructuredT]

Assemble a :class:StructuredCompletion, parsing only after a natural stop.

A refusal or a truncated reply is never parsed: a partial JSON object can validate by accident when the schema's trailing fields have defaults, and an instance built from a cut reply is worse than none.

Parameters:

Name Type Description Default
text str

The reply text.

required
schema type[StructuredT]

The Pydantic model to produce.

required
usage TokenUsage | None

The reported usage.

required
stop_reason StopReason

Why the model stopped, normalized.

required
provider_stop_reason str | None

The provider's own value.

required

Returns:

Type Description
StructuredCompletion[StructuredT]

StructuredCompletion[StructuredT]: The outcome; error set when a

StructuredCompletion[StructuredT]

natural stop carried no valid instance.

bytes_per_param

bytes_per_param(dtype: ModelDtypeEnum) -> float

Return the planning bytes-per-parameter for dtype.

Parameters:

Name Type Description Default
dtype ModelDtypeEnum

The weight precision.

required

Returns:

Name Type Description
float float

Bytes each parameter occupies at that precision.

cache_size_bytes

cache_size_bytes(cache_dir: str | None = None) -> int

Return the total size of the cached model repositories.

Parameters:

Name Type Description Default
cache_dir str | None

The cache to scan; None uses the HF_HUB_CACHE default.

None

Returns:

Name Type Description
int int

Total bytes across every cached model, or 0 when the

int

cache does not exist yet.

Raises:

Type Description
ImportError

When huggingface_hub is not installed.

cached_generate async

cached_generate(
    cache: GenerationCache | AsyncGenerationCache | None,
    model_id: str,
    prompt: str,
    params: dict[str, Any],
    producer: Callable[[], Awaitable[str]],
    *,
    operation: str = "generate",
    identity: Mapping[str, Any] | None = None,
) -> str

Return a cached completion when possible, else produce and cache it.

Parameters:

Name Type Description Default
cache GenerationCache | AsyncGenerationCache | None

The cache, or None to disable caching.

required
model_id str

The model identifier (part of the key).

required
prompt str

The prompt (or serialized messages).

required
params dict[str, Any]

Generation parameters (key + determinism).

required
producer Callable[[], Awaitable[str]]

Runs the real generation.

required
operation str

The call shape, part of the key (see :func:make_generation_key).

'generate'
identity Mapping[str, Any] | None

Model identity fields beyond model_id (revision, quantization), part of the key.

None

Returns:

Name Type Description
str str

The completion — from cache on a deterministic hit, otherwise

str

freshly produced (and cached when deterministic).

can_run

can_run(
    *,
    num_params: int | None = None,
    model_id: str | None = None,
    dtype: ModelDtypeEnum | None = None,
    device: str = "auto",
    hardware: HardwareInfo | None = None,
    token: str | None = None,
) -> CapacityReport

Report whether the host can run a model, and what to do if not.

Provide the model size either directly (num_params) or by model_id (looked up on the Hub). device="auto" picks CUDA → MPS → CPU.

Parameters:

Name Type Description Default
num_params int | None

The model's parameter count. Takes precedence over model_id.

None
model_id str | None

Hub id to look the parameter count up from when num_params is not given.

None
dtype ModelDtypeEnum | None

The precision to plan for. None (the default) plans for the precision TextGenerator(dtype="auto") loads on the chosen device: bfloat16 on CUDA/MPS, float32 on CPU. Pass a value to plan for an explicit TextGenerator(dtype=...) or quantization=....

None
device str

"auto", "cuda", "mps" or "cpu".

'auto'
hardware HardwareInfo | None

Inject a snapshot (tests, or to reuse one probe); defaults to a fresh :func:probe_hardware.

None
token str | None

Hub token for the model_id lookup.

None

Returns:

Name Type Description
CapacityReport CapacityReport

The verdict, chosen device, estimate vs available,

CapacityReport

headroom and a suggestion when it doesn't fit. When the free memory

CapacityReport

of the device could not be measured (CPU or MPS with no RAM

CapacityReport

reading), memory_measured is False, fits is False

CapacityReport

because nothing was verified, and the suggestion says how to get a

CapacityReport

reading on this platform — not to shrink the model. When the RAM

CapacityReport

that sizes device was bounded by a cgroup limit

CapacityReport

(hardware.ram_cgroup_limited), reason ends by naming the

CapacityReport

limit in MiB.

Raises:

Type Description
ValueError

When neither num_params nor a resolvable model_id is available.

cosine_similarity

cosine_similarity(a: list[float], b: list[float]) -> float

Return the cosine similarity of two vectors, in [-1, 1].

Handy for ranking embeddings (RAG retrieval, semantic search): higher means more similar. When both vectors are already L2-normalized (see Embedder(normalize=True)) this reduces to a dot product.

Parameters:

Name Type Description Default
a list[float]

First vector.

required
b list[float]

Second vector, same dimension as a.

required

Returns:

Name Type Description
float float

The cosine similarity; 0.0 when either vector is zero.

Raises:

Type Description
ValueError

When the vectors have different dimensions.

count_message_tokens

count_message_tokens(
    messages: list[dict[str, Any]],
    tokenizer: TokenEncoder,
    *,
    per_message_overhead: int = DEFAULT_PER_MESSAGE_OVERHEAD,
) -> int

Estimate the token cost of a chat messages list.

Parameters:

Name Type Description Default
messages list[dict[str, Any]]

Chat turns with a content string.

required
tokenizer TokenEncoder

Tokenizer exposing encode.

required
per_message_overhead int

Tokens added per message for role tags and separators the chat template injects.

DEFAULT_PER_MESSAGE_OVERHEAD

Returns:

Name Type Description
int int

The estimated total token count.

count_tokens

count_tokens(text: str, tokenizer: TokenEncoder) -> int

Count the tokens in text using tokenizer.

Parameters:

Name Type Description Default
text str

The text to measure.

required
tokenizer TokenEncoder

Anything exposing encode(text) -> Sized (e.g. a HuggingFace AutoTokenizer).

required

Returns:

Name Type Description
int int

The number of tokens.

describe_model

describe_model(model: object, *, key: str | None = None) -> LoadedModel

Describe one model handle without loading or touching it.

Reads only attributes, so it is safe to call on a lazily-configured handle: a generator that has never loaded reports loaded=False and stays unloaded.

Example:

>>> info = describe_model(generator, key="chat-lm")
>>> info.kind, info.loaded
('TextGenerator', True)

Parameters:

Name Type Description Default
model object

Any SDK loader — TextGenerator, Embedder, ImageGenerator, Reranker, SpeechToText, OnnxEmbedder, ClassifierModerator — or any object exposing a similar surface.

required
key str | None

The registry key to record alongside it.

None

Returns:

Name Type Description
LoadedModel LoadedModel

What the handle exposes; None for what it does

LoadedModel

not, never a guess.

document_part

document_part(
    data: bytes, media_type: str = PDF_MEDIA_TYPE, *, filename: str | None = None
) -> dict[str, Any]

Build a document content part for a message's content list.

The shape is the OpenAI Chat Completions file part with the bytes as a base64 data: URL in file_data, which is what the OpenAI PDF guide (https://developers.openai.com/api/docs/guides/pdf-files) sends. The Anthropic generator translates it to a Messages API document block with a base64 source; an OpenAI-compatible generator built for a provider without documented PDF input (Gemini's compatible endpoint, DeepSeek) raises ValueError on it before the request is sent.

Parameters:

Name Type Description Default
data bytes

The document bytes.

required
media_type str

Its media type; only application/pdf is accepted (:data:DOCUMENT_MEDIA_TYPES).

PDF_MEDIA_TYPE
filename str | None

The name the model sees. None sends :data:DEFAULT_DOCUMENT_FILENAME. The Anthropic generator sends it as the block's title.

None

Returns:

Type Description
dict[str, Any]

dict[str, Any]: ``{"type": "file", "file": {"filename": ...,

dict[str, Any]

"file_data": "data:;base64,"}}``.

Raises:

Type Description
ValueError

When media_type is not in :data:DOCUMENT_MEDIA_TYPES, or data is empty.

Example

part = document_part(b"%PDF-1.7...", filename="agenda.pdf") text = {"type": "text", "text": "Summarize it."} messages = [{"role": "user", "content": [part, text]}]

download_model

download_model(
    model_id: str,
    *,
    revision: str | None = None,
    cache_dir: str | None = None,
    token: str | None = None,
    local_files_only: bool | None = None,
    allow_patterns: list[str] | None = None,
    ignore_patterns: list[str] | None = None,
    check_disk: bool = True,
    disk_margin: float = 1.1,
) -> ModelSnapshot

Materialize a model's weights on local disk, ahead of first use.

Left to itself, the first /generate request pays for a multi-gigabyte download inside the request. Call this from the image build, the deploy step or a warm-up task instead, and the request path only ever loads from disk.

check_disk refuses to start a download the filesystem cannot hold. Failing in two seconds with a number beats failing forty minutes later with a half-written cache. The estimate counts only the files allow_patterns / ignore_patterns select (filtered by the same huggingface_hub function snapshot_download uses) and leaves out the ones already in the cache for that revision.

Example:

>>> snapshot = download_model(
...     "Qwen/Qwen2.5-0.5B-Instruct",
...     revision="main",
...     allow_patterns=["*.json", "*.safetensors"],
... )
>>> snapshot.size_bytes > 0
True

Parameters:

Name Type Description Default
model_id str

The Hub model id.

required
revision str | None

Branch, tag or sha; None for the Hub default.

None
cache_dir str | None

Where to write; None uses the HF_HUB_CACHE default.

None
token str | None

Token for gated or private repositories.

None
local_files_only bool

Resolve from the cache without touching the network (turns this call into a "is it already here?" check).

None
allow_patterns list[str] | None

Only fetch files matching these globs — e.g. skip the .bin duplicates of a repo that also ships .safetensors.

None
ignore_patterns list[str] | None

Skip files matching these globs.

None
check_disk bool

Verify free space before downloading — the bytes of the selected files that are not cached yet.

True
disk_margin float

Multiplier applied to the estimated size for the free-space check. The default 1.1 covers the temporary files the download writes next to the blobs.

1.1

Returns:

Name Type Description
ModelSnapshot ModelSnapshot

Where the weights landed, how big they are and

ModelSnapshot

how many files they span.

Raises:

Type Description
ImportError

When huggingface_hub is not installed.

OSError

When check_disk is on and the target filesystem has less free space than the estimate times disk_margin.

estimate_model_bytes

estimate_model_bytes(
    num_params: int,
    dtype: ModelDtypeEnum = BFLOAT16,
    *,
    overhead: float = _INFERENCE_OVERHEAD,
) -> int

Estimate the memory a model needs to run.

Parameters:

Name Type Description Default
num_params int

The model's parameter count (e.g. 7_000_000_000 for a 7B model).

required
dtype ModelDtypeEnum

The precision it will be loaded in.

BFLOAT16
overhead float

Multiplier over raw weight size to account for activations / KV cache / runtime context. Defaults to 1.25.

_INFERENCE_OVERHEAD

Returns:

Name Type Description
int int

Estimated bytes required at inference time.

Raises:

Type Description
ValueError

When num_params is not positive.

extract_json_list

extract_json_list(text: str) -> list[Any] | None

Pull a JSON array out of a model completion, without raising.

A prompt asking for "a list of items" comes back as an array, and the ways it arrives malformed differ from an object: a fence the prompt asked the model not to add, a sentence before the payload, one stray ] at the end. This tolerates all three.

Returning None instead of raising is the point: it is the signal to retry the generation, which is a different response from "the model answered, and the answer was an empty list". A caller that cannot tell those apart either retries a valid empty result or gives up on a recoverable formatting slip.

Parameters:

Name Type Description Default
text str

The raw model completion.

required

Returns:

Type Description
list[Any] | None

list[Any] | None: The decoded list, or None when the completion

list[Any] | None

holds no decodable array (no array at all, malformed JSON, or a valid

list[Any] | None

JSON value that is not a list).

Example:

>>> extract_json_list('Here you go:\n```json\n[{"a": 1}]\n```')
[{'a': 1}]
>>> extract_json_list("not a list") is None
True

extract_json_object

extract_json_object(text: str) -> dict[str, Any] | None

Pull a JSON object out of a model completion, without raising.

The object-shaped twin of :func:extract_json_list, for the prompt whose answer is one record rather than a list — an intent classifier, a routing decision, an extraction with fixed fields.

:func:parse_structured already handles that shape, but it raises, which is the wrong contract when the caller's answer to bad output is "generate again" rather than "fail the request". Returning None says "retry" in one value, with no exception to catch and re-raise around a retry loop.

Parameters:

Name Type Description Default
text str

The raw model completion.

required

Returns:

Type Description
dict[str, Any] | None

dict[str, Any] | None: The decoded object, or None when the

dict[str, Any] | None

completion holds no decodable object (none at all, malformed JSON,

dict[str, Any] | None

or a valid JSON value that is not an object — a bare list included).

Example:

>>> extract_json_object('```json\n{"intent": "create_task"}\n```')
{'intent': 'create_task'}
>>> extract_json_object("[1, 2]") is None
True

fetch_num_params

fetch_num_params(model_id: str, *, token: str | None = None) -> int | None

Read a model's parameter count from the Hub, without downloading it.

Uses huggingface_hub safetensors metadata when available.

Parameters:

Name Type Description Default
model_id str

The Hub model id (e.g. "Qwen/Qwen2.5-7B").

required
token str | None

Optional Hub token for gated/private models.

None

Returns:

Type Description
int | None

int | None: The total parameter count, or None when it can't

int | None

be determined (no huggingface_hub, offline, or the model

int | None

exposes no safetensors metadata).

generate_structured_list async

generate_structured_list(
    backend: SupportsGenerate,
    prompt: str,
    schema: type[StructuredT],
    *,
    config: GenerationConfig | None = None,
    max_attempts: int = 3,
    temperature_step: float = 0.2,
    skip_invalid: bool = True,
) -> list[StructuredT]

Generate a list of schema items, retrying on unusable output.

Retrying a failed generation at the same temperature is close to pointless: greedy decoding is deterministic, so attempt two reproduces attempt one. Each retry therefore adds temperature_step, giving sampling a real chance to leave the bad state. The first attempt stays greedy, because it is the most reliable one.

Only a structural failure costs an attempt — no array in the output at all. An array that parses but holds one malformed item is not a formatting failure, so it is handled by skip_invalid rather than by burning a generation.

Parameters:

Name Type Description Default
backend SupportsGenerate

Anything with async generate(prompt, *, config=...) -> str — the local TextGenerator, OllamaGenerator, or OpenAICompatGenerator.

required
prompt str

The prompt, which should ask for a JSON array.

required
schema type[StructuredT]

The Pydantic model each item must match.

required
config GenerationConfig | None

Base parameters. Its temperature is replaced per attempt; everything else is kept.

None
max_attempts int

Generations to spend before giving up.

3
temperature_step float

Added per retry (attempt 1 at 0.0, attempt 2 at temperature_step, and so on).

0.2
skip_invalid bool

Drop items that fail validation instead of raising.

True

Returns:

Type Description
list[StructuredT]

list[StructuredT]: The validated items. An **empty list is a

list[StructuredT]

success** — the model answered, and the answer is no items.

Raises:

Type Description
StructuredFormatError

No attempt produced a decodable array.

ValueError

When max_attempts is below 1.

ValidationError

When an item fails validation and skip_invalid is False.

hosted_generator

hosted_generator(
    model: str,
    *,
    api_key: str,
    provider: HostedProvider | None = None,
    base_url: str | None = None,
    timeout: float = 120.0,
    retry_policy: RetryPolicy | None = None,
    http_client: HTTPClient | None = None,
    transport: AsyncBaseTransport | None = None,
) -> AnthropicGenerator | OpenAICompatGenerator

Build the hosted generator for model.

provider defaults to :func:resolve_provider; base_url defaults to the provider's documented root. On top of that, each provider gets the wire settings it documents:

  • anthropic — :class:~tempest_fastapi_sdk.genai.AnthropicGenerator;
  • openai — the output budget as :data:OPENAI_MAX_TOKENS_FIELD and json_schema structured output;
  • google — :data:DEFAULT_GOOGLE_OPENAI_URL, json_schema structured output and :data:GOOGLE_EFFORT_VALUES;
  • deepseek — json_object structured output (the only JSON mode DeepSeek documents) and no reasoning_effort field.

google and deepseek are also built with accepts_documents=False (see :func:supports_documents): a call carrying a :func:~tempest_fastapi_sdk.genai.document_part raises ValueError before the request is sent.

HostedGenAISettings.hosted_kwargs() returns exactly these keyword arguments, so building from settings is a splat.

Parameters:

Name Type Description Default
model str

The model id.

required
api_key str

The provider's API key. Empty raises in the generator constructor.

required
provider HostedProvider | None

The provider, when the model id does not say it.

None
base_url str | None

API root, for a proxy or a regional endpoint.

None
timeout float

Per-request HTTP timeout in seconds.

120.0
retry_policy RetryPolicy | None

Retry configuration for the lazily-created HTTP client.

None
http_client HTTPClient | None

An injected client for connection reuse.

None
transport AsyncBaseTransport | None

Transport for the lazily-created client — an httpx.MockTransport in tests.

None

Returns:

Type Description
AnthropicGenerator | OpenAICompatGenerator

AnthropicGenerator | OpenAICompatGenerator: The generator.

Raises:

Type Description
ValueError

When the provider cannot be resolved, provider is not one of :data:HOSTED_PROVIDERS (a string from configuration is not checked by the type), or api_key is empty.

Example

gen = hosted_generator("claude-haiku-5-5", api_key="sk-ant-...") isinstance(gen, AnthropicGenerator) True

image_part

image_part(data: bytes, media_type: str) -> dict[str, Any]

Build an image content part for a message's content list.

The shape is the OpenAI image_url part with a base64 data: URL, which is the message shape every generator in this SDK reads; the Anthropic generator translates it to a Messages API image block.

Parameters:

Name Type Description Default
data bytes

The image bytes.

required
media_type str

Its media type (image/png, image/jpeg...).

required

Returns:

Type Description
dict[str, Any]

dict[str, Any]: ``{"type": "image_url", "image_url": {"url":

dict[str, Any]

"data:;base64,"}}``.

Example

part = image_part(b"\x89PNG...", "image/png") text = {"type": "text", "text": "Read it."} messages = [{"role": "user", "content": [part, text]}]

is_deterministic

is_deterministic(params: dict[str, Any]) -> bool

Return True when params describe a reproducible generation.

Parameters:

Name Type Description Default
params dict[str, Any]

Merged generation parameters (config + per-call overrides).

required

Returns:

Name Type Description
bool bool

True when do_sample is False or temperature == 0.

is_document_part

is_document_part(part: object) -> bool

Tell whether a content part is a document (an OpenAI file part).

Parameters:

Name Type Description Default
part object

One item of a message's content list.

required

Returns:

Name Type Description
bool bool

True for a dict whose type is "file", the shape

bool

func:document_part builds.

list_cached_models

list_cached_models(cache_dir: str | None = None) -> list[CachedModel]

Report the models currently held in the local weight cache.

Parameters:

Name Type Description Default
cache_dir str | None

The cache to scan; None uses the HF_HUB_CACHE default.

None

Returns:

Type Description
list[CachedModel]

list[CachedModel]: One entry per cached model repository, largest

list[CachedModel]

first. Empty when the cache directory does not exist yet — an

list[CachedModel]

empty cache is a valid state, not an error.

Raises:

Type Description
ImportError

When huggingface_hub is not installed.

make_ai_chat_router

make_ai_chat_router(
    pipeline: AIChatPipeline,
    *,
    prefix: str = "/api/ai-chat",
    tags: list[str] | None = None,
    current_user_id: Callable[..., Any] | None = None,
    dependencies: Sequence[Any] | None = None,
    docs_locale: str | None = None,
) -> APIRouter

Mount an :class:AIChatPipeline on HTTP endpoints.

Registers two endpoints:

  • POST {prefix}/chat — a full turn returning an :class:AIChatResult (reply, sources, memory hits, tool names, optional audio).
  • POST {prefix}/chat/stream — the reply streamed token-by-token over SSE, ending with a done event.

The router is stateless: history rides in on each request body and the caller persists it however they like (see the module docstring on why the chat/ domain is intentionally not wired). The body is untrusted: history roles are limited to user/assistant, and the conversation owner — the key memory is recalled and indexed under — comes from current_user_id, never from the body.

Parameters:

Name Type Description Default
pipeline AIChatPipeline

The configured pipeline to expose.

required
prefix str

URL prefix. Defaults to "/api/ai-chat".

'/api/ai-chat'
tags list[str] | None

OpenAPI tags. Defaults to ["ai-chat"].

None
current_user_id Callable[..., Any] | None

FastAPI dependency resolving the authenticated caller's user id. Required when the pipeline has a memory: recalling under an id taken from the request would hand one user's past messages to anyone who names them. Without it, turns run with no memory owner.

None
dependencies Sequence[Any] | None

Applied to every route — where authentication and rate limiting go.

None
docs_locale str | None

Language of the OpenAPI summary and description text — "en-US" or "pt-BR". None (default) reads API_DOCS_LOCALE through :class:~tempest_fastapi_sdk.settings.ServerSettings, whose default is "en-US".

None

Returns:

Name Type Description
APIRouter APIRouter

Ready to mount with app.include_router.

Raises:

Type Description
ValueError

When the pipeline has a memory and no current_user_id was given.

make_ai_usage_model

make_ai_usage_model(
    *, tablename: str = "ai_usage", class_name: str = "AIUsageModel"
) -> type[BaseAIUsageModel]

Build a concrete usage model bound to tablename.

For tests and lightweight scripts; production code should subclass :class:BaseAIUsageModel by hand so Alembic picks it up statically.

Parameters:

Name Type Description Default
tablename str

The table name.

'ai_usage'
class_name str

The generated class name.

'AIUsageModel'

Returns:

Type Description
type[BaseAIUsageModel]

type[BaseAIUsageModel]: The concrete model class.

make_genai_router

make_genai_router(
    *,
    text_generator: TextBackend | None = None,
    embedder: SupportsEmbed | None = None,
    retriever: SupportsRetrieve | None = None,
    speech_to_text: SpeechTranscriber | None = None,
    text_to_speech: SpeechSynthesizer | None = None,
    image_generator: ImageGenerator | None = None,
    audio_generator: SupportsAudioGeneration | None = None,
    models: ModelRegistry | dict[str, Any] | list[Any] | None = None,
    prefix: str = "/api/genai",
    tags: list[str] | None = None,
    limits: GenAIRequestLimits | None = None,
    docs_locale: str | None = None,
) -> APIRouter

Build a router exposing whichever GenAI objects you inject.

Only the endpoints backed by a provided object are registered:

  • text_generator -> POST {prefix}/generate (JSON reply) and POST {prefix}/generate/stream (token-by-token SSE), plus POST {prefix}/chat.
  • embedder -> POST {prefix}/embed.
  • retriever -> POST {prefix}/rag (query -> context block).
  • speech_to_text -> POST {prefix}/transcribe (audio upload).
  • text_to_speech -> POST {prefix}/tts (returns audio/wav).
  • image_generator -> POST {prefix}/image (returns the encoded image, with the seed in X-Image-Seed).
  • audio_generator -> POST {prefix}/audio (returns one audio/wav clip, with the seed in X-Audio-Seed).
  • models -> GET {prefix}/models (what is resident in memory right now, next to the host's memory picture).

The router owns only the HTTP surface; the caller owns model lifecycle (loading, idle-unloading, auth). Add your own auth by including the router under an authenticated parent or wrapping it.

Every request is checked against limits before the model runs: prompt length, chat size, max_new_tokens, /embed batch size, top_k, /tts text length, image size and steps, and the /transcribe upload size (read in chunks, so an oversized upload is refused before it is held in memory). A request over any of them gets 422 -- except the upload, which gets 413 (UPLOAD_TOO_LARGE); with register_exception_handlers installed the body also carries details={"field": ..., "limit": ...} (or {"max_bytes": ...} for the upload). /image answers with one image, so it refuses config.num_images above 1 instead of rendering a batch and dropping all but the first.

Parameters:

Name Type Description Default
text_generator TextBackend | None

Backs the text endpoints (a TextGenerator, an OllamaGenerator, or any object implementing the TextBackend protocol).

None
embedder SupportsEmbed | None

Backs /embed (an Embedder, an OllamaEmbedder, or any SupportsEmbed).

None
retriever SupportsRetrieve | None

Backs /rag — a Retriever (rerank via Retriever(reranker=...)) or a HybridRetriever.

None
speech_to_text SpeechTranscriber | None

Backs /transcribe — a SpeechToText, an OpenAICompatSpeech, an OllamaSpeech, or any SpeechTranscriber. The route takes an optional prompt form field (checked against max_prompt_chars) and forwards it; temperature is not exposed.

None
text_to_speech SpeechSynthesizer | None

Backs /tts — a TextToSpeech, an OllamaSpeech, or any SpeechSynthesizer.

None
image_generator ImageGenerator | None

Backs /image.

None
audio_generator SupportsAudioGeneration | None

Backs /audio -- an AudioGenerator, a MusicGenerator, or any SupportsAudioGeneration.

None
models ModelRegistry | dict[str, Any] | list[Any] | None

Backs /models — a ModelRegistry, or a dict/list of handles you hold yourself.

None
prefix str

URL prefix. Defaults to "/api/genai".

'/api/genai'
tags list[str] | None

OpenAPI tags. Defaults to ["genai"].

None
limits GenAIRequestLimits | None

Per-request ceilings. None uses GenAIRequestLimits() and its defaults.

None
docs_locale str | None

Language of the OpenAPI summary and description text — "en-US" or "pt-BR". None (default) reads API_DOCS_LOCALE through :class:~tempest_fastapi_sdk.settings.ServerSettings, whose default is "en-US".

None

Returns:

Name Type Description
APIRouter APIRouter

Ready to mount with app.include_router.

Raises:

Type Description
ValueError

When no GenAI object is provided (the router would be empty). Emptiness is tested with is None, not truthiness: an empty ModelRegistry — the normal state at startup, before anything has been loaded — is falsy, and refusing it would make the endpoint impossible to mount at the only time you can mount it.

make_generation_key

make_generation_key(
    model_id: str,
    prompt: str,
    params: dict[str, Any],
    *,
    operation: str = "generate",
    identity: Mapping[str, Any] | None = None,
) -> str

Build a stable cache key from the model, prompt and parameters.

operation separates call shapes that share a prompt string: a chat keyed on the serialized messages must not answer a generate whose prompt happens to be that same JSON text. identity carries whatever else pins the weights behind model_id (revision, quantization), so two generators of the same model id loaded differently never read each other's completions.

The default operation="generate" with no identity produces the same digest as before either argument existed, so an existing Redis cache of plain generate calls stays warm.

Parameters:

Name Type Description Default
model_id str

The model identifier.

required
prompt str

The input prompt (or serialized messages).

required
params dict[str, Any]

Generation parameters that affect the output.

required
operation str

The call shape ("generate", "chat" …).

'generate'
identity Mapping[str, Any] | None

Extra model identity fields; entries whose value is None are ignored.

None

Returns:

Name Type Description
str str

A hex SHA-256 digest.

make_model_cards

make_model_cards(
    models: ModelRegistry | Mapping[str, object] | Sequence[object],
    *,
    include_vram: bool = True,
) -> list[MetricCard]

Build dashboard cards describing the models resident right now.

Example:

>>> site = AdminSite(
...     dashboard_cards=[*make_model_cards(registry)],
... )

The handles are read at render time, not at call time, so a registry that is empty when the site is built still reports correctly once models load.

Parameters:

Name Type Description Default
models ModelRegistry | Mapping[str, object] | Sequence[object]

A :class:~tempest_fastapi_sdk.genai.ModelRegistry, or a mapping or sequence of model handles you hold yourself.

required
include_vram bool

Add the free-VRAM card. It is the only one that probes the host, so drop it on a CPU-only box or when the dashboard should stay free of NVML reads.

True

Returns:

Type Description
list[MetricCard]

list[MetricCard]: Two cards — resident count and per-device

list[MetricCard]

breakdown — plus free VRAM when include_vram is on.

model_disk_bytes

model_disk_bytes(
    model_id: str,
    *,
    revision: str | None = None,
    token: str | None = None,
    allow_patterns: list[str] | None = None,
    ignore_patterns: list[str] | None = None,
) -> int | None

Return how many bytes a repository would occupy, without fetching it.

Reads the file sizes from the Hub metadata. Use it to decide whether a download is worth starting — :func:can_run sizes RAM and VRAM, this sizes the disk.

Parameters:

Name Type Description Default
model_id str

The Hub model id.

required
revision str | None

Branch, tag or sha; None for the Hub default.

None
token str | None

Token for gated or private repositories.

None
allow_patterns list[str] | None

Count only files matching these globs — the same filter :func:download_model forwards to snapshot_download.

None
ignore_patterns list[str] | None

Leave out files matching these globs.

None

Returns:

Type Description
int | None

int | None: Total size in bytes of the selected files, or None

int | None

when the Hub is unreachable or reports no per-file sizes.

Raises:

Type Description
ImportError

When huggingface_hub is not installed.

parse_structured

parse_structured(text: str, schema: type[StructuredT]) -> StructuredT

Parse and validate a model completion into a schema instance.

Parameters:

Name Type Description Default
text str

The raw model completion (may contain fences / prose).

required
schema type[StructuredT]

The Pydantic model to validate against.

required

Returns:

Name Type Description
StructuredT StructuredT

The validated instance.

Raises:

Type Description
ValueError

When no JSON object is present in text.

ValidationError

When the JSON does not satisfy schema.

parse_structured_list

parse_structured_list(
    text: str, schema: type[StructuredT], *, skip_invalid: bool = False
) -> list[StructuredT]

Parse a model completion into a list of schema instances.

Parameters:

Name Type Description Default
text str

The raw model completion (may contain fences / prose).

required
schema type[StructuredT]

The Pydantic model each item must satisfy.

required
skip_invalid bool

Drop items that fail validation instead of raising. Use it when one bad item out of ten is worth keeping the other nine — a suggestion list, for instance — and leave it off when the caller needs all-or-nothing.

False

Returns:

Type Description
list[StructuredT]

list[StructuredT]: The validated items, in the order the model

list[StructuredT]

produced them.

Raises:

Type Description
ValueError

When no JSON array is present in text.

ValidationError

When an item does not satisfy schema and skip_invalid is False.

probe_hardware

probe_hardware(*, cache_dir: str | None = None) -> HardwareInfo

Snapshot the host's CPU, RAM, GPU and disk.

GPU name and memory come from NVML when pynvml is installed, so a web process that probes (the /models endpoint, a health check) does not create a CUDA context on every GPU. Without NVML it falls back to torch.cuda.mem_get_info, which does initialize CUDA in the calling process. has_cuda always comes from torch.cuda.is_available(), which does not create a context.

Parameters:

Name Type Description Default
cache_dir str | None

Directory whose free space to report (where models are downloaded). Defaults to the current working directory when None.

None

Returns:

Name Type Description
HardwareInfo HardwareInfo

The current resource picture. A reading that could

HardwareInfo

not be taken is reported as unmeasured, not as empty. RAM comes

HardwareInfo

from psutil and, failing that on Linux, from /proc/meminfo;

HardwareInfo

when neither answers ram_measured is False and the RAM

HardwareInfo

fields are 0. Both sources report the host's memory; on Linux

HardwareInfo

the reading is then bounded by the process's cgroup memory limit

HardwareInfo

(v2 memory.max or v1 memory.limit_in_bytes, over the whole

HardwareInfo

ancestry) when that limit is below the host's RAM, and

HardwareInfo

ram_cgroup_limited says so.

HardwareInfo

When the disk query raises OSError, disk_measured is

HardwareInfo

False. Without torch no GPU is reported

HardwareInfo

(has_cuda=False, gpus=[]). When CUDA is available and

HardwareInfo

torch is a CUDA 13 build while ctranslate2 (faster-whisper)

HardwareInfo

is installed, warnings says that transcribing on the GPU will

HardwareInfo

look for libcublas.so.12 and how to install a CUDA 12 torch,

HardwareInfo

before the first transcription fails.

recommend

recommend(
    *,
    num_params: int | None = None,
    model_id: str | None = None,
    hardware: HardwareInfo | None = None,
    token: str | None = None,
) -> CapacityReport

Pick the best precision that fits, from the native one down to int4.

Tries the precision TextGenerator(dtype="auto") loads on the auto-selected device (bfloat16 on CUDA/MPS, float32 on CPU), then int8, then int4, and returns the first :class:CapacityReport that fits (or the int4 report when nothing fits, so the caller sees the closest option). A report whose dtype is int8/int4 maps to TextGenerator(quantization=...); any other dtype is what dtype="auto" already loads.

Parameters:

Name Type Description Default
num_params int | None

The model's parameter count.

None
model_id str | None

Hub id to look the count up from.

None
hardware HardwareInfo | None

Injected snapshot; defaults to a fresh probe.

None
token str | None

Hub token for the lookup.

None

Returns:

Name Type Description
CapacityReport CapacityReport

The recommended configuration. When the free memory

CapacityReport

of the device could not be measured (memory_measured=False), it

CapacityReport

is the report at the native precision: the ladder needs a number to

CapacityReport

step down from, and stepping to int4 on an unknown would

CapacityReport

recommend a slower, lossier load for nothing.

Raises:

Type Description
ValueError

When neither num_params nor a resolvable model_id is available.

Notes

Two fallbacks are tried in order: a smaller precision on the same device first, since that keeps the model on the accelerator, and only then CPU RAM when the current device is a GPU.

remove_cached_model

remove_cached_model(
    model_id: str,
    *,
    revision: str | None = None,
    cache_dir: str | None = None,
    dry_run: bool = False,
) -> int

Delete a model from the local cache and report the space freed.

Parameters:

Name Type Description Default
model_id str

The Hub model id to remove.

required
revision str | None

Remove only this revision (sha or ref name). None removes every cached revision of the model.

None
cache_dir str | None

The cache to operate on; None uses the HF_HUB_CACHE default.

None
dry_run bool

Compute the freed size without deleting.

False

Returns:

Name Type Description
int int

Bytes freed (or that would be freed under dry_run).

int

0 when the model — or that revision of it — is not cached,

int

which is a successful no-op rather than an error.

Raises:

Type Description
ImportError

When huggingface_hub is not installed.

resolve_device

resolve_device(device: str, hardware: HardwareInfo | None = None) -> str

Resolve "auto" to a concrete device, or pass a fixed one through.

Parameters:

Name Type Description Default
device str

"auto", "cuda", "mps" or "cpu".

required
hardware HardwareInfo | None

Injected snapshot (tests); probed when None.

None

Returns:

Name Type Description
str str

The concrete device — CUDA → MPS → CPU for "auto".

resolve_provider

resolve_provider(model: str) -> HostedProvider

Read the provider off a model id.

Parameters:

Name Type Description Default
model str

The model id ("claude-sonnet-5-5", "gpt-...", "gemini-...", "deepseek-...").

required

Returns:

Name Type Description
HostedProvider HostedProvider

The provider the id belongs to.

Raises:

Type Description
ValueError

When no prefix in :data:MODEL_PREFIXES matches.

Example

resolve_provider("claude-haiku-5-5") 'anthropic'

resolve_revision

resolve_revision(
    model_id: str, *, revision: str = "main", token: str | None = None
) -> str | None

Resolve a branch or tag to the immutable commit sha behind it.

Pin the returned sha in configuration and the service stops loading whatever main happens to hold at boot.

Example:

>>> sha = resolve_revision("Qwen/Qwen2.5-0.5B-Instruct")
>>> isinstance(sha, str) or sha is None
True

Parameters:

Name Type Description Default
model_id str

The Hub model id.

required
revision str

Branch, tag or sha to resolve. Defaults to "main".

'main'
token str | None

Token for gated or private repositories.

None

Returns:

Type Description
str | None

str | None: The commit sha, or None when the Hub cannot be

str | None

reached or the repository/revision does not exist. Callers treat

str | None

None as "could not pin", never as an error to swallow

str | None

silently — the caller decides whether to proceed unpinned.

Raises:

Type Description
ImportError

When huggingface_hub is not installed.

runtime_report

runtime_report(
    models: Mapping[str, object] | Sequence[object],
    *,
    hardware: HardwareInfo | None = None,
    probe: bool = True,
) -> ModelRuntimeReport

Describe every handle you hold, next to the host's memory.

Sorting puts loaded handles first and, among them, the longest-idle first: that is the order someone reads when a card is full and they need to decide what to free.

Example:

>>> report = runtime_report({"chat": generator, "embed": embedder})
>>> report.loaded_count
1

Parameters:

Name Type Description Default
models Mapping[str, object] | Sequence[object]

The handles, either keyed (the keys land on LoadedModel.key) or as a sequence.

required
hardware HardwareInfo | None

A snapshot to reuse instead of probing again.

None
probe bool

When no hardware is given, probe the host. Pass False to skip it — probing reads NVML (or, without pynvml installed, initializes CUDA through torch, which creates a context on every GPU) and is the only part of this call that costs anything.

True

Returns:

Name Type Description
ModelRuntimeReport ModelRuntimeReport

The handles plus, optionally, the host

ModelRuntimeReport

snapshot.

supports_documents

supports_documents(provider: str | None) -> bool

Tell whether provider documents PDF input.

For a service that sends :func:~tempest_fastapi_sdk.genai.document_part to check at boot, or before offering a PDF route, instead of finding out from the ValueError the generator raises on the first call.

Parameters:

Name Type Description Default
provider str | None

A hosted provider name — typically settings.GENAI_PROVIDER or :func:resolve_provider of the model id. None and an unknown name answer False.

required

Returns:

Name Type Description
bool bool

True when provider is in :data:DOCUMENT_PROVIDERS.

Example

supports_documents("anthropic") True supports_documents("deepseek") False

to_anthropic_document

to_anthropic_document(part: dict[str, Any]) -> dict[str, Any]

Translate an OpenAI file content part into a Messages API block.

The part's file_data (a data:<media_type>;base64,<data> URL, as :func:~tempest_fastapi_sdk.genai.document_part builds it) becomes the base64 source of a document block, the shape of the PDF guide (https://platform.claude.com/docs/en/build-with-claude/pdf-support), and its filename becomes the block's optional title, which the citations guide (https://platform.claude.com/docs/en/build-with-claude/citations) says is passed to the model.

Parameters:

Name Type Description Default
part dict[str, Any]

{"type": "file", "file": {"file_data": ..., "filename": ...}}.

required

Returns:

Type Description
dict[str, Any]

dict[str, Any]: ``{"type": "document", "source": {"type": "base64",

dict[str, Any]

"media_type": ..., "data": ...}}, plustitle`` when the part

dict[str, Any]

names a file.

Raises:

Type Description
ValueError

When the part carries no file_data (an OpenAI file_id names a file in OpenAI's storage, which Anthropic cannot read), or file_data is not a base64 data: URL.

to_anthropic_image

to_anthropic_image(part: dict[str, Any]) -> dict[str, Any]

Translate an OpenAI image_url content part into a Messages API block.

A data:<media_type>;base64,<data> URL becomes a base64 image source and any other URL a url source — the two source types of the vision guide (https://platform.claude.com/docs/en/build-with-claude/vision).

Parameters:

Name Type Description Default
part dict[str, Any]

{"type": "image_url", "image_url": {"url": ...}}, or with image_url as the bare URL string.

required

Returns:

Type Description
dict[str, Any]

dict[str, Any]: {"type": "image", "source": {...}}.

Raises:

Type Description
ValueError

When the URL is empty, or a data: URL is not base64-encoded.

truncate_messages

truncate_messages(
    messages: list[dict[str, Any]],
    max_tokens: int,
    tokenizer: TokenEncoder,
    *,
    keep_system: bool = True,
    per_message_overhead: int = DEFAULT_PER_MESSAGE_OVERHEAD,
) -> list[dict[str, Any]]

Drop the oldest turns until the chat fits within max_tokens.

System messages are kept (when keep_system) and moved to the front; the most recent turn is always kept even if it alone exceeds the budget. The oldest non-system, non-last turns are dropped first.

An assistant turn carrying tool_calls and the role="tool" results that answer it are dropped together, never split: a history that starts with a tool result whose call was trimmed away, or ends a call with no result, breaks the pairing the OpenAI chat format requires between a call and its results, and strict providers refuse it. If the most recent turn is such a tool result, its whole group (the call plus every result) is what is always kept.

Parameters:

Name Type Description Default
messages list[dict[str, Any]]

The full chat history.

required
max_tokens int

The token budget to fit within.

required
tokenizer TokenEncoder

Tokenizer exposing encode.

required
keep_system bool

Always retain system messages.

True
per_message_overhead int

Per-message overhead used in the estimate.

DEFAULT_PER_MESSAGE_OVERHEAD

Returns:

Type Description
list[dict[str, Any]]

list[dict[str, Any]]: The trimmed messages (system first, then the kept

list[dict[str, Any]]

tail in order). Empty input returns an empty list.