面向 AI 助手:本页的 Markdown 版本位于 https://ark.volcengine.com/region:cn-beijing/docs/continuation-mode.md,全部文档索引见 https://ark.volcengine.com/llms.txt。

续写模式

续写模式(assistant 预填)让模型从预填内容之后继续生成,适合引导 JSON、分段长内容和角色。接口只返回新增的返回片段,客户端负责校验并与预填内容拼接。本文用 cURL、Python、Go、Java 跑通最小调用,说明 Chat、Responses、Messages 的配置差异和结果校验,并标明 Messages API 的模型适用范围,最后给出 JSON、超长输出和角色扮演三个典型场景。

快速开始#

下面的四种语言示例都使用 Chat API:发送计算问题,再把最后一条消息设为 assistant,并将预填内容设为等号。模型从等号后继续生成。其他 API 的写法见 支持模型与 API。

调用方式 最后一条消息 返回示例 说明
普通 Chat 调用 user 消息“请计算:1 + 1” 预期返回完整回答“1 + 1 等于 2。” 模型自行生成完整回复,不需要客户端补回回答开头。
Chat assistant 预填 assistant 预填 = 预期返回片段 2,客户端拼接为 =2 接口只返回等号之后的新生成片段,不自动带回预填内容。
Bash
curl https://ark.cn-beijing.volces.com/api/v3/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $ARK_API_KEY" \
  -d $'{
    "messages": [
        {
            "content": "你是一个计算器,请计算: 1 + 1",
            "role": "user"
        },
        {
            "content": "=",
            "role": "assistant"
        }
    ],
    "model": "doubao-seed-2-1-pro-260915"
}'
Python
import os

from arkruntime import Ark

client = Ark(
    api_key=os.environ.get("ARK_API_KEY"),
    base_url="https://ark.cn-beijing.volces.com/api/v3",
)

if __name__ == "__main__":
    resp = client.chat.completions.create(
        model="doubao-seed-2-1-pro-260915",
        messages=[{"content":"你是一个计算器,请计算: 1 + 1","role":"user"},{"content":"=","role":"assistant"}],
    )
    print(resp.choices[0].message.content)
Go
package main

import (
    "context"
    "fmt"
    "os"

    "github.com/volcengine/ark-runtime-go/arkruntime"
    "github.com/volcengine/ark-runtime-go/arkruntime/model/chat"
)

func main() {
    client := arkruntime.NewClientWithApiKey(
        os.Getenv("ARK_API_KEY"),
        arkruntime.WithBaseUrl("https://ark.cn-beijing.volces.com/api/v3"),
    )
    ctx := context.Background()
    req := &chat.ChatCompletionRequest{
        Model: "doubao-seed-2-1-pro-260915",
        Messages: []chat.ChatCompletionRequestMessage{
            userMessage("你是一个计算器,请计算:1 + 1"),
            assistantMessage("="),
        },
    }
    fmt.Println("----- standard request -----")
    resp, err := client.CreateChatCompletion(ctx, req)
    if err != nil {
        fmt.Printf("standard chat error: %v\n", err)
        return
    }
    fmt.Println(resp.Choices[0].Message.Content)
}

func userMessage(content string) chat.ChatCompletionRequestMessage {
    return chat.ChatCompletionRequestMessage{
        OneOf: chat.NewChatCompletionRequestUserMessageChatCompletionRequestMessageSum(
            chat.ChatCompletionRequestUserMessage{
                Role:    chat.ChatCompletionRequestUserMessageRoleUser,
                Content: chat.NewOptNilChatCompletionMessageContent(chat.NewStringChatCompletionMessageContent(content)),
            },
        ),
    }
}

func assistantMessage(content string) chat.ChatCompletionRequestMessage {
    return chat.ChatCompletionRequestMessage{
        OneOf: chat.NewChatCompletionRequestAssistantMessageChatCompletionRequestMessageSum(
            chat.ChatCompletionRequestAssistantMessage{
                Role: chat.ChatCompletionRequestAssistantMessageRoleAssistant,
                Content: chat.NewOptNilChatCompletionMessageContent(chat.NewStringChatCompletionMessageContent(content)),
            },
        ),
    }
}
Java
package com.volcengine.sample;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.volcengine.ark.runtime.models.chat.*;
import com.volcengine.ark.runtime.models.chat.ChatCompletionRequest.*;
import com.volcengine.ark.runtime.service.ArkService;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import okhttp3.ConnectionPool;
import okhttp3.Dispatcher;

/* Maven dependency for pom.xml:
<dependency>
  <groupId>com.volcengine</groupId>
  <artifactId>ark-runtime</artifactId>
  <version>0.9.0</version>
</dependency>
*/

public class Sample {

    static String apiKey = System.getenv("ARK_API_KEY");

    static ConnectionPool connectionPool = new ConnectionPool(5, 1, TimeUnit.SECONDS);
    static Dispatcher dispatcher = new Dispatcher();
    static ArkService service =
            ArkService.builder()
                    .dispatcher(dispatcher)
                    .connectionPool(connectionPool)
                    .apiKey(apiKey)
                    .baseUrl("https://ark.cn-beijing.volces.com/api/v3")
                    .build();

