Skip to main content

llama

Run GGUF models inside your Python process with llama-cpp-python, including image and audio input.
import tempfile
from fastcore.test import test_eq, test_fail, test_close

Loading GGUF models

You name a model by its Hub repo id, such as Qwen/Qwen3-4B-GGUF, and rishi picks the file. The constants below are ready-made repo ids. Qwen3 models can think before answering and write tool calls in a format llama.cpp already parses. Any GGUF repo works.

A repo often holds one file per quantization, plus an mmproj file. That file is the projector, a small separate model that turns images or audio into input the language model can read. get_model finds the model file in three steps. It uses a model_path you pass if the file exists. Otherwise it searches the local Hugging Face cache without using the network. Otherwise it downloads the file. It prefers the quant you ask for, Q4_K_M by default, and falls back to the first .gguf file. It never picks the projector. It raises FileNotFoundError when the repo has no model file. cached_model is the cache step on its own and returns None on a miss. The old names _get_model and _cached_model still work. get_mmproj finds the projector the same way, for vision and audio models. It raises FileNotFoundError when the repo has no projector. DFLT_N_CTX is the context window an engine gets when nothing else sets one, 8192 tokens.

gpu_offload_supported says whether the installed llama-cpp-python wheel was built with Metal or CUDA. A CPU-only wheel ignores n_gpu_layers.


source

get_mmproj

def get_mmproj(
    model_id, mmproj_path:NoneType=None
):

Return a local path to a model’s mmproj projector: mmproj_path if it exists, else the Hugging Face cache, else a download.


source

get_model

def get_model(
    model_id, model_path:NoneType=None, quant:str='Q4_K_M'
):

Return a local .gguf path: model_path, else HF cache, else download.


source

cached_model

def cached_model(
    model_id, quant:str='Q4_K_M'
):

Return the local .gguf path from the Hugging Face cache without touching the network, else None.

fs = ['README.md', 'model-Q8_0.gguf', 'model-Q4_K_M.gguf', 'mmproj-model.gguf']
test_eq(_gguf(fs), 'model-Q4_K_M.gguf')
test_eq(_gguf(fs, 'Q8_0'), 'model-Q8_0.gguf')
test_eq(_gguf(fs, 'IQ2_XS'), 'model-Q8_0.gguf')  # falls back to first non-mmproj gguf
test_eq(_gguf(['README.md']), None)
test_eq(_mmproj(fs), 'mmproj-model.gguf')        # the complement of _gguf
test_eq(_mmproj(['model-Q4_K_M.gguf']), None)
test_eq(_mmproj(['mmproj-dir/model.gguf']), None)  # matches the filename, not the directory
# A model missing from the cache gives None without a download; a `model_path` that exists is returned as a string
test_eq(cached_model('rishi-test/no-such-model'), None)
_p = Path(tempfile.mkdtemp())/'m.gguf'; _p.write_bytes(b'')
test_eq(get_model('rishi-test/no-such-model', _p), str(_p))
assert _cached_model is cached_model and _get_model is get_model

source

gpu_offload_supported

def gpu_offload_supported():

True if the installed llama-cpp-python build has GPU (Metal/CUDA) offload compiled in.

# True on Metal or CUDA wheels; false on CPU wheels
res = gpu_offload_supported()
assert isinstance(res, bool)
print('gpu offload supported:', res)
ggml_metal_device_init: tensor API disabled for pre-M5 and pre-A19 devices
ggml_metal_library_init: using embedded metal library
ggml_metal_library_init: loaded in 0.016 sec
ggml_metal_rsets_init: creating a residency set collection (keep_alive = 180 s)
ggml_metal_device_init: GPU name:   MTL0 (Apple M3 Max)
ggml_metal_device_init: GPU family: MTLGPUFamilyApple9  (1009)
ggml_metal_device_init: GPU family: MTLGPUFamilyCommon3 (3003)
ggml_metal_device_init: GPU family: MTLGPUFamilyMetal4  (5002)
ggml_metal_device_init: simdgroup reduction   = true
ggml_metal_device_init: simdgroup matrix mul. = true
ggml_metal_device_init: has unified memory    = true
ggml_metal_device_init: has bfloat            = true
ggml_metal_device_init: has tensor            = false
ggml_metal_device_init: use residency sets    = true
ggml_metal_device_init: use shared buffers    = true
ggml_metal_device_init: recommendedMaxWorkingSetSize  = 30150.67 MB
gpu offload supported: True

