Skip to main content

litert

Run Google’s .litertlm model builds, such as Gemma 4, with LiteRT-LM, on the GPU or the CPU.

Messages

LiteRT-LM has its own Message and Content classes. _mk_content turns a string, bytes or a Path into the right content type, telling image from audio by the bytes themselves or by the file extension. _mk_msg and _mk_msgs build whole messages from those.

import tempfile
from fastcore.test import test_eq, test_fail
test_eq(_mk_msg("hello").to_json(), {"role": "user", "content": [{"type": "text", "text": "hello"}]})
test_eq(_mk_msg("hi", role="model").to_json()["role"], Role.MODEL.value)
test_eq(_mk_msg("hi", role="assistant").role, Role.MODEL)   # either spelling, whichever litert-lm names it
test_eq([x["role"] for x in _mk_msgs(["a", _mk_msg("b", role="model")])], ["user", Role.MODEL.value])
assert isinstance(_mk_content("x"), Text)
# bytes are sniffed: image vs audio
assert isinstance(_mk_content(b'\x89PNG\r\n\x1a\n' + b'\x00'*16), ImageBytes)
assert isinstance(_mk_content(b'RIFF\x00\x00\x00\x00WAVE' + b'\x00'*16), AudioBytes)

Portable history

rishi’s history is a list of OpenAI-shaped dicts, while LiteRT-LM speaks its own Message objects and calls the assistant model. fmt2hist converts LiteRT-LM messages into history dicts, and hist2fmt converts them back. That is what lets a conversation started here continue on llama.cpp or a hosted model through messages=, and the reverse. Images and audio from earlier turns become [image] and [audio] placeholders on the way into the history.

LiteRT callbacks

Urai’s chats run callbacks at fixed points in a turn. LiteRT-LM needs its own versions of three of them, because the engine keeps the conversation itself. _HistoryCallback copies each message and reply into chat.hist in the shared format. _UsageCallback works out token usage from how much the conversation’s token_count grew during the turn. _ToolReminderCallback appends a short reminder of the available tools to the outgoing message.

Tool calling

LiteRT-LM runs the tool loop inside the engine. The other local backends run it in rishi. The engine calls your Python function and feeds the result back to the model. ChatToolHandler connects that loop to the chat. Before each call it runs the chat’s before_tool_calls callbacks, checks the tool-call budget, and asks the chat’s approve function if there is one. A refused call is recorded with its reason instead of running. The handler writes each call and its result into chat.hist, and runs the after_tool_calls callbacks after each result. Approval itself is described on Urai’s chat page.

Several chats can share one engine. The engine runs one generation at a time. engine_lock returns the single lock of an engine, and a chat holds it for the length of a turn. The chat releases it while a tool runs, and the tool can use the engine. Chats on other threads wait their turn. A second chat on the same thread cannot wait, because the thread that holds the lock would never release it. That chat raises EngineBusy at once.

EngineHold is that hold for one send. Use it as a context manager, or call take and let_go. ChatToolHandler calls let_go while a tool runs and take after it. A chat that already holds the engine on this thread can take it again. recover_context and a one-shot call from a callback do this. The lock is a plain Lock, so closing a stream abandoned on another thread frees the engine. The old name _Hold still works.


source

ChatToolHandler

def ChatToolHandler(
    chat
):

Connect LiteRT-LM’s built-in tool loop to the chat’s callbacks, approval function, tool-call budget and history.


source

EngineHold

def EngineHold(
    chat
):

Hold a chat’s engine for one send, raising EngineBusy when another chat on this thread holds it.


source

EngineBusy

def EngineBusy(
    *args, **kwargs
):

Raised when a chat sends on an engine that another chat on the same thread is in the middle of a turn on.


source

engine_lock

def engine_lock(
    engine
):

Return the single lock that chats sharing one LiteRT-LM engine take turns on.

Loading models and LitertChat

A .litertlm repo may hold several builds: a portable one, and others made for one kind of hardware, whose names contain -gpu, -npu, -web or an underscore. get_model prefers the portable build. Searches of the repository exclude file names that contain web. An existing model_path bypasses that filter. It finds the file in three steps. It uses a model_path you pass if the file exists. Otherwise it uses a portable build in the local Hugging Face cache. Otherwise it downloads a build, and uses a hardware-specific cached build only when the repo has no portable build or the Hub is unreachable. It raises FileNotFoundError when neither the cache nor the repo has a .litertlm file. cached_model is the cache step on its own. It returns the cached path, or None, without using the network. The old names _get_model and _cached_model still work.

LitertChat.create_engine builds the engine. Unless you name a backend, it tries the GPU first and falls back to the CPU with a warning. Set RISHI_LITERT_GPU=0 to skip the GPU attempt. Pass backend=Backend.GPU() or backend=Backend.CPU() to choose the hardware. On the GPU, activations default to 32-bit floats. With multimodal=True, the default, it also builds the vision and audio encoders that the model file contains. vision_backend and audio_backend choose their hardware, CPU by default. A backend named for an encoder the file lacks gives a warning. cache_dir is the LiteRT-LM cache directory. rishi creates it if it is missing.

