Sub topic 2
Building the request: prefix, suffix and related context
This chapter assumes you can read Python, know that a language model predicts text from a prompt, and have used an inline completion feature such as ghost text in VS Code. The previous chapter showed how ghost text appears at the cursor. This one covers what the editor sends to the model to produce it.
What a completion request contains
A completion model has no memory of your project. Every request starts from nothing, so the editor must put everything the model needs into one prompt. That prompt is built from four kinds of input:
- The prefix: all text before the cursor.
- The suffix: all text after the cursor.
- Related context: snippets from other files, or other parts of the same file.
- Metadata: the language, the file path, and sometimes the file name of tests or configuration.
The request also carries sampling settings, such as a maximum output length and stop sequences. Those settings affect how long the completion runs, but the quality of the suggestion depends mostly on the text you assemble.
The prefix: the most important input
The prefix tells the model what has already been written, including the current half-typed line. It carries the most signal for three reasons. It holds the imports, which name the libraries in use. It holds the nearby function signatures and variable names. It shows the style of the code, such as indentation, quote style and naming.
A file can be far larger than the model's context window, and sending more tokens also slows the response. So the editor cannot send the whole prefix. It keeps the end of the prefix, the part closest to the cursor, and drops the beginning. Two details matter here:
- Trim on line boundaries. Cutting in the middle of a line gives the model a broken statement and degrades the output.
- Never drop the current line. The text between the last newline and the cursor is the most important part of the whole request.
Some assistants keep a small fixed header from the top of the file, usually the imports, even when the middle is trimmed. This costs few tokens and keeps the model aware of what is available.
The suffix: what comes after the cursor
Many edits happen in the middle of existing code. The text after the cursor tells the model what the new code must connect to: the caller that uses the result, the closing brackets, the next function. Without the suffix, a model may write code that duplicates what is already below the cursor or that returns the wrong type.
The suffix gets a smaller budget than the prefix, because the text just after the cursor matters most and the signal fades quickly. The next chapter covers how the model actually reads a suffix, using fill-in-the-middle prompting. Here the point is only that the editor must collect it.
Related context from other files
Often the right answer lives in another file. If you type parse_config( and the function is defined in config/loader.py, the model can only complete the call correctly if it sees that definition. Assistants gather this related context from several places:
| Source | What it provides | Typical weakness |
|---|---|---|
| Open tabs | Files you are working on right now | Includes unrelated tabs |
| Recently viewed files | Files you looked at to understand the task | May be stale |
| Same-directory files | Neighboring modules with shared conventions | Misses distant definitions |
| Symbol search or language server | Definitions of names near the cursor | Needs a working language server |
| Text similarity search | Snippets that resemble the code around the cursor | Can return near-duplicates |
A common technique for the similarity approach is to slice open files into windows of a few dozen lines. The assistant then scores each window by how many identifiers it shares with the lines around the cursor. The best-scoring windows become snippets. This is cheap, needs no index, and works across languages.
Related snippets are usually added as comments at the top of the prompt, each labelled with its file path. A comment looks like normal code to the model, so it reads the snippet as part of the file.
Working under a token budget
Every model has a context limit, and latency grows with prompt length. Assistants therefore set a budget for the prompt, often well below the limit, and divide it among the parts. The example below uses a fixed split of 60% for the prefix, 20% for the suffix and 20% for related snippets. Real products tune these numbers by experiment.
The code estimates tokens as one per four characters. This is a rough rule for English-like text and code, and a real implementation would call the model's tokenizer.
from dataclasses import dataclass
@dataclass
class Snippet:
path: str
text: str
score: float
def estimate_tokens(text: str) -> int:
# Rough rule: about 4 characters per token. Use a real tokenizer in production.
return max(1, len(text) // 4)
def take_tail_lines(text: str, budget: int) -> str:
"""Keep the lines closest to the cursor at the END of the text (for the prefix)."""
kept, used = [], 0
for line in reversed(text.splitlines(keepends=True)):
cost = estimate_tokens(line)
if kept and used + cost > budget:
break # always keep at least the current line
kept.append(line)
used += cost
return "".join(reversed(kept))
def take_head_lines(text: str, budget: int) -> str:
"""Keep the lines closest to the cursor at the START of the text (for the suffix)."""
kept, used = [], 0
for line in text.splitlines(keepends=True):
cost = estimate_tokens(line)
if kept and used + cost > budget:
break
kept.append(line)
used += cost
return "".join(kept)
def render_related(snippets: list[Snippet], budget: int) -> str:
parts, used = [], 0
for snippet in sorted(snippets, key=lambda s: s.score, reverse=True):
body = "".join(f"# {line}\n" for line in snippet.text.splitlines())
block = f"# Path: {snippet.path}\n{body}"
cost = estimate_tokens(block)
if used + cost > budget:
continue # skip this snippet, a smaller one may still fit
parts.append(block)
used += cost
return "".join(parts)
def build_request(prefix: str, suffix: str, snippets: list[Snippet],
max_tokens: int = 1000) -> dict:
return {
"related": render_related(snippets, int(max_tokens * 0.2)),
"prefix": take_tail_lines(prefix, int(max_tokens * 0.6)),
"suffix": take_head_lines(suffix, int(max_tokens * 0.2)),
}
if __name__ == "__main__":
prefix = "def total(a, b):\n return "
suffix = "\n\nprint(total(1, 2))\n"
snippets = [
Snippet("utils/math_ops.py", "def mul(a, b):\n return a * b", 0.8),
Snippet("README.md", "Project notes and setup steps.", 0.1),
]
request = build_request(prefix, suffix, snippets, max_tokens=200)
for name, value in request.items():
print(f"--- {name} ---")
print(value)Three design choices in this code are worth noting. The prefix is trimmed from the start and the suffix from the end, so both keep the text nearest the cursor. A snippet that does not fit is skipped, not allowed to stop the loop, so a later, smaller snippet can still fit. And snippets are ranked by score before the budget is applied, so the best ones are never the ones that get cut.
Edge cases to know
- Cursor in the middle of a line. The prefix ends mid-line and the suffix begins mid-line. The model must write something that joins both halves, and this is why the later post-processing step removes overlap with the suffix.
- Very large or generated files. A minified bundle or a lock file can fill the entire budget with noise. Assistants usually skip files above a size limit or with very long lines.
- Empty or new files. With no prefix, related context carries most of the signal. The file path and language become the main hints.
- Stale context. Snippets from files with unsaved changes must come from the editor's in-memory buffer. If they come from disk, the model sees old code.
- Ignored and secret files. Files listed in ignore rules, such as
.env, should never become snippets. This is a privacy rule, covered in a later chapter. - Multiple cursors and selections. Most assistants build a request for the primary cursor only.
Cost and latency effects
Prompt size affects both speed and cost. A longer prompt takes longer to process before the first token arrives, and many services bill per input token. Because completions fire very often, a few hundred extra tokens per request add up. A typical design therefore favors a short, well-chosen prompt over a long, complete one. Some services also cache the processed prefix, so an unchanged header lets the next request reuse earlier work.
Exercise
A developer types inside a function near line 900 of a 1,200-line file. The prompt budget only fits 300 lines. Which lines of the prefix should be kept, why should the cut fall on a line boundary, and what small piece from the top of the file might still be worth keeping?
Show answer
Keep the lines closest to the cursor, which are the lines just above it, and drop lines from the top of the file. Cut on a line boundary because a half line is a broken statement that confuses the model. The imports at the top of the file may be worth keeping as a short fixed header, because they name the libraries and helpers available and cost few tokens.
Exercise
In build_request, a snippet scored 0.9 costs 150 tokens, but only 120 tokens of related budget remain. A snippet scored 0.3 costs 40 tokens. What does the code do, and why does it use continue instead of break?
Show answer
It skips the 0.9 snippet because it does not fit, then adds the 0.3 snippet because it does. Using continue lets later, smaller snippets still use the remaining budget. A break would stop at the first snippet that does not fit and waste the leftover budget.