🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Code Assistants: Completion, Chat and Repository Context

đŸŸĸ Free Lesson

Code Assistant

Prerequisites

  • !How language models tokenize and continue code
  • !Repository layout: symbols, imports and tests
  • !Interactive latency and streaming responses

What You'll Learn

  • 1Distinguish completion, chat and agentic modes by latency and verification needs
  • 2Build fill-in-the-middle prompts that respect a strict latency budget
  • 3Retrieve repository context by symbol relevance rather than recency
  • 4Measure assistants with acceptance, edit distance and defect escape instead of raw accuracy

Three products that share a codebase

Completion inserts a line or block as the developer types. It must respond in roughly 100–300 ms, tolerate partial and ungrammatical context, and be willing to say nothing — an unwanted suggestion costs attention, and attention is the scarce resource in an editor.

Chat answers questions and rewrites selections on demand. Seconds of latency are acceptable, the context is a deliberate selection plus conversation history, and the output is text the developer still has to apply.

Agentic mode plans, edits multiple files and runs tools. It is measured in minutes, needs verification loops — run the tests, read the error, revise — and carries the highest blast radius because its edits span files the developer has not read.

ModeLatency budgetContextVerificationTypical failure
Completion100–300 msCurrent buffer, cursor-localAccept or ignoreIrrelevant suggestion
Chat1–10 sSelection, open files, historyHuman reads the diffWrong API usage
AgentMinutesRepository, tool outputsTests and lintersCascading edits

Treating these as one feature with one metric is the classic mistake: a model praised for chat-quality explanations will destroy completion UX, because its answers arrive four seconds late and three paragraphs long.

Fill-in-the-middle and the shape of the prompt

Completion models are trained with a fill-in-the-middle objective: prefix, hole, suffix. Getting the split points right matters more than the model choice. Cut the prefix at a syntactic boundary where possible — the start of a line block rather than mid-token — and keep the suffix short, because tokens near the cursor matter far more than tokens scrolled away.

python
def build_fim_prompt(buffer: str, cursor: int, max_prefix: int = 1800,
                     max_suffix: int = 400) -> dict:
    """Split a document into FIM segments within a token budget."""
    prefix, suffix = buffer[:cursor], buffer[cursor:]

    # Prefer cutting at a blank line: keeps the last statement intact.
    if len(prefix) > max_prefix:
        cut = prefix.rfind("\n\n", 0, max_prefix)
        cut = cut if cut > max_prefix // 2 else prefix.rfind("\n", 0, max_prefix)
        prefix = prefix[cut + 1:] if cut != -1 else prefix[-max_prefix:]

    if len(suffix) > max_suffix:
        nxt = suffix.find("\n\n")
        suffix = suffix[:nxt] if 0 < nxt < max_suffix else suffix[:max_suffix]

    return {
        "prefix": prefix,
        "hole": "<|fim_hole|>",
        "suffix": suffix,
        "stop": ["\n\n\n", "<|fim_end|>"],
        "truncated_prefix": len(buffer[:cursor]) > len(prefix),
    }


buffer = """def transfer(db, src, dst, amount):
    if amount <= 0:
        raise ValueError("amount must be positive")

    # apply the transfer
    """
print(build_fim_prompt(buffer, buffer.index("    # apply"), max_prefix=200))

Two details separate usable completions from noise. Report truncated_prefix so the client knows whether to suppress the suggestion — a model that cannot see the function signature should not be proposing its body. And keep the stop sequences aggressive: a suggestion that continues into the next function is a suggestion the developer undoes, and undo time is not free.

Retrieving repository context

Chat and agent modes need the right files, not the open ones. Recency is a weak signal; symbol relevance and dependency distance are strong ones.

python
import os
import re


def rank_context(root: str, question: str, limit: int = 6,
                 ignore=("node_modules", ".git", "dist", "build")) -> list[str]:
    """Rank files by identifier overlap with the question, boosted by imports."""
    q_tokens = set(re.findall(r"[A-Za-z_][A-Za-z0-9_]*", question.lower()))
    scored = []

    for dirpath, dirnames, filenames in os.walk(root):
        dirnames[:] = [d for d in dirnames if d not in ignore]
        for name in filenames:
            if not name.endswith((".py", ".ts", ".tsx", ".js", ".go", ".rs")):
                continue
            path = os.path.join(dirpath, name)
            try:
                text = open(path, encoding="utf-8", errors="ignore").read(40_000)
            except OSError:
                continue

            symbols = set(re.findall(r"\b(?:def|class|function|const|type)\s+(\w+)", text))
            imports = set(re.findall(r"(?:from|import)\s+['\"]?([\w./]+)", text))
            body_tokens = set(re.findall(r"[A-Za-z_][A-Za-z0-9_]*", text.lower()))

            overlap = len(q_tokens & body_tokens) + 3 * len(q_tokens & {
                s.lower() for s in symbols
            })
            name_hit = 2 if any(t in name.lower() for t in q_tokens) else 0
            import_hit = 1 if any(
                any(t in imp for t in q_tokens) for imp in imports
            ) else 0

            if overlap + name_hit + import_hit:
                scored.append((path, overlap + name_hit + import_hit))

    scored.sort(key=lambda s: -s[1])
    return [p for p, _ in scored[:limit]]


