AD SPACE AVAILABLE · BRAND PARTNERS WELCOME

Configuring the DeepSeek FIM API for Prefix and Suffix Code Autocompletion

최지향 · 365Finds Editorial
Indexed 88,650 Wiki articles

Put 365 Wiki to work with your AI

Copy the prompt below, paste it into the AI you already use, then ask your question.

Download full Skill

Try it with the prompt first. If you use 365 Wiki often, install the full 365Wiki Skill so you do not have to paste it again. No regular AI? Gemini or Microsoft Copilot on the web will work.

365Wiki Skill

Most conversational APIs expect you to append text to the end of a prompt. Code editing does not work that way. When a developer writes code, the cursor sits in the middle of a file: imports and declarations sit above, while closing braces, return statements, and downstream function calls sit below. Standard chat completions generate plausible continuations that ignore existing closing syntax, producing duplicate closing brackets and broken indentations.

To solve this, DeepSeek provides a dedicated Fill-In-the-Middle (FIM) Completion API. It accepts both a prefix (the code preceding the cursor) and a suffix (the code following the cursor), interpolating missing logic directly between them.

At 365Finds, we evaluate AI code generation pipelines across edge and cloud infrastructure. DeepSeek’s FIM endpoint stands out for an unusual combination: low token pricing, automatic prefix context caching, and native OpenAI SDK compatibility. But setting it up requires navigating several non-standard configuration quirks that routinely trip up developers building custom IDE extensions or tab-autocomplete pipelines.


1. The Core Architectural Differences: Beta Endpoint vs. Standard Chat

The most frequent error we encounter in failed DeepSeek autocomplete setups is routing requests to the standard /chat/completions endpoint.

DeepSeek does not expose FIM through its standard chat route. Instead, FIM is hosted exclusively under a dedicated /beta namespace using the legacy OpenAI-compatible text completions schema (/completions).

Parameter / DimensionStandard Chat APIDeepSeek FIM Completion API
Base URLhttps://api.deepseek.com (or /v1)https://api.deepseek.com/beta
Route Path/chat/completions/completions
Primary Input Fieldmessages: [{"role": "user", ...}]prompt (Prefix context)
Infilling FieldNot natively supportedsuffix (Trailing context)
Reasoning / Thinking ModeSupported (e.g., DeepSeek-R1)Disabled (Non-thinking models only)
Output Cap (max_tokens)Up to 8,192 tokensHard ceiling of 4,000 tokens
Primary Production Modeldeepseek-chatdeepseek-chat

If you send suffix to https://api.deepseek.com/chat/completions, the backend silently discards the parameter or throws an unrecognized property error. You must point your client’s base URL directly to https://api.deepseek.com/beta.

Furthermore, DeepSeek explicitly restricts FIM to non-thinking mode. Tab autocompletion requires sub-second execution; reasoning tokens and internal scratchpads would introduce intolerable latency.


2. API Request Structure: Prompt and Suffix Parameters

In the FIM schema, prompt represents the prefix context leading up to the cursor insertion point, while suffix represents the text directly following it.

Here is a raw curl request showing the exact payload structure:

curl --location 'https://api.deepseek.com/beta/completions' \
  --header 'Authorization: Bearer YOUR_DEEPSEEK_API_KEY' \
  --header 'Content-Type: application/json' \
  --data '{
    "model": "deepseek-chat",
    "prompt": "def calculate_effective_rate(nominal_rate: float, compounding_periods: int) -> float:\n    \"\"\"Calculate annual effective rate.\"\"\"\n    ",
    "suffix": "\n    return effective_rate",
    "max_tokens": 64,
    "temperature": 0.0,
    "stop": ["\n\n", "def ", "class "]
  }'

Python SDK Implementation

Because DeepSeek adheres to the OpenAI SDK wire format, you can initialize the standard openai library simply by overriding base_url:

import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ.get("DEEPSEEK_API_KEY"),
    base_url="https://api.deepseek.com/beta"
)

def autocomplete_code(prefix: str, suffix: str) -> str:
    response = client.completions.create(
        model="deepseek-chat",
        prompt=prefix,
        suffix=suffix,
        max_tokens=128,
        temperature=0.0,
        stop=["\n\n", "def ", "class "],
        stream=False
    )
    return response.choices[0].text