think=True turns thinking on. filter_think, on by default, keeps the thought tokens out of the key-value cache (KV cache), where LiteRT-LM stores the keys and values computed for earlier tokens. constrain switches on constrained decoding, which keeps tool calls well formed. It defaults to on when the chat has tools. parallel_tools=True raises NotImplementedError, because the engine’s loop runs one call at a time. If the context window fills during a turn, the chat drops messages from the middle of the history, rebuilds the conversation and sends the turn again. It keeps the first 2 and the last 6 messages. It raises ContextWindowExceededError when nothing can be dropped.

The constants below are the Gemma 4 builds from litert-community.


source

LitertChat

def LitertChat(
    model:NoneType=None, *, runtime:NoneType=None, model_path:NoneType=None, opts:NoneType=None,
    engine:NoneType=None, # an engine to share instead of building one
    backend:NoneType=None, # litert's hardware backend: `Backend.CPU()` or `Backend.GPU()`
    multimodal:bool=True, # build the vision and audio backends too
    cache_dir:NoneType=None, enable_speculative_decoding:NoneType=None,
    eng_kw:NoneType=None, # passed to `create_engine` verbatim
    filter_think:bool=True, # keep thought tokens out of the KV cache
    sampler_config:NoneType=None, # a litert `SamplerConfig`, instead of the portable sampling options
    constrain:NoneType=None, # constrained decoding; default is on when there are tools
    conv_kw:NoneType=None, # passed to `create_conversation` verbatim
    **kw
):

A Chat that runs a .litertlm model inside this process through Google’s LiteRT-LM.


source

get_model

def get_model(
    model_id, model_path:NoneType=None
):

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


source

cached_model

def cached_model(
    model_id
):

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

# A model missing from the cache gives None without a download; a `model_path` that exists is returned as is
test_eq(cached_model('rishi-test/no-such-model'), None)
_p = Path(tempfile.mkdtemp())/'m.litertlm'; _p.write_bytes(b'')
test_eq(get_model('rishi-test/no-such-model', _p), _p)
assert _cached_model is cached_model and _get_model is get_model and _Hold is EngineHold

Recorded model behaviour

These checks run against replies recorded from the real gemma4_e2b model. Urai’s CachedChat replays a recorded reply when it sees the same request again, without loading the model. Each check opens a fresh CachedChat, and they work on a temporary copy of nbs/chatcache so the recordings stay unchanged. They cover one turn, a second turn, a changed system prompt, a one-shot call, a prompt too long for the context window, and a tool call that LiteRT-LM ran itself.

# A normal turn records the response and canonical history produced by LiteRT.
c = CachedChat(**_litert_record_kw)
r = c('Reply with exactly: pong')
test_eq(resp_text(r), 'pong')
test_eq(c.hist, [{'role': 'user', 'content': 'Reply with exactly: pong'},
                 {'role': 'assistant', 'content': 'pong'}])
c.close()
# A second turn sees the first through LiteRT's conversation history.
c = CachedChat(**_litert_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), 'pong')
test_eq([m['role'] for m in c.hist], ['user', 'assistant', 'user', 'assistant'])
c.close()
# Reconfiguration reaches the model without retaining state from another check.
c = CachedChat(**_litert_record_kw)
c.reconfigure(sp='Reply with exactly the word anchor, whatever the user asks.')
r = c('What is two plus two?')
test_eq(resp_text(r), 'anchor')
c.close()
# One-shots use a throwaway LiteRT conversation and do not change history.
c = CachedChat(**_litert_record_kw)
test_eq(c.oneshot('Reply with exactly: solo', think=False, max_tokens=16), 'solo')
test_eq(c.hist, [])
c.close()
c = CachedChat(**{**_litert_record_kw, 'ctx': 64})
test_fail(lambda: c.oneshot('x '*200, think=False, max_tokens=16),
          contains='201 tokens, over the 64-token context window')
test_eq(c.hist, [])
c.close()
# Tool history comes from a real native LiteRT tool round.
def add(a: int, b: int) -> int:
    "Add two integers."
    return a + b

c = CachedChat(**_litert_record_kw, tools=[add])
r = c('Use the add tool to add 2 and 3. Reply with only the result.')
test_eq(resp_text(c.hist[1]), '')
test_eq(c.hist[1]['tool_calls'][0]['function']['name'], 'add')
test_eq(c.hist[2]['role'], 'tool')
test_eq(c.hist[2]['content'], '5.0')
assert '5' in resp_text(r)
c.close()
# fmt2hist / hist2fmt round-trip (model-free)
_nat = [
    'hi',
    Message.model(Contents.of('hello')).to_json(),
    {'role': 'model', 'tool_calls': [{'type': 'function', 'function': {'name': 'add', 'arguments': {'a': 2, 'b': 3}}}]},
    {'role': 'tool', 'content': [{'type': 'tool_response', 'name': 'add', 'response': 5}]},
]
_canon = LitertChat.fmt2hist(_nat)
test_eq(_canon[0], {'role': 'user', 'content': 'hi'})
test_eq(_canon[1], {'role': 'assistant', 'content': 'hello'})
test_eq(_canon[2]['role'], 'assistant')
test_eq(_canon[2]['tool_calls'][0]['function'], {'name': 'add', 'arguments': {'a': 2, 'b': 3}})
assert _canon[2]['tool_calls'][0]['id']                       # a synthetic id was assigned
test_eq(_canon[3], {'role': 'tool', 'name': 'add', 'content': '5'})