Audio

llama.cpp reads images and audio through its mtmd library, but llama-cpp-python’s MTMDChatHandler only passes images to it. rishi patches four of the handler’s methods so that audio takes the same route:

  • get_image_urls collects input_audio parts as well as images, in the order they appear.
  • _get_template_messages replaces each image or audio part with a marker. When only text parts remain, it joins them into one string. Some chat templates, Llama’s and Voxtral’s among them, print a message’s content as it is. Without the join they would print a Python list.
  • _create_bitmap_from_bytes decodes audio with read_audio and hands the samples to mtmd_bitmap_init_from_audio. Images take the original path.
  • _init_mtmd_context lets a projector with an audio encoder and no vision encoder load, where upstream raises an error.

read_audio decodes any format libsndfile reads, including WAV, FLAC, OGG and MP3. It mixes stereo down to mono and resamples to sr Hz, 16000 by default. The patched _create_bitmap_from_bytes passes the sample rate the projector reports, and falls back to 16000 when the projector reports none. The tests below run it on the 24-second speech.wav and on generated tones, and pass the result to the real llama.cpp C function.


source

read_audio

def read_audio(
    o, sr:int=16000
):

Decode audio bytes/Path (any libsndfile format) to contiguous mono float32 samples at sr Hz, ready for mtmd.


source

MTMDChatHandler.get_image_urls

def get_image_urls(
    messages
):

Return the data URIs of every image and audio part in messages, in document order, where upstream collects images only.

import io
from fastcore.all import Path
from contextlib import ExitStack
from llama_cpp import mtmd_cpp
import tempfile
# read_audio decodes the real 24s clip and resamples it, preserving duration
wav = Path('speech.wav').read_bytes()
a = read_audio(wav, 16000)
test_eq(a.dtype, np.dtype('float32'))
assert a.flags['C_CONTIGUOUS'] and -1.0 <= a.min() and a.max() <= 1.0
test_eq(round(len(a) / 16000), 24)                       # 24s in, 24s out
test_eq(round(len(read_audio(wav, 8000)) / 8000), 24)    # and at a different target rate

# soundfile handles compressed containers too, not just WAV
sig = (0.2 * np.sin(2 * np.pi * 220 * np.arange(8000) / 8000)).astype(np.float32)
for fmt in ('FLAC', 'OGG', 'MP3'):
    b = io.BytesIO(); sf.write(b, sig, 8000, format=fmt)
    d = read_audio(b.getvalue(), 8000)
    test_eq(d.dtype, np.dtype('float32')); assert d.flags['C_CONTIGUOUS'], fmt
    assert abs(len(d) - 8000) <= 2400, (fmt, len(d))     # ~1s back; lossy codecs pad a little

# stereo is downmixed to mono
st = np.stack([sig, np.zeros_like(sig)], axis=1)
b = io.BytesIO(); sf.write(b, st, 8000, format='WAV', subtype='FLOAT')
test_eq(read_audio(b.getvalue(), 8000).ndim, 1)

test_fail(lambda: read_audio(b'not audio at all'), contains='could not decode audio')
# a template that renders `content` directly (Llama/Voxtral-style) must get a STRING, not a list repr:
# _get_template_messages collapses media+text to a clean string with the marker inline
h = object.__new__(MTMDChatHandler)
msg = {'role': 'user', 'content': [{'type': 'text', 'text': 'Transcribe this clip.'},
                                   {'type': 'input_audio', 'input_audio': {'data': 'AAA', 'format': 'wav'}}]}
