tempest_fastapi_sdk.genai¶
IA generativa self-hosted: geração de texto, embeddings, VLM, moderação, cache, métricas e router.
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
¶
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
¶
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
¶
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
¶
API root; requests go to {base_url}/v1/messages.
DEFAULT_DEEPSEEK_MODEL
module-attribute
¶
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
¶
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
¶
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
¶
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
¶
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:
anthropic—documentblocks with abase64application/pdfsource (https://platform.claude.com/docs/en/build-with-claude/pdf-support).openai— "Chat Completions accepts only PDF files asfilecontent parts", withfile_dataas adata:application/pdf;base64,...URL (https://developers.openai.com/api/docs/guides/pdf-files).
Left out, because their documentation does not describe it:
google— the OpenAI-compatibility page (https://ai.google.dev/gemini-api/docs/openai, which redirects to https://aistudio.google.com/docs/openai) documents image (image_url) and audio (input_audio) parts, and nofilepart.deepseek— the chat-completion reference (https://api-docs.deepseek.com/api/create-chat-completion) lists afilepart, but describesfile_dataas "a base64-encoded data URL of the image" and names no PDF or document format.
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
¶
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
¶
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
¶
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
¶
The media type of a PDF, the default of :func:document_part.
SPEECH_RESPONSE_FORMAT
module-attribute
¶
The response_format a synthesis asks for when the caller names none.
STREAM_FORMAT
module-attribute
¶
stream_format asking the server to stream the audio bytes as made.
STREAM_RESPONSE_FORMAT
module-attribute
¶
response_format of a streamed synthesis: raw 24 kHz 16-bit mono PCM.
StopReason
module-attribute
¶
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
¶
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 sendsblocked_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
¶
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
¶
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
¶
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
¶
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
|
web_search
|
WebSearch | None
|
Web-search augmenter, or |
None
|
tts
|
TextToSpeech | None
|
Text-to-speech backend, or |
None
|
tools
|
list[Tool] | None
|
Tools the model may call, or |
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 ( |
None
|
max_context_tokens
|
int | None
|
Token budget for the built
message list; oldest turns are dropped to fit (needs
|
None
|
moderator
|
ModerationBackend | None
|
Screens the user input
and every |
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: |
'incremental'
|
parse_text_tool_calls
|
bool
|
When a tool-loop reply has no
native |
True
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
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. |
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
|
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 yieldsblocked_messageas 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 orblocked_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;
|
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 |
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]
|
|
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
|
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
|
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
|
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 |
0
|
Returns:
| Type | Description |
|---|---|
float | None
|
float | None: The estimate, or |
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. |
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 |
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 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 |
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 |
UsageTotals
|
empty window returns zeros, not |
|
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
|
|
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 ( |
DEFAULT_ANTHROPIC_MODEL
|
api_key
|
str
|
The API key, sent as |
required |
base_url
|
str
|
API root; |
DEFAULT_ANTHROPIC_URL
|
timeout
|
float
|
Per-request HTTP timeout in seconds. A long
non-streaming generation can outlive it; prefer
:meth: |
120.0
|
max_tokens
|
int
|
Default |
DEFAULT_ANTHROPIC_MAX_TOKENS
|
config
|
GenerationConfig | None
|
Default generation parameters
for every call. A call's own |
None
|
extra_body
|
dict[str, Any] | None
|
Fields merged into every
request body, under the computed ones — the place for
|
None
|
extra_headers
|
dict[str, str] | None
|
Headers added to every
request ( |
None
|
anthropic_version
|
str
|
The |
ANTHROPIC_VERSION
|
http_client
|
HTTPClient | None
|
An injected client for
connection reuse. When |
None
|
transport
|
AsyncBaseTransport | None
|
Transport for the
lazily-created client — an |
None
|
retry_policy
|
RetryPolicy | None
|
Retry configuration for the
lazily-created client. |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
is_loaded
property
¶
Return True — the provider owns model residency.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
Always |
url
property
¶
Return the Messages endpoint.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
|
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 |
{}
|
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 |
required |
schema
|
type[StructuredT]
|
The Pydantic model to produce. |
required |
config
|
GenerationConfig | None
|
Typed generation parameters. |
None
|
**kwargs
|
Any
|
Per-call parameters, winning over |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
StructuredT |
StructuredT
|
The validated instance. |
Raises:
| Type | Description |
|---|---|
TypeError
|
When |
ValueError
|
When the reply carries no JSON object (a refusal,
or a reply cut at |
ValidationError
|
When the JSON fails |
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 |
required |
tools
|
list[dict[str, Any]]
|
|
required |
config
|
GenerationConfig | None
|
Typed generation parameters. |
None
|
**kwargs
|
Any
|
Per-call parameters, winning over |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: ``{"role": "assistant", "content": |
dict[str, Any]
|
"tool_calls": [...]}``, each call being |
dict[str, Any]
|
|
dict[str, Any]
|
with |
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 |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
tuple[str, TokenUsage | None]: The reply, and the usage the API |
TokenUsage | None
|
reported (cache reads and writes included in |
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: |
required |
schema
|
type[StructuredT]
|
The Pydantic model to produce. |
required |
effort
|
Effort | None
|
Sent as |
None
|
cache_system
|
bool
|
Send the system prompt as one |
False
|
max_tokens
|
int | None
|
|
None
|
config
|
GenerationConfig | None
|
Typed generation parameters. |
None
|
**kwargs
|
Any
|
Per-call body fields, winning over |
{}
|
Returns:
| Type | Description |
|---|---|
StructuredCompletion[StructuredT]
|
StructuredCompletion[StructuredT]: The outcome. |
Raises:
| Type | Description |
|---|---|
TypeError
|
When |
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 |
{}
|
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
|
None
|
**kwargs
|
Any
|
Per-call parameters, winning over |
{}
|
Returns:
| Type | Description |
|---|---|
tuple[str, TokenUsage | None]
|
tuple[str, TokenUsage | None]: The text and its usage. |
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 |
{}
|
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 |
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 |
{}
|
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 |
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
¶
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 |
set
async
¶
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
¶
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 |
set
async
¶
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 |
steps |
int | None
|
Denoising steps, at most |
guidance_scale |
float | None
|
How hard to follow the prompt. |
seed |
int | None
|
RNG seed, |
num_waveforms |
int
|
Clips per call, at most |
to_pipeline_kwargs
¶
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 ( |
dtype |
ModelDtypeEnum
|
The resolved compute precision. |
source |
ModelRef
|
The resolved weight identity forwarded to
|
pipeline_kwargs |
dict[str, Any]
|
Extra |
idle_unload_seconds |
float | None
|
Idle threshold used by
:meth: |
Configure the generator (does not load weights yet).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_id
|
str
|
HuggingFace model id of an AudioLDM-family
pipeline ( |
required |
device
|
str
|
|
'auto'
|
dtype
|
str | ModelDtypeEnum
|
Compute precision, or |
'auto'
|
cache_dir
|
str | None
|
Where weights are downloaded and read
back; |
None
|
hf_token
|
str | None
|
Hub token for gated or private
repositories; |
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
|
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
|
None
|
max_concurrent
|
int
|
Simultaneous renders. Defaults to |
1
|
idle_unload_seconds
|
float | None
|
When set,
:meth: |
None
|
hardware
|
HardwareInfo | None
|
Injected snapshot for device
resolution (tests); probed when |
None
|
metrics
|
GenAIMetrics | None
|
Optional Prometheus metrics;
:meth: |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
is_loaded
property
¶
Return True once the pipeline is in memory.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
Whether :meth: |
bool
|
meth: |
pipeline
property
¶
pipeline: AudioDiffusionPipeline
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
¶
Return seconds since the pipeline was last in use.
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
Idle time in seconds; |
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 |
list[GeneratedAudio]
|
so reproducing clip |
list[GeneratedAudio]
|
|
list[GeneratedAudio]
|
one is drawn. |
Raises:
| Type | Description |
|---|---|
ImportError
|
When the extras are missing. |
ValueError
|
When the model is not supported. |
load
¶
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: |
unload_if_idle
¶
Free the pipeline when it has been idle past the threshold.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
AudioPipelineOutput
¶
Bases: Protocol
Output object returned by a diffusers audio pipeline.
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. |
service |
str | None
|
Which capability spent it ("summary",
"suggest_tasks"). |
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 |
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 |
submit
async
¶
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 |
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 |
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 |
str
|
The chosen device — |
dtype |
ModelDtypeEnum
|
The precision the estimate assumes. |
estimated_bytes |
int
|
Estimated memory the model needs (weights + inference overhead). |
available_bytes |
int
|
Memory available on |
headroom_pct |
float
|
|
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 |
memory_measured |
bool
|
Whether the free memory of |
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 |
required |
config
|
GenerationConfig | None
|
Generation parameters; |
...
|
**kwargs
|
Any
|
Extra generation parameters, overriding |
{}
|
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
|
|
window_tokens |
int | None
|
Tokens per window, special tokens
included; |
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
|
threshold
|
float
|
Minimum probability for a label to flag. |
0.5
|
device
|
str
|
|
'auto'
|
cache_dir
|
str | None
|
Where the downloaded weights are
written and read back from. |
None
|
hf_token
|
str | None
|
Hub token for gated or private
repositories. |
None
|
revision
|
str | None
|
Branch, tag or commit sha to load;
|
None
|
local_files_only
|
bool | None
|
Load from the cache without
touching the network — what an air-gapped or deploy-frozen
host wants. |
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: |
None
|
hardware
|
HardwareInfo | None
|
Injected snapshot (tests). |
None
|
activation
|
str
|
|
'auto'
|
window_tokens
|
int | None
|
Tokens per classified window, special
tokens included, capped at the model's context (the
tokenizer's |
64
|
window_overlap
|
int
|
Tokens shared by consecutive windows, so a
phrase of up to |
16
|
Raises:
| Type | Description |
|---|---|
ValueError
|
On an unknown |
seconds_idle
property
¶
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 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 |
unload
¶
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
¶
Free the classifier when idle past its configured threshold.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
bool
|
when it was already free, still in use, or no |
|
bool
|
|
DailyUsage
dataclass
¶
One day of one service.
Attributes:
| Name | Type | Description |
|---|---|---|
day |
date
|
The UTC day. |
service |
str | None
|
The capability, or |
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: |
query_prefix |
str
|
Prepended by :meth: |
passage_prefix |
str
|
Prepended by :meth: |
Configure the embedder (does not load weights yet).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_id
|
str
|
HuggingFace model id. |
required |
device
|
str
|
|
'auto'
|
dtype
|
str | ModelDtypeEnum
|
Compute precision or |
'auto'
|
cache
|
EmbeddingCache | AsyncEmbeddingCache | None
|
Optional
per-text vector cache (sync like
:class: |
None
|
normalize
|
bool
|
When |
False
|
cache_dir
|
str | None
|
Where the downloaded weights are
written and read back from. |
None
|
hf_token
|
str | None
|
Hub token for gated or private
repositories. |
None
|
revision
|
str | None
|
Branch, tag or commit sha to load;
|
None
|
local_files_only
|
bool | None
|
Load from the cache without
touching the network — what an air-gapped or deploy-frozen
host wants. |
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: |
None
|
hardware
|
HardwareInfo | None
|
Injected snapshot for device
resolution (tests); probed when |
None
|
metrics
|
GenAIMetrics | None
|
Optional Prometheus metrics; when
set, :meth: |
None
|
query_prefix
|
str
|
Text prepended to every input of
:meth: |
''
|
passage_prefix
|
str
|
Text prepended to every input of
:meth: |
''
|
seconds_idle
property
¶
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 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 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 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 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 |
unload
¶
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 the model once idle past idle_unload_seconds.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
bool
|
while a batch is in flight. |
EmbeddingCache
¶
Bases: Protocol
A synchronous per-text vector cache (e.g. a dict wrapper).
get
¶
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 |
set
¶
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
|
passage_prefix |
str
|
Prepended to every corpus passage by
|
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. |
vram_total_bytes |
int
|
Total VRAM on the device. |
vram_free_bytes |
int
|
Currently free VRAM. |
GenAIMetrics
¶
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 |
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: |
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 ( |
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'
|
record_tokens
¶
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
¶
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 |
max_chat_messages |
int
|
Most messages one |
max_new_tokens |
int
|
Largest |
max_embed_texts |
int
|
Most texts one |
max_top_k |
int
|
Largest |
max_tts_chars |
int
|
Largest |
max_image_side |
int
|
Largest |
max_image_steps |
int
|
Largest |
max_audio_seconds |
float
|
Largest |
max_audio_steps |
int
|
Largest |
max_upload_bytes |
int
|
Largest |
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 |
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 |
str
|
The encoding, lowercase ( |
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
¶
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 |
set
¶
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 ( |
temperature |
float | None
|
Sampling temperature ( |
top_p |
float | None
|
Nucleus sampling probability mass ( |
top_k |
int | None
|
Top-k sampling cutoff ( |
repetition_penalty |
float | None
|
Penalty for repeated tokens
( |
do_sample |
bool | None
|
Sample ( |
seed |
int | None
|
RNG seed for reproducible sampling. |
stop |
list[str]
|
Stop strings that end generation early. |
to_generate_kwargs
¶
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_available_bytes |
int
|
Currently available RAM, bounded by the
cgroup when |
ram_measured |
bool
|
Whether the two RAM fields were read.
:func: |
ram_cgroup_limited |
bool
|
Whether the RAM fields come from a Linux
cgroup memory limit (a container's |
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;
|
disk_measured |
bool
|
Whether |
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 |
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 ( |
status_code |
int
|
The HTTP status. For an error that arrived inside
a stream it is the status the provider documents for that error
|
error_type |
str | None
|
The provider's own error type
( |
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 |
retry_after |
float | None
|
Seconds the provider asked to wait,
from a numeric |
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 |
height |
int | None
|
Output height in pixels. At most |
steps |
int | None
|
Denoising steps. Distilled/turbo models want
1-8; full models want 20-50. At most |
guidance_scale |
float | None
|
How hard to follow the prompt.
Turbo models want |
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
|
to_pipeline_kwargs
¶
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 ( |
dtype |
ModelDtypeEnum
|
The resolved compute precision. |
source |
ModelRef
|
The resolved weight identity forwarded to
|
image_format |
str
|
Encoding of the returned bytes. |
pipeline_kwargs |
dict[str, Any]
|
Extra |
idle_unload_seconds |
float | None
|
Idle threshold used by
:meth: |
Configure the generator (does not load weights yet).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_id
|
str
|
HuggingFace diffusion model id. |
required |
device
|
str
|
|
'auto'
|
dtype
|
str | ModelDtypeEnum
|
Compute precision, or |
'auto'
|
cache_dir
|
str | None
|
Where the downloaded weights are
written and read back from. |
None
|
hf_token
|
str | None
|
Hub token for gated or private
repositories. |
None
|
revision
|
str | None
|
Branch, tag or commit sha to load;
|
None
|
local_files_only
|
bool | None
|
Load from the cache without
touching the network — what an air-gapped or deploy-frozen
host wants. |
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'
|
pipeline_kwargs
|
dict[str, Any] | None
|
Extra keywords for
|
None
|
max_concurrent
|
int
|
Simultaneous renders. Defaults to |
1
|
idle_unload_seconds
|
float | None
|
When set,
:meth: |
None
|
hardware
|
HardwareInfo | None
|
Injected snapshot for device
resolution (tests); probed when |
None
|
metrics
|
GenAIMetrics | None
|
Optional Prometheus metrics;
when set, :meth: |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
is_loaded
property
¶
Return True once the pipeline is in memory.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
Whether :meth: |
bool
|
meth: |
pipeline
property
¶
pipeline: ImageDiffusionPipeline
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 |
seconds_idle
property
¶
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, |
required |
strength
|
float
|
How far to move from the input, |
0.8
|
config
|
ImageGenerationConfig | None
|
Steps, guidance, seed
and count. |
None
|
Returns:
| Type | Description |
|---|---|
list[GeneratedImage]
|
list[GeneratedImage]: The redrawn images. |
Raises:
| Type | Description |
|---|---|
ImportError
|
When the |
TypeError
|
When |
ValueError
|
When |
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 |
load
¶
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 |
unload
¶
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
¶
Free the pipeline when it has been idle past the threshold.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
bool
|
when it was already free, still in use, or no |
|
bool
|
|
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.
InMemoryEmbeddingCache
¶
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 |
Initialize an empty cache.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_entries
|
int | None
|
Maximum number of vectors kept.
|
_DEFAULT_MAX_ENTRIES
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
get
¶
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 |
set
¶
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
¶
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 |
Initialize the empty cache.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_entries
|
int | None
|
Maximum number of completions kept.
|
_DEFAULT_MAX_ENTRIES
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
get
¶
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 |
set
¶
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 ( |
model_id |
str | None
|
Hub id, Whisper size or graph path. |
device |
str | None
|
Where it is resident ( |
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 |
idle_past_threshold
property
¶
Return whether this handle is due to be unloaded.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
bool
|
time, has a threshold configured, and has crossed it. Any |
|
bool
|
missing piece answers |
|
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 ( |
revision |
str | None
|
Branch, tag or commit sha. |
cache_dir |
str | None
|
Where weights are cached. |
token |
str | None
|
Hub token for gated or private repositories.
|
local_files_only |
bool | None
|
When |
trust_remote_code |
bool
|
When |
download_kwargs
¶
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 |
loader_kwargs
¶
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 |
ModelRegistry
¶
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 |
evict
¶
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
|
|
get
¶
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 |
None
|
probe
|
bool
|
When no snapshot is given, probe the host.
|
True
|
Returns:
| Name | Type | Description |
|---|---|---|
ModelRuntimeReport |
ModelRuntimeReport
|
The held handles plus, optionally, the |
ModelRuntimeReport
|
host's memory picture. |
items
¶
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
¶
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 ( |
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 |
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 ( |
dtype |
ModelDtypeEnum
|
The resolved compute precision. |
source |
ModelRef
|
The resolved weight identity. |
idle_unload_seconds |
float | None
|
Idle threshold used by
:meth: |
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'
|
dtype
|
str | ModelDtypeEnum
|
Compute precision, or |
'auto'
|
cache_dir
|
str | None
|
Where weights are downloaded and read
back; |
None
|
hf_token
|
str | None
|
Hub 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
|
max_concurrent
|
int
|
Simultaneous renders. Defaults to |
1
|
idle_unload_seconds
|
float | None
|
When set,
:meth: |
None
|
hardware
|
HardwareInfo | None
|
Injected snapshot for device
resolution (tests); probed when |
None
|
metrics
|
GenAIMetrics | None
|
Optional Prometheus metrics;
:meth: |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
accepts_melody
property
¶
Return whether the checkpoint conditions on a reference melody.
Loads the model on first access, which blocks.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
is_loaded
property
¶
Return True once the model is in memory.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
Whether :meth: |
max_seconds
property
¶
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
|
|
float
|
MusicGen checkpoints measured). |
seconds_idle
property
¶
Return seconds since the model was last in use.
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
Idle time in seconds; |
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
|
|
None
|
melody
|
str | Path | bytes | None
|
A reference clip (path or
bytes) whose melody the music follows; only a
|
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]
|
|
list[GeneratedAudio]
|
takes the same seed, the same |
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 |
ValidationException
|
When the config cannot be honoured;
|
FileNotFoundError
|
When |
load
¶
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 |
OSError
|
When the checkpoint cannot be downloaded or read. |
ValueError
|
When the checkpoint is not a MusicGen model (raised
by |
unload_if_idle
¶
Free the model when it has been idle past the threshold.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
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
( |
context_window |
int | None
|
The window the request ran with
( |
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: |
passage_prefix |
str
|
Prepended by :meth: |
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. |
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 |
None
|
http_client
|
HTTPClient | None
|
An injected client; when
|
None
|
transport
|
AsyncBaseTransport | None
|
Explicit transport
for the lazily-created client ( |
None
|
retry_policy
|
RetryPolicy | None
|
Retry configuration for the
lazily-created client. Ignored when |
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: |
''
|
passage_prefix
|
str
|
Text prepended to every input of
:meth: |
''
|
embed
async
¶
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 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 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
¶
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 |
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 |
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 |
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 |
think |
ThinkLevel | None
|
Default top-level |
truncate |
bool | None
|
Default top-level |
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 |
None
|
http_client
|
HTTPClient | None
|
An injected client; one is
created lazily and owned by this instance when |
None
|
transport
|
AsyncBaseTransport | None
|
Transport for the
lazily-created client (tests). Ignored with |
None
|
retry_policy
|
RetryPolicy | None
|
Retry configuration for the
lazily-created 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 |
None
|
num_ctx
|
int | None
|
Context window in tokens, sent as the
|
None
|
options
|
dict[str, Any] | None
|
Raw Ollama |
None
|
think
|
ThinkLevel | None
|
Default |
None
|
truncate
|
bool | None
|
Default |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
is_loaded
property
¶
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 |
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
|
required |
config
|
GenerationConfig | None
|
Typed generation parameters. |
None
|
think
|
ThinkLevel | None
|
Top-level |
None
|
truncate
|
bool | None
|
Top-level |
None
|
**kwargs
|
Any
|
Per-call generation overrides (win over
|
{}
|
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 |
OllamaContextExceededError
|
When |
OllamaError
|
When the daemon answers with an |
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
|
required |
schema
|
type[StructuredT]
|
The Pydantic model to produce. |
required |
config
|
GenerationConfig | None
|
Typed generation parameters. |
None
|
think
|
ThinkLevel | None
|
Top-level |
None
|
truncate
|
bool | None
|
Top-level |
None
|
**kwargs
|
Any
|
Per-call generation overrides (win over
|
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
StructuredT |
StructuredT
|
The validated instance. |
Raises:
| Type | Description |
|---|---|
TypeError
|
When |
OllamaFormatIgnoredError
|
When the reply holds no JSON object,
so the daemon did not apply the |
OllamaThinkingUnsupportedError
|
When |
OllamaContextExceededError
|
When |
ValidationError
|
When the JSON fails |
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
|
required |
tools
|
list[dict[str, Any]]
|
Tool specifications in the Ollama /
OpenAI |
required |
config
|
GenerationConfig | None
|
Typed generation parameters. |
None
|
think
|
ThinkLevel | None
|
Top-level |
None
|
truncate
|
bool | None
|
Top-level |
None
|
**kwargs
|
Any
|
Per-call generation overrides (win over
|
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: The full response |
dict[str, Any]
|
|
dict[str, Any]
|
dict when the daemon returns no message. |
Raises:
| Type | Description |
|---|---|
OllamaThinkingUnsupportedError
|
When |
OllamaContextExceededError
|
When |
OllamaError
|
When the daemon answers with an |
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. |
None
|
think
|
ThinkLevel | None
|
Top-level |
None
|
truncate
|
bool | None
|
Top-level |
None
|
**kwargs
|
Any
|
Per-call generation overrides (HuggingFace-style
names such as |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The generated text. |
Raises:
| Type | Description |
|---|---|
OllamaThinkingUnsupportedError
|
When |
OllamaContextExceededError
|
When |
OllamaError
|
When the daemon answers with an |
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 |
None
|
config
|
GenerationConfig | None
|
Typed generation parameters. |
None
|
think
|
ThinkLevel | None
|
Top-level |
None
|
truncate
|
bool | None
|
Top-level |
None
|
**kwargs
|
Any
|
Per-call generation overrides (win over |
{}
|
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 |
OllamaThinkingUnsupportedError
|
When |
OllamaContextExceededError
|
When |
ValueError
|
When the daemon answers with no content. |
ValidationError
|
When the JSON fails |
load
¶
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 |
None
|
truncate
|
bool | None
|
Top-level |
None
|
**kwargs
|
Any
|
Per-call generation overrides (win over
|
{}
|
Yields:
| Name | Type | Description |
|---|---|---|
str |
AsyncIterator[str]
|
Text pieces as the daemon produces them. |
Raises:
| Type | Description |
|---|---|
OllamaThinkingUnsupportedError
|
When |
OllamaContextExceededError
|
When |
OllamaError
|
When a stream line is an |
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
|
required |
config
|
GenerationConfig | None
|
Typed generation parameters. |
None
|
think
|
ThinkLevel | None
|
Top-level |
None
|
truncate
|
bool | None
|
Top-level |
None
|
**kwargs
|
Any
|
Per-call generation overrides (win over
|
{}
|
Yields:
| Name | Type | Description |
|---|---|---|
str |
AsyncIterator[str]
|
Reply pieces as the daemon produces them. |
Raises:
| Type | Description |
|---|---|
OllamaThinkingUnsupportedError
|
When |
OllamaContextExceededError
|
When |
OllamaError
|
When a stream line is an |
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: |
required |
tools
|
list[Any]
|
Tool specifications in the Ollama / OpenAI
|
required |
config
|
GenerationConfig | None
|
Typed generation parameters. |
None
|
think
|
ThinkLevel | None
|
Top-level |
None
|
truncate
|
bool | None
|
Top-level |
None
|
**kwargs
|
Any
|
Per-call generation overrides (win over
|
{}
|
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 |
OllamaContextExceededError
|
When |
OllamaError
|
When a stream line is an |
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. |
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 |
120.0
|
http_client
|
HTTPClient | None
|
An injected client (connection
reuse). When |
None
|
transport
|
AsyncBaseTransport | None
|
Explicit transport
for the lazily-created client, such as an
|
None
|
retry_policy
|
RetryPolicy | None
|
Retry configuration for the
lazily-created client; |
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: |
None
|
speaker
|
str | None
|
The same as |
None
|
language
|
str | None
|
Must stay |
None
|
response_format
|
SpeechFormat
|
|
'pcm'
|
Returns:
| Name | Type | Description |
|---|---|---|
StreamingResponse |
StreamingResponse
|
The audio, streamed. |
Raises:
| Type | Description |
|---|---|
ValidationException
|
When the request or the daemon refuses
(see :meth: |
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: |
None
|
speaker
|
str | None
|
The same as |
None
|
language
|
str | None
|
Must stay |
None
|
response_format
|
SpeechFormat
|
|
'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 |
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 |
required |
voice
|
str | None
|
A voice name from :meth: |
None
|
speaker
|
str | None
|
The same as |
None
|
language
|
str | None
|
Must stay |
None
|
response_format
|
SpeechFormat
|
|
'wav'
|
out_path
|
str | Path | None
|
When given, also write the audio
there (exactly the returned bytes, so raw samples for
|
None
|
Returns:
| Name | Type | Description |
|---|---|---|
bytes |
bytes
|
The synthesized audio. |
Raises:
| Type | Description |
|---|---|
ValidationException
|
When |
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
|
prompt
|
str | None
|
Must stay |
None
|
temperature
|
float | None
|
Must stay |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
Transcription |
Transcription
|
The text, the duration the daemon measured, and its segments. |
Raises:
| Type | Description |
|---|---|
ValidationException
|
When |
FileNotFoundError
|
When |
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
¶
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
¶
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 |
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']
|
|
idle_unload_seconds |
float | None
|
Idle threshold for
:meth: |
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
|
required |
tokenizer_revision
|
str | None
|
Branch, tag or commit sha for
the Hub tokenizer; ignored for a local |
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
|
pooling
|
Literal['mean', 'cls']
|
How token embeddings become a sentence
vector — |
'mean'
|
idle_unload_seconds
|
float | None
|
When set,
:meth: |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
seconds_idle
property
¶
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 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. |
unload
¶
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
¶
Drop the session when it has been idle past the threshold.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
bool
|
already free, still in use, or no |
|
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: |
passage_prefix |
str
|
Prepended by :meth: |
Configure the client. No network call happens here.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
str
|
Embedding model id, e.g. |
required |
api_key
|
str
|
Bearer token. Empty raises here. |
required |
base_url
|
str
|
API root; |
DEFAULT_OPENAI_URL
|
timeout
|
float
|
Per-request HTTP timeout in seconds. |
60.0
|
dimensions
|
int | None
|
Sent as |
None
|
extra_headers
|
dict[str, str] | None
|
Headers added to every
request; |
None
|
http_client
|
HTTPClient | None
|
An injected client; one is
created lazily and owned by this instance when |
None
|
transport
|
AsyncBaseTransport | None
|
Transport for the
lazily-created client (tests). Ignored with |
None
|
retry_policy
|
RetryPolicy | None
|
Retry configuration for the
lazily-created client; |
None
|
provider
|
str
|
Label carried by the errors this raises. |
'openai-compatible'
|
query_prefix
|
str
|
Text prepended to every input of
:meth: |
''
|
passage_prefix
|
str
|
Text prepended to every input of
:meth: |
''
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
embed
async
¶
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
|
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 |
list[list[float]]
|
empty input. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
HostedAPIError
|
A typed subclass for any error status. |
embed_passages
async
¶
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: |
256
|
Returns:
| Type | Description |
|---|---|
list[list[float]]
|
list[list[float]]: One vector per passage, in input order. |
embed_query
async
¶
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: |
256
|
Returns:
| Type | Description |
|---|---|
list[list[float]]
|
list[list[float]]: One vector per query, in input order. |
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
( |
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 |
None
|
extra_headers
|
dict[str, str] | None
|
Headers added to every
request (an OpenRouter |
None
|
http_client
|
HTTPClient | None
|
An injected client for
connection reuse. When |
None
|
transport
|
AsyncBaseTransport | None
|
Explicit transport
for the lazily-created client — pass an
|
None
|
retry_policy
|
RetryPolicy | None
|
Retry configuration for the
lazily-created client. |
None
|
metrics
|
GenAIMetrics | None
|
Optional Prometheus recorder. |
None
|
forward_params
|
Iterable[str]
|
HuggingFace-only generation
fields ( |
()
|
provider
|
str
|
Label carried by the errors this instance raises
( |
'openai-compatible'
|
max_tokens_field
|
str
|
Body field that |
'max_tokens'
|
structured_output
|
StructuredOutputMode
|
How
:meth: |
'json_schema'
|
effort_field
|
str | None
|
Body field that the |
'reasoning_effort'
|
effort_values
|
Mapping[str, str] | None
|
Translation of
:data: |
None
|
accepts_documents
|
bool
|
Whether this provider takes the
|
True
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
is_loaded
property
¶
Return True — the provider owns model residency.
Present for surface-compatibility with TextGenerator.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
Always |
aclose
async
¶
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 |
{}
|
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 |
required |
schema
|
type[StructuredT]
|
The Pydantic model to produce. |
required |
config
|
GenerationConfig | None
|
Typed generation parameters. |
None
|
**kwargs
|
Any
|
Per-call parameters, winning over |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
StructuredT |
StructuredT
|
The validated instance. |
Raises:
| Type | Description |
|---|---|
TypeError
|
When |
ValueError
|
When the reply carries no JSON object (DeepSeek documents that JSON mode can return empty content). |
ValidationError
|
When the JSON fails |
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 |
required |
tools
|
list[dict[str, Any]]
|
Function specs. |
required |
config
|
GenerationConfig | None
|
Typed generation parameters. |
None
|
**kwargs
|
Any
|
Per-call parameters, winning over |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: ``{"role": "assistant", "content": |
dict[str, Any]
|
"tool_calls": [...]} |
dict[str, Any]
|
sent |
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 |
{}
|
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: |
required |
schema
|
type[StructuredT]
|
The Pydantic model to produce. |
required |
effort
|
Effort | None
|
Reasoning effort, sent as
|
None
|
cache_system
|
bool
|
Accepted for interchangeability with
:class: |
False
|
max_tokens
|
int | None
|
Output budget, sent as
|
None
|
config
|
GenerationConfig | None
|
Typed generation parameters. |
None
|
**kwargs
|
Any
|
Per-call body fields, winning over |
{}
|
Returns:
| Type | Description |
|---|---|
StructuredCompletion[StructuredT]
|
StructuredCompletion[StructuredT]: The outcome. |
Raises:
| Type | Description |
|---|---|
TypeError
|
When |
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 |
{}
|
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 |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
tuple[str, TokenUsage | None]: The text, and the provider's |
TokenUsage | None
|
reported usage — |
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 |
{}
|
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 |
{}
|
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: |
required |
tools
|
list[Any]
|
Function specs. |
required |
config
|
GenerationConfig | None
|
Typed generation parameters. |
None
|
**kwargs
|
Any
|
Per-call parameters, winning over |
{}
|
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: |
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 ( |
required |
api_key
|
str
|
Bearer token. Empty raises immediately, where the
configuration is read, instead of as a |
required |
base_url
|
str
|
API root including the version segment;
|
DEFAULT_OPENAI_URL
|
speech_model
|
str
|
The |
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. |
None
|
http_client
|
HTTPClient | None
|
An injected client for
connection reuse. When |
None
|
transport
|
AsyncBaseTransport | None
|
Explicit transport
for the lazily-created client — pass an
|
None
|
retry_policy
|
RetryPolicy | None
|
Retry configuration for the
lazily-created client. |
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 |
aclose
async
¶
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
|
speaker
|
str | None
|
The same as |
None
|
language
|
LanguageEnum | str | None
|
Sent as the |
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
|
None
|
response_format
|
str
|
The audio format asked for. |
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 |
FileNotFoundError
|
When |
FileTooLargeException
|
When the server answers |
ValidationException
|
When the server answers |
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 |
None
|
language
|
LanguageEnum | str | None
|
As in :meth: |
None
|
speaker_wav
|
str | Path | bytes | None
|
As in :meth: |
None
|
Yields:
| Name | Type | Description |
|---|---|---|
bytes |
AsyncIterator[bytes]
|
PCM pieces, in order. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
FileNotFoundError
|
When |
FileTooLargeException
|
When the server answers |
ValidationException
|
When the server answers |
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: |
None
|
with_segments
|
bool
|
Keep the per-span timestamps. |
True
|
with_words
|
bool
|
Ask for per-word timestamps. |
False
|
prompt
|
str | None
|
Sent as the |
None
|
temperature
|
float | None
|
Sent as the |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
Transcription |
Transcription
|
|
Transcription
|
|
|
Transcription
|
or, when the response has none, the requested code ( |
|
Transcription
|
nothing was requested), and the segments. |
|
Transcription
|
stays |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
When |
FileTooLargeException
|
When the server answers |
ValidationException
|
When the server answers |
HostedAPIError
|
A typed subclass for any other error status
( |
ValueError
|
When a success response is not a JSON object. |
HTTPError
|
When the server cannot be reached or does not answer in time. |
RedisEmbeddingCache
¶
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 |
required |
prefix
|
str
|
Key prefix for stored vectors. |
'genai:emb:'
|
ttl_seconds
|
int | None
|
Optional expiry per entry; |
None
|
get
async
¶
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 |
set
async
¶
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 |
required |
namespace
|
str
|
Prefix prepended to every key. |
'genai:gen:'
|
ttl_seconds
|
int | None
|
Per-entry TTL, or |
None
|
get
async
¶
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 |
set
async
¶
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
¶
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
|
|
ServiceUsage
dataclass
¶
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
¶
A piece of the reply text, as the model produced it.
Attributes:
| Name | Type | Description |
|---|---|---|
text |
str
|
The piece; never empty. |
StreamToolCalls
dataclass
¶
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 |
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 |
text |
str
|
The reply text as received, |
usage |
TokenUsage | None
|
What the provider reported the call cost,
present whatever the outcome; |
stop_reason |
StopReason
|
Why the model stopped, normalized. |
provider_stop_reason |
str | None
|
The provider's own value
( |
error |
ValueError | None
|
Why |
ok
property
¶
Whether the call produced a validated instance.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
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: |
required |
schema
|
type[StructuredT]
|
The Pydantic model to produce. |
required |
effort
|
Effort | None
|
Reasoning effort, or |
...
|
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
¶
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
|
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.
SubjectUsage
dataclass
¶
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
|
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; |
...
|
**kwargs
|
Any
|
Extra generation parameters, overriding |
{}
|
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; |
...
|
**kwargs
|
Any
|
Extra generation parameters, overriding |
{}
|
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 ( |
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
|
idle_unload_seconds |
float | None
|
Idle threshold used by
:meth: |
config |
GenerationConfig | None
|
Default generation parameters, layered under every call's own. |
max_concurrent |
int | None
|
How many decodings run at once, or
|
Configure the generator (does not load weights yet).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_id
|
str
|
HuggingFace model id. |
required |
device
|
str
|
|
'auto'
|
dtype
|
str | ModelDtypeEnum
|
Compute precision, or |
'auto'
|
quantization
|
str | ModelDtypeEnum | None
|
|
None
|
cache_dir
|
str | None
|
Where the downloaded weights are
written and read back from. |
None
|
hf_token
|
str | None
|
Hub token for gated or private
repositories. |
None
|
revision
|
str | None
|
Branch, tag or commit sha to load.
|
None
|
local_files_only
|
bool | None
|
Load from the cache without
touching the network — what an air-gapped or deploy-frozen
host wants. |
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: |
None
|
hardware
|
HardwareInfo | None
|
Injected snapshot for device
resolution (tests); probed when |
None
|
generation_cache
|
GenerationCache | AsyncGenerationCache | None
|
Optional prompt→completion cache. Only deterministic
generations ( |
None
|
metrics
|
GenAIMetrics | None
|
Optional Prometheus metrics;
when set, |
None
|
config
|
GenerationConfig | None
|
Default generation parameters
for every call. A call's own |
None
|
max_concurrent
|
int | None
|
Decodings this instance runs at
once; the rest wait their turn, in arrival order. |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
is_loaded
property
¶
Return True once the weights are in memory.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
Whether :meth: |
seconds_idle
property
¶
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
|
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 |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The assistant reply. |
Raises:
| Type | Description |
|---|---|
GenerationStoppedError
|
When |
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
|
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 |
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 |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
StructuredT |
StructuredT
|
The validated instance. |
Raises:
| Type | Description |
|---|---|
ImportError
|
When |
ValueError
|
When the output carries no JSON object. |
GenerationStoppedError
|
When |
ValidationError
|
When the JSON fails |
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.AIChatPipelinetool loop drives either backend.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
messages
|
list[dict[str, Any]]
|
Chat turns (a turn may carry
|
required |
tools
|
list[dict[str, Any]]
|
Tool specs in the
|
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 |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: |
dict[str, Any]
|
call has the |
dict[str, Any]
|
|
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 ( |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The generated text (prompt stripped). |
Raises:
| Type | Description |
|---|---|
GenerationStoppedError
|
When |
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
|
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 |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
StructuredT |
StructuredT
|
The validated instance. |
Raises:
| Type | Description |
|---|---|
ImportError
|
When |
ValueError
|
When the output carries no JSON object. |
GenerationStoppedError
|
When |
ValidationError
|
When the JSON fails |
load
¶
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 |
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 |
{}
|
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
|
required |
config
|
GenerationConfig | None
|
Typed generation parameters. |
None
|
**kwargs
|
Any
|
Generation overrides (win over |
{}
|
Yields:
| Name | Type | Description |
|---|---|---|
str |
AsyncIterator[str]
|
Text pieces as they are produced. |
unload
¶
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 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
|
|
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.
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.
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 |
cache_write_tokens |
int
|
The slice of |
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 |
required |
Returns:
| Type | Description |
|---|---|
TokenUsage | None
|
TokenUsage | None: The parsed usage, or |
TokenUsage | None
|
is not a mapping — including when it is |
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
¶
Render the tool as an OpenAI / Ollama function specification.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: The |
dict[str, Any]
|
spec passed to the backend's |
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 |
required |
tools
|
list[Any]
|
The tool specs, the same list
|
required |
config
|
GenerationConfig | None
|
Generation parameters; |
...
|
**kwargs
|
Any
|
Extra generation parameters, overriding |
{}
|
Returns:
| Type | Description |
|---|---|
AsyncIterator[ChatStreamEvent]
|
AsyncIterator[ChatStreamEvent]: :class: |
AsyncIterator[ChatStreamEvent]
|
as they arrive and, when the model asked for tools, one |
AsyncIterator[ChatStreamEvent]
|
class: |
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 |
cache_hit_tokens |
int
|
Cached-prefix tokens summed — already part
of |
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 ( |
dtype |
ModelDtypeEnum
|
The resolved compute precision. |
idle_unload_seconds |
float | None
|
Idle threshold for
:meth: |
max_concurrent |
int | None
|
How many decodings run at once, or
|
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'
|
dtype
|
str | ModelDtypeEnum
|
Compute precision, or |
'auto'
|
cache_dir
|
str | None
|
Where the downloaded weights are
written and read back from. |
None
|
hf_token
|
str | None
|
Hub token for gated or private
repositories. |
None
|
revision
|
str | None
|
Branch, tag or commit sha to load;
|
None
|
local_files_only
|
bool | None
|
Load from the cache without
touching the network — what an air-gapped or deploy-frozen
host wants. |
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: |
None
|
hardware
|
HardwareInfo | None
|
Injected snapshot for device
resolution (tests); probed when |
None
|
max_concurrent
|
int | None
|
Decodings this instance runs at
once; the rest wait their turn. |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
seconds_idle
property
¶
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 |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The assistant reply. |
Raises:
| Type | Description |
|---|---|
GenerationStoppedError
|
When |
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
|
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 |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The generated text. |
Raises:
| Type | Description |
|---|---|
GenerationStoppedError
|
When |
load
¶
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 |
unload
¶
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 the model when idle past idle_unload_seconds.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
bool
|
while a generation is in flight. |
genai_span
¶
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
( |
tokens_out |
int | None
|
Set inside the block to record output tokens
( |
Configure the span (no span is started until entry).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
operation
|
str
|
The genai operation name
( |
required |
model
|
str
|
The model id ( |
required |
**attributes
|
Any
|
Extra span attributes; |
{}
|
auto_dtype_name
¶
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
|
|
str
|
no fast half-precision path). The capacity planner |
|
str
|
(:func: |
|
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 |
PrefixAllowedTokensFn
|
|
Raises:
| Type | Description |
|---|---|
ImportError
|
When the |
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; |
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
¶
Return the total size of the cached model repositories.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cache_dir
|
str | None
|
The cache to scan; |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
Total bytes across every cached model, or |
int
|
cache does not exist yet. |
Raises:
| Type | Description |
|---|---|
ImportError
|
When |
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
|
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: |
'generate'
|
identity
|
Mapping[str, Any] | None
|
Model identity fields beyond
|
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 |
None
|
model_id
|
str | None
|
Hub id to look the parameter count up from
when |
None
|
dtype
|
ModelDtypeEnum | None
|
The precision to plan for. |
None
|
device
|
str
|
|
'auto'
|
hardware
|
HardwareInfo | None
|
Inject a snapshot (tests, or to
reuse one probe); defaults to a fresh :func: |
None
|
token
|
str | None
|
Hub token for the |
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), |
|
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 |
|
CapacityReport
|
( |
|
CapacityReport
|
limit in MiB. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When neither |
cosine_similarity
¶
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 |
required |
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
The cosine similarity; |
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 |
required |
tokenizer
|
TokenEncoder
|
Tokenizer exposing |
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 |
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 — |
required |
key
|
str | None
|
The registry key to record alongside it. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
LoadedModel |
LoadedModel
|
What the handle exposes; |
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 |
PDF_MEDIA_TYPE
|
filename
|
str | None
|
The name the model sees. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: ``{"type": "file", "file": {"filename": ..., |
dict[str, Any]
|
"file_data": "data: |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
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
|
cache_dir
|
str | None
|
Where to write; |
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 |
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 |
OSError
|
When |
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. |
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 |
_INFERENCE_OVERHEAD
|
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
Estimated bytes required at inference time. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
extract_json_list
¶
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 |
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
¶
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 |
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
¶
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. |
required |
token
|
str | None
|
Optional Hub token for gated/private models. |
None
|
Returns:
| Type | Description |
|---|---|
int | None
|
int | None: The total parameter count, or |
int | None
|
be determined (no |
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
|
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
|
None
|
max_attempts
|
int
|
Generations to spend before giving up. |
3
|
temperature_step
|
float
|
Added per retry (attempt 1 at |
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 |
ValidationError
|
When an item fails validation and
|
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_FIELDandjson_schemastructured output;google— :data:DEFAULT_GOOGLE_OPENAI_URL,json_schemastructured output and :data:GOOGLE_EFFORT_VALUES;deepseek—json_objectstructured output (the only JSON mode DeepSeek documents) and noreasoning_effortfield.
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 |
None
|
Returns:
| Type | Description |
|---|---|
AnthropicGenerator | OpenAICompatGenerator
|
AnthropicGenerator | OpenAICompatGenerator: The generator. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When the provider cannot be resolved, |
Example
gen = hosted_generator("claude-haiku-5-5", api_key="sk-ant-...") isinstance(gen, AnthropicGenerator) True
image_part
¶
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 ( |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: ``{"type": "image_url", "image_url": {"url": |
dict[str, Any]
|
"data: |
Example
part = image_part(b"\x89PNG...", "image/png") text = {"type": "text", "text": "Read it."} messages = [{"role": "user", "content": [part, text]}]
is_deterministic
¶
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
|
|
is_document_part
¶
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 |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
bool
|
func: |
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
|
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 |
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 adoneevent.
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'
|
tags
|
list[str] | None
|
OpenAPI tags. Defaults to |
None
|
current_user_id
|
Callable[..., Any] | None
|
FastAPI dependency
resolving the authenticated caller's user id. Required when
the pipeline has a |
None
|
dependencies
|
Sequence[Any] | None
|
Applied to every route — where authentication and rate limiting go. |
None
|
docs_locale
|
str | None
|
Language of the OpenAPI |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
APIRouter |
APIRouter
|
Ready to mount with |
Raises:
| Type | Description |
|---|---|
ValueError
|
When the pipeline has a |
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) andPOST {prefix}/generate/stream(token-by-token SSE), plusPOST {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(returnsaudio/wav).image_generator->POST {prefix}/image(returns the encoded image, with the seed inX-Image-Seed).audio_generator->POST {prefix}/audio(returns oneaudio/wavclip, with the seed inX-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 |
None
|
embedder
|
SupportsEmbed | None
|
Backs |
None
|
retriever
|
SupportsRetrieve | None
|
Backs |
None
|
speech_to_text
|
SpeechTranscriber | None
|
Backs |
None
|
text_to_speech
|
SpeechSynthesizer | None
|
Backs |
None
|
image_generator
|
ImageGenerator | None
|
Backs |
None
|
audio_generator
|
SupportsAudioGeneration | None
|
Backs |
None
|
models
|
ModelRegistry | dict[str, Any] | list[Any] | None
|
Backs
|
None
|
prefix
|
str
|
URL prefix. Defaults to |
'/api/genai'
|
tags
|
list[str] | None
|
OpenAPI tags. Defaults to |
None
|
limits
|
GenAIRequestLimits | None
|
Per-request ceilings. |
None
|
docs_locale
|
str | None
|
Language of the OpenAPI |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
APIRouter |
APIRouter
|
Ready to mount with |
Raises:
| Type | Description |
|---|---|
ValueError
|
When no GenAI object is provided (the router would be
empty). Emptiness is tested with |
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'
|
identity
|
Mapping[str, Any] | None
|
Extra model identity fields;
entries whose value is |
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: |
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 |
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
|
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: |
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 |
int | None
|
when the Hub is unreachable or reports no per-file sizes. |
Raises:
| Type | Description |
|---|---|
ImportError
|
When |
parse_structured
¶
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 |
ValidationError
|
When the JSON does not satisfy |
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 |
ValidationError
|
When an item does not satisfy |
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
|
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 |
|
HardwareInfo
|
when neither answers |
|
HardwareInfo
|
fields are |
|
HardwareInfo
|
the reading is then bounded by the process's cgroup memory limit |
|
HardwareInfo
|
(v2 |
|
HardwareInfo
|
ancestry) when that limit is below the host's RAM, and |
|
HardwareInfo
|
|
|
HardwareInfo
|
When the disk query raises |
|
HardwareInfo
|
|
|
HardwareInfo
|
( |
|
HardwareInfo
|
|
|
HardwareInfo
|
is installed, |
|
HardwareInfo
|
look for |
|
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 ( |
|
CapacityReport
|
is the report at the native precision: the ladder needs a number to |
|
CapacityReport
|
step down from, and stepping to |
|
CapacityReport
|
recommend a slower, lossier load for nothing. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When neither |
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
|
cache_dir
|
str | None
|
The cache to operate on; |
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 |
int
|
|
|
int
|
which is a successful no-op rather than an error. |
Raises:
| Type | Description |
|---|---|
ImportError
|
When |
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
|
|
required |
hardware
|
HardwareInfo | None
|
Injected snapshot (tests); probed
when |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The concrete device — CUDA → MPS → CPU for |
resolve_provider
¶
resolve_provider(model: str) -> HostedProvider
Read the provider off a model id.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
str
|
The model id ( |
required |
Returns:
| Name | Type | Description |
|---|---|---|
HostedProvider |
HostedProvider
|
The provider the id belongs to. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When no prefix in :data: |
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'
|
token
|
str | None
|
Token for gated or private repositories. |
None
|
Returns:
| Type | Description |
|---|---|
str | None
|
str | None: The commit sha, or |
str | None
|
reached or the repository/revision does not exist. Callers treat |
str | None
|
|
str | None
|
silently — the caller decides whether to proceed unpinned. |
Raises:
| Type | Description |
|---|---|
ImportError
|
When |
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 |
required |
hardware
|
HardwareInfo | None
|
A snapshot to reuse instead of probing again. |
None
|
probe
|
bool
|
When no |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
ModelRuntimeReport |
ModelRuntimeReport
|
The handles plus, optionally, the host |
ModelRuntimeReport
|
snapshot. |
supports_documents
¶
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
|
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
Example
supports_documents("anthropic") True supports_documents("deepseek") False
to_anthropic_document
¶
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]
|
|
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: ``{"type": "document", "source": {"type": "base64", |
dict[str, Any]
|
"media_type": ..., "data": ...}} |
dict[str, Any]
|
names a file. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When the part carries no |
to_anthropic_image
¶
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]
|
|
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: |
Raises:
| Type | Description |
|---|---|
ValueError
|
When the URL is empty, or a |
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 |
required |
keep_system
|
bool
|
Always retain |
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. |