prefix_code = """import math

def calculate_circle_area(radius: float) -> float:
    if radius < 0:
        raise ValueError("Radius cannot be negative")
    """

suffix_code = """
    return area
"""

completion = autocomplete_code(prefix_code, suffix_code)
print(f"Generated Infill:\n{completion}")

3. Managing the Context Window and Budget Allocation

While DeepSeek models feature broad 64K token context windows, feeding entire multi-thousand-line files into an autocompletion pipeline is a mistake.

Autocompletion latency is directly correlated with prompt token length. In local editor plugins, acceptable tab-completion latency must fall between 250ms and 600ms. 365Finds recommends enforcing strict context budget rules before dispatching payloads to the FIM endpoint.

Recommended Window Budget Slicing

For an inline autocomplete trigger, cap the total input context between 2,048 and 4,096 tokens. We recommend an asymmetric 80/20 or 75/25 split between prefix and suffix:

  1. Prefix Context (75%–80% of budget): Language models rely overwhelmingly on preceding tokens to infer scope, variable types, active function definitions, and module imports. Truncate prefix code from the top (preserving lines immediately preceding the cursor).
  2. Suffix Context (20%–25% of budget): The suffix serves primarily to ground indentation, anticipate return variables, and prevent duplicate closing brackets. Truncate suffix code from the bottom (preserving lines immediately following the cursor).
  3. Generation Cap (max_tokens): Set max_tokens between 64 and 128 tokens for single-line or tight block autocompletion. Never leave max_tokens unset or configured to the 4,000 token maximum; doing so invites runaway generation when the model fails to hit a stop condition.
Total Context Window Budget (e.g., 2048 Tokens)
┌───────────────────────────────────────┬───────────────────┬──────────────┐
│ Prefix Context (~1536 Tokens)         │ Suffix (~384 Tok) │ Output Buffer│
│ [Truncate file top; keep near cursor] │ [Keep near cursor]│ (64-128 Tok) │
└───────────────────────────────────────┴───────────────────┴──────────────┘

Leveraging DeepSeek's Prefix Context Caching

DeepSeek runs automatic context caching at the server level. When multiple API requests share an identical token prefix starting from token zero, DeepSeek serves cached tokens under prompt_cache_hit_tokens at a fraction of standard input pricing.

To exploit this in your IDE pipeline:


4. IDE Integration: Configuring Continue for Tab Autocomplete

If you use open-source IDE extensions like Continue in VS Code or JetBrains, configuring DeepSeek for inline tab completion requires binding the FIM role inside your configuration file.

Continue Configuration (config.yaml / config.json)

In Continue’s configuration file (~/.continue/config.json or equivalent config.yaml), specify DeepSeek as your tabAutocompleteModel:

{
  "tabAutocompleteModel": {
    "title": "DeepSeek FIM Autocomplete",
    "provider": "deepseek",
    "model": "deepseek-chat",
    "apiKey": "YOUR_DEEPSEEK_API_KEY",
    "apiBase": "https://api.deepseek.com/beta",
    "completionOptions": {
      "temperature": 0.0,
      "maxTokens": 64,
      "stop": ["\n\n", "class ", "def "]
    }
  },
  "tabAutocompleteOptions": {
    "debounceDelay": 350,
    "maxPromptTokens": 2048,
    "multilineCompletions": "always"
  }
}

Key configuration considerations:


5. Practical Implementation Checklist

When integrating DeepSeek FIM into a production autocomplete pipeline, verify these operational boundaries:

  1. Verify Endpoint Path: Confirm your network client points to https://api.deepseek.com/beta/completions.
  2. Payload Key Names: Ensure your payload uses prompt for the prefix and suffix for the trailing context.
  3. Set Defensive Stop Sequences: Provide language-specific stop tokens (e.g., ["\n\n"] for single-statement completions, or closing bracket sequences) to prevent the model from hallucinating subsequent functions.
  4. Inspect Usage Telemetry: Inspect usage.prompt_cache_hit_tokens versus usage.prompt_cache_miss_tokens in API responses to verify that your prefix structure successfully triggers server-side caching.

DeepSeek returns usage.prompt_tokens, usage.completion_tokens, and usage.prompt_cache_hit_tokens in every FIM response payload, confirming active cache utilization on consecutive keystroke evaluations.

References