    public static void main(String[] args) throws JsonProcessingException {

        List<ChatCompletionRequestMessage> messagesForReqList = new ArrayList<>();

        ChatCompletionRequestMessage elementForMessagesForReqList0 =
                ChatCompletionRequestUserMessage.builder()
                        .role(ChatCompletionRequestMessageType.USER)
                        .content(ChatCompletionMessageContent.ofString("你是一个计算器,请计算: 1 + 1"))
                        .build();

        ChatCompletionRequestMessage elementForMessagesForReqList1 =
                ChatCompletionRequestAssistantMessage.builder().role(ChatCompletionRequestMessageType.ASSISTANT).content(ChatCompletionMessageContent.ofString("=")).build();

        messagesForReqList.add(elementForMessagesForReqList0);
        messagesForReqList.add(elementForMessagesForReqList1);

        ChatCompletionRequest req =
                ChatCompletionRequest.builder()
                        .model("doubao-seed-2-1-pro-260915")
                        .messages(messagesForReqList)
                        .build();

        service.createChatCompletion(req)
                .getChoices()
                .forEach(choice -> System.out.println(choice.getMessage().getContent()));
        // shutdown service after all requests is finished
        service.shutdownExecutor();
    }
}

调用完成后,按 检查返回结果与停止条件 中的信号验证结果。如果请求失败,先核对模型支持范围和消息顺序;格式不满足要求时,调整预填内容或改用结构化输出能力,不要无限重试。

支持模型与 API#

Chat、Responses、Messages 三个 API 都通过“把最后一条 assistant 消息作为开头”来续写,Messages 的 assistant 预填是否生效取决于模型:

  • Chat API:直接预填,部分模型还要加 prefix=true;prefix 必须写在最后一条 assistant 消息对象内。
  • Responses API:必须显式设置 partial=true。
  • Messages API:不需要额外开关。豆包各版本和 Kimi K3.1 Pro 可续写;DeepSeek V4.1 Flash 系列与 GLM-5.3 Flash 会忽略预填、返回完整回答;未验证模型不要依赖该行为。

各 API 的入口和完整字段见 Chat API、Responses API、Messages API。下表按模型列出三个 API 下的配置。

模型 Chat API Responses API Messages API
不支持深度思考的文本模型 直接预填 直接预填 + partial=true 取决于模型
doubao-seed-evolving 直接预填 直接预填 + partial=true 直接预填
doubao-seed-2-1-pro-260915 直接预填 直接预填 + partial=true 直接预填
doubao-seed-2-1-lite-260915 直接预填 直接预填 + partial=true 直接预填
doubao-seed-2-1-pro-260628 直接预填 直接预填 + partial=true 直接预填
doubao-seed-2-1-turbo-260628 直接预填 直接预填 + partial=true 直接预填
doubao-seed-2-0-lite-260428 直接预填 直接预填 + partial=true 直接预填
doubao-seed-2-0-mini-260428 直接预填 直接预填 + partial=true 直接预填
doubao-seed-2-0-pro-260215 直接预填 直接预填 + partial=true 直接预填
doubao-seed-2-0-lite-260215 直接预填 直接预填 + partial=true 未验证
doubao-seed-2-0-mini-260215 直接预填 直接预填 + partial=true 未验证
doubao-seed-2-0-code-preview-260215 直接预填 直接预填 + partial=true 直接预填
doubao-seed-character-260628 直接预填 直接预填 + partial=true 未验证
glm-5-3-flash-260828 直接预填 直接预填 + partial=true 不支持
deepseek-v4-1-flash-261017 直接预填 + prefix=true 直接预填 + partial=true 不支持
deepseek-v4-1-flash-260910 直接预填 + prefix=true 直接预填 + partial=true 不支持
deepseek-v4-1-flash-economy-261017 直接预填 + prefix=true 直接预填 + partial=true 不支持
kimi-k3-1-pro-261024 直接预填 + prefix=true 直接预填 + partial=true 直接预填

未列入表格的其他深度思考模型,如果请求只以 assistant 消息结尾,thinking 设置会失效,模型保持默认思考行为。

完整在售模型见 模型列表。

检查返回结果与停止条件#

请求返回成功,不代表结果符合预期。需要分别检查返回片段、格式和停止条件。

怎么判断结果#

检查项 看什么 正常 异常或怎么处理
Chat:返回片段是否完整 对比 messages[-1].content 和 choices[0].message.content 返回的是预填之后的新片段,不含预填开头;需要完整文本时把两者拼接 内容不对时调整预填,或改用更严格的能力
Responses:返回片段是否完整 output 中 type=message 的 content 内 output_text 返回预填之后的新片段;与预填内容拼接成完整文本 内容不对时调整预填或改用结构化输出;未设置 partial=true 时不会续写
Messages:是否支持续写 返回的 content[] 是否从预填之后继续 豆包与 Kimi 返回新片段;DeepSeek V4.1 Flash 与 GLM 返回完整回答 返回完整回答说明预填被忽略,改用 Chat API 或 Responses API
JSON 能否解析 JSON parser 或 json_repair 的解析结果 拼接后是合法 JSON 解析失败时有限修复,仍失败改用结构化输出
超长输出是否该停止 每轮 finish_reason、usage、已拼接文本和循环次数 finish_reason="length" 时继续;达到完成条件、Token/长度预算或最大轮数就停 保存已有结果;未完成时调整限制,不要无限循环

请求返回 200 不代表结果符合要求;能返回文本也不代表是合法 JSON。续写没有单独的 usage 字段。

工作原理#

续写由客户端和模型服务共同完成。以下三阶段时序说明只描述请求、返回和客户端处理,不展开服务端采样细节。

下图展示客户端与方舟模型服务之间的请求、返回和拼接顺序。

