A code completion can be syntactically valid and still be the wrong edit. It might repeat the function's final return, rename an argument, or replace a carefully reviewed comment. If your application needs only the missing middle of a function, DeepSeek's fill-in-the-middle API gives you a more appropriate request shape: send the text before the insertion and the text after it separately, then receive a candidate for the gap.

The important engineering question is what your application does with that candidate. The model can use surrounding code as context; your application must preserve that code, bind the response to the correct document revision, and reject edits that cross the intended boundary.

This repair lab uses an illustrative Python invoice function. The examples are authored fixtures, not measured model responses. We will construct an insertion, parse the resulting program without executing it, and identify what those checks can and cannot establish before attempting a live API call.

Put the actual FIM contract on the bench

DeepSeek's FIM guide describes a prefix, an optional suffix, and a maximum FIM completion of 4K tokens. The documented direct-provider base URL is https://api.deepseek.com/beta. The completion endpoint reference uses POST /completions, with the prefix in prompt and trailing context in suffix. Read the candidate from choices[0].text.

Checked on November 7, 2026, that reference lists deepseek-flash and deepseek-v4-pro. The model capability table marks FIM as a non-thinking capability. Record the model actually enabled for your account; do not substitute a historical model name from an old example. A general model output allowance does not override the smaller limit documented for FIM.

There is a nearby API that is easy to confuse with this one. Chat prefix completion continues a final assistant message marked with prefix: true. Our insertion has a separate suffix and uses the completions interface. An adapter that only accepts a messages array has not yet demonstrated this contract.

That distinction is also useful when applying the broader agent harness connection guide. A successful chat configuration is one piece of integration evidence; your editor's particular completion operation needs its own request inspection.

First repair: define exactly which bytes may change

The fixture begins with a subtotal initialized to zero and ends with a return statement. The missing middle should iterate through prices. A module-level label follows the function, giving us another piece of surrounding context to protect.

For this lab, the selected region is the entire marker line, including its indentation and newline. That choice avoids an ambiguous cursor boundary where the prefix already contains four spaces and the candidate supplies another four. In an editor, store the actual selection offsets and the document revision together. If the interface uses character positions, convert them consistently before slicing encoded bytes.

Keep three distinct values: immutable prefix, candidate insertion, immutable suffix. Build the proposed document by concatenation. Do not ask the model to return the whole file and then trust its claim that only the middle changed. Do not trim the generated text automatically: leading spaces and trailing newlines can be part of the edit.

The model sees the suffix to understand what should follow. The suffix is not an instruction to copy those lines into the insertion. If the candidate includes another return total, inspect it as a possible duplication rather than silently deleting the first matching string. A legitimate insertion could itself contain an early return, so substring cleanup can change behavior.

Choose context around the hole deliberately. Include the function signature and the nearby values the insertion must consume. Include enough following code to reveal the required result and indentation. A huge suffix is not automatically more useful: unrelated code makes it harder to understand which contract your evaluation is testing. If you shorten the request context, retain the complete original prefix and suffix locally for assembly; the model-visible context and the protected document need not be identical in size.

Keep the fixture's text encoding and line endings explicit as well. A document opened with automatic newline conversion can appear unchanged while its bytes differ from the saved revision. The example uses UTF-8-compatible source and line-feed newlines throughout. A production editor should follow its existing file representation and compare revisions within that representation. Byte hashes, editor version numbers, and character offsets are useful only when their relationship is defined.

Second repair: verify the edit offline

This standalone Python example sends no request and executes no generated program. It checks a small, bounded fixture using the standard library. The assertions describe this lab's acceptance conditions; production validation should raise explicit errors because Python assertions can be disabled.

import ast
import hashlib

ORIGINAL = (
    b'def subtotal(items):\n'
    b'    """Sum the supplied prices."""\n'
    b'    total = 0\n'
    b'    # FILL\n'
    b'    return total\n\n'
    b'LABEL = "invoice"\n'
)
MARKER = b'    # FILL\n'
assert ORIGINAL.count(MARKER) == 1
start = ORIGINAL.index(MARKER)
end = start + len(MARKER)
prefix, suffix = ORIGINAL[:start], ORIGINAL[end:]
revision = hashlib.sha256(ORIGINAL).hexdigest()
reference = ast.parse(ORIGINAL.replace(MARKER, b'    pass\n').decode())

def insert(candidate, current=ORIGINAL):
    assert hashlib.sha256(current).hexdigest() == revision, 'stale edit'
    middle = candidate.encode('utf-8')
    assert 0 < len(middle) <= 8192, 'local fixture size limit'
    proposed = prefix + middle + suffix
    assert proposed[:len(prefix)] == prefix
    assert proposed[len(prefix) + len(middle):] == suffix
    tree = ast.parse(proposed.decode('utf-8'))
    assert len(tree.body) == 2
    fn, original_fn = tree.body[0], reference.body[0]
    assert isinstance(fn, ast.FunctionDef)
    assert fn.name == original_fn.name
    assert ast.dump(fn.args) == ast.dump(original_fn.args)
    assert ast.dump(fn.body[-1]) == ast.dump(original_fn.body[-1])
    assert ast.dump(tree.body[1]) == ast.dump(reference.body[1])
    return proposed

fixture = '    for price in items:\n        total += price\n'
assert b'for price in items' in insert(fixture)
try:
    insert(fixture, current=ORIGINAL + b'# another edit\n')
except AssertionError as error:
    assert str(error) == 'stale edit'
else:
    raise AssertionError('stale document accepted')
try:
    insert('    if :\n')
except SyntaxError:
    pass