# canonical -> litert Messages ready for the engine
_ms = LitertChat.hist2fmt(_canon)
test_eq([m.role for m in _ms], [Role.USER, Role.MODEL, Role.MODEL, Role.TOOL])
test_eq(str(_ms[1]), 'hello')
test_eq(_ms[2].tool_calls[0].name, 'add')
test_eq(_ms[3].contents.to_json(), [{'type': 'tool_response', 'name': 'add', 'response': '5'}])

# fmt2hist is idempotent on an already-canonical (llama-origin) tool round
_llama = [{'role': 'assistant', 'content': '', 'tool_calls': [{'id': 'call_x', 'type': 'function',
                                                               'function': {'name': 'add', 'arguments': {'a': 1}}}]},
          {'role': 'tool', 'tool_call_id': 'call_x', 'name': 'add', 'content': '1'}]
test_eq(LitertChat.fmt2hist(_llama), _llama)
class _FakeCtx:
    ctx_limit = 100
    def count_tokens(self, text): return len(text)
_f = _FakeCtx()
LitertChat._ck_fits(_f, 'x'*100)
test_fail(lambda: LitertChat._ck_fits(_f, 'x'*101), contains='101 tokens')
test_fail(lambda: LitertChat._ck_fits(_f, 'x'*61, sp='y'*40), contains='over the 100-token')
_f.ctx_limit = None
LitertChat._ck_fits(_f, 'x'*10000)

One turn can be several model steps, because litert runs the tool loop inside one send: text, a tool call, the tool’s result prefilled, and more text. When a step fills the window before it yielded anything, that step alone is sent again after evicting. The first step resends the turn message. A later step preloads the turn’s finished tool rounds and resends only the last round’s results, so earlier text is not repeated and tools do not run again. A step that already yielded text is refused with ContextWindowExceededError. A stream closed early cancels the native generation.

# Chats sharing one engine take turns on it (model-free)
import time
from types import SimpleNamespace
def _free(lock):
    "Whether another thread could take `lock` right now."
    out = []
    def _try():
        ok = lock.acquire(blocking=False); out.append(ok)
        if ok: lock.release()
    t = threading.Thread(target=_try); t.start(); t.join()
    return out[0]
def _chat(eng, **kw): return SimpleNamespace(engine=eng, cbs=L(), _budget_exceeded=False, max_steps=None, _steps=0, approve=None, hist=[], tool_max_len=None, **kw)
_eng = SimpleNamespace(); _lk = engine_lock(_eng)
assert engine_lock(_eng) is _lk and _free(_lk)

# Two threads: sends never overlap
_log = []
def _send(ch, tag):
    with EngineHold(ch): _log.append((tag, 'in')); time.sleep(0.05); _log.append((tag, 'out'))
_ts = [threading.Thread(target=_send, args=(_chat(_eng), t)) for t in 'ab']
for t in _ts: t.start()
for t in _ts: t.join()
test_eq([x[1] for x in _log], ['in', 'out', 'in', 'out'])
assert _free(_lk)

# One thread, two streams: the second fails fast instead of hanging the thread that holds the first
def _stream(ch):
    with EngineHold(ch): yield 1; yield 2
_c1, _c2 = _chat(_eng), _chat(_eng)
_a = _stream(_c1); next(_a)
_b = _stream(_c2)
test_fail(lambda: next(_b), contains='mid-turn on this engine')
_a.close(); assert _free(_lk)
test_eq(list(_stream(_c2)), [1, 2]); assert _free(_lk)   # `_b` died with the error; a fresh stream gets in

# A stream abandoned on another thread frees the engine when closed from this one
_box = []
_t = threading.Thread(target=lambda: (_box.append(_stream(_chat(_eng))), next(_box[0]))); _t.start(); _t.join()
assert not _free(_lk)
_box[0].close(); assert _free(_lk)

# An exception mid-stream lets go
def _bad(ch):
    with EngineHold(ch): yield 1; raise ValueError('boom')
_g = _bad(_c1); next(_g); test_fail(lambda: next(_g), contains='boom'); assert _free(_lk)

# The same chat, deeper in its own turn (recover_context, a one-shot from a callback), gets straight in
with EngineHold(_c1):
    with EngineHold(_c1): assert not _free(_lk)
    assert not _free(_lk)
assert _free(_lk)

# The tool loop lets go while a tool runs, so a tool may use the engine, and takes it back for the reply
_ch = _chat(_eng); _ch._hold, _th = EngineHold(_ch), ChatToolHandler(_ch)
with _ch._hold:
    assert not _free(_lk)
    assert _th.approve_tool_call({'function': {'name': 'add', 'arguments': {'a': 2, 'b': 3}}})
    assert _free(_lk)
    with EngineHold(_c2): pass                       # another chat on this thread, from inside the tool
    test_eq(_th.process_tool_response('5'), '5')
    assert not _free(_lk)
assert _free(_lk)
test_eq([m['role'] for m in _ch.hist], ['assistant', 'tool'])
_ch._hold.let_go(); assert _free(_lk)           # letting go twice is harmless
set_min_log_severity(5)
get_model(gemma4_12b)
'/Users/71293/.cache/huggingface/hub/models--litert-community--gemma-4-12B-it-litert-lm/snapshots/44cf85a326f79b814fa86a60af414c042755b43a/gemma-4-12B-it.litertlm'

Examples (manual)

These cells load real models on the GPU. The test run skips them. The output shown was saved from an earlier run. The first run downloads the weights.

