Chat data: the message formatter
A chat model expects its input in its own chat format, which is a particular layout, with special tokens, for turning a list of messages into one sequence of tokens. Each model family has a different one.
Your training data has to use the same format the model sees when it's sampled. Otherwise the model is trained on prompts that look different from the ones it gets later, and learns the wrong thing.
The cookbook has a message formatter for each model family that does this for you. It turns conversations into prompts for sampling, and into training data for fine-tuning, both in the model's own format. In this tutorial you'll:
- create a formatter and use it to write a prompt;
- turn conversations into training data, and see which tokens each example trains;
- use Qwen's thinking mode;
- read a sampled reply back as a message;
- format a conversation with a tool call;
- load a file of conversations.
Everything here runs on your machine. You don't need an API key, and nothing calls Looper. It uses the cookbook's package, looper_cookbook, which isn't on PyPI yet, so install it from a clone of its repository first, as The cookbook shows.
Settings
MODEL is the model whose tokenizer and formatter the notebook uses. MAX_SEQ_LEN is the longest training example a run will take, in tokens.
MODEL = "Qwen/Qwen3.5-9B"
MAX_SEQ_LEN = 2048
A formatter and a prompt
message_formatter creates the formatter for a model Looper serves, using the model's tokenizer. Each model family has its own. This one is for Qwen3.5, and there are others for Qwen3.8 and Muse Glimmer.
enable_thinking=False is a setting of Qwen's format. It makes the model answer straight away, without writing out its reasoning first. The section The thinking switch, further down, covers the other mode.
build_generation_prompt turns a conversation into a prompt for sampling. It writes the conversation in the model's format, then the start of a new assistant message, so the model's next tokens are its reply. These token ids are what you'd send to a sampler.
stop_token_ids holds the token that ends an assistant message. Pass it to the sampler, so it stops when the reply is finished.
from transformers import AutoTokenizer
from looper_cookbook.message_formatters.models import message_formatter
tokenizer = AutoTokenizer.from_pretrained(MODEL)
formatter = message_formatter(MODEL, tokenizer, enable_thinking=False)
question = [{"role": "user", "content": "Tell me about the red fox."}]
prompt = formatter.build_generation_prompt(question)
print(type(formatter).__name__)
print(len(prompt), "tokens:")
print(tokenizer.decode(prompt))
print("a turn ends on", tokenizer.decode(formatter.stop_token_ids))
Qwen3_5MessageFormatter
19 tokens:
<|im_start|>user
Tell me about the red fox.<|im_end|>
<|im_start|>assistant
<think>
</think>
a turn ends on <|im_end|>
One conversation, one datum per assistant reply
A conversation is a list of chat messages, where each message has a role (user, assistant and so on) and its content.
build_supervised_examples writes a conversation in the model's format, and turns it into training data: one Datum for each assistant message. A Datum is one training example, made of its tokens plus a weight per token that says whether to train on it. This conversation has one assistant reply, so it makes one datum.
In the code below, [datum] = ... takes the one datum out of the list, and raises an error if there isn't exactly one. int(sum(datum.weights)) adds up the weights, which counts the tokens the datum trains.
conversation = [
*question,
{
"role": "assistant",
"content": "Habitat: forests, grasslands and cities.\nDiet: rodents, birds and fruit.",
},
]
[datum] = formatter.build_supervised_examples(conversation, max_seq_len=MAX_SEQ_LEN)
print(len(datum.tokens), "tokens,", int(sum(datum.weights)), "of them targets")
41 tokens, 22 of them targets
What a datum trains
A datum's tokens are the prompt for one assistant reply, followed by the reply itself. The weights split them in two:
- Context, weight 0: everything before the assistant starts writing. The model reads it, but isn't trained to write it. It's exactly the prompt from the section A formatter and a prompt, so it's the same tokens the model gets when it's sampled.
- Targets, weight 1: the assistant's reply, up to and including the end token. These are what the model is trained to write. Including the end token teaches the model when to stop.
The cell below checks that the context matches the prompt, then prints the targets as text. In the code, context keeps each token whose weight is 0. formatter.targets(datum) returns the text of the trained tokens, with one string for each unbroken run of tokens with weight 1.
context = [token for token, weight in zip(datum.tokens, datum.weights) if not weight]
print("the context is the prompt:", context == prompt)
print()
print("targets:")
for text in formatter.targets(datum):
print(repr(text))
the context is the prompt: True
targets:
'Habitat: forests, grasslands and cities.\nDiet: rodents, birds and fruit.<|im_end|>'
Several replies
A conversation with two assistant replies makes two datums. The first trains the first reply. The second holds the whole first exchange as context, and trains only the second reply.
Why not one datum for the whole conversation? Some formats write an earlier message differently once more messages follow it. Qwen3.5's does, because it keeps a reply's reasoning only after the last user message. So in one long sequence, an early reply would sit after a prompt that's different from the one the model sees when it writes that reply. With one datum per reply, each reply is trained after exactly the prompt it would be sampled with.
longer = [
*conversation,
{"role": "user", "content": "And the Arctic fox?"},
{
"role": "assistant",
"content": "Habitat: the tundra and sea ice.\nDiet: lemmings, birds and carrion.",
},
]
datums = formatter.build_supervised_examples(longer, max_seq_len=MAX_SEQ_LEN)
for number, datum in enumerate(datums, start=1):
print(f"datum {number}: {len(datum.tokens)} tokens, trains {formatter.targets(datum)}")
datum 1: 41 tokens, trains ['Habitat: forests, grasslands and cities.\nDiet: rodents, birds and fruit.<|im_end|>']
datum 2: 80 tokens, trains ['Habitat: the tundra and sea ice.\nDiet: lemmings, birds and carrion.<|im_end|>']
The thinking switch
A Qwen formatter created without enable_thinking=False uses thinking mode. Its prompt opens a reasoning block, <think>, and the model writes out its reasoning before it answers.
To train reasoning, give each assistant message a reasoning_content field, alongside content. The reasoning becomes part of the targets, so the model learns to reason as well as answer. The <think> that opens the block is part of the prompt, so the targets start just after it.
thinking = message_formatter(MODEL, tokenizer)
reasoned = [
{"role": "user", "content": "Is a red fox bigger than an Arctic fox?"},
{
"role": "assistant",
"reasoning_content": "Red foxes weigh up to 14 kg. Arctic foxes weigh up to 9 kg.",
"content": "Yes. The red fox is the larger of the two.",
},
]
print(repr(tokenizer.decode(thinking.build_generation_prompt(reasoned[:1]))))
[datum] = thinking.build_supervised_examples(reasoned, max_seq_len=MAX_SEQ_LEN)
for text in thinking.targets(datum):
print(repr(text))
'<|im_start|>user\nIs a red fox bigger than an Arctic fox?<|im_end|>\n<|im_start|>assistant\n<think>\n'
'Red foxes weigh up to 14 kg. Arctic foxes weigh up to 9 kg.\n</think>\n\nYes. The red fox is the larger of the two.<|im_end|>'
The two modes give the model different prompts, so train and sample a model in the same mode.
With thinking off, the prompt itself opens and closes an empty reasoning block, which tells the model not to reason. A reply with reasoning_content can't follow that prompt. So instead of training something that doesn't match, the formatter refuses it, with an error that names the message and how to fix it.
A conversation without reasoning can be trained in either mode. In thinking mode, its reply closes the reasoning block the prompt opened, leaving it empty.
try:
formatter.build_supervised_examples(reasoned, max_seq_len=MAX_SEQ_LEN)
except ValueError as error:
print(error)
print()
[plain] = thinking.build_supervised_examples(conversation, max_seq_len=MAX_SEQ_LEN)
print(thinking.targets(plain))
messages[1] of the conversation starting 'Is a red fox bigger than an Arctic fox?': this assistant turn carries reasoning, and the formatter has thinking off: its prompt closes an empty <think> block, which tells the model not to reason. Build the formatter with enable_thinking=True, or drop the turn's reasoning
['\n</think>\n\nHabitat: forests, grasslands and cities.\nDiet: rodents, birds and fruit.<|im_end|>']
Reading a reply back
A sampler returns the model's reply as token ids. parse_response turns them back into an assistant message, with any reasoning in reasoning_content, separate from the answer in content.
It also tells you whether the reply ended on its end token. A reply that was cut off because it reached max_tokens didn't. A reply cut off while it was still reasoning has no content yet.
Here, the datum's targets stand in for a sampled reply, and the last line shows a reply cut short after 8 tokens.
In the code below, list(datum.weights).index(1) finds the first token with weight 1, where the reply starts, and reply is every token from there on. parse_response returns two things, the message and whether the reply ended on its end token.
reply = datum.tokens[list(datum.weights).index(1) :]
message, ended = thinking.parse_response(reply)
print(message)
print("ended on its end token:", ended)
print("cut short:", thinking.parse_response(reply[:8]))
{'role': 'assistant', 'reasoning_content': 'Red foxes weigh up to 14 kg. Arctic foxes weigh up to 9 kg.', 'content': 'Yes. The red fox is the larger of the two.'}
ended on its end token: True
cut short: ({'role': 'assistant', 'reasoning_content': 'Red foxes weigh up to 1', 'content': ''}, False)
Tool calls
A model can be given tools, which are functions it can ask to call, such as a lookup. You describe each tool with a JSON schema, in the tools format that chat APIs use, and pass the list with the conversation. The formatter puts the tool descriptions where the model's format expects them.
In the conversation:
- an assistant message that calls a tool has a
tool_callsfield; - the tool's answer is a message with the role
tool.
When you train on a conversation with tool calls, the assistant message that calls the tool becomes a datum like any other, and its targets are the call.
When the model calls a tool while it's being sampled, parse_response reads the call back as tool_calls, with the call's arguments as a dictionary. If you also pass it the tools, each argument gets the type the tool declares, such as a number. Without them, every argument is the text the model wrote.
In the code below:
toolsdescribes one tool,weigh, which takes an animal's name as a string.looked_upis a conversation where the assistant callsweigh, the tool answers14, and the assistant replies.build_supervised_examples(looked_up, tools, ...)makes two datums, one for each assistant message.calledtrains the tool call, andansweredtrains the final reply.- The last two lines take
called's targets as if the model had sampled them, and read them back withparse_response.
tools = [
{
"type": "function",
"function": {
"name": "weigh",
"description": "An animal's largest weight, in kilograms.",
"parameters": {
"type": "object",
"properties": {"animal": {"type": "string"}},
"required": ["animal"],
},
},
}
]
call = {"type": "function", "function": {"name": "weigh", "arguments": {"animal": "red fox"}}}
looked_up = [
{"role": "user", "content": "How heavy is a red fox?"},
{"role": "assistant", "content": "", "tool_calls": [call]},
{"role": "tool", "name": "weigh", "content": "14"},
{"role": "assistant", "content": "Up to 14 kg."},
]
called, answered = formatter.build_supervised_examples(looked_up, tools, max_seq_len=MAX_SEQ_LEN)
print(formatter.targets(called))
print(formatter.targets(answered))
print()
sampled = called.tokens[list(called.weights).index(1) :]
print(formatter.parse_response(sampled, tools))
['<tool_call>\n<function=weigh>\n<parameter=animal>\nred fox\n</parameter>\n</function>\n</tool_call><|im_end|>']
['Up to 14 kg.<|im_end|>']
({'role': 'assistant', 'content': '', 'tool_calls': [{'type': 'function', 'function': {'name': 'weigh', 'arguments': {'animal': 'red fox'}}}]}, True)
A file of conversations
read_conversations reads a JSONL file with one conversation per line, written as {"messages": [...]}. A line can also have tools, which you pass to the formatter as its second argument.
The cookbook comes with a small example file of 16 conversations. Each answers a question about an animal with a three-line card. Two of them have a follow-up question, so they make two datums each.
In the code below:
resources.files("looper_cookbook")finds the cookbook's installed files, wherever it's installed, so the path to the example file works on any machine.- The list comprehension makes the datums for every conversation and puts them all in one list.
conversation.get("tools")is the line's tools, orNoneif it has none.- The last lines count the datums' tokens, and how many of them are trained.
from importlib import resources
from looper_cookbook.datasets.conversations import read_conversations
path = resources.files("looper_cookbook") / "example_data" / "conversations.jsonl"
conversations = read_conversations(path)
data = [
datum
for conversation in conversations
for datum in formatter.build_supervised_examples(
conversation["messages"], conversation.get("tools"), max_seq_len=MAX_SEQ_LEN
)
]
tokens = sum(len(datum.tokens) for datum in data)
trained = sum(int(sum(datum.weights)) for datum in data)
print(f"{len(conversations)} conversations: {len(data)} datums, {tokens} tokens, {trained} targets")
16 conversations: 18 datums, 1366 tokens, 805 targets
What the formatter refuses
Rather than make a datum the model's format can't hold, the formatter raises an error for any of these:
- A reply that starts past
max_seq_len. A reply that only ends past it is cut off atmax_seq_leninstead. The datum keeps the start of the reply, so the prompt before it never changes. - A conversation with no assistant message, since there's nothing in it to train.
- Content that isn't text.
- A tokenizer from a different model, when you create the formatter.
Each family's formatter is a module in looper_cookbook/message_formatters/, written from the model's chat template and short enough to read.
Next steps
- The SFT loop trains on these datums with the cookbook's SFT loop, then samples the result.
- Message formatting covers the formatters in full.