else:
    raise AssertionError('invalid syntax accepted')

The two rejection fixtures matter as much as the successful insertion. One demonstrates that a response cannot be applied after another edit changes the source. The other demonstrates that a malformed candidate never reaches a reviewable proposal. These are deterministic properties of the local adapter, not evidence of DeepSeek accuracy.

Python's AST documentation explains the parser and its limits. Parsing produces a syntax tree; it does not prove that the program will run correctly, and some checks occur later in compilation. For larger or untrusted inputs, enforce resource limits before parsing and use a constrained worker. The fixture's 8,192-byte ceiling is our local demonstration limit, not a provider token limit.

What survived, and what remains unproven

The prefix and suffix survive byte for byte because the application constructs the document from the originals. That preservation is separate from syntactic meaning. A candidate can introduce a string or comment boundary that causes subsequent text to be interpreted differently even though its bytes remain unchanged. The targeted tree checks help catch certain boundary changes by requiring the final return and following module statement to remain recognizable.

Those checks are deliberately narrow. They do not reject every dangerous or incorrect program. A candidate could add an unwanted call, ignore an input value, or produce incorrect arithmetic while passing the demonstrated assertions. Treat the parser as a structural gate, followed by human review and the project's normal controlled validation process. This lab does not execute the resulting function.

There is also a product-level question: what does subtotal mean? Are inputs integers, decimal currency values, or quantities paired with unit prices? Should negative values represent refunds? The insertion task needs a local specification. Without it, several plausible loops may satisfy the same syntax checks while implementing different business behavior.

Keep that specification close to the selected code using existing type annotations, approved comments, or relevant nearby definitions. Avoid adding synthetic instructions to a real document and forgetting to remove them afterward. If you build a separate request-context representation, keep its offsets distinct from the original document's edit offsets.

The Chinese-model API acceptance tests provide a useful evaluation framework. For FIM, adapt the acceptance unit to an insertion plus preserved context, instead of scoring an isolated block of attractive code.

A small failure notebook for the editor adapter

Before involving a remote model, feed the adapter authored examples representing the failures you want it to contain.

Candidate or eventWhat the repair tool should do
Markdown fences around the insertionReject or request a new candidate under an explicit policy; preserve the original document
A second copy of the suffixFlag an unexpected boundary change for review
A candidate missing the separating newlineParse the assembled document and report the combined syntax failure
The user edits another line while waitingDiscard the stale proposal or explicitly recompute the edit
Valid syntax with the wrong calculationKeep the semantic review gate closed

Store failures by category. Transport errors, malformed response envelopes, invalid syntax, stale revisions, and incorrect behavior have different remedies. Increasing the output allowance cannot fix a response being read from the wrong field. Repeating a request cannot make an obsolete document revision current.

An editor can also issue duplicate requests as a selection changes. Assign each proposal a local operation identifier and apply only the response belonging to the current operation. This does not imply server-side idempotency. The related TRAE duplicate-request diagnosis is useful when investigating overlapping client attempts; preserve that distinction between observing requests and controlling which edit is accepted.

Only then prepare the live request

The following is a live-request template, not an executed test. It reuses prefix and suffix from the offline fixture. Configure the API key issued for the selected service, an explicitly confirmed FIM base URL, and a model enabled for that route. For direct DeepSeek access, the documented FIM base URL is the beta URL given above. A gateway route may have a different contract and must be confirmed separately.

# LIVE TEMPLATE — not executed. Requires the openai package.
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ['FIM_API_KEY'],
    base_url=os.environ['VERIFIED_FIM_BASE_URL'],
)
response = client.completions.create(
    model=os.environ['VERIFIED_FIM_MODEL'],
    prompt=prefix.decode('utf-8'),
    suffix=suffix.decode('utf-8'),
    max_tokens=256,
    stream=False,
)
candidate = response.choices[0].text
# Inspect completion status, then validate against the current revision.
# Do not execute candidate or write it directly into the source file.

The small output allowance suits this fixture; it is not a universal setting. Preserve the response status and reject a completion stopped by its length budget until it has been deliberately reviewed or regenerated. Keep the initial request minimal. In particular, the endpoint reference forbids combining echo with suffix; an application wanting the full proposed file can assemble it locally.

Avoid inventing a stop sequence from the suffix's first word. A word such as return might also be needed inside the missing block, so that choice can cut off a legitimate candidate. Start with the bounded nonstreaming operation, inspect how completions end, and introduce stopping rules only when you can explain their effect on the selected language and edit boundary.

If your editor says the provider is connected but this operation fails, inspect the actual URL and JSON body. The WorkBuddy custom-model troubleshooting guide offers relevant distinctions among authentication, model selection, and protocol mismatch. A failure at the FIM boundary should remain visible instead of being converted into an unrelated chat operation without the caller's knowledge.

Make the first pilot an insertion you can inspect

Choose a short, non-sensitive function and one selected region. Record the source revision, prefix and suffix lengths, requested model, returned completion status, and local validation outcome. Compare proposed edits using the same fixture and acceptance policy. Keep source text out of routine operational logs unless your own handling policy permits it.

The broader Chinese LLM gateway selection guide can help frame provider evaluation, but this pilot has a specific purchasing question: does the selected route preserve the FIM request and return the completion shape your editor needs?

If you want to evaluate Treerouter for this workflow, first confirm account access, the exact model, the FIM endpoint, suffix forwarding, and response behavior with its current documentation or support. Native FIM availability through Treerouter has not been verified here. Once confirmed, begin with the bounded repair fixture and inspect the first accepted proposal before connecting a larger codebase.

Learn more: Treerouter.