Skip to content
ImagineWorld

Appendix G: Building a chat interface

node_idnode-book_build-a-reasoning-model_appendix-g-building-a-chat-interface
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_titleAppendix G: Building a chat interface
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

appendix G Building a chat interface

The supplementary code repository for this book includes a small browser-based chat interface, built with the open source Chainlit Python package (https://github.com/Chainlit/chainlit). This ChatGPT-like interface allows us to interact with the various LLMs and reasoning models in this book, as shown in the screenshot in figure G.1. This interface can be useful when we want a more convenient way to interact with the models than typing prompts into a notebook cell or terminal.

Building upon the Chainlit library, the implementation of this interface is relatively straightforward. Instead of printing tokens to the terminal, we wrap the same model-loading and generation functions from the earlier chapters inside a small web application, which stays local on the computer and runs in a browser. In practice, this means that we can reuse the from-scratch Qwen3Model implementation and the chapter 2 streaming helper while letting Chainlit handle the browser UI and message events.

The book’s supplementary materials contain two variants of the interface in chG/01_main-chapter-code (https://github.com/rasbt/reasoning-from-scratch/tree/main/chG/01_main-chapter-code):

  • qwen3_chat_interface.py is a single-turn interface.
  • qwen3_chat_interface_multiturn.py stores conversation history and supports multi-turn interactions.

bar-fig-g.1-chainlit-chat-interface.png

Figure G.1 Chainlit interface for the Qwen3 model, which mimics the ChatGPT interface. Print annotation: “A ChatGPT-like interface that runs locally in the web browser.” (Crop from scan page-410.png, printed p. 398. Embedded rather than recreated: the figure is a browser screenshot.) Figure G.1 Chainlit interface for the Qwen3 model, which mimics the ChatGPT interface

In this appendix, we’ll walk through both versions. We’ll also discuss how to install Chainlit and how to download the scripts via the download_from_github helper from chapter 7.

Before running the chat interface, we first need to install Chainlit. This is the simplest option:

pip install chainlit

If you are using uv, this is the equivalent command:

uv add chainlit

If you are working directly inside the reasoning-from-scratch repository, Chainlit is also listed as an optional dependency in the project’s pyproject.toml. In that case, this is a convenient alternative:

uv sync —extra extra or

pip install -e ".[extra]"

Chainlit runs ordinary Python scripts. This is important, because Chainlit imports the script as a module and looks for special functions decorated with @chainlit.on_chat_start and @chainlit.on_message, as you’ll see later.

This means that if you want to reuse the code shown in this appendix, you should place it into a .py file such as

qwen3_chat_interface.py

or

app.py

Then launch it from the terminal as follows:

chainlit run app.py

Or, if you are using uv, the command is

uv run chainlit run app.py

In other words, while you can inspect the code in a notebook, the actual Chainlit application is expected to live in a standalone Python script.

If you cloned the repository, the files are already present in ch6/01_main-chapter-code, and you can skip this section. Otherwise, as discussed in chapter 7, you can use download_from_github(…) to fetch the two scripts.

Listing G.1 Downloading Chainlit scripts

from reasoning_from_scratch.ch07 import download_from_github
download_from_github(
"ch6/01_main-chapter-code/qwen3_chat_interface.py"
)
download_from_github(
"ch6/01_main-chapter-code/qwen3_chat_interface_multiturn.py"
)

The regular single-turn version of the interface, in qwen3_chat_interface.py, is intentionally compact. It reuses the LLM and inference code from chapter 2 almost directly

The CHECKPOINT_PATH environment variable in listing G.2 is optional. If it is set, the script loads that custom .pth checkpoint instead of the default official weights. The load_app_model_and_tokenizer() helper handles these two cases. If no custom checkpoint is provided, it delegates to load_model_and_tokenizer(…) from chapter 3. If a custom checkpoint path is provided, it loads only the tokenizer via load_tokenizer_only(…), constructs a fresh Qwen3Model(QWEN_CONFIG_06_B), and then loads the weights from the custom state dictionary.

This is useful because it means the single-turn Chainlit interface can also be used to inspect chapter 6, 7, and 8 checkpoints interactively, provided that the tokenizer setting remains aligned with the checkpoint. The next section explains exactly how the custom checkpoint can be provided as input from the command line.

The @chainlit.on_chat_start function initializes a history object and inserts a default system message, which is a common convention:

{“role”: “system”, “content”: “You are a helpful assistant.”}

But the single-turn script does not actually use that stored history when generating the response. Inside main(…), the prompt is built only from the current message .content:

input_ids = TOKENIZER.encode(message.content)

So even though the browser UI looks like a chat application, the single-turn version behaves more like a prompt box that shows earlier messages visually, without the model actually remembering earlier conversations. In other words, the model itself sees only the current user message and treats each turn independently.

The rest of the generation logic is very similar to what you saw in chapter 2.

If you are inside the supplementary code repository, the most convenient command to launch the user interface is usually the following:

uv run chainlit run chG/01_main-chapter-code/qwen3_chat_interface.py

If you saved the code under another filename, such as app.py, you can simply replace the path accordingly:

uv run chainlit run app.py

After launching the server, Chainlit usually opens a browser tab automatically. If it doesn’t, you can copy the local address shown in the terminal to the browser manually. Typically this is http://localhost:8000.

Figure G.2 shows some example output in the Chainlit interface.

bar-fig-g.2-chainlit-example-response.png

Figure G.2 Example response in the Chainlit interface. Print annotation: “Truncated response to a simple prompt like ‘What is 1+1?’ to demo the user interface.” (Crop from scan page-413.png, printed p. 403. Embedded rather than recreated: the figure is a browser screenshot.)

By default, the script initializes the Qwen3 reasoning variant I briefly introduced in chapter 3, which produced the response shown in figure G.2. To run the same script with a custom checkpoint, you can pass the path via the CHECKPOINT_PATH environment variable. Here’s an example:

CHECKPOINT_PATH=path/to/qwen3-0.6B-distill-step06682-epoch1.pth \ uv run chainlit run chG/01_main-chapter-code/qwen3_chat_interface.py

When doing so, WHICH_MODEL must remain aligned with the tokenizer expected by the checkpoint. The chapter 8 distillation checkpoints use the reasoning tokenizer, so in that case you should keep WHICH_MODEL = “reasoning”. For the chapter 6 checkpoints, for example, you would change it to WHICH_MODEL = “base”.

Editing the configuration directly in the script may seem a bit cumbersome. The reason for doing this, rather than using command-line arguments, is that Chainlit itself launches and manages the application entry point via chainlit run … As a result, the script does not behave like a normal standalone Python program where we can freely define and parse custom command-line arguments with the Python argparse library, for example. For simple options such as model choice, generation length, or checkpoint paths, it is more convenient to keep the settings in the script or pass them via environment variables.

Downloading model checkpoints If you want to explore some of the model checkpoints from chapters 6, 7, or 8 but don’t have the compute capacity to train them yourself, you can find information on how to download them in the supplementary materials at https://github.com/rasbt/reasoning-from-scratch/tree/main/ch07/04_download_training_checkpoints and https://github.com/rasbt/reasoning-from-scratch/tree/main/ch08/05_download_training_checkpoints.

The second script, qwen3_chat_interface_multiturn.py, extends the basic Chainlit interface so that the model can condition on earlier turns in the same conversation. The following subsections explain what multi-turn means in practice, how the script implements it, and when it is appropriate to use.

In a single-turn setup, the model only sees the current input. For illustration purposes, suppose the interaction looks like this:

User: What is 1 + 1? Assistant: 2 User: What did I just ask?

In the regular single-turn script, when the model receives the second message, “What did I just ask?”, it might respond with “I don’t know what you are asking”. The earlier question and answer are visible in the browser, but they are not included in the model input, so the model does not truly have conversational memory.

In a multi-turn setup (qwen3_chat_interface_multiturn.py), we explicitly include, or more specifically prepend, the earlier messages in the prompt, similar to what ChatGPT and other chat assistants do. In this case, the model might answer the question “What did I just ask?” with “You asked me what 1+1 is”.

The multi-turn script begins in the same way as the regular version, but it adds two helper functions and uses the stored session history during generation.

The first helper, in the following listing, turns the stored message history into the Qwen chat format we require.

Listing G.3 Building a prompt from conversation history

def build_prompt_from_history(history, add_assistant_header=True):
parts = []
for m in history:
role = m["role"]
content = m["content"]
parts.append(f"<|im_start|>{role}\n{content}<|im_end|>\n")
if add_assistant_header:
parts.append("<|im_start|>assistant\n")
return "".join(parts)

The build_prompt_from_history function in the preceding listing serializes the message list into the chat-template style that the Qwen reasoning model expects. Conceptually, the resulting prompt looks like this:

<|im_start|>system
You are a helpful assistant.<|im_end|>
<|im_start|>user
What is 1 + 1?<|im_end|>
<|im_start|>assistant
2<|im_end|>
<|im_start|>user
What did I just ask?<|im_end|>
<|im_start|>assistant

The model then continues generating from that final assistant header.

The second helper, shown next, trims the messages if they exceed the context length, since multi-turn conversations can grow very long.

Listing G.4 Trimming the prompt to fit the context window

def trim_input_tensor(input_ids_tensor, context_len, max_new_tokens):
assert max_new_tokens < context_len
keep_len = max(1, context_len - max_new_tokens)
if input_ids_tensor.shape[1] > keep_len:
input_ids_tensor = input_ids_tensor[:, -keep_len:]
return input_ids_tensor

This trim_input_tensor helper function ensures that enough room remains in the context window for the new tokens. If the conversation becomes too long, the oldest tokens are discarded first via left truncation. (Other, more sophisticated options also exist, such as summarizing the previous context, but that isn’t implemented here for the sake of simplicity.)

G.6.3 How the multi-turn script uses history

Section titled “G.6.3 How the multi-turn script uses history”

The multi-turn behavior appears inside the message handler. At the beginning of each turn, the script retrieves the current session history and appends the new user message:

history = chainlit.user_session.get("history")
history.append({"role": "user", "content": message.content})

It then builds the full prompt from that history, tokenizes it, optionally trims it, and streams the answer in the same way as before. At the end of generation, it stores the model reply back into the same history list:

history.append({"role": "assistant", "content": out_msg.content})
chainlit.user_session.set("history", history)

This is the multi-turn script’s core difference from the single-turn script. The multi-turn version does not merely display a chat transcript in the browser; it feeds the earlier turns back into the model so future responses can condition on them.

The launch command is analogous to the single-turn case:

Terminal window
uv run chainlit run chG/01_main-chapter-code/qwen3_chat_interface_multiturn.py

Operationally, the script behaves just like the regular Chainlit interface, as shown in figure G.3. The only difference is in how the prompt is constructed internally.

The second response in figure G.3 indicates that the model remembers the first question through the provided context.

The multi-turn Chainlit script is intended for the official Qwen3 reasoning variant. It is not a good fit for the chapter 8 distillation checkpoints, for example, because the distillation checkpoints were trained on prompt-response style supervision rather than on persistent multi-turn chat histories. They were not trained to continue a conversation over several turns in the same way as the official reasoning checkpoint.

As a consequence, the multi-turn script should not be expected to work reliably with the distillation checkpoints. I recommend you use them as follows:

  • Use the single-turn Chainlit script for quick interactive tests, including custom checkpoints for chapters 6, 7, and 8.
  • Use the multi-turn Chainlit script with the official reasoning checkpoint when you want conversation memory.

What is 1+1? The answer is simple, don’t overthink.

<think> Okay, the user is asking what 1+1 is, and they want the answer to be simple. I need to make sure I respond in a way that’s straightforward. Let me think… The answer is definitely 2. But wait, should I explain why? Maybe add a simple sentence to confirm. Also, check if there’s any trick here. No, it’s a basic math problem. Just state the answer clearly. Alright, time to put it all together. </think> 1 + 1 = 2.

The second LLM response shows that the LLM is remembering the first question.

What did I just ask you?

<think> Okay, the user just asked, “What did I just ask you?” I need to respond appropriately. Let me think. The previous message was a simple math question, “What is 1+1?” and the assistant provided the answer. Now the user is asking, “What did I just ask you?” So they’re probably testing if I can recognize the question and provide the correct answer. I should acknowledge their question and confirm the answer again. Let me make sure the response is friendly and clear. Maybe say something like, “I just asked you, ‘What is 1+1?’ and the answer is 2.” That way, it’s concise and confirms the previous interaction. </think>

Type your message here…

LLMs can make mistakes. Check important info.

bar-fig-g.3-chainlit-multi-turn-response.png

Figure G.3 Example response in the Chainlit interface with multiple prompts, showing the model’s <think> reasoning traces. Print annotation: “The second LLM response shows that the LLM is remembering the first question.” (Crop from scan page-417.png, printed p. 405. Embedded rather than recreated: the figure is a browser screenshot.)