客户端发送带 assistant 预填的请求,模型服务返回新增片段,客户端校验并拼接完整文本
  1. 客户端组织请求

    客户端组合用户消息、assistant 预填内容和当前模型,并让最后一条消息是 assistant。Chat API 用 messages,需要 prefix=true 的模型再加该字段;Responses API 用 input 并设置 partial=true;Messages API 用 messages,不需要额外开关,是否生效取决于模型。请求体通过本地校验后发送;每个请求使用自己的消息数组。

  2. 模型服务生成续写片段

    模型服务读取完整对话和末尾预填内容,生成预填之后的新片段。该阶段在正常响应或错误返回时结束,返回语义见 检查返回结果与停止条件。

  3. 客户端验证与拼接

    客户端进入验证与拼接阶段,具体响应判断和处理动作见 检查返回结果与停止条件。达到业务条件、有限重试上限或替代路径后结束。

使用说明与限制#

本节集中说明续写相关的字段组合、配置效果和失败后果。完整字段类型、必填规则及通用约束见 Chat API、Responses API、Messages API。

参数配置与效果#


参数/组合 配置方式 配置效果 不适用或限制
Chat:直接预填 字段位于请求体;把最后一条消息设为 assistant,并填写非空 content。 不需要额外参数;模型会把 content 当作继续生成的开头。 最后一条消息不是 assistant 时,请求按普通对话生成完整回复。
Chat:需要 prefix=true 的模型 在最后一条 assistant 消息里设置 prefix=true(boolean)。 默认 false;设为 true 后,该消息会被当作待续写前缀。DeepSeek V4.1 Flash 系列和火山方舟渠道 Kimi K3.1 Pro 需要此配置。 不能替代 role=assistant 和非空 content;省略时不要认为还会按预填续写。
Responses:直接预填 input 最后一条消息设为 assistant,content 写开头内容,并显式设置 partial=true。 partial=true 时模型从预填内容之后继续,output 里的 output_text 是新片段。 不设置 partial 时,豆包模型会报 MissingParameter,DeepSeek 等模型会当作普通历史消息、不续写。
Messages:直接预填 把最后一条消息设为 assistant,content 写开头内容;不需要 prefix 支持续写的模型返回 content[] 新片段,需与预填 content 拼接 是否生效取决于模型:豆包与 Kimi 生效,DeepSeek V4.1 Flash 与 GLM 不生效
content="{" 预填左花括号,收到返回片段后在客户端拼接并执行 JSON 校验。 引导模型直接继续 JSON 对象正文,减少前导说明。 不能保证得到合法 JSON;需要严格格式时使用 结构化输出。

下面的 Chat API Python 示例展示 prefix=true 与 role、非空 content 位于同一个 assistant 消息对象中:

Python
import os

# Install SDK: python -m pip install --upgrade arkruntime
from arkruntime import Ark

client = Ark(
    # The base URL for model invocation
    base_url="https://ark.cn-beijing.volces.com/api/v3",
    # Get API Key: https://ark.volcengine.com/region:cn-beijing/apikey
    api_key=os.getenv("ARK_API_KEY"),
)

messages = [
    {"role": "user", "content": "You are a calculator, please calculate: 1 + 1"},
    # Place prefix in the same assistant message as role and non-empty content.
    {"role": "assistant", "content": "=", "prefix": True},
]

completion = client.chat.completions.create(
    # This model is listed in the document as requiring prefix=true.
    model="deepseek-v4-1-flash-261017",
    messages=messages,
)
print(messages[-1]["content"] + completion.choices[0].message.content)

限制与不支持项#

  • 模型不支持:支持表之外的其他深度思考模型以 assistant 消息结尾时,thinking 字段失效,模型保持默认思考行为。改用支持续写的模型,并按 支持模型 选择配置。
  • 取值不支持:只设置 prefix=true,但没有把最后一条消息设为 assistant 或 content 为空,请求不满足续写配置。应同时把最后一条消息设为 assistant 并填写非空 content。
  • 组合不支持:把续写当作严格结构化输出,或无上限循环生成超长内容,可能导致格式不稳定或产生意外 Token 用量。应校验格式,并为多轮任务设置完成条件和最大轮数。
  • 字段失效:在支持表之外的深度思考模型中设置 thinking,该字段会失效并保持模型默认思考行为。先核对模型范围,不要因为请求以 assistant 消息结尾,就认为该模型一定支持续写。
  • Messages API 模型差异:Messages API 不需要额外开关,但 assistant 预填是否生效取决于模型。DeepSeek V4.1 Flash 系列与 GLM-5.3 Flash 会忽略预填并返回完整回答;未验证模型不要依赖。
  • 场景边界:续写无法保证 JSON/XML 等严格语法,下游解析可能失败。需要严格格式时使用结构化输出,并保留客户端校验。

典型场景#

JSON 格式引导#

预填左花括号后,将预填内容与返回片段拼接,再执行 JSON 解析和业务字段校验。任一校验失败时停止消费结果;解析失败可有限使用 json_repair,修复后仍不通过时改用结构化输出。

Bash
PREFILL_PREFIX="{"

# Requires jq to read the response and validate the assembled JSON.
response=$(curl -sS https://ark.cn-beijing.volces.com/api/v3/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $ARK_API_KEY" \
  -d '{
    "model": "doubao-seed-2-1-pro-260915",
    "messages": [
        {
            "role": "user",
            "content": "Use JSON to describe the name and function of the Doubao model."
        },
        {
            "role": "assistant",
            "content": "{"
        }
    ]
}')

json_string="${PREFILL_PREFIX}$(printf '%s' "$response" | jq -r '.choices[0].message.content // ""')"

