Use the tokenizer from the local MLX-LM model and apply the same chat template you will use for generation. Count the resulting IDs, including the assistant’s reply marker, then compare that count with a limit that reserves room for your output.

Decide which combination you want to count

Start with a local MLX-LM checkpoint you can load on an Apple silicon Mac. Use the tokenizer and template that your chat path actually uses. An input can be represented differently across checkpoints, and formatting a conversation adds tokens beyond the user-visible text. Counting characters or words gives only an approximation. A count of the exact formatted input is more useful when an application needs to decide whether it can submit a conversation. MLX-LM Python usage · Hugging Face chat template documentation

Pick the context limit used by your running application rather than borrowing the maximum from a model card. If you control the inference call, record its configured capacity and any reserved output. If you only have a remote or different runtime, use that runtime’s measurement method. This exercise counts a local text chat built with the checkpoint’s template. The result applies when the actual conversation and template match those used in this code.

Prepare a sample conversation with distinct source text. Put Use the supplied inventory facts only in a system message if your model supports that role. Add a user message asking about a workshop label. For another sample, include a previous assistant response and a new user request. The second conversation should let you see exactly what changes when you retain history. Write down which roles you expect the model to receive before reading any count.

Count the encoded chat template

Save this script in the same local environment that can import MLX-LM. Prepare a file called messages.json containing a JSON list of role and content objects. Supply the model path, context limit, and output reserve as arguments.

import json
import sys
from pathlib import Path

from mlx_lm import load


def main():
    if len(sys.argv) != 5:
        raise SystemExit("Usage: count.py MODEL_DIR MESSAGES.json LIMIT OUTPUT_RESERVE")
    model_dir = Path(sys.argv[1]).expanduser()
    if not model_dir.is_dir():
        raise SystemExit("Choose an existing local model folder")
    messages = json.loads(Path(sys.argv[2]).read_text(encoding="utf-8"))
    limit, reserve = int(sys.argv[3]), int(sys.argv[4])
    if not isinstance(messages, list) or not messages or reserve < 1 or limit <= reserve:
        raise SystemExit("Provide message objects and a positive reserve below the limit")
    _, tokenizer = load(str(model_dir))
    ids = tokenizer.apply_chat_template(
        messages, tokenize=True, add_generation_prompt=True
    )
    count = len(ids)
    budget = limit - reserve
    print(f"Formatted input tokens: {count}")
    print(f"Input allowance: {budget}")
    if count > budget:
        print("Input exceeds the configured allowance")
        return 1
    print("Input fits the configured allowance")
    return 0


if __name__ == "__main__":
    sys.exit(main())

Use a model whose tokenizer supports the roles and text chat format you pass. The example loads the checkpoint with the normal API to get its tokenizer. That may require enough memory to load the weights even though the script only counts tokens. An application that already has a tokenizer can reuse it inside the running process. Retain the same tokenizer configuration rather than loading a generic one.

Create a first input with a simple user turn, such as Return only the current room label. Set a limit and reserve appropriate to your planned exercise. For arithmetic practice, an input allowance is the context limit minus the reserved completion length. With a configured example limit of 1,024 and a reserve of 128, the allowance is 896. Those numbers illustrate the calculation and say nothing about the capacity of a particular model. Use your own runtime settings for the comparison.

Include the system message, history and reply marker

View the exact conversation list before making a decision. Text that your app inserts automatically, such as an instruction prefix and recent history, should appear in the input you count. A single user line may look short enough while the complete input exceeds the budget. If one integration adds earlier messages after your check, move the count later in the request construction so it measures what will be submitted.

Keep the assistant reply marker included if you are starting a new model response. The dedicated chat-template option may add role and generation markers appropriate to that tokenizer. The count can differ from encoding only the visible words. Follow the tokenizer’s intended format. Avoid adding special tokens a second time by formatting to a string and independently applying a default encoding unless you have checked that behavior for your exact path. Hugging Face chat templates and generation prompts

Some checkpoints require a particular order of roles or do not support a system message. If the tokenizer rejects a role sequence, use the model’s supported conversation format or document what changed. Keep a single user message as a baseline. Compare the result after adding history that the template accepts. A role error is a different problem from exceeding the budget. Fix the conversation shape first so you can interpret the count.

