New Tool Radar

Local AI

How to Cap mlx_lm.generate Output With a Maximum Token Limit

Set a maximum token limit for an mlx_lm.generate run and confirm the answer stops at the limit.

Schematic with three steps: Run once without a limit; Run again with a limit; Compare the two answers.

A model left to itself can ramble on long past the useful answer. The –max-tokens flag caps the output length for one run, which keeps answers short and saves time and memory.

What you need

  • A Mac with Apple Silicon and mlx-lm installed
  • A downloaded MLX model
  • A terminal with the virtual environment activated

Step 1: Run once without a limit

Run mlx_lm.generate with a model and a prompt and note how long the answer is. This is the baseline to compare against.

Step 2: Run again with a limit

Run the same prompt again with –max-tokens 50 added. The model should stop after about 50 tokens, even if the answer feels unfinished.

Step 3: Compare the two answers

Read both answers. The limited one should be shorter and end at the cap; if it runs past the cap, check the flag was typed correctly.

Worked example: synthetic token limit

The table below is a synthetic example. It shows the expected result of capping output; no run was made.

Run Max tokens Answer length
No limit None set Long, several paragraphs
Limited 50 Stops near 50 tokens
Limited 200 Stops near 200 tokens

Expected result (UNTESTED). the unlimited run gives a long answer, and the limited runs stop near 50 and 200 tokens as set. This check was not run live; the table shows the expected result for the synthetic example.

Limits

  • A low limit can cut an answer mid-sentence; raise it if the answer is unfinished.
  • The limit counts output tokens, not input tokens, so it does not shorten the prompt.
  • The flag applies to that run only; save the working limit in a script or a note.

Sources

See all