print(rank_context(".", "where is the transfer validator defined"))

Weighting symbols three times heavier than raw token overlap is deliberate: identifiers are what questions are made of, while prose inside comments dilutes the signal. After ranking, pack the budget by relevance rather than taking whole files — read the symbol and its callers first — because a single 2,000-line file can evict every useful fragment in the context window.

💡Show the model what it will change

Always include the definitions of symbols the answer touches. A model that cannot see the helper's signature will invent parameters, and the error only appears when the developer runs the code.

Latency is a design constraint, not a metric

Completion UX collapses at around 400 ms of visible delay; past that, developers stop looking at suggestions entirely, and the feature becomes an expensive no-op. The budget therefore dictates engineering decisions end to end.

Debounce input so you send one request per pause rather than one per keystroke. Cache aggressively on prefix hashes — typing a method body usually reuses the same prefix dozens of times. Stream tokens so the first glyph appears immediately; perceived latency improves far more from time-to-first-token than from total time. Cancel in-flight requests on the next keystroke rather than letting abandoned generations queue behind live ones. And ship a local or small distilled model for the single-line case, reserving the large model for block completions and chat where the latency budget is roomier.

Measure each of these: time to first token, total time, cancellation rate, and — the one that actually matters — the fraction of suggestions that were displayed at all. A system that computes diligently and arrives late has optimised the wrong quantity.

Diff-aware chat and the verification loop

Chat output that developers must apply by hand gets applied wrong, so successful assistants propose diffs and let the editor apply them. The discipline around those diffs is what earns trust: changes should be minimal, explained in one sentence, and accompanied by the command that proves them — the test, the type check, the linter.

For agentic runs, make verification explicit in the loop rather than assumed at the end. Run the test suite after each file edit, feed failures back into the next step, and stop after a bounded number of attempts instead of generating increasingly speculative fixes. Cap the blast radius too: refuse to edit files outside a declared scope, and show a summary of touched files grouped by directory before anything is applied. Developers accept broad changes when they can see the shape of them; they abandon assistants that quietly rewrite a dozen files they never opened.

Trust, licensing and privacy

Three risks are structural rather than model-dependent. Secrets: source buffers contain keys and tokens, so redaction must run before transmission and telemetry must never include buffer contents. Licensing: suggestions derived from copyleft repositories can carry obligations, and provenance tracking or filter lists are how you find out before legal does. Verification: unreviewed generated code is unowned code; the assistant's job is to make review cheap, not to make it unnecessary.

Publish these guarantees in the product, not the marketing. A developer who knows what leaves the machine, what is retained and for how long, uses the tool on real work; one who does not, uses it on throwaway files and quietly stops.

Evaluating with the metrics users feel

Acceptance rate is the headline number, but it is gameable: shorter suggestions are accepted more often, and a model that only proposes trivial lines will look excellent. Pair it with edit distance between the suggestion and what was ultimately typed — large edits mean the suggestion was nearly right and still useless — and with defect escape: how many generated lines survived review but later failed a test.

For chat and agent modes, use task-based evaluation on real repositories: given an issue and a test that fails before and passes after, did the patch succeed? Report pass rate, files touched, and wall-clock cost per success, because an assistant that solves the task in forty edits and six minutes is a different product from one that solves it in two. Track regression sets of previously solved tasks; models drift with every update, and the only way to know a version change helped is to re-run the tasks you already solved.

Common Mistakes

Judging completion models by explanation quality

Fix: Measure time to first token, acceptance rate and edit distance on real editing sessions

Sending whole files as context until the window overflows

Fix: Rank by symbol relevance, then pack the budget with definitions and callers

Letting an agent run unbounded retries on failing tests

Fix: Cap attempts, require a verification command per step and surface touched files for approval

Shipping without stating what leaves the developer's machine

Fix: Redact secrets before transmission, publish retention terms and exclude buffers from telemetry

Best Practices

  • Split the product into completion, chat and agent with separate budgets and metrics
  • Cut FIM prefixes at syntactic boundaries and suppress suggestions when context was truncated
  • Stream tokens and cancel stale requests; time-to-first-token dominates perceived speed
  • Return diffs with a one-line rationale and the command that proves them
  • Keep a regression suite of solved tasks and re-run it on every model update

Key Takeaways

  • Completion, chat and agent are different products with different latency, context and verification contracts
  • Fill-in-the-middle quality depends on where you cut the buffer, not only on the model
  • Context retrieval should rank symbols and dependency distance, then pack definitions before prose
  • Latency budgets are design constraints: debounce, cache, stream, cancel and measure time to first token
  • Evaluate with acceptance plus edit distance plus defect escape, and keep a regression suite across model updates
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Generative AI Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement