SiliconFlow FIM: fill in code between a prefix and a suffix
Send extra_body.prefix and extra_body.suffix to /chat/completions, get the middle section back, splice it into your code and compile it. No API call was made here.
Task and deliverable · Prepare the input and environment · How the parameters work
At a glance
SiliconFlow's FIM guide describes one concrete job: you supply the text you want before and after a gap, and the model writes the missing middle, typically for code completion or for generating the middle of a document. This tutorial stitches three official pages into one path: the FIM page covers the request shape and the supported models, the prefix continuation page covers what happens when you send only a prefix, and the quickstart page covers the API key plus the OpenAI SDK install and base_url. By the end you have a piece of code that compiles, and a way to decide whether the fill-in actually succeeded. Passages marked editorial are this site's checking practice, not vendor-defined behavior. No API was called in this batch, and none of the sample code was executed.
Fill-in-the-middle workflow
Tell filling from continuing
The FIM page defines the task as users supplying the content they want before and after, with the model completing the middle; the two parameters are prefix and suffix. The prefix continuation page is a different job: you send only
extra_body={"prefix": "希望的前缀内容"}and the model keeps writing forward from that prefix, which the page says gives better instruction following and satisfies requested formats. Both pages use/chat/completionsand both pass parameters through extra_body; the difference is whether there is a suffix. Choosing the wrong page has a concrete symptom: you get a repeated prefix or a fresh paragraph instead of the text for the gap.Check the model is in range
The FIM page lists concrete IDs and warns that the list may change, so you should filter the model marketplace for current FIM support. The prefix continuation page lists no IDs and describes a range instead: non-reasoning large language models support the parameter, reasoning models in the Qwen3 series support it after "增加 enable_thinking=true 关闭推理", and the deepseek R1 series does not support it for now. The two pages disagree about DeepSeek-R1: the FIM page lists DeepSeek-R1 as supported, while the prefix continuation page says the prefix parameter is unsupported. This article records both pages and does not pick a winner; check the marketplace filter and your own small sample before you commit.
Prepare the API key and SDK
The quickstart page lays out the path: log in, click "新建 API 密钥" on the API keys page, then call through the OpenAI library; its example sets
base_urltohttps://api.siliconflow.cn/v1, installs withpip install --upgrade openai, and requires Python 3.7.1 or newer in a virtual environment. The FIM page comment says the key comes fromcloud.siliconflow.cn/account/ak. The quickstart page also points at the model marketplace for model prices and rate limits; this article did not collect those numbers.Hand the gap to extra_body and collect the middle
A FIM request still sends
messages: the page sample has a single user message,Please write quick sort code, while the real prefix and suffix ride inextra_body. The page illustrates the JSON body as "在 /chat/completions 接口中,通过 extra_body 传入 prefix 和 suffix", and its SDK sample passesextra_body={...}as a keyword argument tocreate(); the page never explains how those two forms map onto the wire, so this article does not guess. The sample setsstream=Trueandmax_tokens=4096and printschunk.choices[0].delta.contentchunk by chunk.Splice, compile and read it yourself
The model returns only the middle, so the finished artifact is prefix plus middle plus suffix. The editorial check order is: look at whether the middle is empty or simply repeats the prefix or suffix, then run
compile()on the spliced text, then execute the assertions in the suffix, and finally read the logic to see whether it honors the comment it was asked to satisfy. The official pages define none of this delivery check, and they give no standard for completion quality.
Task and deliverable
The task is a single fill-in-the-middle completion: you hold a prefix, such as a function signature, a docstring and a TODO line, and a suffix, such as assertions and a print. What is missing is the implementation between them. The deliverable is the spliced code text that passes a syntax check and makes the suffix assertions hold. Compared with prefix continuation, the value of FIM is that the suffix gives the model an explicit stopping edge, so it does not have to guess how the block ends. No API was called in this batch; the article only reports what the official pages say plus the editorial checking practice.
Prepare the input and environment
- A SiliconFlow API key created on the API keys page and placed in an environment variable (the sample here uses
SILICONFLOW_API_KEY); the code reads only the variable. The pages do not state free quota or concrete rate limits, only that the model marketplace shows prices and rate limits. - Python 3.7.1 or newer with the OpenAI library installed as the quickstart page describes (
pip install --upgrade openai);base_urlishttps://api.siliconflow.cn/v1. - An input that really has a gap: you have to be able to write both the prefix and what follows. FIM does not fit a task where you only know the opening, which is an editorial judgement the official pages do not discuss.
- A model ID from the FIM support list that you have confirmed in the model marketplace. The example keeps the page sample's
Pro/zai-org/GLM-5.1, which appears both in the FIM list and in the samples on both pages.
How the parameters work
Request shape: the page places the parameters as "在 /chat/completions 接口中,通过 extra_body 传入 prefix 和 suffix" and shows a JSON body whose top level holds model, messages, params and extra_body. The "params" value there is a placeholder string; the page body never says which fields it stands for, so do not copy it as a real field name. Only extra_body.prefix and extra_body.suffix are actually read. The SDK sample on the same page passes extra_body as a keyword argument to create(), and the page does not explain how the two spellings relate on the wire.
Difference from sending a prefix alone: the prefix continuation page uses extra_body={"prefix": "希望的前缀内容"} and sets the prefix to "```python \n " so the output starts with a python code fence, which is about pinning the start of the answer rather than filling a gap. If you already know what the end looks like, send a suffix; if you only want a fixed opening format, the prefix-only page is closer to your intent.
Reading the response: the FIM sample streams and prints chunk.choices[0].delta.content with end=""; the prefix continuation sample is not streaming and prints response.choices[0].message.content directly. The quickstart sample adds one guard, if not chunk.choices: continue, plus printing only when delta.content exists, and this article reuses that guard because it is the platform's own documented pattern rather than something this site invented.
Parameters and model comparison
| Parameter | Placement and sample value | What the official page says |
|---|---|---|
extra_body.prefix | Used by both the FIM page and the prefix continuation page; the FIM sample puts an opening quick-sort function here | The FIM page treats it as the leading content; the continuation page uses it alone to steer the output format |
extra_body.suffix | Appears only on the FIM page; the sample puts the call and print test code here | Supplies the trailing content that the middle must fit; the continuation page has no such parameter |
model | The FIM sample uses Pro/zai-org/GLM-5.1 | Must come from the support list; the page warns the list may change and points to the marketplace filter |
messages | The FIM sample has one user message, Please write quick sort code | A fill-in request still needs messages: the task goes there while the gap goes to prefix and suffix |
stream, max_tokens | The FIM sample sets stream=True and max_tokens=4096; the continuation sample sends no stream | The pages read differently: stream reads delta.content, non-stream reads message.content; no page relates max_tokens to completion length |
| Model or series | FIM support list | Prefix continuation page |
|---|---|---|
Pro/zai-org/GLM-5.1, Pro/zai-org/GLM-5 | Listed | Falls under non-reasoning models supporting the parameter; both pages use Pro/zai-org/GLM-5.1 as the sample |
Pro/deepseek-ai/DeepSeek-R1, deepseek-ai/DeepSeek-R1 | Listed | Says the deepseek R1 series does not support the parameter for now, which contradicts the FIM page |
Pro/deepseek-ai/DeepSeek-V3, deepseek-ai/DeepSeek-V3 | Listed | Named nowhere; covered only by the general non-reasoning statement |
Qwen/Qwen3-Coder-30B-A3B-Instruct and the other Qwen IDs | Six Qwen IDs listed, spanning VL, Omni and Coder series | No IDs named; says Qwen3 reasoning series support it after "增加 enable_thinking=true 关闭推理" |
Complete the task
Install and set the key: run the quickstart install command and put the API key in SILICONFLOW_API_KEY. The sample script reads it with os.environ["SILICONFLOW_API_KEY"], so a missing variable raises a KeyError before any request goes out, which is the behavior you want instead of calling the API with an empty string. Keep the key out of scripts, logs and screenshots.
Write both halves by hand: draft the prefix and the suffix and leave the middle empty. In the sample the prefix is def split_tags(raw): plus a docstring and a TODO, and the suffix is a _check() assertion. The practical test: if you cannot write the suffix, FIM is the wrong tool for the task; if your suffix uses names from the prefix, that is useful, because the suffix then pins the identifiers the middle has to use.
Send the request: call client.chat.completions.create(...) with a supported model, a messages task description, prefix and suffix inside extra_body, and stream=True. If you set max_tokens, note that the sample uses 4096 without explaining how it relates to completion length, so treat it as a ceiling rather than a target.
Collect the middle: iterate the stream, skip chunks with no choices, and join the non-empty delta.content fragments in order. The two common mistakes are judging each chunk as if it were a whole sentence, and indexing chunk.choices[0] with no guard; the quickstart sample checks first and only then reads.
Splice and compile: build candidate = prefix + completion + suffix and run compile(candidate, "<fim-splice>", "exec"). Syntax errors are usually splice errors rather than content errors: a missing newline at the end of the prefix, an indented first line inside the middle, or the model repeating the def line will all produce a duplicate definition or an IndentationError. Fix the splice before judging the content.
Run the assertions, read the logic, choose an exit (editorial recommendation): passing assertions only prove the examples in the suffix, not that the implementation is sensible. Read three things by hand: whether the function does what the docstring promises, whether obvious boundaries are missing (empty string, stray spaces), and whether it imported anything unused. Hand the code over only when all of that holds; otherwise keep the original prefix, suffix and returned middle, mark the attempt undelivered, and do not treat "it compiles" as done.
Worked example
The sample task: fill in the body of split_tags(raw) so it turns a comma separated tag string into lowercase tags, and make the suffix assertion split_tags("AI, Tools ,ai") == ["ai", "tools"] hold. The prefix is the signature, docstring and TODO line; the suffix is the _check() assertion and print. The model should return only the middle lines, and your script builds the finished text. The three excerpts below are the install command, the request body exactly as the page illustrates it, and a runnable script in the page's shape (editorial completion, not executed).
pip install --upgrade openai
export SILICONFLOW_API_KEY='YOUR_API_KEY'
{
"model": "model info",
"messages": "prompt message",
"params": "params",
"extra_body": {"prefix": "前缀内容", "suffix": "后缀内容"}
}
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ['SILICONFLOW_API_KEY'],
base_url='https://api.siliconflow.cn/v1',
)
prefix = '''def split_tags(raw):
"""Split a comma separated tag string into lowercase tags."""
# TODO: replace this line with the implementation
'''
suffix = '''
def _check():
assert split_tags('AI, Tools ,ai') == ['ai', 'tools']
print('ok')
'''
response = client.chat.completions.create(
model='Pro/zai-org/GLM-5.1',
messages=[{'role': 'user', 'content': 'Please complete the function body'}],
extra_body={'prefix': prefix, 'suffix': suffix},
stream=True,
max_tokens=4096,
)
middle = []
for chunk in response:
if not chunk.choices:
continue
delta = chunk.choices[0].delta.content
if delta:
middle.append(delta)
completion = ''.join(middle)
candidate = prefix + completion + suffix
compile(candidate, '<fim-splice>', 'exec')
print(candidate)
What to look at afterwards: first whether completion is empty, then whether it repeats def split_tags(raw): or def _check():, then whether compile raised anything, and finally whether _check() passes, which is the actual success signal for this fill-in. Note the sample script only performs the syntax check; running _check() is your next step and this article did not run it for you.
Check the result and failure paths
- Success (editorial rule): the middle is non-empty, does not repeat the prefix or suffix,
prefix + middle + suffixpassescompile, every suffix assertion holds, and a human has read the logic and accepts it. Receiving a non-empty string is not delivery. - Request failure: a non-2xx status or an SDK exception. The pages list no error codes, error body fields or retry policy, so this article invents none; keep the model ID, messages, prefix and suffix, then stop instead of retrying with guessed parameter changes.
- Empty completion: the joined stream is an empty string. Treat it as undelivered; do not infer a cause from
max_tokens, and first repeat the same request on another supported model so you can separate a model problem from a splicing problem. - Repeated or out-of-range output: the middle contains the prefix or suffix text, meaning the model rewrote the whole block instead of filling the gap. The splice then holds duplicate definitions and
compileor the assertions fail, so it is undelivered. - Suspected truncation: the text still looks unfinished after the stream ends, for example a dangling body or unbalanced brackets. The pages never say how truncation is flagged in a stream, so only a structural check finds it; this article does not assume a marker field exists.
- Stopping and rollback (editorial recommendation): if the same model returns empty or repeated content twice in a row, stop using that model and roll back to the last artifact that passed
compile; keep no version that fails its assertions.
Scope and limits
- This tutorial covers the fill-in-the-middle use only. Prefix continuation is a separate path with a prefix and no suffix, and the page frames it as stronger instruction following and format control; neither page defines a maximum request length, concurrency limit or backoff policy.
- What happens with an unsupported model is not stated. The prefix continuation page says the deepseek R1 series does not support "上述参数" for now, but it never describes the response shape in that case, so this article draws no conclusion about whether the call errors or silently ignores the parameters.
- The two pages fetched here contradict each other about DeepSeek-R1, which shows that public documentation for one parameter is not always in sync. Both are recorded as written; the marketplace filter and your own small sample are the tie-breaker.
- The page warns the supported-model list can change, so the IDs recorded here are what the page said when fetched on 2026-11-23 and may differ later.
No SiliconFlow API, model or code excerpt was run, installed or called in this batch, and no account, login state, key validity or billing was checked. Every fact comes from three official pages: the FIM guide, the prefix continuation guide, and the quickstart. The sample script is an editorial completion in the page's request shape, and the compile and assertion checks are actions you perform in your own environment, not results measured by this site.
Article sources
Original editorial content; official descriptions and checking suggestions are distinguished.