The KV-cache example asks LiteRT-LM how many tokens it prefilled on each turn. It prefilled 304 on the first turn and 25 on the second, while the 306 tokens from the first turn stayed in the cache.

chat=Chat(backend=Backend.GPU(), cache_dir='.cache/litertlm', think=True)
# chat_12 = LitertChat(engine=LitertChat.create_engine(gemma4_12b, multimodal=False, cache_dir='.cache/litertlm', be=Backend.GPU()))
# set_min_log_severity(2)
r = chat("Reply with exactly: pong")
assert 'pong' in resp_text(r).lower()
assert resp_text(chat.hist[-1]) == resp_text(r) and chat.hist[0]['role'] == 'user'
assert chat.use.total_tokens > 0 and chat.token_count > 0
print(chat.use); chat.print_hist()
total=116|in=115|out=1|turns=1

user

Reply with exactly: pong


assistant

🧠 Thinking

Thinking Process:

  1. Analyze the Request: The user has instructed me to reply with exactly the word “pong”.
  2. Determine the Constraint: The constraint is strict: the output must be only “pong”.
  3. Generate the Output: The required output is “pong”.
  4. Final Check: Does the output meet the requirement? Yes. (It is exactly “pong”).

pong

# A real `LitertChat` on a fake engine, driven through the public `chat(msg)` and `chat(msg, stream=True)` (model-free)
from contextlib import contextmanager
class _FakeConv:
    "One fake litert conversation. Each send plays the engine's next `plan` entry: a list of chunk texts, where an exception is raised."
    def __init__(self, eng, messages): self.eng, self.messages, self.token_count, self.cancelled = eng, messages, 0, 0
    def send_message_async(self, m, **kw):
        self.eng.sends += 1
        for c in (self.eng.plan.pop(0) if self.eng.plan else ['ok']):
            if isinstance(c, Exception): raise c
            yield {'role': 'assistant', 'content': [{'type': 'text', 'text': c}]}
    def send_message(self, m, **kw):
        return {'role': 'assistant', 'content': [{'type': 'text', 'text': ''.join(resp_text(c) for c in self.send_message_async(m, **kw))}]}
    def cancel_process(self): self.cancelled += 1

class _FakeEng:
    "A fake litert engine that records every conversation it builds."
    def __init__(self, *plan): self.plan, self.convs, self.sends = list(plan), [], 0
    @contextmanager
    def create_conversation(self, messages=None, **kw):
        c = _FakeConv(self, messages); self.convs.append(c); yield c
    def tokenize(self, t): return t.split()

def _fake_chat(*plan, n=0):
    "A `LitertChat` on a `_FakeEng` playing `plan`, preloaded with `n` earlier exchanges."
    c = LitertChat(engine=_FakeEng(*plan))
    for i in range(n): c.hist += [{'role': 'user', 'content': f'm{i}'}, {'role': 'assistant', 'content': f'a{i}'}]
    c._recreate_conv()
    return c

# the public entry points reach litert: `Chat.__call__` calls `self._stream_turn(msg, cbs, **kw)`, which rishi must not shadow
c = _fake_chat(['hel', 'lo'], ['hello'])
test_eq(''.join(c('hi', stream=True)), 'hello')
test_eq(resp_text(c('hi')), 'hello')
test_eq([m['role'] for m in c.hist], ['user', 'assistant'] * 2)
test_eq([n for n in vars(LitertChat) if n.startswith('_litert_') and n in dir(Chat)], [])

# closing a stream early cancels the native generation; reading it to the end does not
c = _fake_chat(['a', 'b'], ['a', 'b'])
s = c('hi', stream=True); next(s); s.close()
test_eq(c.conv.cancelled, 1)
list(c('hi', stream=True))
test_eq(c.conv.cancelled, 1)

# `recover_context` with a recorded message and its tool rounds: they leave the history, and only earlier messages preload the rebuilt conversation
c = _fake_chat(n=7)
c.hist += [{'role': 'user', 'content': 'q'}, {'role': 'assistant', 'content': '', 'tool_calls': [{'id': '1', 'function': {'name': 'f', 'arguments': {}}}]},
           {'role': 'tool', 'tool_call_id': '1', 'name': 'f', 'content': 'r'}]
c.turn_msg, c._turn_msg_recorded, c._tc0 = Message.user('q'), True, 0
resp_text(c.recover_context(RuntimeError('ctx')))
test_eq({m.to_json()['role'] for m in c.conv.messages if m.to_json()['role'] == 'tool'}, set())
test_eq([m['content'] for m in c.hist[-2:]], ['a6', 'q'])
assert c.evicted > 0
# A full window, through `chat(msg, stream=True)` and `chat(msg)`: both recover through the one `_litert_evict_retry`, a stream only before its first chunk (model-free)
# litert's three wordings: before litert-lm 0.19; from it, history plus input; from it, one input alone (which eviction cannot fix)
_full_old = lambda: RuntimeError('FAILED_PRECONDITION: Prefill input length exceeds available state entries (remaining capacity: 428)')
_full = lambda: RuntimeError('RESOURCE_EXHAUSTED: Not enough space left in the context window for the input: 1097 tokens in the context + 1084 input tokens >= 2048 max number of tokens.')
_too_long = lambda: RuntimeError('INVALID_ARGUMENT: Input token ids are too long. Exceeding the maximum number of tokens allowed: 2200 >= 2048')
def _roles(c): return [m['role'] for m in c.hist]