Use a known pair of input files to verify decisions

Make a short message file and another with two previous turns added. Run the same script against both and compare the printed counts. The exact numbers depend on the tokenizer, so avoid hard-coding a universal expected difference. Instead, inspect that the printed allowance is the same for both runs and that changes match the input supplied. Open the two JSON files and confirm the history was actually added. If the longer conversation’s count unexpectedly matches the shorter, check whether the tokenizer ignored unsupported roles or an adapter changed the input.

Test the gate deterministically with an input at the boundary. Use a count you observed from the short file and select a test limit equal to that count plus the desired reserve. The count should be accepted because it exactly matches the allowance. Reduce this synthetic limit by one and run again. The input should be rejected. This verifies the decision rule using an observed count. It does not prove a runtime will allocate that context for real inference.

Try another file containing a code block, a long identifier, or text in a different script. Counting by words can behave very differently for these inputs. Compare the result with your earlier approximation to see why the application needs the actual IDs. Preserve the text unchanged between counting and generation. Trimming line breaks or normalizing punctuation afterward can change the encoded length and invalidate the earlier decision.

Test the exact handoff to inference

Put counting beside the code that builds the message list. Capture one harmless fixture from just before the actual generation call. Include any role supplied automatically by your own application. Then try the message file you originally thought would be submitted. If the two counts differ, inspect the extra fields and history. Some interfaces keep instructions, a system greeting or a previous answer offscreen. The model can still receive them. A correct gate has to count the final input rather than an earlier version of it.

Decide where attachments are converted. A document’s file size is not the amount of text your application will supply. An attachment reader might provide a few retrieved paragraphs, extract a full page, or insert source labels. Count the actual resulting text messages after that step. For this script, media inputs are outside the example. If your runtime adds image representations, you need its documented method for accounting for those inputs. Keep the count and its applicable input type in your notes.

For a route that later adds a response marker, turn that option on for the count and verify the same option is active during generation. A test with one user turn and a second with an assistant reply already present reveals an easy mistake. Use the conversation shape supported by the model. If your application is asking the model to continue an existing assistant message, verify the appropriate templating behavior for that special case. Starting a new reply and continuing a partial one need different assumptions.

Track context trimming as a user-visible decision

Suppose your original conversation includes instructions for keeping units and an old answer about a delivery quantity. The conversation no longer fits when you add the third report. If you trim an earlier answer, record that it was removed and preserve the controlling unit instruction. Recount and run a practice question that expects the units to survive. If the answer now drops a qualification, refine the trimming plan even when the new token count fits the target. The numeric check is useful for size. The second check protects the meaning of the conversation.

For repeated tests, save the request file with synthetic content, the limit and reserve, and the exact model identifier. After changing a chat template, keep an old sample and a new sample and inspect the formatted result for role markers before assuming that a changed count is a defect. Some updates legitimately change the template. Confirm that the application and the counter use the new one together. Run the exact-boundary acceptance test again so a change in counts cannot mask a mistake in the budget comparison.

If your runtime returns actual prompt usage, compare it with the estimate in a run with one small synthetic request. A mismatch can come from extra server-side framing, different template settings or a request you did not count after a final edit. Reproduce the mismatch on the smallest message you can. Avoid adjusting the reserve to hide it until you know which path adds the extra tokens.

Choose the smallest repair when a request exceeds its allowance

Start by deciding which parts of the conversation are required. Keep the current user request and its controlling instruction. If earlier history repeats itself, replace related turns with a verified short record, then recount the exact result. For a document question, keep the relevant source passages with their page labels. Avoid dropping a qualification just to make the number smaller. Use a separate response reserve that fits your task rather than reducing it without considering how long the answer should be.

If you change the model or checkpoint, count again with its own tokenizer. Keep the tokenizer and template identifier beside test results so the next developer can reproduce them. A successful preflight means the formatted size fits the limit you chose. A live call still needs enough actual context, memory and the expected model settings. Check those through the runtime if it reports a different usage count or refuses the request.