Sub topic 5
Cleaning model output before showing it
This chapter assumes you know how a fill-in-the-middle (FIM) prompt is built and that you can read short Python and TypeScript snippets. A model's raw output is not safe to show as it is. This chapter covers the cleanup between the model's reply and the ghost text on screen.
Why raw output needs cleanup
A FIM model predicts the missing middle between the prefix (text before the cursor) and the suffix (text after it). It does not always stop where the middle ends. Common problems:
- It repeats text that already follows the cursor, such as a closing bracket the editor auto-inserted.
- It keeps generating past the useful point, into the next function or an unrelated block.
- It returns nothing useful, such as only whitespace or a repeat of the line above.
- It emits special tokens or stray markup that are not code.
Cleanup is a pipeline of small, cheap checks that run after generation and before display.
Step 1: Truncate at a stop point
Generation is usually capped by a token limit and by stop sequences. For a single-line completion, a newline can be a stop sequence. For a multi-line completion, you can stop when the indentation returns to the level of the line where the cursor sits. Stopping early also lowers latency, because the request finishes sooner.
Step 2: Trim overlap with the suffix
Suppose the editor auto-closed a bracket, so the suffix starts with ). The model may also produce the ). If you insert both, the user gets )). The fix is to find the longest end of the completion that matches the start of the suffix, and remove it.
def trim_overlap(completion: str, suffix: str) -> str:
"""Drop the end of the completion if it repeats the start of the text after the cursor."""
for n in range(min(len(completion), len(suffix)), 0, -1):
if completion.endswith(suffix[:n]):
return completion[:-n]
return completion
print(repr(trim_overlap("foo(a, b)", ")\n"))) # 'foo(a, b'
print(repr(trim_overlap("x + 1", ")\n"))) # 'x + 1'The loop tries the longest possible overlap first and shortens it one character at a time. The first match wins, so the longest overlap is removed. In the first call, the completion ends with ), which matches the first character of the suffix, so ) is dropped. In the second call nothing matches, so the text is unchanged.
This version is simplified. A single-character match can be a coincidence, for example a completion that legitimately ends with a space when the suffix begins with a space. Production code often compares line by line or ignores whitespace-only overlaps.
Step 3: Filter out bad suggestions
After trimming, apply checks that decide whether to show anything at all. Showing nothing is better than showing noise.
| Check | What it catches |
|---|---|
| Empty or whitespace-only | The model had nothing useful to add |
| Repeats the line above | Looping output |
| Matches the suffix exactly | The code already exists after the cursor |
| Unbalanced brackets or quotes | Output cut off mid-expression |
| Special tokens in the text | Leaked sentinels such as `<fim_middle>` |
Some systems also run a quick syntax check on the combined prefix, completion and suffix. This catches broken code, but it costs time and can reject valid code in a file that was already incomplete. Treat it as a tuning choice, not a rule.
Step 4: Match the insertion range
After the text is clean, the editor needs to know where it goes. In a VS Code provider, the result is an InlineCompletionItem with a range. An empty range at the cursor inserts text. A range that covers the rest of the line replaces it. Choosing between the two is part of cleanup too. If the model rewrote the end of the line, replacing that range can be safer than appending to it.
Common mistakes
- Trimming only the exact suffix, so partial overlaps such as
)followed by;slip through. - Filtering too hard, so useful suggestions never appear and the acceptance rate drops.
- Running slow checks on every response, which adds latency on top of the model's own.
- Forgetting that the suffix changes while the user types, so a cleaned suggestion can go stale. Re-check against the current document before showing it.
Exercise
The cursor is inside print( and the editor auto-inserted ), so the suffix is )\n. The model returns "hello"). What does trim_overlap return, and why?
Show answer
It returns "hello". The completion ends with ), which equals the first character of the suffix, so the function removes it. Inserting the cleaned text leaves exactly one ) from the editor.
Exercise
Give two reasons to discard a suggestion instead of showing it, and one risk of discarding too often.
Show answer
Two valid reasons are an empty or whitespace-only completion and a completion that repeats text already present after the cursor. Leaked special tokens or unbalanced brackets also qualify. The risk is that useful suggestions are hidden, which lowers the acceptance rate and makes the feature feel unhelpful.