# the first prefill of a stream fills the window: evict, rebuild, and stream the reply from the second send
for err in (_full_old, _full):
    c = _fake_chat([err()], ['hel', 'lo'], n=8); nconv = len(c.engine.convs)
    test_eq(''.join(c('hi', stream=True)), 'hello')
    test_eq((c.engine.sends, len(c.engine.convs) - nconv), (2, 1))
    assert c.evicted > 0 and len(c.hist) < 18 and c.hist[-2:] == [{'role': 'user', 'content': 'hi'}, {'role': 'assistant', 'content': 'hello'}]

# the plain send recovers the same way
c = _fake_chat([_full()], ['hello'], n=8)
test_eq((resp_text(c('hi')), c.engine.sends), ('hello', 2))
assert c.evicted > 0 and len(c.hist) < 18

# a history too short to have a middle all leaves, so the current message still gets its reply
c = _fake_chat([_full()], ['hello'], n=1)
test_eq((''.join(c('hi', stream=True)), _roles(c), c.evicted), ('hello', ['user', 'assistant'], 2))

# one input longer than the whole window: a clear error after one send, no eviction loop, and the chat as it was before the turn
for stream in (True, False):
    c = _fake_chat([_too_long()], n=3); nconv = len(c.engine.convs)
    test_fail(lambda: ''.join(c('x', stream=True)) if stream else c('x'), contains='alone is longer than', exc=ContextWindowExceededError)
    test_eq((c.engine.sends, len(c.hist), len(c.engine.convs) - nconv), (1, 6, 1))
    test_eq(resp_text(c('next')), 'ok')     # a fresh conversation takes the next turn

# the window fills after a chunk was yielded: no retry, so 'hel' is never repeated, and the caller sees the typed error
c = _fake_chat(['hel', _full()], n=8)
s = c('hi', stream=True)
test_eq(next(s), 'hel')
test_fail(lambda: next(s), contains='already yielded', exc=ContextWindowExceededError)
test_eq((c.engine.sends, len(c.hist)), (1, 16))
test_eq(''.join(c('next', stream=True)), 'ok')

# the window is still full after eviction, streamed or sent; the next turn still works
for stream in (True, False):
    c = _fake_chat([_full()], [_full()], n=8)
    test_fail(lambda: list(c('hi', stream=True)) if stream else c('hi'), contains='could not recover', exc=ContextWindowExceededError)
    test_eq(c.hist[-1]['role'], 'assistant')
    test_eq(resp_text(c('next')), 'ok')

# any other error passes through unchanged
c = _fake_chat([RuntimeError('INTERNAL: tokenizer failed')], n=8)
test_fail(lambda: list(c('hi', stream=True)), contains='tokenizer failed')
assert not getattr(c, 'evicted', 0)
from litert_lm import Tool, tool_from_function
# A turn of several model steps, as litert runs it inside one `send_message_async`: text, a tool call, the tool's result prefilled, more text (model-free)
class _StepConv(_FakeConv):
    "A fake conversation running litert's own tool loop. A plan entry is one model step; a `('call', name, args)` item ends the step with a tool call, and the next entry is the step that follows the tool results. Tools are indexed as `Engine.create_conversation` indexes them and run by litert's own `Conversation._handle_tool_calls`."
    def __init__(self, eng, messages, tools=None, tool_event_handler=None, **kw):
        super().__init__(eng, messages)
        ts = [t if isinstance(t, Tool) else tool_from_function(t) for t in tools or []]
        self._tools_map, self.tool_event_handler = {t.get_tool_description()['function']['name']: t for t in ts}, tool_event_handler
    def _steps(self, m):
        while True:
            self.eng.sent.append(m); self.eng.sends += 1; self.token_count += 10   # the prefill of `m`
            calls = []
            for c in (self.eng.plan.pop(0) if self.eng.plan else ['ok']):
                if isinstance(c, Exception): raise c
                if isinstance(c, tuple): calls.append(c); continue
                self.token_count += 1
                yield {'role': 'assistant', 'content': [{'type': 'text', 'text': c}]}
            # litert asks for every call in the response, then sends the approved results together
            tcs = [{'type': 'function', 'function': {'name': name, 'arguments': args}} for _, name, args in calls]
            m = Conversation._handle_tool_calls(self, {'tool_calls': tcs}) if tcs else None
            if not m: return
            yield None   # a step boundary, which litert's `send_message` uses to return only the last step
    def send_message_async(self, m, **kw): return (o for o in self._steps(m) if o is not None)
    def send_message(self, m, **kw):
        last = []
        for o in self._steps(m): last = [] if o is None else last + [resp_text(o)]
        return {'role': 'assistant', 'content': [{'type': 'text', 'text': ''.join(last)}]}

class _StepEng(_FakeEng):
    "A fake engine whose conversations run the tool loop, recording every message each send was given."
    def __init__(self, *plan): super().__init__(*plan); self.sent = []
    @contextmanager
    def create_conversation(self, messages=None, **kw):
        c = _StepConv(self, messages, **kw); self.convs.append(c); yield c

ran = []
def lookup(x:int):
    "Look `x` up."
    ran.append(x); return f'r{x}'

