What is FIM

FIM (Fill-in-the-Middle) is a special completion mode. Traditional text generation can only continue from left to right, while FIM allows the model to fill in the missing "middle" part based on the "preceding context" and "following context". This is extremely useful in code completion scenarios—you write the first half and the second half of a function signature, and the model helps you complete the implementation in between.

FIM Completion API

Both DeepSeek V4 Flash and Pro support FIM completion (non-thinking mode only):

from openai import OpenAI
import os

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

response = client.completions.create(
    model='deepseek-v4-flash',
    prompt='def fibonacci(n):\n    if n <= 1:\n        return n',
    suffix='\n\n# テスト\nprint(fibonacci(10))',
    max_tokens=256,
    temperature=0,
    stop=['\n\n#']
)

print(response.choices[0].text)
# 出力:
#     return fibonacci(n-1) + fibonacci(n-2)

Prompt Design Best Practices

StrategyExampleEffect
Function signature hintPreceding context = function signature + docstring, following context = return statementComplete the function body implementation
Test-drivenPreceding context = function definition, following context = test casesGenerate code that satisfies the tests
Comment-drivenPreceding context = comment description, following context = type annotationsGenerate code according to comments

Integration into Editors

VS Code (via Continue plugin): Configure tabAutocompleteModel to point to DeepSeek to enable FIM completion.

Neovim (via llm.nvim): Configure the fim endpoint to point to the DeepSeek completions API.

FIM vs Chat API Comparison

FIM CompletionChat Completion
Endpoint/v1/completions/v1/chat/completions
ContextPreceding + following contextOnly preceding context (conversation history)
SpeedFaster (no conversation overhead)Slower
CostLower (no system messages)Higher
Use casesReal-time completion, inline suggestionsConversational programming, complex Q&A

Notes

  • FIM only supports non-thinking mode; enabling thinking will result in an error.
  • The suffix parameter is required (unlike the standard completions API).
  • It is recommended to set the stop parameter to the first few characters of the following context to avoid over-generation.
  • This is currently a Beta feature; the API may be subject to changes.