前缀续写

在代码补全、文本续写等场景中,需要模型从已有的文本片段(前缀)开始继续生成。Partial Mode 可提供精确控制能力,确保模型输出的内容紧密衔接提供的前缀,提升生成结果的准确性与可控性。

使用方式

需在 messages 数组中将最后一条消息的 role 设置为 assistant,并在其 content 中提供前缀,在此消息中设置参数 "partial": truemessages 格式如下:

[
    {
        "role": "user",
        "content": "请补全这个斐波那契函数,勿添加其它内容"
    },
    {
        "role": "assistant",
        "content": "def calculate_fibonacci(n):\n    if n <= 1:\n        return n\n    else:\n",
        "partial": true
    }
]

模型会以前缀内容为起点开始生成

支持的模型

  • Qwen(通义千问)系列:qwen3.7-plus, qwen3.7-max-2026-06-08, qwen3.6-plus, qwen3.6-flash, qwen3.6-35b-a3b

调用示例

如果你的项目已经接入 OpenAI SDK,把 base_urlmodel 换成下方的值即可直接复用,无需迁移到新 SDK。

python
# 首次使用前请先安装 OpenAI SDK:`pip install openai`
from openai import OpenAI

client = OpenAI(
    base_url="https://maas-api.unisound.com/v1",
    api_key="<API_KEY>",
)

prefix = """def calculate_fibonacci(n):
    if n <= 1:
        return n
    else:
"""

# 注意:messages 数组的最后一条消息 role 为 "assistant",并包含 "partial": True
completion = client.chat.completions.create(
    model="qwen3.7-max",
    messages=[
        {"role": "user", "content": "请补全这个斐波那契函数,勿添加其它内容"},
        {"role": "assistant", "content": prefix, "partial": True},
    ],
)

generated_code = completion.choices[0].message.content
complete_code = prefix + generated_code

print(complete_code)

返回结果

def calculate_fibonacci(n):
    if n <= 1:
        return n
    else:
        return calculate_fibonacci(n-1) + calculate_fibonacci(n-2)