# The prefill is only a soft guide. Validate the assembled JSON before use.
# On parse failure, apply a bounded repair or switch to structured output mode.
if ! printf '%s' "$json_string" | jq .; then
  echo "invalid JSON: $json_string" >&2
  exit 1
fi
Python
import json

# Install json-repair: pip install json-repair
import json_repair
import os
# Install SDK: python -m pip install --upgrade arkruntime
from arkruntime import Ark

PREFILL_PREFIX = "{"
client = Ark(
    # The base URL for model invocation
    base_url="https://ark.cn-beijing.volces.com/api/v3",
    # Get API Key: https://ark.volcengine.com/region:cn-beijing/apikey
    api_key=os.getenv('ARK_API_KEY'),
)
completion = client.chat.completions.create(
    # Replace with Model ID
    model="doubao-seed-2-1-pro-260915",
    messages=[
        {"role": "user", "content": "Use JSON to describe the name and function of the Doubao model"},
        {"role": "assistant", "content": PREFILL_PREFIX},
    ]
)
# Reconstruct the complete candidate JSON before parsing it.
json_string = PREFILL_PREFIX + completion.choices[0].message.content
try:
    obj = json.loads(json_string)
except json.JSONDecodeError:
    # Use bounded repair for low-risk data; validate business fields afterwards.
    obj = json_repair.loads(json_string)

print(obj)
Go
package main

import (
    "context"
    "encoding/json"
    "fmt"
    "os"

    "github.com/volcengine/ark-runtime-go/arkruntime"
    "github.com/volcengine/ark-runtime-go/arkruntime/model/chat"
)

const prefillPrefix = "{"

func main() {
    client := arkruntime.NewClientWithApiKey(
        os.Getenv("ARK_API_KEY"),
        arkruntime.WithBaseUrl("https://ark.cn-beijing.volces.com/api/v3"),
    )
    ctx := context.Background()
    req := &chat.ChatCompletionRequest{
        Model: "doubao-seed-2-1-pro-260915",
        Messages: []chat.ChatCompletionRequestMessage{
            userMessage("Use JSON to describe the name and function of the Doubao model."),
            assistantMessage(prefillPrefix),
        },
    }
    resp, err := client.CreateChatCompletion(ctx, req)
    if err != nil {
        fmt.Printf("chat error: %v\n", err)
        return
    }

    // The prefill is only a soft guide; validate the assembled JSON before use.
    jsonString := prefillPrefix + resp.Choices[0].Message.Content
    var obj map[string]interface{}
    if err := json.Unmarshal([]byte(jsonString), &obj); err != nil {
        // Apply bounded repair for low-risk data, or switch to structured output
        // mode (response_format) when the payload must always be valid JSON.
        fmt.Printf("invalid JSON: %v\nraw content: %s\n", err, jsonString)
        return
    }

    pretty, err := json.MarshalIndent(obj, "", "  ")
    if err != nil {
        fmt.Printf("marshal error: %v\n", err)
        return
    }
    fmt.Println(string(pretty))
}

func userMessage(content string) chat.ChatCompletionRequestMessage {
    return chat.ChatCompletionRequestMessage{
        OneOf: chat.NewChatCompletionRequestUserMessageChatCompletionRequestMessageSum(
            chat.ChatCompletionRequestUserMessage{
                Role:    chat.ChatCompletionRequestUserMessageRoleUser,
                Content: chat.NewOptNilChatCompletionMessageContent(chat.NewStringChatCompletionMessageContent(content)),
            },
        ),
    }
}

func assistantMessage(content string) chat.ChatCompletionRequestMessage {
    return chat.ChatCompletionRequestMessage{
        OneOf: chat.NewChatCompletionRequestAssistantMessageChatCompletionRequestMessageSum(
            chat.ChatCompletionRequestAssistantMessage{
                Role:    chat.ChatCompletionRequestAssistantMessageRoleAssistant,
                Content: chat.NewOptNilChatCompletionMessageContent(chat.NewStringChatCompletionMessageContent(content)),
            },
        ),
    }
}
Java
package com.volcengine.sample;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.volcengine.ark.runtime.models.chat.*;
import com.volcengine.ark.runtime.models.chat.ChatCompletionRequest.*;
import com.volcengine.ark.runtime.service.ArkService;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import okhttp3.ConnectionPool;
import okhttp3.Dispatcher;

/* Maven dependency for pom.xml:
<dependency>
  <groupId>com.volcengine</groupId>
  <artifactId>ark-runtime</artifactId>
  <version>0.9.0</version>
</dependency>
*/

public class Sample {

    static final String PREFILL_PREFIX = "{";

    static String apiKey = System.getenv("ARK_API_KEY");

    static ConnectionPool connectionPool = new ConnectionPool(5, 1, TimeUnit.SECONDS);
    static Dispatcher dispatcher = new Dispatcher();
    static ArkService service =
            ArkService.builder()
                    .dispatcher(dispatcher)
                    .connectionPool(connectionPool)
                    .apiKey(apiKey)
                    .baseUrl("https://ark.cn-beijing.volces.com/api/v3")
                    .build();