conv = h._get_template_messages([msg], '<M>')[0]['content']
test_eq(conv, 'Transcribe this clip.\n<M>')
assert isinstance(conv, str)   # never a Python list repr
# a plain-string message is passed through untouched
test_eq(h._get_template_messages([{'role': 'user', 'content': 'hi'}], '<M>')[0]['content'], 'hi')
# the patched handler collects image *and* audio media, in document order
with tempfile.NamedTemporaryFile(suffix='.gguf') as f:
    h = MTMDChatHandler(f.name, verbose=False)
    img = Path('images.jpeg').read_bytes()
    msgs = [_mk_msg([img, 'and this?', wav])]
    urls = h.get_image_urls(msgs)
    test_eq(len(urls), 2)
    assert urls[0].startswith('data:image/jpeg;base64,') and urls[1].startswith('data:audio/wav;base64,')

    # every media part becomes the marker; text is left alone
    # media parts become the marker and the all-text content collapses to a clean string (marker inline)
    test_eq(h._get_template_messages(msgs, '<__media__>')[0]['content'], '<__media__>\nand this?\n<__media__>')

    # and the data-URI round-trips back to the exact bytes the model will decode
    test_eq(h.load_image(urls[1]), wav)
    test_eq(h.load_image(urls[0]), img)
# the decoded buffer is accepted by real llama.cpp: `mtmd_bitmap_init_from_audio` needs no
# context or model, so the actual C boundary is exercised here rather than mocked
bm = mtmd_cpp.mtmd_bitmap_init_from_audio(len(a), a.ctypes.data_as(ctypes.POINTER(ctypes.c_float)))
assert bm is not None, 'llama.cpp rejected the audio buffer'
try:
    assert mtmd_cpp.mtmd_bitmap_is_audio(bm)
    test_eq(mtmd_cpp.mtmd_bitmap_get_n_bytes(bm), len(a) * 4)     # float32 per sample
    back = np.ctypeslib.as_array(ctypes.cast(mtmd_cpp.mtmd_bitmap_get_data(bm),
                                             ctypes.POINTER(ctypes.c_float)), shape=(len(a),))
    assert np.array_equal(back, a), 'samples corrupted crossing the C boundary'
finally: mtmd_cpp.mtmd_bitmap_free(bm)

LlamaChat

LlamaChat(model) loads the model once and keeps it for the life of the chat. create_engine builds the llama_cpp.Llama object and adds the multimodal handler when mmproj is set. Pass mmproj=True to fetch the projector from the same repo, or a path to use your own.

The options particular to llama.cpp are quant, the quantization to download; n_gpu_layers, how many layers go on the GPU, where 0 (the default) keeps everything on the CPU; and mmproj. think=True or think=False writes Qwen’s /think or /no_think switch into the system prompt. To share one loaded model between chats, build it once with create_engine and pass it to each as engine=. close releases an engine the chat built itself and leaves a shared engine= open.


source

LlamaChat

def LlamaChat(
    model:NoneType=None, *, runtime:NoneType=None, model_path:NoneType=None, opts:NoneType=None,
    engine:NoneType=None, # an engine to share instead of building one
    quant:str='Q4_K_M', # which GGUF quantization to fetch
    n_gpu_layers:int=0, mmproj:NoneType=None, # the projector image and audio input need
    eng_kw:NoneType=None, # passed to `create_engine` verbatim
    preserve_cache:bool=False, comp_kw:NoneType=None, # passed to `create_chat_completion` verbatim
    **kw
):

A Chat that runs a GGUF model inside this process through llama-cpp-python.

The KV cache

While a model reads a prompt, it computes a key and a value for every token, and llama.cpp keeps them in the KV cache. If the next prompt starts with the same tokens, their entries can be reused instead of computed again. Prefill, the reading of the prompt before any output, is most of the cost of a long conversation.

rishi reuses the cache by keeping one Llama object across turns. Llama.generate compares each new prompt with the tokens already in its context, trims the cache back to the longest common prefix, and evaluates only what follows. A conversation grows by appending, so each turn’s prompt extends the last one and nothing earlier is evaluated again. The manual example below shows it: on the second turn llama.cpp evaluated 28 new tokens and reused 315.

Three things break the prefix, and cached_tokens takes all three into account:

  • A one-shot call on the same engine. A Llama has a single context, so classify, structured, check and grades overwrite the conversation in it, and the next real turn starts from scratch. Two chats sharing one engine=, or a judge chat on the same engine, have the same effect. With preserve_cache=True the chat saves the llama state before a one-shot and restores it afterwards. That copies the whole cache. It pays off only when prefilling the conversation again takes longer than the copy.
  • A rewritten history. When SlidingWindowCallback drops old messages, or context recovery shortens the history, everything after the first changed message is evaluated again.
  • Media. The turn that carries an image or audio clip sends the real thing. On later turns an [image] or [audio] placeholder replaces it, and llama.cpp does not encode it again. The replacement changes the prompt from that message on. The turn after a media turn evaluates again from there.