def _step_chat(*plan, n=0):
    "A `LitertChat` with the `lookup` tool on a `_StepEng` playing `plan`, preloaded with `n` earlier exchanges."
    ran.clear()
    c = LitertChat(engine=_StepEng(*plan), tools=[lookup])
    for i in range(n): c.hist += [{'role': 'user', 'content': f'm{i}'}, {'role': 'assistant', 'content': f'a{i}'}]
    c._recreate_conv()
    return c

def _js(m): return m if isinstance(m, dict) else m.to_json()
_work_group = lambda: RuntimeError('FAILED_PRECONDITION: Chosen prefill work group size exceeds available state entries (82).')
_tool_msg = lambda x: {'role': 'tool', 'content': [{'type': 'tool_response', 'name': 'lookup', 'response': f'r{x}'}]}

# step 1 yields text and calls a tool; the prefill of its result fills the window. Only step 2 is sent again:
# the text is not repeated, the tool does not run again, and the turn message is not resent
for stream in (True, False):
    for err in (_full, _full_old, _work_group):
        c = _step_chat(['I will ', 'look.', ('call', 'lookup', {'x': 1})], [err()], ['done'], n=8)
        out = ''.join(c('q', stream=True)) if stream else resp_text(c('q'))
        test_eq(out, 'I will look.done' if stream else 'done')
        test_eq((ran, c.engine.sends, c.engine.sent[-1]), ([1], 3, _tool_msg(1)))
        pre = [_js(m) for m in c.engine.convs[-1].messages]   # the rebuilt conversation ends with the turn message and the call
        assert pre[-1].get('tool_calls') and pre[-2]['role'] == 'user', pre[-2:]
        test_eq([(m['role'], m.get('content')) for m in c.hist[-4:]],
                [('user', 'q'), ('assistant', 'I will look.' if stream else ''), ('tool', 'r1'), ('assistant', 'done')])
        assert c.evicted > 0 and len(c.hist) < 20
        test_eq(resp_text(c('next')), 'ok')

# a model step that yields text, so the text said before a tool call is kept beside the call in `hist`, not folded into the final reply
c = _step_chat(['Scaling.', ('call', 'lookup', {'x': 1})], ['Done.'])
test_eq(''.join(c('q', stream=True)), 'Scaling.Done.')
test_eq([(m['role'], m.get('content')) for m in c.hist], [('user', 'q'), ('assistant', 'Scaling.'), ('tool', 'r1'), ('assistant', 'Done.')])

# two calls in one response: the retry preloads one call message holding both calls, and sends both results in one tool message, as litert-lm 0.19 does
c = _step_chat([('call', 'lookup', {'x': 1}), ('call', 'lookup', {'x': 2})], [_full()], ['done'], n=8)
test_eq((''.join(c('q', stream=True)), ran), ('done', [1, 2]))
pre = [_js(m) for m in c.engine.convs[-1].messages]
test_eq((len(pre[-1]['tool_calls']), pre[-2]['role']), (2, 'user'))
test_eq(c.engine.sent[-1], {'role': 'tool', 'content': _tool_msg(1)['content'] + _tool_msg(2)['content']})

# nothing from before the turn to evict: earlier tool rounds of this turn leave instead, and the step is sent again
c = _step_chat([('call', 'lookup', {'x': 1})], [('call', 'lookup', {'x': 2})], [_work_group()], ['done'])
test_eq((''.join(c('q', stream=True)), ran, c.engine.sent[-1]), ('done', [1, 2], _tool_msg(2)))
test_eq([m['role'] for m in c.hist], ['user', 'assistant', 'tool', 'assistant'])
assert c.evicted == 2

# a later step that fills the window after its own text was yielded: refused, its text never repeated, the next turn works
c = _step_chat(['a', ('call', 'lookup', {'x': 1})], ['b', _full()], n=8)
s = c('q', stream=True)
test_eq([next(s), next(s)], ['a', 'b'])
test_fail(lambda: next(s), contains='already yielded', exc=ContextWindowExceededError)
test_eq((ran, c.engine.sends, len(c.hist)), ([1], 2, 16))
test_eq(resp_text(c('next')), 'ok')

# the step is still full after eviction: one retry per step, then a clear error and the chat as before the turn
c = _step_chat([('call', 'lookup', {'x': 1})], [_full()], [_full()], n=8)
test_fail(lambda: list(c('q', stream=True)), contains='could not recover', exc=ContextWindowExceededError)
test_eq((ran, c.engine.sends, c.hist[-1]['role']), ([1], 3, 'assistant'))
test_eq(resp_text(c('next')), 'ok')

# a full window on the first step of a later turn still resends that turn after evicting, as before
c = _step_chat([_work_group()], ['hello'], n=8)
test_eq((''.join(c('hi', stream=True)), c.engine.sends, ran), ('hello', 2, []))
# Approval may rewrite the call in place, as Leela does: an edited approval changes the tool or its arguments, a rejection becomes `user_steering`.
# litert reads the name and arguments before it asks, so rishi must run what approval left, through `chat(msg)` and `chat(msg, stream=True)` (model-free)
def other(y:int):
    "Another tool."
    ran.append(('other', y)); return f'o{y}'
def user_steering(instruction:str):
    "Steer the model."
    ran.append(('steer', instruction)); return f'steer: {instruction}'

def _rewrite(name=None, args=None, ok=True, times=None):
    "An approver that rewrites the call to `name`/`args` (the first `times` calls only, when given) and returns `ok`."
    seen = []
    def approve(tc):
        seen.append(tc_name(tc))
        if times is None or len(seen) <= times:
            fn = tc['function']
            if name is not None: fn['name'] = name
            if args is not None: fn['arguments'] = args
        return ok
    return approve

