Sub topic 3
Fill-in-the-middle prompting
This chapter assumes you know what an inline completion request contains (text before the cursor, text after it, and some related context). It also assumes you can read short Python snippets. Here you will see how that request becomes a prompt for a model that can write text in the middle of a file.
Why left-to-right generation is not enough
A standard language model predicts the next token from the tokens before it. That works at the end of a file, but most edits happen in the middle of existing code. Consider this document with the cursor after return :
def add(a, b):
return
print(add(1, 2))If you send only the text before the cursor, the model sees def add(a, b):\n return and has no idea what follows. It may produce a long, unrelated continuation, or code that duplicates the print line. The text after the cursor holds useful information: it shows how the function is called, what the surrounding indentation is, and where the completion should stop.
Fill-in-the-middle (FIM) solves this. The model is trained to receive the prefix and the suffix, and to generate only the missing middle.
How a model learns FIM
FIM is a training-data transformation, not a new architecture. Take a training document and split it at two random points into three parts: prefix, middle, and suffix. Then rearrange the parts so the middle comes last, and mark each part with a special sentinel token. A decoder-only model still predicts left to right, but the middle is now the "next" text it must produce, conditioned on both sides.
Two orderings are common:
- PSM (prefix, suffix, middle):
<PRE> prefix <SUF> suffix <MID> middle - SPM (suffix, prefix, middle): the suffix comes first, then the prefix, then the middle.
Which one a model expects depends on how it was trained. Some models were trained on a mix of both. At inference time you must use an ordering the model was trained on.
Building a FIM prompt
The sentinel tokens are literal strings that the tokenizer maps to single special token IDs. The following function builds a prompt in the StarCoder style:
def build_fim_prompt(prefix: str, suffix: str) -> str:
# StarCoder-style sentinel tokens; other models use different ones.
return f"<fim_prefix>{prefix}<fim_suffix>{suffix}<fim_middle>"
document = "def add(a, b):\n return \n\nprint(add(1, 2))\n"
cursor = document.index("return ") + len("return ")
prompt = build_fim_prompt(document[:cursor], document[cursor:])
print(prompt)The prompt ends with <fim_middle>. The model continues from there and writes the middle. For this example a good model produces a + b, and then emits an end-of-text token. That final token matters, and it is covered below.
Sentinel tokens differ between model families. Always copy them from the model card or the tokenizer configuration.
| Model family | Prefix token | Suffix token | Middle token | Column | Column | Column | Column | Column | Column |
|---|---|---|---|---|---|---|---|---|---|
| StarCoder | `<fim_prefix>` | `<fim_suffix>` | `<fim_middle>` | ||||||
| Code Llama | `<PRE>` | `<SUF>` | `<MID>` | ||||||
| Qwen2.5-Coder | `<\ | fim_prefix\ | >` | `<\ | fim_suffix\ | >` | `<\ | fim_middle\ | >` |
Code Llama also has spacing rules around its tokens, so check its documentation before reusing the string template above.
Where related files fit
The chapter on context assembly covered related files and snippets from other tabs. With FIM, they go before the prefix, inside the prefix section, usually as comments that name the source file:
# File: utils/math_ops.py
# def clamp(x, lo, hi): ...
def normalize(values):
return [clamp(v, 0, 1) for v in Putting them in the prefix keeps the layout the model saw during training: one prefix, one suffix, one middle. Some models trained on whole repositories define extra tokens for file boundaries, such as a file separator. If yours does, prefer those tokens over ad-hoc comments.
Fitting prefix and suffix into a token budget
A model has a maximum context length, and a long prompt adds latency. A real editor therefore truncates both sides. Two rules are widely used:
- Keep the text nearest the cursor. Cut the prefix from its start and the suffix from its end.
- Give the prefix more room than the suffix. A ratio such as 3 to 1 is a common starting point, because the code above the cursor usually matters more than the code below.
Cutting in the middle of a line can leave a half-line at the edge that confuses the model, so cut at line boundaries. This sketch uses characters as a stand-in for tokens. A real implementation would count tokens with the model's tokenizer.
def truncate_context(
prefix: str, suffix: str, max_prefix: int, max_suffix: int
) -> tuple[str, str]:
"""Keep the text nearest the cursor, cutting at line boundaries."""
if len(prefix) > max_prefix:
prefix = prefix[-max_prefix:]
newline = prefix.find("\n")
if newline != -1:
prefix = prefix[newline + 1 :] # drop the partial first line
if len(suffix) > max_suffix:
suffix = suffix[:max_suffix]
newline = suffix.rfind("\n")
if newline != -1:
suffix = suffix[: newline + 1] # drop the partial last line
return prefix, suffix
long_prefix = "".join(f"line {i}\n" for i in range(100))
long_suffix = "".join(f"after {i}\n" for i in range(100))
p, s = truncate_context(long_prefix, long_suffix, 60, 30)
print(repr(p))
print(repr(s))Note that a truncated prefix changes what the model sees. If the cut removes an import or a class header, the completion may use the wrong names. That is one reason related-file context is useful.
Stopping the generation
In plain left-to-right completion, the model can stop anywhere. In FIM, the model must stop at the point where the middle connects to the suffix. A well-trained FIM model learns to emit an end-of-text token at that point. Your request should still set limits:
- A maximum token count, often small for inline completions (for example 64 to 256 tokens).
- Stop sequences, such as a blank line or a sequence that signals the end of a block, when you want shorter, single-statement suggestions.
- A multi-line policy: many editors ask for one line when the cursor is in the middle of a line, and allow several lines only when the cursor sits on an empty line or at the end of a block.
The model does not always stop cleanly. It may repeat the start of the suffix, for example by writing a closing bracket that already exists after the cursor. The next chapter covers the cleanup step for this.
Common errors
These problems appear often when building or debugging a FIM pipeline:
- Wrong or missing sentinel tokens. Symptoms are random prose, repeated sentinel text in the output, or completions that ignore the suffix. Check the exact token strings and ordering.
- Trailing whitespace in the prefix. A prefix ending in a space (as in
return) can tokenize differently from the way the model saw it in training, where a space usually joins the following word. Some systems trim the trailing space from the prefix and add it back to the completion. Test both ways on your model. - Empty suffix. At the end of a file the suffix is empty. Most FIM models handle this, but check that your template does not leave stray tokens.
- Suffix too long. A large suffix wastes budget and slows the response, and it can pull the model toward code far from the cursor.
- Output includes the sentinel tokens. Strip any special tokens from the response, or configure the server to skip them.
- Completions that never end. The model does not emit the end-of-text token, or the server ignores it. Set a hard token limit and stop sequences as a safety net.
Where FIM stops helping
FIM predicts text at one position. It cannot change code elsewhere, and the model sees only the prefix, the suffix, and whatever context you add. If a rename in one place requires updates in three others, FIM will not make them. That limit is the reason next edit suggestions exist, and later chapters compare the two.
Exercise
A developer places the cursor in the middle of a function body and sends only the text before the cursor to a model. The model keeps writing code that duplicates lines already present below the cursor. What change to the prompt addresses this, and what must be true of the model?
Show answer
Send the text after the cursor too, as a suffix, in a fill-in-the-middle prompt with the model's sentinel tokens (for example prefix, suffix, then the middle token). The model must have been trained with FIM, so it understands the sentinel tokens and stops when the middle joins the suffix.
Exercise
Why does the truncation function cut the prefix from its start and the suffix from its end, and why does it cut at newlines?
Show answer
The text nearest the cursor is the most relevant, so the far ends are dropped first. Cutting at newlines avoids leaving a partial line at the edge of the context, which can confuse the model.