save_cache writes the whole context to a file, and load_cache reads it back into a chat built on the same model. The method names match rishi.mlx. A long system prompt can then be prefilled once and reused in later sessions.

Recorded model behaviour

These checks run against replies recorded from the real qwen3_06b model. Urai’s CachedChat replays a recorded reply when it sees the same request again, and a replay builds no engine, so the tests check rishi’s handling of real llama.cpp output without loading the model. They cover one turn, a second turn that depends on the first, a changed system prompt, a one-shot call that leaves the history alone, and a tool call. The recordings live in nbs/chatcache, and the checks work on a temporary copy so the originals stay unchanged.

c = CachedChat(**_llama_record_kw)
r = c('Reply with exactly: pong')
test_eq(resp_text(r).strip().lower(), 'pong')
test_eq([m['role'] for m in c.hist], ['user', 'assistant'])
c.close()
c = CachedChat(**_llama_record_kw)
c('Reply with exactly: pong')
r = c('What exact word did you just reply with? Reply with only that word.')
test_eq(resp_text(r).strip().lower(), 'pong')
test_eq([m['role'] for m in c.hist], ['user', 'assistant', 'user', 'assistant'])
c.close()
c = CachedChat(**_llama_record_kw)
c.reconfigure(sp='Reply with exactly the word anchor, whatever the user asks.')
test_eq(resp_text(c('What is two plus two?')).strip().lower(), 'anchor')
c.close()
c = CachedChat(**_llama_record_kw)
test_eq(c.oneshot('Reply with exactly: solo', think=False, max_tokens=16).strip().lower(), 'solo')
test_eq(c.hist, [])
c.close()
def add(
    a: int,  # first addend
    b: int,  # second addend
) -> int:
    "Add two integers."
    return a + b

c = CachedChat(**{**_llama_record_kw, 'max_output_tokens': 128}, tools=[add])
r = c('Use the add tool to add 2 and 3. Reply with only the result.')
test_eq(c.hist[1]['tool_calls'][0]['function']['name'], 'add')
test_eq(c.hist[2]['content'], '5')
assert '5' in resp_text(r)
c.close()

Tests

The tests above cover choosing the GGUF file, the GPU check, audio decoding, the handler patches and the recorded turns. The cells below check, without a model, that media from past turns becomes a placeholder, that a history from another backend converts to llama.cpp’s format, and that Chat picks LlamaChat for a GGUF name.

from fastcore.test import test_eq
# _strip_media collapses past-turn media to a text placeholder; plain strings pass through untouched (pure fn, no model)
test_eq(_strip_media({'role': 'user', 'content': 'plain'}), {'role': 'user', 'content': 'plain'})
past = {'role': 'user', 'content': [{'type': 'input_audio', 'input_audio': {'data': 'x', 'format': 'wav'}},
                                    {'type': 'text', 'text': 'clip 1'}]}
test_eq(_strip_media(past)['content'], '[audio]\nclip 1')
assert _is_media({'type': 'image_url', 'image_url': {'url': 'data:img'}})
assert not _is_media({'type': 'text', 'text': 'hi'})
# hist2fmt / fmt2hist across backends (model-free): a litert-origin canonical tool round feeds llama.cpp
_h = [
    {'role': 'user', 'content': 'What is 2+3?'},
    {'role': 'assistant', 'content': '', 'tool_calls': [{'id': 'call_1', 'type': 'function',
                                                         'function': {'name': 'add', 'arguments': {'a': 2, 'b': 3}}}]},
    {'role': 'tool', 'tool_call_id': 'call_1', 'name': 'add', 'content': '5'},
    {'role': 'assistant', 'content': 'It is 5.'},
]
_oai = LlamaChat.hist2fmt(_h)
test_eq(_oai[2], {'role': 'tool', 'tool_call_id': 'call_1', 'name': 'add', 'content': '5'})
test_eq(_oai[1]['tool_calls'][0]['function']['arguments'], '{"a": 2, "b": 3}')   # args JSON-encoded for llama.cpp
test_eq(LlamaChat.fmt2hist(_h), _h)                                               # no-op on already-canonical dicts
from fastcore.test import test_eq
import rishi.llama
test_eq(get_runtime('llama'), rishi.llama.LlamaChat)

