backends¶
Responsibility¶
Generate assistant text for a rendered snapshot, with the audio and images the model takes, returning a
GenerationRecord; optional prefix reuse and embeddings.
Public surface¶
Backends read
context.config.backend;generate(snapshot, generation).MockBackend(mock): deterministic text hashed from the snapshot id, eachmessage_chat_text, model id and generation; at most 16 four-character tokens.score_continuationsdraws an 8-token law per position from the prompt hash.MockAudioBackend(mock_audio): echoes words, then a token per voiced run of eachAudioPart(amplitude aboveSILENCE0.01, runs split byMIN_GAP_S0.01 s) (decision). 16-bit WAV decodes withwave, other formats withdecode_audio.MockImageBackend(mock_image): a token per square of one saturated colour.ReplayBackend(replay): serves archived rows by coalition key; a miss raisesReplayMissErrorunlessfallbackserves it.ApiBackend(api): OpenAI-compatible/chat/completionsoverhttpx, withTimeout(backend.timeout_s)andmax_inflightconnections.Retries
RETRYABLE_STATUS(408, 429, 5xx gateway codes) and transport errors up tobackend.max_retrieswith backoff, honouringRetry-Afterup totimeout_s. Non-JSON responses raiseBackendUnavailableError.snapshot_to_api_messages: a message with media sends text, base64 WAVinput_audioand data-URIimage_urlparts.Sends
"logprobs": true;extract_logprobsreadschoices[0].logprobs.content[*].logprob, elseNone; an empty reply gets()(LM Studio sendsnull), whichself_logprobscores 0.returns_logprobsis true (SupportsLogprobs).Caches temperature-0 records in an LRU of
RESPONSE_CACHE_SIZE(1024).backend.api_hostis required (ConfigErrorwithout it; no environment or localhost fallback).Key:
MLLM_SHAP_API_KEY, orOPENAI_API_KEYforapi.openai.com.
LmStudioBackend(lmstudio): local LM Studio server through thelmstudioSDK.LmStudioOptions(hub_search,quantization,auto_download,serialize_generate,audio) come frombackend.options; unknown keys raiseConfigError.audio: refuse(default) raisesValueErroron audio;transcriptsends the text parts and warns once. Images upload once per hash (prepare_image) and attach to their user message.match_downloaded_model_keymatches exactly, by last-segment prefix, then by substring; ambiguity raises, as doespick_search_resultwithout a matching hub hit.Retries once on transient connection errors (
_is_transient); no logprobs.
TransformersTextBackend(transformers): Hugging Face model on CUDA (Compute Unified Device Architecture), MPS (Metal Performance Shaders) or CPU.TransformersOptions:dtype(auto: bfloat16 where supported, else float16, float32 on CPU),revision,model_class,processor_kwargs.A config in
MODEL_FOR_CAUSAL_LM_MAPPINGloads as text; any other (ormodel_class) loads its class withAutoProcessor(decision).processor.processor_inputssends images, and audio when the chat template mentions it, as template parts (base64 WAV for mistral-common); else oneaudio_tokenper clip. Empty clips drop; media batch bycollate_inputs. Omni models run through theirthinker, without prefix cache.One model lock covers encoding, generation, decoding and scoring.
With the key-value (KV) cache enabled (
SupportsKvCache),_attach_prefix_cachecopies and crops the longest cached prefix and runs the uncovered tokens;kv_cache_hitsandkv_cache_reused_tokenscount the reuse.Embeddings need
generation.compute_embeddings.generatereturns raw logits (output_logits);_token_logprobstakes their log-softmax at each generated token, end-of-sequence included.returns_logprobsis true.score_continuations: one forward pass over prompt plus continuation (audio prompts with features); optional top-knext tokens.
backends/_chat.py:snapshot_has_audio,snapshot_has_image,snapshot_has_media,chat_role,message_chat_text("<speaker>: <text>"unless the text is empty; speaker rendering),message_parts(percontent_order),snapshot_to_chat_messages.
Data flow¶
In: rendered
ConversationSnapshotandGenerationConfigfrom the pipeline orchestrator;PluginContextat construction.Out:
GenerationRecordbuilt withvalue.generation_records.generation_record_from_text(text)(value), with model embeddings when requested; other backends have none, so their records equal thosereanalyzebuilds.Optional dependencies (
httpx,lmstudio,torch,torchaudio,transformers) are imported lazily; a missing extra raisesBackendUnavailableError(core).
Invariants¶
Media prompts skip the prefix cache; a text model refuses media and
lmstudioaudio (unlessaudio: transcript) withValueError;mockhashes text and the snapshot id only.mock_audio: a run’s token depends on its samples only, so silencing or cutting another run leaves it unchanged.In float32, greedy transformers outputs are identical with the prefix cache on and off, and their logprobs agree within 1e-4; in float16 and bfloat16 they agree up to rounding, and the backend warns once (decision). No prompt token is processed twice.
An injected backend is reused across calls and closed by the runner; otherwise one is built and closed per
explain().
Known issues¶
None open. Fixed: C06, C08, C15, D02, D04, D05, D07 (Fixed issues).