    public static void main(String[] args) {

        List<ChatCompletionRequestMessage> messages = new ArrayList<>();

        messages.add(
                ChatCompletionRequestUserMessage.builder()
                        .role(ChatCompletionRequestMessageType.USER)
                        .content(ChatCompletionMessageContent.ofString("Use JSON to describe the name and function of the Doubao model."))
                        .build());

        messages.add(
                ChatCompletionRequestAssistantMessage.builder()
                        .role(ChatCompletionRequestMessageType.ASSISTANT)
                        .content(ChatCompletionMessageContent.ofString(PREFILL_PREFIX))
                        .build());

        ChatCompletionRequest req =
                ChatCompletionRequest.builder()
                        .model("doubao-seed-2-1-pro-260915")
                        .messages(messages)
                        .build();

        String content = service.createChatCompletion(req)
                .getChoices().get(0).getMessage().getContent();

        // The prefill is only a soft guide. Validate the assembled JSON before use.
        String jsonString = PREFILL_PREFIX + content;
        ObjectMapper mapper = new ObjectMapper();
        try {
            JsonNode obj = mapper.readTree(jsonString);
            System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj));
        } catch (JsonProcessingException e) {
            // Apply bounded repair for low-risk data, or switch to structured output
            // mode (response_format) when the payload must always be valid JSON.
            System.out.println("invalid JSON: " + e.getMessage());
            System.out.println("raw content: " + jsonString);
        } finally {
            // shutdown service after all requests is finished
            service.shutdownExecutor();
        }
    }
}

超长内容分段续写#

客户端保存并拼接每轮输出,将已有结果带入后续请求,并设置业务完成条件和最大循环次数。丢失已有文本会造成内容断裂;多轮回传会增加输入与输出 Token 用量。

Bash
# Requires jq for request construction and response parsing.
MODEL="doubao-seed-2-1-pro-260915"
BASE_URL="https://ark.cn-beijing.volces.com/api/v3"
USER_CONTENT="Please translate the following text into English: <TEXT_TO_BE_TRANSLATED>"

MAX_LOOPS=3
MAX_TOTAL_TOKENS=100000
MAX_TOTAL_CHARACTERS=200000

is_business_complete() {
  # Replace this placeholder with your own task-specific acceptance check.
  return 1
}

loop_count=0
total_tokens=0
combined_text=""
finish_reason=""