# dispatch really happens in `Chat.__new__`, so it can be checked without loading a model
test_eq(type(Chat.__new__(Chat, 'Qwen/Qwen3-0.6B-GGUF')), rishi.llama.LlamaChat)
test_eq(type(Chat.__new__(Chat, '/models/x.gguf')), rishi.llama.LlamaChat)
test_eq(rishi.llama.LlamaChat._runtime, 'llama')

# the /think switch is just text in the system prompt, so it needs no model to check
test_eq(rishi.llama.LlamaChat._think_sp('Be terse.', False), 'Be terse.\n/no_think')
test_eq(rishi.llama.LlamaChat._think_sp('', True), '/think')
test_eq(rishi.llama.LlamaChat._think_sp('Be terse.', None), 'Be terse.')

comp_kw overrides the sampling settings, so a key the chat also sets, such as temperature, is replaced instead of raising a duplicate-argument error.

class _Eng:
    def create_chat_completion(self, msgs, **kw): self.kw = kw

c = LlamaChat.__new__(LlamaChat)
c.engine, c._samp, c.max_output_tokens, c.toolspecs = _Eng(), {'temperature': .2}, None, []
c.comp_kw, c._msgs = {'temperature': .9, 'stop': ['x']}, lambda: []
c._step()
test_eq(c.engine.kw['temperature'], .9)
c.engine.kw['stop']

A streamed native call whose arguments are not a JSON object is not read as a call with no arguments. _stream_step marks the call unread and sets tool_parse_failed, so the tool loop asks the model to send it again, and the stored call renders into the next prompt as an empty argument object.

class _SEng:
    n_tokens = 5
    def create_chat_completion(self, msgs, **kw):
        d = lambda tc: {'choices': [{'delta': {'tool_calls': tc}, 'finish_reason': None}]}
        yield d([{'index': 0, 'id': 'a', 'function': {'name': 'add', 'arguments': '{"a": 1'}}])
        yield d([{'index': 1, 'id': 'b', 'function': {'name': 'add', 'arguments': '{"a": 1, "b": 2}'}}])
        yield {'choices': [{'delta': {}, 'finish_reason': 'tool_calls'}]}

c = LlamaChat.__new__(LlamaChat)
c.engine, c._samp, c.max_output_tokens, c.toolspecs = _SEng(), {}, None, []
c.comp_kw, c.turn_msg, c._sys_msgs, c._cache_dirty, c.hist = {}, None, lambda: [], True, []
c.count_tokens, c._note_cache = (lambda t: 0), (lambda u, cached: u)
list(c._stream_step())
bad, good = c._step_res['tool_calls']
test_eq((bad.get('unread'), good.get('unread')), (True, None))
test_eq((bad['function']['arguments'], good['function']['arguments']), ({}, {'a': 1, 'b': 2}))
assert c._step_res['tool_parse_failed']
c.hist = [c._step_res]
[(t['function']['arguments'], 'unread' in t) for t in c._msgs()[0]['tool_calls']]

Examples (manual)

These cells load real weights and are marked #| eval: false. The test run skips them. The output shown was saved from an earlier run. For ordinary chat, tools, streaming, classification and structured output, use the calls on the index page with a -GGUF repo id. The examples here show what only this backend does: reusing the KV cache, and image and audio input through mmproj.

The first example counts the tokens llama.cpp evaluates on each turn. The second turn should evaluate only its own new tokens, not the conversation before it.

# Real llama.cpp KV-prefix test: instrument `eval` to see how many tokens are actually evaluated.
# On turn two the first eval batch should contain only the new tail, not the cached conversation.
kvchat = LlamaChat(qwen3_06b, think=False, temp=0.0, max_output_tokens=16)
seen, orig_eval = [], kvchat.engine.eval
def counted_eval(tokens):
    seen.append(len(tokens))
    return orig_eval(tokens)