def _ap_chat(approve, *plan, n=0):
    "A `LitertChat` with three tools and `approve` on a `_StepEng`; by default one `lookup(x=1)` call, then 'done'."
    ran.clear()
    c = LitertChat(engine=_StepEng(*(plan or ([('call', 'lookup', {'x': 1})], ['done']))), tools=[lookup, other, user_steering], approve=approve)
    for i in range(n): c.hist += [{'role': 'user', 'content': f'm{i}'}, {'role': 'assistant', 'content': f'a{i}'}]
    if n: c._recreate_conv()
    return c

def _run(c, stream): return ''.join(c('q', stream=True)) if stream else resp_text(c('q'))
def _trail(c):
    "The turn in `hist` as (role, tool name, arguments or content)."
    return [(m['role'], m['tool_calls'][0]['function']['name'], m['tool_calls'][0]['function']['arguments']) if m.get('tool_calls')
            else (m['role'], m.get('name'), m.get('content')) for m in c.hist]
def _sent(c):
    "The tool messages litert sent after the call: a list before litert-lm 0.19, one message from 0.19."
    return listify(c.engine.sent[1])
def _results(c):
    "The tool results litert sent to the model after the call."
    return [p['response'] for msg in _sent(c) for p in msg['content']]

for stream in (True, False):
    # (1) approved after a rewrite to another tool: the rewritten tool runs with its arguments, the model's does not
    c = _ap_chat(_rewrite('other', {'y': 7}))
    test_eq((_run(c, stream), ran, _results(c)), ('done', [('other', 7)], ['o7']))
    test_eq(_trail(c), [('user', None, 'q'), ('assistant', 'other', {'y': 7}), ('tool', 'other', 'o7'), ('assistant', None, 'done')])

    # (2) approved with only the arguments rewritten: the same tool runs with the new arguments
    c = _ap_chat(_rewrite(args={'x': 5}))
    test_eq((_run(c, stream), ran, _results(c)), ('done', [5], ['r5']))
    test_eq(_trail(c)[1:3], [('assistant', 'lookup', {'x': 5}), ('tool', 'lookup', 'r5')])

    # (3) a rejection rewritten to `user_steering` and returned as approved: user_steering runs, the model's tool does not
    c = _ap_chat(_rewrite('user_steering', {'instruction': 'use other'}))
    test_eq((_run(c, stream), ran, _results(c)), ('done', [('steer', 'use other')], ['steer: use other']))
    test_eq(_trail(c)[1:3], [('assistant', 'user_steering', {'instruction': 'use other'}), ('tool', 'user_steering', 'steer: use other')])

    # (4) refused: nothing runs, litert sends the model no result and the turn ends on the call; `hist` holds the call and the denial
    c = _ap_chat(_rewrite(ok=False))
    test_eq((_run(c, stream), ran, c.engine.sends, len(c.engine.sent)), ('', [], 1, 1))
    test_eq(_trail(c), [('user', None, 'q'), ('assistant', 'lookup', {'x': 1}), ('tool', 'lookup', 'Denied by human operator'), ('assistant', None, '')])

    # (5) a plain approval, and no approver at all, behave as before
    for ap in (lambda tc: True, None):
        c = _ap_chat(ap)
        test_eq((_run(c, stream), ran, _sent(c)), ('done', [1], [_tool_msg(1)]))
        test_eq(_trail(c), [('user', None, 'q'), ('assistant', 'lookup', {'x': 1}), ('tool', 'lookup', 'r1'), ('assistant', None, 'done')])

# a rewrite applies to its own call only: of two calls in one response only the first is rewritten, and the second runs as the model asked
c = _ap_chat(_rewrite('other', {'y': 7}, times=1), [('call', 'lookup', {'x': 1}), ('call', 'lookup', {'x': 2})], ['done'])
test_eq((_run(c, True), ran, _results(c)), ('done', [('other', 7), 2], ['o7', 'r2']))

# a rewrite to a name that is not a tool gives litert's error string as the result, and nothing runs
c = _ap_chat(_rewrite('nope', {}))
test_eq((_run(c, True), ran, _results(c)), ('done', [], ['Error: interfaces.Tool nope not found']))

# a window that fills after a rewritten call resends the result under the name that ran, matching the call kept in `hist`
c = _ap_chat(_rewrite('other', {'y': 7}), [('call', 'lookup', {'x': 1})], [_full()], ['done'], n=8)
test_eq((_run(c, True), ran), ('done', [('other', 7)]))
test_eq(c.engine.sent[-1], {'role': 'tool', 'content': [{'type': 'tool_response', 'name': 'other', 'response': 'o7'}]})
test_eq(_js(c.engine.convs[-1].messages[-1])['tool_calls'][0]['function']['name'], 'other')
# Real LiteRT conversation-cache test. BenchmarkInfo reports the actual last prefill performed by
# the runtime; turn two should prefill only its short new message while retaining the old KV context.
kvchat = Chat(backend=Backend.GPU(), cache_dir='.cache/litertlm', think=False, max_output_tokens=16,
              eng_kw={'enable_benchmark': True})
