tml-renderers turns structured text, image, and audio chat into model-ready
tokens and media for training and inference. It supports Thinking Machines Lab
models, including Inkling, Inkling-Small, Inkling 2 Small, Inkling 2 Mini, and
TML-d24-varloop-research, through TMLv0, and the
supported third-party models served on Tinker
through model-specific renderers.
See the changelog
for the changes in each release.
Installation
Always use the latest release:
pip install --upgrade tml-renderers
tml-renderers is a compiled extension that requires PyTorch 2.11 or newer.
Quickstart
Create a short conversation with native chat objects and render it for
inference or training:
To continue from the exact sampled token prefix, bridge the parsed semantic
history to the next user or tool messages instead of rerendering earlier turns:
The first return value preserves every token in the supplied prefix and appends
suffix. The returned parser is configured for the combined semantic history.
Glm52 clears reasoning from earlier turns. Glm53 and Glm53Flash keep it. Pass
clear_thinking=True to clear it, as
Z.ai recommends. Use the same setting for
rollout and SFT.
OpenAI message compatibility
Convert OpenAI-style message dictionaries before passing them to a renderer:
The renderer also accepts openai_messages for completion. The conversion
supports text, reasoning, images, tool calls, and tool results; it handles message
formats, not the OpenAI network API. An assistant dict keeps its reasoning in a
top-level reasoning_content. As in an OpenAI request, tools are not a message:
pass the tools list as chat.OpenAIMessage.from_openai_chat_dicts(openai_dicts, tools=tools).
The from_oss_* and to_oss_* methods read and write tinker_cookbook message
dicts. They are deprecated.
Anthropic Messages compatibility
chat.MessageList.from_anthropic_messages(messages, *, system=None, tools=None) reads an
Anthropic Messages request body, and to_anthropic_messages() writes one:
The conversion supports text, image, thinking, tool_use, and tool_result blocks:
A tool_result with is_error: true reads as ToolError parts. A tool message with
ToolError parts writes is_error: true. A tool message that mixes Text and
ToolError parts raises ValueError.
A {"role": "system"} message in messages reads as a system message in place. A system
message after the conversation starts writes back in place.
An integer in a tool_use input must fit in 64 bits.
The reader ignores these keys, so to_anthropic_messages() does not write them back:
cache_control, citations, and the thinking signature; a tool's defer_loading, strict,
and eager_input_streaming; and a system message's clear_at and output_config. A
turn-scoped system message applies to every later turn.
The reader raises ValueError for content that has no TML form that round-trips:
The blocks redacted_thinking, document, search_result, and container_upload, the
server-tool blocks (server_tool_use, *_tool_result, mcp_tool_use, and
mcp_tool_result), and the tool_addition and tool_removal blocks of a system message.
An image with a file source.
A tool with a type other than "custom", such as a server tool.
Malformed input also raises ValueError: a wrong value type, an unknown role or block type, or
a tool_result without an earlier tool_use.
Rendering and parsing (TMLv0)
Rendering converts structured chat messages into the token and media-span
sequence consumed by the model. renderers.Inkling and renderers.Inkling2 use
the same TMLv0 grammar for both inference and training:
render_for_completion(...) renders an inference prompt and returns a parser
for turning generated model tokens back into messages.
render_for_sft(...) renders supervised-training examples with aligned,
per-token loss weights.
The parser reconstructs structured messages from generated token spans:
For incremental sampling, open a parser stream and feed it only the newly sampled
token IDs. It returns the same messages as a batch parse of the same tokens:
completed_messages = []
with parser.parse_stream() as stream:
for token_ids in sampled_token_chunks:
for update in stream.feed(token_ids):
event = update.update
if isinstance(event, chat.StreamingMessageHeader):
print(f"[{event.author.kind}] ", end="")
elif isinstance(event, chat.StreamingContent):
print(event.content.text, end="", flush=True)
elif isinstance(event, chat.Message):
completed_messages.append(event)
for update in stream.finish():
if isinstance(update.update, chat.Message):
completed_messages.append(update.update)
finish() validates the end of the stream and releases the parser. Leaving the
context unfinished discards partial state and releases the parser. Parse exceptions
expose completed_messages, which contains any complete prefix parsed before the
error, and completed, which pairs each of those messages with its sampled token
count. Inkling and Inkling2 raise parse_errors.ParseError, a ValueError
subclass; the other renderers raise ValueError.
The package includes native tokenizers for these renderers. It does not need
Hugging Face chat templates, remote code, or network access. Inkling uses
tokenizers.O200kBaseChatTokenizer() and Inkling2 uses
tokenizers.H200kBaseChatTokenizer(). Both share the same special-token IDs.
— (special-token markup is encoded as literal text)
encode_special(name)
name → id
raises if name isn't a special token
decode(ids)
ids → text
lossy — invalid/partial bytes become U+FFFD, never raises (tiktoken parity)
decode_strict(ids)
ids → text
raisesValueError on invalid/partial UTF-8
decode_bytes(ids)
ids → bytes
raw bytes, no UTF-8 handling
decode_special(id)
id → name
None if id isn't a special token
The tokenizer also provides is_special_token(id), special_tokens(),
eos_token, bos_token, and all_special_tokens.
render_for_completion accepts a MessageList, a list[Message], or a
list[OpenAIMessage].
To render at one thinking effort, pass effort (a float in [0, 1]) to
renderers.Inkling or renderers.Inkling2. The renderer then adds the effort
message to every completion and SFT render. Do not also put a
ThinkingEffort message in the input.
Multimodal inputs
tml-renderers includes multimodal codecs for the TMLv0 renderer:
An ImagePointer is rendered as an ImageAssetPointerTokenSpan with the
expected image-token count.
An AudioPointer is rendered as a DmelTokenSpan by Inkling. Inkling2
does not accept audio.
Image and audio messages use the same completion and training APIs as text:
Media locations are represented as pointers. Audio is read from local files;
tml-renderers never fetches remote media.
Token spans
Renderers work with token-span types you can construct directly:
from tml_renderers.chat import (
EncodedTextTokenSpan,
ImageAssetPointerTokenSpan,
ImageFormat,
PaddingTokenSpan,
TokenSpan,
)
text = EncodedTextTokenSpan([101, 102])
image = ImageAssetPointerTokenSpan(
location="image.png", format=ImageFormat.Png, width=512, height=512, num_tokens=256
)
padding = PaddingTokenSpan(4)
# Wrap in the oneof only where a call boundary asks for a TokenSpan.
wrapped = TokenSpan(text)
DmelTokenSpan is the encoded-audio span produced by the renderer. Its
dmel field is a uint8 tensor of shape
[num_audio_tokens, num_dmel_bins].
chat.DmelTokenSpan(tensor, target_audio_token=...) copies a 2-D CPU torch.uint8
tensor. The .dmel getter returns a tensor that shares the span's storage, so writes
to it change the span.
Using with Tinker
In Tinker Cookbook, use the recommended renderer for your model. Cookbook
converts rendered text, image, and audio inputs for sampling and SFT.
The lower-level tml_renderers.tinker helpers are also available for direct
Tinker SDK integration. Provide local media files or base64 image data.
Tool args: ToolArg, ToolMetadata. ToolArg.value is a JSON-encoded
string, matching the OpenAI function.arguments convention.
Tool declarations: ToolSpecJson (one declared tool with name,
description, type_name, and JSON-schema parameters), grouped into
ToolDeclareJson. The constructor accepts a dict for parameters and
serializes it.
Examples
examples/run_tml_v0.py — low-level rendering and parsing of text and audio.
examples/cookbook_tinker_demo.py — native and OpenAI-style messages,
including tool calls and results. See the
public tool-call example.
License
Apache-2.0. The wheel includes LICENSE, NOTICE, and
THIRD_PARTY_LICENSES.md.
Alternatives
Use instead of tml-renderers: tools that do the same job, closest first.