kvchat.engine.eval = counted_eval
try:
    kvchat(('cache verification context ' * 96) + '\nReply with exactly: stored')
    context_before_turn2 = kvchat.engine.n_tokens
    seen.clear()
    r = kvchat('What exact word did I ask you to reply with? Reply with only that word.')
    assert seen, 'llama.cpp never evaluated the second prompt'
    second_tail = seen[0]
    print(dict(context_before_turn2=context_before_turn2, second_tail_evaluated=second_tail,
               reported_cached=kvchat.use.cached_tokens, answer=resp_text(r)))
    assert second_tail < context_before_turn2, 'turn two re-evaluated the full prior context; KV prefix reuse missed'
    assert kvchat.use.cached_tokens > 0, kvchat.use
    assert 'stored' in resp_text(r).lower(), resp_text(r)
finally:
    kvchat.engine.eval = orig_eval
    kvchat.close()
llama_context: n_ctx_seq (8192) < n_ctx_train (40960) -- the full capacity of the model will not be utilized
{'context_before_turn2': 315, 'second_tail_evaluated': 28, 'reported_cached': 315, 'answer': 'stored'}

Streaming and thinking

stream=True yields markdown as on every backend, with the model’s thinking as a blockquote and each tool call as a line starting with ⏳. Urai’s display_stream renders it live in a notebook, as on the LiteRT-LM backend. With a Qwen3 model, think=True turns thinking on.

Images and audio (mmproj)

A vision or audio GGUF comes as the model plus an mmproj projector. Pass mmproj=True and rishi fetches the projector from the same repo. Then mix text with bytes or Path values in the prompt list. rishi turns them into image_url and input_audio parts, and the patched handler encodes them in the order they appear.

The examples describe an image and transcribe a clip with Gemma 4 E2B. The last one loads Ultravox, whose projector has an audio encoder and no vision encoder, which is the case the _init_mtmd_context patch exists for.