try:
    kvchat(('cache verification context ' * 96) + '\nReply with exactly: stored')
    first = kvchat.conv.get_benchmark_info()
    context_before_turn2 = kvchat.token_count
    r = kvchat('What exact word did I ask you to reply with? Reply with only that word.')
    second = kvchat.conv.get_benchmark_info()
    print(dict(first_prefill=first.last_prefill_token_count,
               second_prefill=second.last_prefill_token_count,
               context_before_turn2=context_before_turn2,
               context_after_turn2=kvchat.token_count,
               reported_cached=kvchat.use.cached_tokens,
               answer=resp_text(r)))
    assert context_before_turn2 > 0 and kvchat.token_count > context_before_turn2
    assert second.last_prefill_token_count < context_before_turn2, 'turn two appears to have re-prefilled the old context'
    assert kvchat.use.cached_tokens == context_before_turn2, kvchat.use
    assert 'stored' in resp_text(r).lower(), resp_text(r)
finally:
    kvchat.close()
{'first_prefill': 304, 'second_prefill': 25, 'context_before_turn2': 306, 'context_after_turn2': 333, 'reported_cached': 306, 'answer': 'stored'}

Images and audio

Gemma 4 builds take images and audio next to the text in one call, in the same list form as the other backends. The second call passes a LiteRT-LM AudioFile directly, which also works.

from PIL import Image
from fastcore.all import img_bytes, Path
from rishi.core import repo_root
im = Image.open(repo_root()/'nbs'/'images.jpeg')
chat(['explain this image', img_bytes(im)])
chat(['transcribe this audio', AudioFile(str(repo_root()/'nbs'/'speech.wav'))])

🧠 Thinking

Thinking Process:

  1. Analyze the Request: The user has provided an audio transcription and wants me to transcribe it.
  2. Examine the Input (Audio Transcription): “Dancing in the masquerade, idle truth and plain sight jaded. Pop, roll, click, dot. Who will I be today or not? But such a tide as moving seems a sleep, too full for sound and foam. When that drew from out the boundless deep turns again home, twilight and evening bell and after that”
  3. Perform Transcription (Verification): I will read the provided text and ensure accuracy.
    • “Dancing in the masquerade, idle truth and plain sight jaded.” (Looks accurate)
    • “Pop, roll, click, dot.” (Looks accurate)
    • “Who will I be today or not?” (Looks accurate)
    • “But such a tide as moving seems a sleep, too full for sound and foam.” (Looks accurate)
    • “When that drew from out the boundless deep turns again home, twilight and evening bell and after that” (Looks accurate)
  4. Final Output Generation: Present the transcribed text clearly. (Self-Correction: The provided text is already a transcription, so I just need to confirm it or present it as the final result.)

Dancing in the masquerade, idle truth and plain sight jaded. Pop, roll, click, dot. Who will I be today or not? But such a tide as moving seems a sleep, too full for sound and foam. When that drew from out the boundless deep turns again home, twilight and evening bell and after that

Utilities and bench

classify, structured and check come from Urai and work here as on every backend. The example below classifies a sentence and extracts a dataclass from another. bench() is particular to LiteRT-LM. It runs LiteRT-LM’s Benchmark on a model and reports the load time, the time to the first token, and the prefill and decode speeds in tokens per second. It uses the CPU backend and 64 prefill and 64 decode tokens unless you pass backend, prefill_tokens or decode_tokens. This backend has no log-likelihood scoring. LiteRT-LM cannot score how likely a given text is.


source

bench

def bench(
    model_id:str='litert-community/gemma-4-E2B-it-litert-lm', model_path:NoneType=None,
    backend:litert_lm.interfaces.CPU=CPU(thread_count=None), prefill_tokens:int=64, decode_tokens:int=64, **kw
):

Measure a model’s load time, time to first token, and prefill and decode speed with LiteRT-LM’s Benchmark.

# classify + structured on a real model
sm = Chat(cache_dir='.cache/litertlm')
test_eq(sm.classify("I absolutely loved this film!", ['positive', 'negative']), 'positive')

from dataclasses import dataclass
@dataclass
class Person: name:str; age:int
p = sm.structured("Extract the person: John Smith is 30 years old.", Person)
print(p); assert isinstance(p, Person) and 'John' in p.name
sm.close()
Person(name='John Smith', age=30)
from fastcore.test import test_eq
import rishi.litert
test_eq(get_runtime('litert'), rishi.litert.LitertChat)

# dispatch really happens in `Chat.__new__`, so it can be checked without loading a model
test_eq(type(Chat.__new__(Chat)), rishi.litert.LitertChat)              # the default runtime
test_eq(type(Chat.__new__(Chat, 'litert-community/gemma-4-E2B-it-litert-lm')),
        rishi.litert.LitertChat)
test_eq(rishi.litert.LitertChat._runtime, 'litert')

Sharing one engine

A LiteRT-LM Engine lives inside one process, so separate programs cannot attach to it. LitertBroker keeps one in a long-lived process and serves a LitertChat to each client over a Unix socket. Each client has its own conversation and history, and all of them share one copy of the weights. Turns run one at a time, because one engine cannot be driven from two threads at once. The protocol is Urai’s ChatBroker, described on Urai’s broker page.


source

LitertBroker

def LitertBroker(
    address, engine:NoneType=None, model_id:str='litert-community/gemma-4-E2B-it-litert-lm', **engine_kw
):

Serve one LiteRT-LM engine to several processes over a Unix socket, each client with its own LitertChat conversation.