Sub topic 5
Cleaning model output before showing it
A model's raw output is rarely ready to show as ghost text. It can include special tokens, repeat code that is already in the file, run past the end of the logical block, or return only whitespace. This chapter covers the post-processing step between the model response and the editor.
This chapter assumes you have read the earlier chapters on building the request and on fill-in-the-middle prompting. You should also be able to read short Python and know what a prefix and a suffix are in this setting: the text before and after the cursor.
Why raw output needs cleaning
Fill-in-the-middle (FIM) prompting asks the model to generate only the missing middle. The model does not always do that cleanly, for four reasons:
- It was trained to predict tokens, not to respect an editor's cursor. It may continue past the point where the middle should stop and start writing the suffix again.
- The editor may have changed the document in ways the model never saw. A common case is an auto-inserted closing bracket that is already in the suffix.
- Sampling is probabilistic. Some responses are empty, whitespace-only, or stuck in a loop.
- The server may return special tokens that were never meant for the user.
Post-processing is a short pipeline of cheap, deterministic checks. Each step either edits the text or rejects it. Rejecting is a valid result. Showing no suggestion costs the user nothing, while showing a broken one costs trust.
Order matters. Special tokens must go first, because they can hide an overlap with the suffix. The overlap trim should run after any truncation, because truncating changes where the completion ends.
The steps in detail
Strip special tokens and stop at them
FIM models use sentinel tokens such as <fim_middle> and end-of-text markers such as <|endoftext|>. If one appears in the output, everything from that token onward is not part of the completion. Cut at the first sentinel instead of deleting just the sentinel text. A model that emits <|endoftext|> and keeps going is producing unrelated text.
Where possible, also set stop sequences and a token limit in the request. That saves latency and cost. The client-side check is a second layer for backends you don't control.
Remove an echoed prefix
Sometimes the model repeats the current line up to the cursor. If the line before the cursor is return and the model answers return a + b, inserting it as is produces return return a + b. Compare the start of the completion with the text of the current line before the cursor, and remove the match.
The check here is exact. Real implementations also handle a model that repeats the line without its leading indentation. If you add that case, compare stripped text, so a model that echoes return is still caught.
Limit mid-line completions to one line
If there is text after the cursor on the same line, a multi-line completion usually makes no sense. The editor would push the rest of the line to the end of a block the model did not plan for. A common rule: when the suffix's first line is non-blank, keep only the first line of the completion.
Trim overlap with the suffix
Editors often auto-close brackets and quotes. If you type foo(, the document may become foo() with the cursor between the brackets. The model may complete a, b), which duplicates the existing ). The fix is to find the longest piece of the completion's end that equals the start of the suffix, and remove it. This is the trim_overlap function from the topic's examples.
Reject low-quality output
After the edits, drop the suggestion if any of these hold:
- It is empty or contains only whitespace.
- It is a loop, for example the same non-trivial line repeated three times at the end.
- It is identical to text already after the cursor (the model just copied the suffix).
- The backend reported a very low confidence, if it exposes token log-probabilities. Pick the threshold by measuring acceptance, not by guessing.
A working pipeline
The following script combines the steps and runs as shown. The examples at the bottom each exercise a different step.
SPECIAL_TOKENS = ["<fim_prefix>", "<fim_suffix>", "<fim_middle>", "<|endoftext|>", "<file_sep>"]
def strip_special_tokens(text: str) -> str:
"""Cut the text at the first special token."""
cut = len(text)
for token in SPECIAL_TOKENS:
index = text.find(token)
if index != -1:
cut = min(cut, index)
return text[:cut]
def remove_prefix_echo(completion: str, prefix: str) -> str:
"""Drop the part of the completion that repeats the current line before the cursor."""
line_prefix = prefix.rsplit("\n", 1)[-1]
if line_prefix.strip() and completion.startswith(line_prefix):
return completion[len(line_prefix):]
return completion
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
def is_repetitive(text: str) -> bool:
"""True if the last three non-blank lines are identical and not trivially short."""
lines = [line.strip() for line in text.splitlines() if line.strip()]
return len(lines) >= 3 and len(set(lines[-3:])) == 1 and len(lines[-1]) > 3
def clean_completion(completion: str, prefix: str, suffix: str):
"""Return the cleaned completion, or None if it should not be shown."""
text = strip_special_tokens(completion)
text = remove_prefix_echo(text, prefix)
mid_line = suffix.split("\n", 1)[0].strip() != ""
if mid_line:
text = text.split("\n", 1)[0]
text = trim_overlap(text, suffix)
text = text.rstrip()
if not text.strip() or is_repetitive(text):
return None
return text
# Special token plus a repeated blank line from the suffix.
print(repr(clean_completion(
"a + b\n\n<|endoftext|>",
"def add(a, b):\n return ",
"\n\nprint(add(1, 2))\n",
))) # 'a + b'
# Mid-line: keep one line, then remove the duplicated bracket.
print(repr(clean_completion(
"values)\nprint(total)",
"total = sum(",
")\nprint(total)\n",
))) # 'values'
# The model echoed the current line.
print(repr(clean_completion(" return a + b", " return ", "\n"))) # 'a + b'
# Whitespace only.
print(repr(clean_completion(" \n", "x = ", "\n"))) # NoneEdge cases and trade-offs
| Step | Catches | Risk if too aggressive |
|---|---|---|
| Strip special tokens | Sentinels and unrelated text after them | None if tokens are exact. A token-like string in real code is rare. |
| Remove prefix echo | Repeated current line | Can remove legitimate text when the code really repeats a line. |
| Single-line limit | Multi-line text pushed into the middle of a line | Rejects useful multi-line completions after an auto-closed bracket. |
| Overlap trim | Duplicated closing brackets and quotes | Can cut valid text that happens to match the suffix start. |
| Quality check | Empty and looping output | A too-loose repetition rule rejects valid code such as repeated `}` lines. |
The overlap trim deserves care. The simple version accepts any match, even one character long. Suppose the completion is x = (1) and the suffix starts with ). The function removes the final ) and leaves x = (1, which has a bracket the user did not need. A safer version removes the overlap only when brackets in the combined text would otherwise be unbalanced. Counting brackets is cheap, though it ignores brackets inside strings and comments.
Timing and cancellation
Post-processing runs after the response arrives, so it must be fast. Keep it to simple string operations on a few hundred characters. Run it only for responses that are still current. If the user typed again and the request was cancelled, discard the response before cleaning it. If you process a stale response, you can show a suggestion for a cursor position that no longer exists.
With streaming responses, you can clean incrementally, but the overlap trim and the mid-line limit need the full text, or at least the first line. Many implementations wait for the first line, clean and show it, then extend the suggestion as more text arrives.
Beyond string rules
Some products add heavier checks, such as parsing the result with a syntax parser to confirm the file still parses, or filtering matches against public code or secrets. These cost more time and are covered later, in the privacy and failure-mode chapters. String-level cleaning comes first because it is cheap and catches most of the obvious defects.
Exercise
The user types print( and the editor auto-inserts ), so the document is print() with the cursor inside. The model returns "hello") followed by a newline and the line print("bye"). The suffix is )\nprint("bye")\n. Using clean_completion, what is the result, and which two steps produced it?
Show answer
The result is "hello". The mid-line limit runs first: the suffix's first line is ), which is non-blank, so only the first line of the completion, "hello"), is kept. Then trim_overlap finds that the completion ends with ), which matches the start of the suffix, and removes it.
Exercise
A teammate removes the strip_special_tokens step and puts the trim_overlap step first. A response arrives as a + b\n\n<|endoftext|> with the suffix \n\nprint(add(1, 2))\n. What goes wrong?
Show answer
trim_overlap compares the end of the completion with the start of the suffix. The text ends with <|endoftext|>, so the real overlap (\n\n) is no longer at the end and no trimming happens. The special token then has to be removed afterward, leaving trailing newlines that were not trimmed. In the correct order, the token is cut first, so the overlap is at the end of the text and trim_overlap removes it.
Exercise
Why is returning no suggestion a better outcome than showing a suggestion that fails a quality check, even when the failing suggestion is partly correct?
Show answer
Ghost text interrupts the user. A bad suggestion costs reading time and can lower trust, which reduces later acceptance. Showing nothing costs nothing. Rejection rules should therefore lean toward dropping doubtful output, and you can tune how strict they are by watching the acceptance rate.