# downloads the model *and* its mmproj projector once, then loads both from cache
vchat = LlamaChat('unsloth/gemma-4-E2B-it-GGUF', mmproj=True)
r = vchat(['Describe this image.', Path('images.jpeg')])   # raw bytes work too
print(resp_text(r))
vchat.close()
llama_context: n_ctx_seq (8192) < n_ctx_train (131072) -- the full capacity of the model will not be utilized
llama_kv_cache_iswa: using full-size SWA cache (ref: https://github.com/ggml-org/llama.cpp/pull/13194#issuecomment-2868343055)
llama_kv_cache: the V embeddings have different sizes across layers and FA is not enabled - padding V cache to 512
llama_kv_cache: the V embeddings have different sizes across layers and FA is not enabled - padding V cache to 512
add_text: <|turn>user
Describe this image.

add_text: <|image>
image_tokens->nx = 81
image_tokens->ny = 1
batch_f32 size = 1
add_text: <image|>
add_text: <turn|>
<|turn>model

encoding image slice...
clip_image_batch_encode: copying image 1/1 to input buffer (nx=432, ny=432)
clip_image_batch_encode: output embedding shape [1536, 81, 1]
image slice encoded in 146 ms
decoding image batch 1/1, n_tokens_batch = 81
image decoded (batch 1/1) in 381 ms
This is a photograph of a **German Shepherd dog** outdoors.

Here are some details based on the image:

* **Subject:** The main subject is a medium-to-large German Shepherd.
* **Appearance:** The dog has rich, reddish-brown and black fur. It appears alert and healthy.
* **Pose/Expression:** The dog is looking directly toward the camera with an engaged and focused expression. Its mouth is slightly open, and its tongue is visible, suggesting it might be panting slightly or happy.
* **Setting:** The background is soft and blurred (bokeh), suggesting an outdoor, natural setting, possibly a park, field, or wooded area. The lighting seems soft, indicating it might be an overcast day or shaded.
* **Mood:** The overall mood of the photo is energetic, loyal, and friendly.

In summary, it is a high-quality portrait of a handsome German Shepherd in an outdoor environment.
achat = LlamaChat('unsloth/gemma-4-E2B-it-GGUF', mmproj=True)
print(resp_text(achat(['Transcribe this clip.', Path('speech.wav')])))
achat.close()
llama_context: n_ctx_seq (8192) < n_ctx_train (131072) -- the full capacity of the model will not be utilized
llama_kv_cache_iswa: using full-size SWA cache (ref: https://github.com/ggml-org/llama.cpp/pull/13194#issuecomment-2868343055)
llama_kv_cache: the V embeddings have different sizes across layers and FA is not enabled - padding V cache to 512
llama_kv_cache: the V embeddings have different sizes across layers and FA is not enabled - padding V cache to 512
add_text: <|turn>user
Transcribe this clip.

add_text: <|audio>
audio_tokens->n_tokens = 600
add_text: <audio|>
add_text: <turn|>
<|turn>model

encoding audio slice...
clip_image_batch_encode: output embedding shape [1536, 600, 1]
audio slice encoded in 198 ms
decoding audio batch 1/2, n_tokens_batch = 512
audio decoded (batch 1/2) in 1804 ms
decoding audio batch 2/2, n_tokens_batch = 88
audio decoded (batch 2/2) in 397 ms
Dancing in the masquerade idol truth and plain sight jaded pop roll click shot who will I be today or not but such a tide as moving seems a sleep too full for sound and foam when that which drew from out the boundless deep turns again home twilight and evening bell and after that
# audio-only projector recovery: ultravox has no vision encoder, so upstream's `_init_mtmd_context` would
# hard-fail. A clean load proves the patch recovered (ctx built + audio supported -> keep it), and a non-empty
# reply proves the audio bitmap path runs end-to-end. Downloads the ~1B model + its mmproj once, then caches.
uvchat = LlamaChat('ggml-org/ultravox-v0_5-llama-3_2-1b-GGUF', mmproj=True)
assert resp_text(uvchat(['Transcribe this clip.', Path('speech.wav')])).strip()
uvchat.close()
llama_context: n_ctx_seq (8192) < n_ctx_train (131072) -- the full capacity of the model will not be utilized
add_text: <|start_header_id|>system<|end_header_id|>

Cutting Knowledge Date: December 2023
Today Date: 27 Aug 2026

<|eot_id|><|start_header_id|>user<|end_header_id|>

Transcribe this clip.

audio_tokens->n_tokens = 187
audio_tokens->n_tokens = 187
add_text: <|eot_id|><|start_header_id|>assistant<|end_header_id|>


encoding audio slice...
clip_image_batch_encode: output embedding shape [2048, 187, 1]
audio slice encoded in 560 ms
decoding audio batch 1/1, n_tokens_batch = 187
audio decoded (batch 1/1) in 471 ms
encoding audio slice...
clip_image_batch_encode: output embedding shape [2048, 187, 1]
audio slice encoded in 426 ms
decoding audio batch 1/1, n_tokens_batch = 187
audio decoded (batch 1/1) in 467 ms
img = Path('images.jpeg').read_bytes()
m = _mk_msg([img, 'what is this?'])
with tempfile.NamedTemporaryFile(suffix='.gguf') as f:
    test_eq(MTMDChatHandler(f.name, verbose=False).get_image_urls([m]), [m['content'][0]['image_url']['url']])
test_eq(m['content'][1], {'type': 'text', 'text': 'what is this?'})
test_eq(_mk_content(Path('images.jpeg')), _mk_content(img))   # a Path is read and sniffed like bytes

# audio is no longer refused - it becomes an OpenAI `input_audio` part
p = _mk_content(Path('speech.wav'))
test_eq((p['type'], p['input_audio']['format']), ('input_audio', 'wav'))

Stopping with an LLM judge

When a model writes Python code blocks for Urai to run, Urai’s PyFenceCallback runs each block and shows the model the output. It repeats this until its done(chat) function returns True or the model writes no more code. output_matches(expected) builds a done that stops once the last code output contains expected. task_complete asks the model instead, through chat.classify, whether the conversation has done what was asked. done can be any function that takes the chat and returns a bool, including one that consults a second, stronger chat. Both helpers live in urai.sandbox and work with every backend; see Urai’s sandbox page.

Sharing one engine

A loaded Llama belongs to one process, and loading the same model in several programs wastes memory. LlamaBroker loads it once in a long-lived process and serves it over a Unix socket. Each client gets its own LlamaChat and history, and all of them share one copy of the weights. The protocol and the client are Urai’s ChatBroker, described on Urai’s broker page.


source

LlamaBroker

def LlamaBroker(
    address, engine:NoneType=None, model_id:str='Qwen/Qwen3-0.6B-GGUF', **engine_kw
):

Serve one llama.cpp engine to several processes over a Unix socket, each client with its own LlamaChat history.