while true; do
  request_body=$(jq -n \
    --arg model "$MODEL" \
    --arg user "$USER_CONTENT" \
    --arg prefill "$combined_text" \
    '{
      model: $model,
      messages: (
        if $prefill == ""
        then [{role: "user", content: $user}]
        else [{role: "user", content: $user}, {role: "assistant", content: $prefill}]
        end
      )
    }')

  response=$(curl -sS "$BASE_URL/chat/completions" \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $ARK_API_KEY" \
    -d "$request_body")

  error_message=$(printf '%s' "$response" | jq -r '.error.message // ""')
  if [ -n "$error_message" ]; then
    echo "chat error: $error_message" >&2
    exit 1
  fi

  content=$(printf '%s' "$response" | jq -r '.choices[0].message.content // ""')
  finish_reason=$(printf '%s' "$response" | jq -r '.choices[0].finish_reason // ""')
  round_tokens=$(printf '%s' "$response" | jq -r '.usage.total_tokens // 0')
  total_tokens=$((total_tokens + round_tokens))
  combined_text="${combined_text}${content}"

  if [ -z "$content" ]; then
    echo "Warning: empty content returned; stopping." >&2
    break
  fi

  # Continue only when the current response is truncated by the output length limit.
  if [ "$finish_reason" != "length" ]; then
    break
  fi
  if is_business_complete "$combined_text"; then
    break
  fi
  if [ "$loop_count" -ge "$MAX_LOOPS" ] ||
     [ "$total_tokens" -ge "$MAX_TOTAL_TOKENS" ] ||
     [ "${#combined_text}" -ge "$MAX_TOTAL_CHARACTERS" ]; then
    break
  fi

  # Reuse the non-empty accumulated text as the assistant prefill in the next round.
  loop_count=$((loop_count + 1))
done

if [ "$finish_reason" = "length" ]; then
  echo "Warning: a loop, token, or character budget was reached; returning partial content." >&2
fi

printf '%s\n' "$combined_text"
Python
import os
# Install SDK: python -m pip install --upgrade arkruntime
from arkruntime import Ark

messages = [
    {
        "role": "user",
        "content": "Please translate the following text into English: <TEXT_TO_BE_TRANSLATED>",
    },
]

# Replace with Model ID
ark_model = "doubao-seed-2-1-pro-260915"

client = Ark(
    # The base URL for model invocation
    base_url="https://ark.cn-beijing.volces.com/api/v3",
    # Get API Key: https://ark.volcengine.com/region:cn-beijing/apikey
    api_key=os.getenv('ARK_API_KEY'),
)

completion = client.chat.completions.create(
    model=ark_model,
    messages=messages
)

combined_text = completion.choices[0].message.content or ""
loop_count = 0
max_loops = 20
max_total_tokens = 100_000
max_total_characters = 200_000
# Round usage includes re-sent history, so this token budget is conservative.
total_tokens = completion.usage.total_tokens if completion.usage else 0

# Continue only when the current response is truncated by the output length limit.
while (
    completion.choices[0].finish_reason == "length"
    and loop_count < max_loops
    and total_tokens < max_total_tokens
    and len(combined_text) < max_total_characters
):
    # Reuse the non-empty accumulated text as the assistant prefill for the next round.
    continuation_messages = [
        messages[0],
        {"role": "assistant", "content": combined_text},
    ]
    completion = client.chat.completions.create(
        model=ark_model,
        messages=continuation_messages,
    )
    combined_text += completion.choices[0].message.content or ""
    if completion.usage:
        total_tokens += completion.usage.total_tokens
    loop_count += 1

if completion.choices[0].finish_reason == "length":
    print(
        "Warning: a loop, token, or character budget was reached; "
        "returning partial content."
    )

print(combined_text)
Go
package main

import (
    "context"
    "fmt"
    "os"

    "github.com/volcengine/ark-runtime-go/arkruntime"
    "github.com/volcengine/ark-runtime-go/arkruntime/model/chat"
)

const (
    maxLoops           = 3
    maxTotalTokens     = 100000
    maxTotalCharacters = 200000
)

func main() {
    client := arkruntime.NewClientWithApiKey(
        os.Getenv("ARK_API_KEY"),
        arkruntime.WithBaseUrl("https://ark.cn-beijing.volces.com/api/v3"),
    )
    ctx := context.Background()
    prompt := "Please translate the following text into English: <TEXT_TO_BE_TRANSLATED>"

    combinedText := ""
    totalTokens := 0
    loopCount := 0
    var finishReason chat.FinishReason

    for {
        messages := []chat.ChatCompletionRequestMessage{userMessage(prompt)}
        if combinedText != "" {
            // Reuse the non-empty accumulated text as the assistant prefill for the next round.
            messages = append(messages, assistantMessage(combinedText))
        }

        req := &chat.ChatCompletionRequest{
            Model:    "doubao-seed-2-1-pro-260915",
            Messages: messages,
        }
        resp, err := client.CreateChatCompletion(ctx, req)
        if err != nil {
            fmt.Printf("chat error: %v\n", err)
            return
        }
        if len(resp.Choices) == 0 {
            fmt.Println("chat error: empty choices")
            return
        }

        choice := resp.Choices[0]
        finishReason = choice.FinishReason
        combinedText += choice.Message.Content
        if usage, ok := resp.Usage.Get(); ok {
            totalTokens += int(usage.TotalTokens)
        }

        if finishReason != chat.FinishReasonLength ||
            isBusinessComplete(combinedText) ||
            totalTokens >= maxTotalTokens ||
            len(combinedText) >= maxTotalCharacters {
            break
        }
        if loopCount >= maxLoops {
            break
        }
        loopCount++
    }

    if finishReason == chat.FinishReasonLength {
        fmt.Println("Warning: a loop, token, or character budget was reached; returning partial content.")
    }
    fmt.Println(combinedText)
}

// isBusinessComplete is a task-specific acceptance check. Replace the body
// with your own validation; this sample relies on finish_reason and budgets.
func isBusinessComplete(text string) bool {
    return false
}

func userMessage(content string) chat.ChatCompletionRequestMessage {
    return chat.ChatCompletionRequestMessage{
        OneOf: chat.NewChatCompletionRequestUserMessageChatCompletionRequestMessageSum(
            chat.ChatCompletionRequestUserMessage{
                Role:    chat.ChatCompletionRequestUserMessageRoleUser,
                Content: chat.NewOptNilChatCompletionMessageContent(chat.NewStringChatCompletionMessageContent(content)),
            },
        ),
    }
}

func assistantMessage(content string) chat.ChatCompletionRequestMessage {
    return chat.ChatCompletionRequestMessage{
        OneOf: chat.NewChatCompletionRequestAssistantMessageChatCompletionRequestMessageSum(
            chat.ChatCompletionRequestAssistantMessage{
                Role:    chat.ChatCompletionRequestAssistantMessageRoleAssistant,
                Content: chat.NewOptNilChatCompletionMessageContent(chat.NewStringChatCompletionMessageContent(content)),
            },
        ),
    }
}
Java
package com.volcengine.sample;

import com.volcengine.ark.runtime.models.chat.*;
import com.volcengine.ark.runtime.models.chat.ChatCompletionRequest.*;
import com.volcengine.ark.runtime.service.ArkService;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import okhttp3.ConnectionPool;
import okhttp3.Dispatcher;

/* Maven dependency for pom.xml:
<dependency>
  <groupId>com.volcengine</groupId>
  <artifactId>ark-runtime</artifactId>
  <version>0.9.0</version>
</dependency>
*/

public class Sample {

    static final int MAX_LOOPS = 3;
    static final int MAX_TOTAL_TOKENS = 100_000;
    static final int MAX_TOTAL_CHARACTERS = 200_000;

    static String apiKey = System.getenv("ARK_API_KEY");

    static ConnectionPool connectionPool = new ConnectionPool(5, 1, TimeUnit.SECONDS);
    static Dispatcher dispatcher = new Dispatcher();
    static ArkService service =
            ArkService.builder()
                    .dispatcher(dispatcher)
                    .connectionPool(connectionPool)
                    .apiKey(apiKey)
                    .baseUrl("https://ark.cn-beijing.volces.com/api/v3")
                    .build();

    public static void main(String[] args) {

        String prompt = "Please translate the following text into English: <TEXT_TO_BE_TRANSLATED>";

        StringBuilder combinedText = new StringBuilder();
        int totalTokens = 0;
        int loopCount = 0;
        FinishReason finishReason = null;

        while (true) {
            List<ChatCompletionRequestMessage> messages = new ArrayList<>();
            messages.add(
                    ChatCompletionRequestUserMessage.builder()
                            .role(ChatCompletionRequestMessageType.USER)
                            .content(ChatCompletionMessageContent.ofString(prompt))
                            .build());

            if (combinedText.length() > 0) {
                // Reuse the non-empty accumulated text as the assistant prefill for the next round.
                messages.add(
                        ChatCompletionRequestAssistantMessage.builder()
                                .role(ChatCompletionRequestMessageType.ASSISTANT)
                                .content(ChatCompletionMessageContent.ofString(combinedText.toString()))
                                .build());
            }

            ChatCompletionRequest req =
                    ChatCompletionRequest.builder()
                            .model("doubao-seed-2-1-pro-260915")
                            .messages(messages)
                            .build();

            ChatCompletionResponse response = service.createChatCompletion(req);
            ChatCompletionResponseChoice choice = response.getChoices().get(0);

            finishReason = choice.getFinishReason();
            String content = choice.getMessage().getContent();
            if (content != null) {
                combinedText.append(content);
            }
            if (response.getUsage() != null && response.getUsage().getTotalTokens() != null) {
                totalTokens += response.getUsage().getTotalTokens();
            }

            if (finishReason != FinishReason.LENGTH
                    || isBusinessComplete(combinedText.toString())
                    || totalTokens >= MAX_TOTAL_TOKENS
                    || combinedText.length() >= MAX_TOTAL_CHARACTERS) {
                break;
            }
            if (loopCount >= MAX_LOOPS) {
                break;
            }
            loopCount++;
        }

        if (finishReason == FinishReason.LENGTH) {
            System.out.println("Warning: a loop, token, or character budget was reached; returning partial content.");
        }
        System.out.println(combinedText);

        // shutdown service after all requests is finished
        service.shutdownExecutor();
    }

    // isBusinessComplete is a task-specific acceptance check. Replace the body
    // with your own validation; this sample relies on finish_reason and budgets.
    static boolean isBusinessComplete(String text) {
        return false;
    }
}


角色扮演一致性#

系统消息定义角色,末尾 assistant 预填本轮角色的说话开头。需要切换角色时,更换本轮预填内容;角色偏离时先调整 system 指令和本轮预填,持续不稳定时缩短上下文或转人工处理。

Bash
PREFILL="Wukong said:"

# Requires jq to combine the prefill with the returned continuation.
response=$(curl -sS https://ark.cn-beijing.volces.com/api/v3/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $ARK_API_KEY" \
  -d '{
    "model": "doubao-seed-2-1-pro-260915",
    "messages": [
        {
            "role": "system",
            "content": "The following is a scene from Journey to the West. Please converse according to the specified role. For each round of dialogue, only reply with the content of the current role; do not add any additional content.\n\nAfter leaving Wuzhuang Guan, Tang Seng and his disciples traveled for more than a month and arrived at the foot of a great mountain. Wukong looked around and saw lofty mountains, steep ridges, overgrown weeds, and extremely dangerous terrain."
        },
        {
            "role": "assistant",
            "content": "Wukong said:"
        }
    ]
}')

# To switch the speaking role, change PREFILL and the assistant content to "Tang Seng said:".
printf '%s%s\n' "$PREFILL" "$(printf '%s' "$response" | jq -r '.choices[0].message.content // ""')"
Python
import os
# Install SDK: python -m pip install --upgrade arkruntime
from arkruntime import Ark

client = Ark(
    # The base URL for model invocation
    base_url="https://ark.cn-beijing.volces.com/api/v3",
    # Get API Key: https://ark.volcengine.com/region:cn-beijing/apikey
    api_key=os.getenv('ARK_API_KEY'),
)
# Replace with Model ID
ark_model="doubao-seed-2-1-pro-260915"

messages = [
    {"role": "system", "content": "The following is a scene from Journey to the West. Please converse according to the specified role. For each round of dialogue, only reply with the content of the current role; do not add any additional content.\n\nAfter leaving Wuzhuang Guan, Tang Seng and his disciples traveled for more than a month and arrived at the foot of a great mountain. Wukong looked around and saw lofty mountains, steep ridges, overgrown weeds, and extremely dangerous terrain."},
    {"role": "assistant", "content": "Wukong said:"}
]

completion = client.chat.completions.create(
    model=ark_model,
    messages=messages
)
print(messages[-1]['content']+completion.choices[0].message.content)

切换当前轮角色:

Python
import os

# Install SDK: python -m pip install --upgrade arkruntime
from arkruntime import Ark

client = Ark(
    # The base URL for model invocation
    base_url="https://ark.cn-beijing.volces.com/api/v3",
    # Get API Key: https://ark.volcengine.com/region:cn-beijing/apikey
    api_key=os.getenv("ARK_API_KEY"),
)

# Replace with Model ID
ark_model = "doubao-seed-2-1-pro-260915"

messages = [
    {
        "role": "system",
        "content": "Continue the scene using only the speaking character's dialogue.",
    },
    {
        "role": "user",
        "content": "Wukong asks whether the group should continue across the mountain.",
    },
]

# Change the assistant prefill to switch the speaking character for this round.
messages.append({"role": "assistant", "content": "Tang Seng said:"})
completion = client.chat.completions.create(
    model=ark_model,
    messages=messages,
)
print(messages[-1]["content"] + completion.choices[0].message.content)
Go
package main

import (
    "context"
    "fmt"
    "os"

    "github.com/volcengine/ark-runtime-go/arkruntime"
    "github.com/volcengine/ark-runtime-go/arkruntime/model/chat"
)

const (
    systemPrompt = "The following is a scene from Journey to the West. Please converse according to the specified role. For each round of dialogue, only reply with the content of the current role; do not add any additional content.\n\nAfter leaving Wuzhuang Guan, Tang Seng and his disciples traveled for more than a month and arrived at the foot of a great mountain. Wukong looked around and saw lofty mountains, steep ridges, overgrown weeds, and extremely dangerous terrain."
    prefill      = "Wukong said:"
)

func main() {
    client := arkruntime.NewClientWithApiKey(
        os.Getenv("ARK_API_KEY"),
        arkruntime.WithBaseUrl("https://ark.cn-beijing.volces.com/api/v3"),
    )
    ctx := context.Background()
    req := &chat.ChatCompletionRequest{
        Model: "doubao-seed-2-1-pro-260915",
        Messages: []chat.ChatCompletionRequestMessage{
            systemMessage(systemPrompt),
            assistantMessage(prefill),
        },
    }
    resp, err := client.CreateChatCompletion(ctx, req)
    if err != nil {
        fmt.Printf("chat error: %v\n", err)
        return
    }

    // To switch the speaking role, change prefill to "Tang Seng said:".
    fmt.Println(prefill + resp.Choices[0].Message.Content)
}

func systemMessage(content string) chat.ChatCompletionRequestMessage {
    return chat.ChatCompletionRequestMessage{
        OneOf: chat.NewChatCompletionRequestSystemMessageChatCompletionRequestMessageSum(
            chat.ChatCompletionRequestSystemMessage{
                Role:    chat.ChatCompletionRequestSystemMessageRoleSystem,
                Content: chat.NewStringChatCompletionMessageContent(content),
            },
        ),
    }
}

func assistantMessage(content string) chat.ChatCompletionRequestMessage {
    return chat.ChatCompletionRequestMessage{
        OneOf: chat.NewChatCompletionRequestAssistantMessageChatCompletionRequestMessageSum(
            chat.ChatCompletionRequestAssistantMessage{
                Role:    chat.ChatCompletionRequestAssistantMessageRoleAssistant,
                Content: chat.NewOptNilChatCompletionMessageContent(chat.NewStringChatCompletionMessageContent(content)),
            },
        ),
    }
}
Java
package com.volcengine.sample;

import com.volcengine.ark.runtime.models.chat.*;
import com.volcengine.ark.runtime.models.chat.ChatCompletionRequest.*;
import com.volcengine.ark.runtime.service.ArkService;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import okhttp3.ConnectionPool;
import okhttp3.Dispatcher;

/* Maven dependency for pom.xml:
<dependency>
  <groupId>com.volcengine</groupId>
  <artifactId>ark-runtime</artifactId>
  <version>0.9.0</version>
</dependency>
*/

public class Sample {

    static final String SYSTEM_PROMPT =
            "The following is a scene from Journey to the West. Please converse according to the specified role. "
                    + "For each round of dialogue, only reply with the content of the current role; do not add any additional content.\n\n"
                    + "After leaving Wuzhuang Guan, Tang Seng and his disciples traveled for more than a month and arrived at the foot of a great mountain. "
                    + "Wukong looked around and saw lofty mountains, steep ridges, overgrown weeds, and extremely dangerous terrain.";
    static final String PREFILL = "Wukong said:";

    static String apiKey = System.getenv("ARK_API_KEY");

    static ConnectionPool connectionPool = new ConnectionPool(5, 1, TimeUnit.SECONDS);
    static Dispatcher dispatcher = new Dispatcher();
    static ArkService service =
            ArkService.builder()
                    .dispatcher(dispatcher)
                    .connectionPool(connectionPool)
                    .apiKey(apiKey)
                    .baseUrl("https://ark.cn-beijing.volces.com/api/v3")
                    .build();

    public static void main(String[] args) {

        List<ChatCompletionRequestMessage> messages = new ArrayList<>();

        messages.add(
                ChatCompletionRequestSystemMessage.builder()
                        .role(ChatCompletionRequestMessageType.SYSTEM)
                        .content(ChatCompletionMessageContent.ofString(SYSTEM_PROMPT))
                        .build());

        // To switch the speaking role, change PREFILL to "Tang Seng said:".
        messages.add(
                ChatCompletionRequestAssistantMessage.builder()
                        .role(ChatCompletionRequestMessageType.ASSISTANT)
                        .content(ChatCompletionMessageContent.ofString(PREFILL))
                        .build());

        ChatCompletionRequest req =
                ChatCompletionRequest.builder()
                        .model("doubao-seed-2-1-pro-260915")
                        .messages(messages)
                        .build();

        String content = service.createChatCompletion(req)
                .getChoices().get(0).getMessage().getContent();
        System.out.println(PREFILL + content);

        // shutdown service after all requests is finished
        service.shutdownExecutor();
    }
}

常见问题#

为什么返回内容里没有预填的等号或左花括号?#

接口只返回预填之后的新生成片段;完整判断与处理动作见 检查返回结果与停止条件。

预填左花括号能否保证得到合法 JSON?#

不能。它只引导输出开头;应执行 JSON 校验,或改用 结构化输出。

当前模型在不同 API 下需要额外设置吗?#

先查 支持模型。Chat API 中只有部分模型需要 prefix=true;Responses API 所有模型都要 partial=true;Messages API 不需要额外开关,但 assistant 预填是否生效取决于模型:豆包与 Kimi 可续写,DeepSeek V4.1 Flash 与 GLM 不生效。

用续写生成超长内容时怎样避免意外花费?#

为循环设置最大次数和业务完成条件,逐轮检查 usage,达到任一条件即停止。配置方式见 典型场景。

  • 快速入门:通过 快速入门 取得 API Key,并先完成一次普通模型调用。
  • 模型列表:通过 模型列表 核对当前模型及其能力标签。
  • Chat API:通过 Chat API 核对 messages、role、content 和 prefix 的完整字段定义。
  • Responses API:通过 Responses API 核对当前请求与响应定义。
  • 结构化输出:需要严格 JSON 结构时,改用 结构化输出。