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 ghost-text completions in an editor. It covers what goes into a completion request and how that context is chosen.
What the model needs to see
A completion model has no access to your editor. It sees only the text the client sends. The quality of a suggestion depends mostly on what that text contains, so assembling the request is a core part of the feature.
A typical request has three parts:
- The prefix is all text before the cursor, usually cut to fit a budget.
- The suffix is all text after the cursor, also cut to fit.
- Related context is snippets from other places, such as open tabs, imported files or recently viewed code.
The prefix tells the model what you have written so far. The suffix tells it what must still fit afterward, such as a closing bracket or a following function. Related context supplies names and conventions that are not in the current file.
Splitting the document at the cursor
The editor reports the cursor as a line and column. The client converts that to an offset and splits the text there.
def split_at_cursor(text: str, line: int, column: int) -> tuple[str, str]:
"""Split text into (prefix, suffix) at a zero-based line and column."""
lines = text.split("\n")
offset = sum(len(l) + 1 for l in lines[:line]) + column
return text[:offset], text[offset:]
source = "def add(a, b):\n return \n\nprint(add(1, 2))\n"
prefix, suffix = split_at_cursor(source, line=1, column=11)
print(repr(prefix))
print(repr(suffix))The prefix ends with return and the suffix begins with a newline. The model must produce text that fits between them.
Staying inside a token budget
Models accept a limited number of tokens, and long prompts are slower. Clients therefore trim. The usual rule is to keep the text nearest the cursor, because it is the most relevant. That means cutting the start of the prefix and the end of the suffix.
def trim_context(prefix: str, suffix: str, max_chars: int = 2000) -> tuple[str, str]:
"""Keep about 3/4 of the budget for the prefix and 1/4 for the suffix."""
prefix_budget = max_chars * 3 // 4
suffix_budget = max_chars - prefix_budget
return prefix[-prefix_budget:], suffix[:suffix_budget]This sketch counts characters. Real clients count tokens with the model's tokenizer, since characters and tokens do not map evenly. Many also cut at line boundaries, so the prompt never starts in the middle of a line.
Choosing related context
A single file often does not hold enough information. If you call load_config() and it is defined elsewhere, the model has to guess its signature. Clients add snippets from other files to reduce this guessing.
Common sources are:
- Files open in other editor tabs.
- Files imported by the current file.
- Recently viewed or edited files.
- Snippets found by similarity search against the text near the cursor.
Each snippet is scored and the best ones are added until the budget runs out. A simple version scores by word overlap with the prefix.
import re
def words(text: str) -> set[str]:
return set(re.findall(r"[A-Za-z_]\w+", text))
def pick_snippets(prefix: str, candidates: list[str], limit: int = 2) -> list[str]:
target = words(prefix[-500:])
ranked = sorted(candidates, key=lambda c: len(words(c) & target), reverse=True)
return ranked[:limit]Common errors
- Sending the whole file. This wastes budget and adds latency. Trim to the cursor's neighborhood.
- Ignoring the suffix. The model then repeats code that already exists below the cursor.
- Adding unrelated snippets. Irrelevant context can lead the model to copy the wrong style or names. Fewer, better snippets usually win.
- Using stale content. Build the request from the editor's current buffer, not the file on disk, or unsaved edits are missing.
Exercise
A user's cursor is in the middle of a 3,000-line file, and the prompt budget is small. Which parts of the prefix and suffix should be dropped first, and why?
Show answer
Drop the text farthest from the cursor: the start of the prefix and the end of the suffix. Text nearest the cursor is the most relevant to what comes next, so it is kept.
Exercise
A completion repeats a function that already appears below the cursor. Which part of request assembly is the most likely cause?
Show answer
The suffix was left out or cut too short, so the model could not see the code that follows the cursor.