请求体 model string (必选) 模型名称。 支持的模型 qwen4-max、qwen4-35b-a3b、qwen3.8-max、qwen3.8-max-0902、qwen3.8-flash、qwen3.8-2.4t-a95b、qwen3.8-27b、qwen3.8-omni-flash、qwen3.7-max、qwen3.7-max-2026-05-20、qwen3.7-max-2026-06-08、qwen3.7-max-2026-05-17、qwen3.7-max-preview、qwen3.7-plus、qwen3.7-plus-2026-05-26、qwen3.6-plus、qwen3.6-plus-2026-04-02、qwen3.5-plus、qwen3.5-plus-2026-04-20、qwen3.5-plus-2026-02-15、qwen3.7-flash、qwen3.7-flash-2026-07-15、qwen3.6-flash、qwen3.6-flash-2026-04-16、qwen3.5-flash、qwen3.5-flash-2026-02-23、qwen3.6-35b-a3b、qwen3.5-397b-a17b、qwen3.5-122b-a10b、qwen3.5-27b、qwen3.5-35b-a3b、deepseek-v4.1-flash、deepseek-v4.1-flash-1017、deepseek-v4-pro、deepseek-v4-pro-0813、deepseek-v4-flash-0731、glm-5.3、glm-5.2、kimi-k3.1-pro、kimi-k3
重要非列表中阿里云百炼直供文本生成模型仅支持基础兼容能力,Agent 能力(内置工具等)受限。 input string 或 array (必选) 模型输入,支持以下格式:
string:纯文本,如 "你好"。
array:消息数组,按对话顺序排列。
条目限制:开启存储时,单次请求主动传入的 input 最多支持 1000 个 item。任意角色的一条消息计 1 个 item,一问一答计 2 个 item;通过 previous_response_id 或 conversation 自动回溯的历史不计入。超出限制时,请求仍正常处理并返回结果,但本次响应不被存储,后续无法查询该响应或通过 previous_response_id 引用。建议适时开启新会话,或精简传入的 item 数量。 array 输入项类型 EasyInputMessage object 通过 role 区分消息类型,通过content传递消息内容。 属性 role string (必选) 消息角色,可选值:user、assistant、system、developer。 content string 或 array (必选) 消息内容,支持以下格式:
string:纯文本输入。
array:内容数组,包含一个或多个内容项,可混合不同类型。system/developer 角色的元素类型为 input_text,assistant 角色的元素类型为 output_text。
array 元素类型 以下类型之一: input_text { type, text } 文本输入。 属性 type string (必选) 固定为 input_text。 text string (必选) 输入模型的文本内容。 prompt_cache_breakpoint object (可选) 用于手动标记缓存断点,优先级高于顶层缓存模式。支持 qwen4-max、qwen4-35b-a3b、kimi-k3.1-pro 和 kimi-k3。 详见显式缓存。 属性 mode string (必选) 仅支持 explicit;设置断点时需显式传入。 input_image { type, image_url } 图片输入,仅 user 角色。 属性 type string (必选) 固定为 input_image。 image_url string (必选) 图片的公网 URL 或 Base64 编码。Base64 请传入完整的 Data URI,例如:data:image/png;base64,iVBORw0K...。 prompt_cache_breakpoint object (可选) 用于手动标记缓存断点,优先级高于顶层缓存模式。支持 qwen4-max、qwen4-35b-a3b、kimi-k3.1-pro 和 kimi-k3。 详见显式缓存。 属性 mode string (必选) 仅支持 explicit;设置断点时需显式传入。 input_file { type, file_url } 文件输入,仅 user 角色。目前 qwen4-max、qwen4-35b-a3b、qwen3.8-flash、qwen3.8-max、qwen3.5-ocr 支持此类型。 属性 type string (必选) 固定为 input_file。 file_url string (必选) PDF 文件的公网 URL,文件最大 100 MB。 PDF 的页数上限取决于 ocr_options 中的 task:设置为 document_parsing 时最大 50 页;未设置 task 或设置为其他任务时,最大 10 页。 prompt_cache_breakpoint object (可选) 用于手动标记缓存断点,优先级高于顶层缓存模式。支持 qwen4-max、qwen4-35b-a3b、kimi-k3.1-pro 和 kimi-k3。 详见显式缓存。 属性 mode string (必选) 仅支持 explicit;设置断点时需显式传入。 input_audio { type, format, audio_url, 2 more } 音频输入,仅适用于 qwen3.8-omni-flash 的 user 消息。 属性 type string (必选) 固定为 input_audio。 format string (必选) 音频格式,例如 wav、mp3。 audio_url string 音频的公网 URL。与 data 二选一,不能同时传入。 data string 包含 MIME 类型前缀和 Base64 编码音频的完整 Data URI,例如:data:audio/wav;base64,UklGR...。与 audio_url 二选一,不能同时传入。 use_multichannel boolean (可选) 是否对音频进行空间音频解析,默认 false。设为 true 时,对双通道或四通道音频进行空间音频解析;设为 false 时,按单通道音频解析。 input_video { type, video_url, fps } 视频输入,仅适用于 qwen3.8-omni-flash 的 user 消息。 属性 type string (必选) 固定为 input_video。 video_url string (必选) 视频的公网 URL。 fps number (可选) 抽帧频率,表示每秒抽取的帧数,例如 2 表示每秒抽取 2 帧,不要传字符串。 output_text { type, text } 助手回复,仅 assistant 角色。 属性 type string (必选) 固定为 output_text。 text string (必选) 助手回复的文本内容。 音视频输入沿用普通文本响应格式和流式事件,流式文本使用 response.output_text.delta、response.output_text.done。音视频输入、文本输出示例见Qwen3.8-Omni-Flash。 type string (可选) 固定为 message。 ResponseOutputMessage object (可选) 模型的输出消息对象。可直接将上一轮响应的 output 中的 message 项传回 input,用于多轮对话场景。与 EasyInputMessage 的区别在于它携带了完整的输出结构(含 id、status 和结构化 content)。 属性 type string (必选) 固定为 message。 id string (必选) 输出消息的唯一标识,来自上一轮响应。 role string (必选) 固定为 assistant。 status string (必选) 消息状态,可选值:in_progress、completed、incomplete。 content array (必选) 内容数组,元素为 output_text 类型对象。 属性 type string (必选) 固定为 output_text。 text string (必选) 回复文本。 annotations array (可选) 标注信息。 Custom Tool Call object (可选) 模型返回的自定义工具调用。执行工具后,将调用项和对应的 custom_tool_call_output 追加到下一轮请求的 input 中。 属性 type string (必选) 固定为 custom_tool_call。 id string (可选) 上一轮响应中的调用项 ID,原样回传。 name string (必选) 工具名称,例如 emit_code。 input string (必选) 自定义工具的自由文本输入,仅当 type 为 custom_tool_call 时存在。 call_id string (必选) 工具调用标识符,使用模型返回的 call_id。 namespace string (可选) 工具所属的命名空间。调用命名空间内的 function 或 custom 工具时返回,回传调用项时保留该字段。 Custom Tool Call Output object (可选) 自定义工具的执行结果,通过 call_id 关联对应的调用。 属性 type string (必选) 固定为 custom_tool_call_output。 call_id string (必选) 工具调用标识符,使用模型返回的 call_id。 output string (必选) 自定义工具的执行结果,通过 call_id 关联对应的调用。 Function Call object (可选) 模型决定调用外部工具时生成的结构化指令。 属性 type string (必选) 固定为 function_call。 id string (可选) Function Call 的唯一标识,来自上一轮响应。 name string (必选) 工具函数名称。 namespace string (可选) 工具所属的命名空间。调用命名空间内的 function 或 custom 工具时返回,回传调用项时保留该字段。 arguments string (必选) 工具调用参数,JSON 字符串格式。 call_id string (必选) 工具调用的标识符,需与模型返回的 call_id 一致。 status string (可选) 状态,可选值:in_progress、completed、incomplete。 Function Call Output object (可选) 工具调用的输出结果。在消息列表中必须紧跟对应的 function_call 消息,否则会报错。 属性 type string (必选) 固定为 function_call_output。 id string (可选) Function Call Output 的唯一标识。 call_id string (必选) 工具调用的标识符,需与模型返回的 call_id 一致。 output string 或 array (必选) 工具函数的执行结果。纯文本结果传入 string;需要模型理解工具产出的图片时传入 array,一个 output 中可包含多张图片。图片 URL 作为 string 传入时按普通文本处理,不会被解析为图片。 array 元素类型 以下类型之一,不支持 input_file、output_text 以及音频、视频类型: input_text { type, text } 文本结果。 属性 type string (必选) 固定为 input_text。 text string (必选) 文本内容。 input_image { type, image_url } 图片结果。 属性 type string (必选) 固定为 input_image。 image_url string (必选) 图片的公网 URL 或 Base64 编码。Base64 请传入完整的 Data URI,例如:data:image/png;base64,iVBORw0K...。此处为 string 类型,不支持 {"url": "..."} 嵌套对象形式。 status string (可选) 状态,可选值:in_progress、completed、incomplete。 Reasoning object (可选) 模型的思考内容。可直接将上一轮响应的 output 中的 reasoning 项传回 input,用于在多轮对话中传递思考内容。 属性 type string (必选) 固定为 reasoning。 id string (必选) 思考内容的唯一标识,来自上一轮响应。 encrypted_content string 加密的完整思维链,用于多轮对话中恢复历史思考。 用于 qwen4-max 的历史思考回传。每轮设置 reasoning.summary="auto",并原样回传历史 reasoning item 的密文。 思维链摘要与加密 summary array (必选) 思考摘要内容。 属性 type string (必选) 固定为 summary_text。 text string (必选) 摘要文本。 status string (可选) 状态,可选值:in_progress、completed、incomplete。 Web Search Call object (可选) 搜索调用对象。可直接将上一轮响应的 output 中的 web_search_call 项传回 input,用于在多轮对话中传递搜索结果上下文。 属性 type string (必选) 固定为 web_search_call。 id string (必选) 搜索调用的唯一标识,来自上一轮响应。 status string (必选) 搜索状态,可选值:in_progress、searching、completed、failed。 action object (必选) 搜索信息。仅支持 search 类型。 属性 type string (必选) 搜索类型,固定为 search。 queries array (可选) 搜索查询词列表,元素类型为 string。 sources array (可选) 搜索结果来源列表。 属性 type string (必选) 来源类型,固定为 url。 url string (必选) 来源 URL。 instructionsstring (可选) 作为系统指令插入到上下文的起始位置。使用 previous_response_id 时,上一轮指定的 instructions 不会传入本轮上下文。 previous_response_id string (可选) 上一个响应的唯一 ID,当前响应id有效期为7天。使用此参数可创建多轮对话,服务端会自动检索并组合该轮次的输入与输出作为上下文。当同时提供 input 消息数组和 previous_response_id 时,input 中的新消息会追加到历史上下文之后。不能与 conversation 同时使用。 请求间隔:多轮连续对话中,建议每次请求之间保留约 300 毫秒的延迟,避免高峰期上下文存储未完成导致调用失败。 conversation string (可选) 当前响应所属的会话(参考Conversations API)。会话中的历史项会自动作为上下文传入本次请求,本次请求的输入和输出也会在响应完成后自动添加到会话中。不能与 previous_response_id 同时使用。 prompt_cache_options object (可选) 请求顶层的缓存配置。支持 qwen4-max、qwen4-35b-a3b、kimi-k3.1-pro 和 kimi-k3。 Python SDK 通过 extra_body 传入顶层非标准参数;Node.js SDK 和 curl 直接传入。 详见显式缓存。 属性 mode string implicit(默认):开启显式缓存,在最后一条输入消息末尾自动设置断点,与手动断点同时生效。
explicit:开启显式缓存,必须设置手动断点才会创建缓存,没有断点时不生效。
ttl string (可选) 缓存有效期,支持 5m 和 1h,默认为 5m。 stream boolean (可选)默认值为 false 是否开启流式输出。设置为 true 时,模型响应数据将实时流式返回给客户端。 background boolean (可选)默认值为 false 是否在后台执行请求。设为 true 时,省略 store 或设为 true。显式传入 store=false 会返回 HTTP 400。
- 省略
stream 或设为 false 时,返回包含 id 的 JSON,初始状态为 queued。
- 设为
stream=true 时,从首个 SSE 事件 response.created 的 response.id 获取 ID。连接断开后任务继续执行,可用同一 ID 获取响应。
默认执行时限为 3600 秒(1 小时),从服务端受理请求起算,含排队时间。超时后状态为 failed,通过获取响应查看 error.message。 store boolean (可选)默认值为 true 是否储存本次会话生成的模型响应。
false:不储存,对话内容不能被 previous_response_id 和后续 API 使用。
true:储存,当前模型响应可被 previous_response_id 和后续 API 使用。
tools array (可选) 模型在生成响应时可调用的工具数组。支持内置工具、自定义 function 和 custom 工具;可通过 namespace 将相关工具分组。 kimi-k3.1-pro(阿里云百炼部署)支持 web_search、web_extractor 和 code_interpreter 三项内置工具,适用于北京、新加坡、美国(弗吉尼亚)、德国(法兰克福)、日本(东京)和中国香港。
deepseek-v4.1-flash-1017 支持 web_search、web_extractor 和 code_interpreter 三项内置工具。
qwen3.8-omni-flash 的内置工具仅支持 web_search,同时支持自定义 function 工具。
属性 web_search联网搜索工具,允许模型搜索互联网上的最新信息。相关文档:联网搜索 注:codex 模式下,在 tools 中开启 web_search 会自动启用 web_extractor。 属性 type string (必选) 固定为web_search。 使用示例:[{"type": "web_search"}] web_extractor网页抽取工具,允许模型访问并提取网页内容。当前必须配合web_search工具一起使用。相关文档:网页抓取 属性 type string (必选) 固定为web_extractor。 使用示例:[{"type": "web_search"}, {"type": "web_extractor"}] code_interpreter代码解释器工具,允许模型执行代码并返回结果,支持数据分析。相关文档:代码解释器 属性 type string (必选) 固定为code_interpreter。 使用示例:[{"type": "code_interpreter"}] web_search_image根据文本描述搜索图片。相关文档:文搜图 属性 type string (必选) 固定为web_search_image。 使用示例:[{"type": "web_search_image"}] image_search根据图片搜索相似或相关图片,输入中需要包含图片的URL。相关文档:图搜图 属性 type string (必选) 固定为image_search。 使用示例:[{"type": "image_search"}] file_search在已上传或关联的知识库中搜索。相关文档:知识检索 属性 type string (必选) 固定为file_search。 vector_store_ids array(必选) 要检索的知识库 ID。当前仅支持传入一个知识库 ID。 使用示例:[{"type": "file_search", "vector_store_ids": ["your_knowledge_base_id"]}] MCP调用通过 MCP(Model Context Protocol)调用外部服务,相关文档:MCP 属性 type string (必选) 固定为mcp。 server_protocol string (必选) 与 MCP 服务的通信协议,如 "sse" server_label string (必选) 服务标签,用于标识该 MCP 服务。 server_description string (可选) 服务描述,帮助模型理解其功能与适用场景。 server_url string (必选) MCP 服务端点的 URL。 headers object (可选) 请求头,用于携带身份验证等信息,如 Authorization。 使用示例: mcp_tool = {
"type": "mcp",
"server_protocol": "sse",
"server_label": "amap-maps",
"server_description": "高德地图MCP Server现已覆盖15大核心接口,提供全场景覆盖的地理信息服务,包括生成专属地图、导航到目的地、打车、地理编码、逆地理编码、IP定位、天气查询、骑行路径规划、步行路径规划、驾车路径规划、公交路径规划、距离测量、关键词搜索、周边搜索、详情搜索等。",
"server_url": "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/mcps/amap-maps/sse",
"headers": {
"Authorization": "Bearer <your-mcp-server-token>"
}
}
自定义工具function自定义函数工具,允许模型调用您定义的函数。当模型判断需要调用工具时,响应会返回 function_call 类型的输出。相关文档:Function Calling 属性 type string (必选) 必须设置为function。 namestring(必选) 工具名称。仅允许字母、数字、下划线(_)和短划线(-),最长 64 个 Token。 descriptionstring(必选) 工具描述信息,帮助模型判断何时以及如何调用该工具。 parameters object (可选) 工具的参数描述,需要是一个合法的 JSON Schema。若parameters参数为空,表示该工具没有入参(如时间查询工具)。
为提高工具调用的准确性,建议传入 parameters。
使用示例: [{
"type": "function",
"name": "get_weather",
"description": "获取指定城市的天气信息",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "城市名称"
}
},
"required": ["city"]
}
}]
自定义工具custom自定义格式工具,调用输入为自由文本,可通过 Lark 或 Regex 文法描述输入格式。模型返回 custom_tool_call,工具输入位于 input 字段。 属性 type string (必选) 固定为 custom。 name string (必选) 工具名称,例如 emit_code。 description string (可选) 工具描述,说明用途及调用时机。 format object (可选) 工具输入的格式配置。 若工具依赖特定的文法结构(如 apply_patch 补丁文件格式),建议将 format.type 设置为 grammar 并提供文法规则,帮助模型按指定格式生成调用输入。 当 format.type 为 grammar 时,需配对提供 syntax 和 definition;为 text 时,表示无约束的自由文本,syntax 和 definition 均可选。 属性 type string (可选) 取值为 text(无特定文法约束的自由文本)或 grammar(文法格式)。 syntax string (可选) 文法语法类型:lark 或 regex。 definition string (可选) 文法规则定义。Lark 使用产生式,Regex 使用正则表达式。 以下对象作为 tools 数组的一个元素传入。 {
"type": "custom",
"name": "apply_patch",
"description": "Use the `apply_patch` tool to edit files. This is a FREEFORM tool, so do not wrap the patch in JSON.",
"format": {
"type": "grammar",
"syntax": "lark",
"definition": "start: begin_patch hunk+ end_patch\nbegin_patch: \"*** Begin Patch\" LF\nend_patch: \"*** End Patch\" LF?\n\nhunk: add_hunk | delete_hunk | update_hunk\nadd_hunk: \"*** Add File: \" filename LF add_line+\ndelete_hunk: \"*** Delete File: \" filename LF\nupdate_hunk: \"*** Update File: \" filename LF change_move? change?\n\nfilename: /[^\\n]+/\nadd_line: ADD_LINE\nADD_LINE: /\\+[^\\n]*\\n/\n\nchange_move: \"*** Move to: \" filename LF\nchange: (change_context | change_line)+ eof_line?\nchange_context: CONTEXT_LINE\nCONTEXT_LINE: /@@[^\\n]*\\n/\nchange_line: CHANGE_LINE\nCHANGE_LINE: /[+\\- ][^\\n]*\\n/\neof_line: \"*** End of File\" LF\n\n%import common.LF\n"
}
}
命名空间namespace将相关的 function 或 custom 工具归拢在同一命名空间中。 属性 type string (必选) 固定为 namespace。 name string (必选) 命名空间名称,例如 crm。 description string (可选) 命名空间的整体描述。 tools array[object] (必选) 命名空间内的工具列表。每个元素为 function 或 custom 工具对象,字段与对应工具定义相同。 以下对象作为 tools 数组的一个元素传入。 {
"type": "namespace",
"name": "crm",
"description": "Customer Relationship Management tools",
"tools": [
{
"type": "function",
"name": "get_customer",
"description": "Get customer details by ID",
"parameters": {
"type": "object",
"properties": {
"customer_id": {
"type": "string"
}
},
"required": [
"customer_id"
]
}
},
{
"type": "custom",
"name": "import_patch",
"description": "Import customer batch patch",
"format": {
"type": "text"
}
}
]
}
tool_choice string or object (可选)默认值为 auto 控制模型如何选择和调用工具。此参数支持两种赋值格式:字符串模式和对象模式。 字符串模式
auto:模型自动决定是否调用工具。
none:禁止模型调用任何工具。
required:强制模型调用工具(仅当 tools 列表中只有一个工具时可用)。
对象模式为模型设定可用的工具范围,仅限在预定义的工具列表中进行选择和调用。 属性 mode string (必选)
auto:模型自动决定是否调用工具。
required:强制模型调用工具(仅当 tools 列表中只有一个工具时可用)。
tools array(必选) 一个包含工具定义的列表,模型将被允许调用这些工具。 [
{ "type": "function", "name": "get_weather" }
]
typestring (必选) 允许的工具配置类型,固定为 allowed_tools。 parallel_tool_calls boolean (可选)默认值为 true 是否开启并行工具调用。相关文档:并行工具调用
kimi-k3 不支持通过此参数控制工具调用的并行性。设置为 false 也不能保证串行调用,模型仍可能在一次响应中返回多个 function_call。请按实际返回结果处理。
可选值: temperaturefloat(可选) 采样温度,控制模型生成文本的多样性。 temperature越高,生成的文本更多样,反之,生成的文本更确定。 取值范围: [0, 2) qwen4-max:思考模式为 1.0,非思考模式为 0.7。
temperature与top_p均可以控制生成文本的多样性,建议只设置其中一个值。更多说明,请参见概述。 top_pfloat(可选) 核采样的概率阈值,控制模型生成文本的多样性。 top_p越高,生成的文本更多样。反之,生成的文本更确定。 取值范围:(0,1.0] qwen4-max:思考模式为 0.95,非思考模式为 0.8。
temperature与top_p均可以控制生成文本的多样性,建议只设置其中一个值。更多说明,请参见概述。 enable_thinking boolean (可选) 是否开启思考模式。开启后,模型会在回复前进行思考,思考内容将通过 reasoning 类型的输出项返回。开启思考模式时,建议开启内置工具,以在处理复杂任务时获得最佳的模型效果。 可选值: 不同模型的默认值:支持的模型
该参数非OpenAI标准参数。Python SDK 通过 extra_body={"enable_thinking": True} 传递;Node.js SDK 和 curl 直接使用 enable_thinking: true 作为顶层参数。建议使用 reasoning.effort 替代,enable_thinking 后续将不再支持。
reasoning object (可选) 控制模型的思考强度。模型会在回复前进行思考,思考内容将通过 reasoning 类型的输出项返回。 kimi-k3.1-pro(阿里云百炼部署)的 reasoning.effort 默认值为 max,支持 max(深度推理)、high(增强推理)、medium(中度推理)和 low(轻度推理)。建议保持默认思考配置,关闭思考会显著影响输出效果。 属性 kimi-k3.1-pro 的档位与默认值以上述说明为准,以下说明适用于其他模型。 effort string (可选):思考强度档位。 可传入以下值,实际档位和默认值因模型而异: none、minimal、low、medium、high、xhigh、max。 qwen4-max
默认值: reasoning.effort=high. reasoning.effort | 实际档位 |
|---|
minimal, low | low | medium, high | high | xhigh, max | xhigh | none | 关闭思考 |
仅设置 reasoning.effort 时,思考长度上限默认为 131072 Token。 | 模型 | 支持的档位 | 其余档位的映射 |
|---|
qwen3.8-max、qwen3.8-max-0902、qwen3.8-flash、qwen3.8-2.4t-a95b、qwen3.8-27b | none、low、medium、xhigh(默认) | minimal 映射为 low,high 和 max 映射为 xhigh | deepseek-v4-flash-0731、deepseek-v4-pro-0813 | none、low、high(默认)、max | minimal 映射为 low,medium 映射为 high,xhigh 映射为 max | deepseek-v4.1-flash | none、low、high(默认)、max | minimal 映射为 low,medium 和 xhigh 映射为 high,传入 ultra 会返回错误 | glm-5.3 | low、high、max(默认) | minimal 映射为 low,medium 映射为 high,xhigh 映射为 max | glm-5.2、deepseek-v4-pro | none、high(默认)、max | minimal、low 和 medium 映射为 high,xhigh 映射为 max |
glm-5.3 推荐使用 max 档位。
summary string (可选) 思维链的返回形式。默认返回完整明文;开启摘要后,返回用于展示的摘要和用于恢复历史思考的完整密文。 qwen4-max:设为 "auto" 开启摘要。 思维链摘要与加密
reasoning.effort 的优先级高于 enable_thinking,建议优先使用 reasoning.effort,enable_thinking 后续将不再支持。
ocr_options object (可选) OCR 定制任务参数。仅适用于 qwen3.5-ocr 模型。通过此参数可调用内置的 OCR 任务(如信息抽取、文字定位等),定制任务结果通过响应中的 ocr_result 字段返回。 解析 PDF 文件时,task 的取值决定支持的页数:设置为 document_parsing 时最大 50 页;未设置 task 或设置为其他任务时,最大 10 页。
该参数非 OpenAI 标准参数。Python SDK 通过 extra_body={"ocr_options": {...}} 传递;Node.js SDK 和 curl 直接使用 ocr_options 作为顶层参数。
max_output_tokens integer(可选) 限制生成输出的 Token 数量。 qwen4-max:思考模式限制思考与回复的 Token 总数,最大值和未传入时的默认值均为 262144;非思考模式最大值和默认值均为 131072。
- Qwen3.8 系列:模型回复内容和思维链之和的最大Token数。
- Qwen3.7、Qwen3.6、Qwen3.5、Qwen3-Max、DeepSeek、GLM 和 Kimi:模型回复内容的最大Token数。
上述型号的最小值为16。生成的 Token 数达到所设置的上限时,生成将提前停止,状态为incomplete。 text object (可选) 文本输出配置,用于控制模型输出纯文本或结构化 JSON 数据。 属性 format object (可选) 指定模型必须输出的格式。默认值为 {"type": "text"}。 以下类型之一: ResponseFormatText { type } 默认值,输出文字。 属性 type string (必选) 固定为 text。 ResponseFormatTextJSONSchemaConfig { type, json_schema } 输出严格符合指定 JSON Schema 的 JSON 字符串,可精确控制输出结构与字段类型。适用于 qwen3.8 系列、deepseek-v4 系列、glm-5 系列等模型;deepseek-v4.1 系列即将支持。使用该类型时,提示词无需包含 JSON 关键词。 属性 type string (必选) 固定为 json_schema。 json_schema object (必选) JSON Schema 配置。 属性 name string (必选) Schema 的名称。 schema object (必选) 描述输出结构的 JSON Schema 对象。通过 properties 定义字段结构,通过 required 声明必填字段列表,通过 additionalProperties 控制是否允许输出未在 Schema 中定义的字段(推荐设置为 false,即只输出已定义的字段)。支持的数据类型:string、number、integer、boolean、object、array、enum。相关文档:配置指南。 strict boolean (可选) 是否严格遵循 schema 定义的结构。推荐设置为 true。 ResponseFormatJSONObject { type } 输出标准格式的 JSON 字符串。适用于 qwen3.8 系列、deepseek-v4 系列、deepseek-v4.1 系列、glm-5 系列模型及 kimi-k3.1-pro(阿里云百炼部署)。使用该类型时,需在提示词中明确指示模型输出 JSON,如:“请按照json格式输出”,否则会报错。 属性 type string (必选) 固定为 json_object。 | 流式输出import os
from openai import OpenAI
client = OpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"),
base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)
stream = client.responses.create(
model="qwen4-max",
input="请简单介绍一下人工智能。",
stream=True
)
print("开始接收流式输出:")
for event in stream:
if event.type == 'response.output_text.delta':
print(event.delta, end='', flush=True)
elif event.type == 'response.completed':
print("\n流式输出完成")
print(f"总Token数: {event.response.usage.total_tokens}")
import OpenAI from "openai";
const openai = new OpenAI({
apiKey: process.env.DASHSCOPE_API_KEY,
baseURL: "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1"
});
async function main() {
const stream = await openai.responses.create({
model: "qwen4-max",
input: "请简单介绍一下人工智能。",
stream: true
});
console.log("开始接收流式输出:");
for await (const event of stream) {
if (event.type === 'response.output_text.delta') {
process.stdout.write(event.delta);
} else if (event.type === 'response.completed') {
console.log("\n流式输出完成");
console.log(`总Token数: ${event.response.usage.total_tokens}`);
}
}
}
main();
curl -X POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/responses \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
--no-buffer \
-d '{
"model": "qwen4-max",
"input": "请简单介绍一下人工智能。",
"stream": true
}'
后台执行设置 background=true 创建响应,使用返回的 id 查询进度和结果。 import os
import time
from openai import OpenAI
client = OpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"),
base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)
response = client.responses.create(
model="qwen4-max",
input="用三句话介绍杭州。",
background=True,
)
response_id = response.id
print(response_id, response.status)
while response.status in ("queued", "in_progress"):
time.sleep(2)
response = client.responses.retrieve(response_id)
if response.status == "completed":
print(response.output_text)
else:
print(response.status, response.error)
import OpenAI from "openai";
import { setTimeout } from "node:timers/promises";
const openai = new OpenAI({
apiKey: process.env.DASHSCOPE_API_KEY,
baseURL: "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1"
});
async function main() {
let response = await openai.responses.create({
model: "qwen4-max",
input: "用三句话介绍杭州。",
background: true
});
const responseId = response.id;
console.log(responseId, response.status);
while (response.status === "queued" || response.status === "in_progress") {
await setTimeout(2000);
response = await openai.responses.retrieve(responseId);
}
if (response.status === "completed") {
console.log(response.output_text);
} else {
console.log(response.status, response.error);
}
}
main();
# 记录返回的 id
curl -X POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/responses \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen4-max",
"input": "用三句话介绍杭州。",
"background": true
}'
# 将 resp_example 替换为返回的 id
curl -X GET https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/responses/resp_example \
-H "Authorization: Bearer $DASHSCOPE_API_KEY"
{
"id": "resp_example",
"background": true,
"status": "queued"
}
status 为 completed 时,从 output 的 message 项中读取 content。正文是其中 type 为 output_text 的 text。
{
"id": "resp_example",
"status": "completed",
"output": [
{
"type": "message",
"content": [
{
"type": "output_text",
"text": "杭州是浙江省省会。西湖和灵隐寺是当地的代表性景点。杭州也是中国重要的数字经济城市。"
}
]
}
]
}
任务仍在执行时,可将 resp_example 替换为任务的响应 ID,调用取消接口。 curl -X POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/responses/resp_example/cancel \
-H "Authorization: Bearer $DASHSCOPE_API_KEY"
取消请求可能返回 in_progress。继续用同一 ID 查询最终状态。cancelled 表示已取消。 调用内置工具import os
from openai import OpenAI
client = OpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"),
base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)
response = client.responses.create(
model="qwen4-max",
input="帮我找一下阿里云官网,并提取首页的关键信息",
# 建议同时开启内置工具以取得最佳效果
tools=[
{"type": "web_search"},
{"type": "code_interpreter"},
{"type": "web_extractor"}
],
)
# 取消以下注释查看中间过程输出
# print(response.output)
print(response.output_text)
import OpenAI from "openai";
const openai = new OpenAI({
apiKey: process.env.DASHSCOPE_API_KEY,
baseURL: "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1"
});
async function main() {
const response = await openai.responses.create({
model: "qwen4-max",
input: "帮我找一下阿里云官网,并提取首页的关键信息",
tools: [
{ type: "web_search" },
{ type: "code_interpreter" },
{ type: "web_extractor" }
]
});
for (const item of response.output) {
if (item.type === "reasoning") {
console.log("模型正在思考...");
} else if (item.type === "web_search_call") {
console.log(`搜索查询: ${item.action.query}`);
} else if (item.type === "web_extractor_call") {
console.log("正在抽取网页内容...");
} else if (item.type === "message") {
console.log(`回复内容: ${item.content[0].text}`);
}
}
}
main();
curl -X POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/responses \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen4-max",
"input": "帮我找一下阿里云官网,并提取首页的关键信息",
"tools": [
{
"type": "web_search"
},
{
"type": "code_interpreter"
},
{
"type": "web_extractor"
}
]
}'
自定义 Function Callfrom openai import OpenAI
import json
import os
import random
# 初始化客户端
client = OpenAI(
# 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:api_key="sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)
# 模拟用户问题
USER_QUESTION = "北京天气咋样"
# 定义工具列表
tools = [
{
"type": "function",
"name": "get_current_weather",
"description": "当你想查询指定城市的天气时非常有用。",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "城市或县区,比如北京市、杭州市、余杭区等。",
}
},
"required": ["location"],
},
}
]
# 模拟天气查询工具
def get_current_weather(arguments):
weather_conditions = ["晴天", "多云", "雨天"]
random_weather = random.choice(weather_conditions)
location = arguments["location"]
return f"{location}今天是{random_weather}。"
# 封装模型响应函数
def get_response(input_data):
response = client.responses.create(
model="qwen4-max",
input=input_data,
tools=tools,
)
return response
# 维护对话上下文
conversation = [{"role": "user", "content": USER_QUESTION}]
response = get_response(conversation)
function_calls = [item for item in response.output if item.type == "function_call"]
# 如果不需要调用工具,直接输出内容
if not function_calls:
print(f"助手最终回复:{response.output_text}")
else:
# 进入工具调用循环
while function_calls:
for fc in function_calls:
func_name = fc.name
arguments = json.loads(fc.arguments)
print(f"正在调用工具 [{func_name}],参数:{arguments}")
# 执行工具
tool_result = get_current_weather(arguments)
print(f"工具返回:{tool_result}")
# 将工具调用和结果成对追加到上下文中
conversation.append(
{
"type": "function_call",
"name": fc.name,
"arguments": fc.arguments,
"call_id": fc.call_id,
}
)
conversation.append(
{
"type": "function_call_output",
"call_id": fc.call_id,
"output": tool_result,
}
)
# 携带完整上下文再次调用模型
response = get_response(conversation)
function_calls = [
item for item in response.output if item.type == "function_call"
]
print(f"助手最终回复:{response.output_text}")
import OpenAI from "openai";
// 初始化客户端
const openai = new OpenAI({
// 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:apiKey: "sk-xxx",
apiKey: process.env.DASHSCOPE_API_KEY,
baseURL:
"https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
});
// 定义工具列表
const tools = [
{
type: "function",
name: "get_current_weather",
description: "当你想查询指定城市的天气时非常有用。",
parameters: {
type: "object",
properties: {
location: {
type: "string",
description: "城市或县区,比如北京市、杭州市、余杭区等。",
},
},
required: ["location"],
},
},
];
// 模拟天气查询工具
const getCurrentWeather = (args) => {
const weatherConditions = ["晴天", "多云", "雨天"];
const randomWeather =
weatherConditions[Math.floor(Math.random() * weatherConditions.length)];
const location = args.location;
return `${location}今天是${randomWeather}。`;
};
// 封装模型响应函数
const getResponse = async (inputData) => {
const response = await openai.responses.create({
model: "qwen4-max",
input: inputData,
tools: tools,
});
return response;
};
const main = async () => {
const userQuestion = "北京天气";
// 维护对话上下文
const conversation = [{ role: "user", content: userQuestion }];
let response = await getResponse(conversation);
let functionCalls = response.output.filter(
(item) => item.type === "function_call"
);
// 如果不需要调用工具,直接输出内容
if (functionCalls.length === 0) {
console.log(`助手最终回复:${response.output_text}`);
} else {
// 进入工具调用循环
while (functionCalls.length > 0) {
for (const fc of functionCalls) {
const funcName = fc.name;
const args = JSON.parse(fc.arguments);
console.log(`正在调用工具 [${funcName}],参数:`, args);
// 执行工具
const toolResult = getCurrentWeather(args);
console.log(`工具返回:${toolResult}`);
// 将工具调用和结果成对追加到上下文中
conversation.push({
type: "function_call",
name: fc.name,
arguments: fc.arguments,
call_id: fc.call_id,
});
conversation.push({
type: "function_call_output",
call_id: fc.call_id,
output: toolResult,
});
}
// 携带完整上下文再次调用模型
response = await getResponse(conversation);
functionCalls = response.output.filter(
(item) => item.type === "function_call"
);
}
console.log(`助手最终回复:${response.output_text}`);
}
};
// 启动程序
main().catch(console.error);
# 第一步:提交用户问题与工具定义,模型返回 function_call
curl -X POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/responses \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen4-max",
"input": [
{
"role": "user",
"content": "北京天气咋样"
}
],
"tools": [
{
"type": "function",
"name": "get_current_weather",
"description": "当你想查询指定城市的天气时非常有用。",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "城市或县区,比如北京市、杭州市、余杭区等。"
}
},
"required": ["location"]
}
}
]
}'
# 第二步:在本地执行函数后,将 function_call 与 function_call_output 成对追加到 input 中,获取最终回复
# 请将 call_id 与 arguments 替换为第一步响应中实际返回的值
curl -X POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/responses \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen4-max",
"input": [
{
"role": "user",
"content": "北京天气咋样"
},
{
"type": "function_call",
"name": "get_current_weather",
"arguments": "{\"location\": \"北京市\"}",
"call_id": "call_xxx"
},
{
"type": "function_call_output",
"call_id": "call_xxx",
"output": "北京市今天是晴天。"
}
],
"tools": [
{
"type": "function",
"name": "get_current_weather",
"description": "当你想查询指定城市的天气时非常有用。",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "城市或县区,比如北京市、杭州市、余杭区等。"
}
},
"required": ["location"]
}
}
]
}'
工具返回多模态结果from openai import OpenAI
import json
import os
# 初始化客户端
client = OpenAI(
# 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:api_key="sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)
# 模拟用户问题
USER_QUESTION = "画一张小狗的照片,然后告诉我图里的小狗是什么品种、在什么场景里"
# 定义工具列表
tools = [
{
"type": "function",
"name": "generate_image",
"description": "当你需要根据文字描述生成图片时非常有用。",
"parameters": {
"type": "object",
"properties": {
"prompt": {
"type": "string",
"description": "图片内容的文字描述。",
}
},
"required": ["prompt"],
},
}
]
# 模拟文生图工具,实际使用时请替换为真实的图片生成调用
def generate_image(arguments):
print(f"正在生成图片,提示词:{arguments['prompt']}")
return "https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"
# 封装模型响应函数
def get_response(input_data):
response = client.responses.create(
model="qwen4-max",
input=input_data,
tools=tools,
)
return response
# 维护对话上下文
conversation = [{"role": "user", "content": USER_QUESTION}]
response = get_response(conversation)
function_calls = [item for item in response.output if item.type == "function_call"]
# 进入工具调用循环
while function_calls:
for fc in function_calls:
arguments = json.loads(fc.arguments)
# 执行工具,得到图片地址
image_url = generate_image(arguments)
# 将工具调用和结果成对追加到上下文中
conversation.append(
{
"type": "function_call",
"name": fc.name,
"arguments": fc.arguments,
"call_id": fc.call_id,
}
)
# output 传入内容数组,模型才能理解图片内容
conversation.append(
{
"type": "function_call_output",
"call_id": fc.call_id,
"output": [
{"type": "input_text", "text": "图片生成成功。"},
{"type": "input_image", "image_url": image_url},
],
}
)
# 携带完整上下文再次调用模型
response = get_response(conversation)
function_calls = [item for item in response.output if item.type == "function_call"]
print(f"助手最终回复:{response.output_text}")
import OpenAI from "openai";
// 初始化客户端
const openai = new OpenAI({
// 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:apiKey: "sk-xxx",
apiKey: process.env.DASHSCOPE_API_KEY,
baseURL:
"https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
});
// 定义工具列表
const tools = [
{
type: "function",
name: "generate_image",
description: "当你需要根据文字描述生成图片时非常有用。",
parameters: {
type: "object",
properties: {
prompt: {
type: "string",
description: "图片内容的文字描述。",
},
},
required: ["prompt"],
},
},
];
// 模拟文生图工具,实际使用时请替换为真实的图片生成调用
const generateImage = (args) => {
console.log(`正在生成图片,提示词:${args.prompt}`);
return "https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg";
};
// 封装模型响应函数
const getResponse = async (inputData) => {
const response = await openai.responses.create({
model: "qwen4-max",
input: inputData,
tools: tools,
});
return response;
};
const main = async () => {
const userQuestion = "画一张小狗的照片,然后告诉我图里的小狗是什么品种、在什么场景里";
// 维护对话上下文
const conversation = [{ role: "user", content: userQuestion }];
let response = await getResponse(conversation);
let functionCalls = response.output.filter(
(item) => item.type === "function_call"
);
// 进入工具调用循环
while (functionCalls.length > 0) {
for (const fc of functionCalls) {
const args = JSON.parse(fc.arguments);
// 执行工具,得到图片地址
const imageUrl = generateImage(args);
// 将工具调用和结果成对追加到上下文中
conversation.push({
type: "function_call",
name: fc.name,
arguments: fc.arguments,
call_id: fc.call_id,
});
// output 传入内容数组,模型才能理解图片内容
conversation.push({
type: "function_call_output",
call_id: fc.call_id,
output: [
{ type: "input_text", text: "图片生成成功。" },
{ type: "input_image", image_url: imageUrl },
],
});
}
// 携带完整上下文再次调用模型
response = await getResponse(conversation);
functionCalls = response.output.filter(
(item) => item.type === "function_call"
);
}
console.log(`助手最终回复:${response.output_text}`);
};
// 启动程序
main().catch(console.error);
文档理解import os
from openai import OpenAI
client = OpenAI(
# 若没有配置环境变量,请用百炼API Key将下行替换为:api_key="sk-xxx"
api_key=os.getenv("DASHSCOPE_API_KEY"),
base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)
response = client.responses.create(
model="qwen3.5-ocr",
input=[
{
"role": "user",
"content": [
{
"type": "input_file",
"file_url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20260616/qmycjl/1506.02640v5.pdf",
},
{
"type": "input_text",
"text": "Read all the text in the file.",
},
],
}
],
extra_body={
"ocr_options": {"task": "document_parsing"}
},
)
print(response.output_text)
import OpenAI from 'openai';
const client = new OpenAI({
// 若没有配置环境变量,请用百炼API Key将下行替换为:apiKey: "sk-xxx"
apiKey: process.env.DASHSCOPE_API_KEY,
baseURL: "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
});
async function main() {
const response = await client.responses.create({
model: "qwen3.5-ocr",
input: [{
role: "user",
content: [{
type: "input_file",
file_url: "https://example.com/your-document.pdf"
}]
}],
ocr_options: { task: "document_parsing" }
});
// 获取定制任务结果
console.log(response.output[0].content[0].ocr_result);
}
main();
curl -X POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/responses \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen3.5-ocr",
"input": [
{
"role": "user",
"content": [
{
"type": "input_file",
"file_url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20260616/qmycjl/1506.02640v5.pdf"
},
{
"type": "input_text",
"text": "Read all the text in the file."
}
]
}
],
"ocr_options": {"task": "document_parsing"}
}'
Session 缓存在请求 Header 中设置 x-dashscope-session-cache: enable 开启 Session 缓存,多轮对话通过 previous_response_id 关联上下文。详细说明见Session 缓存。 自动生效的隐式缓存另见上下文缓存。 import os
from openai import OpenAI
client = OpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"),
base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
# 通过 default_headers 开启 Session 缓存
default_headers={"x-dashscope-session-cache": "enable"}
)
# 构造超过 1024 Token 的长文本,确保能触发缓存创建(若未达到1024 Token,后续累积对话上下文超过1024 Token时将触发缓存创建)
long_context = "人工智能是计算机科学的一个重要分支,致力于研究和开发能够模拟、延伸和扩展人类智能的理论、方法、技术及应用系统。" * 50
# 第一轮对话
response1 = client.responses.create(
model="qwen4-max",
input=long_context + "\n\n基于以上背景知识,请简短介绍机器学习中的随机森林算法。",
)
print(f"第一轮回复: {response1.output_text}")
# 第二轮对话:通过 previous_response_id 关联上下文,缓存由服务端自动处理
response2 = client.responses.create(
model="qwen4-max",
input="它和 GBDT 有什么主要区别?",
extra_body={"previous_response_id": response1.id},
)
print(f"第二轮回复: {response2.output_text}")
# 查看缓存命中情况
usage = response2.usage
print(f"输入 Token: {usage.input_tokens}")
print(f"缓存命中 Token: {usage.input_tokens_details.cached_tokens}")
import OpenAI from "openai";
const openai = new OpenAI({
apiKey: process.env.DASHSCOPE_API_KEY,
baseURL: "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
// 通过 defaultHeaders 开启 Session 缓存
defaultHeaders: {"x-dashscope-session-cache": "enable"}
});
// 构造超过 1024 Token 的长文本,确保能触发缓存创建(若未达到1024 Token,后续累积对话上下文超过1024 Token时将触发缓存创建)
const longContext = "人工智能是计算机科学的一个重要分支,致力于研究和开发能够模拟、延伸和扩展人类智能的理论、方法、技术及应用系统。".repeat(50);
async function main() {
// 第一轮对话
const response1 = await openai.responses.create({
model: "qwen4-max",
input: longContext + "\n\n基于以上背景知识,请简短介绍机器学习中的随机森林算法,包括基本原理和应用场景。"
});
console.log(`第一轮回复: ${response1.output_text}`);
// 第二轮对话:通过 previous_response_id 关联上下文,缓存由服务端自动处理
const response2 = await openai.responses.create(
{
model: "qwen4-max",
input: "它和 GBDT 有什么主要区别?",
},
{
body: { previous_response_id: response1.id }
}
);
console.log(`第二轮回复: ${response2.output_text}`);
// 查看缓存命中情况
console.log(`输入 Token: ${response2.usage.input_tokens}`);
console.log(`缓存命中 Token: ${response2.usage.input_tokens_details.cached_tokens}`);
}
main();
# 第一轮对话
# 长文本重复 50 次以确保超过 1024 Token,触发缓存创建
curl -X POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/responses \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-H "x-dashscope-session-cache: enable" \
-d '{
"model": "qwen4-max",
"input": "人工智能是计算机科学的一个重要分支..."
}'
# 第二轮对话 - 使用上一轮返回的 id 作为 previous_response_id
curl -X POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/responses \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-H "x-dashscope-session-cache: enable" \
-d '{
"model": "qwen4-max",
"input": "它和 GBDT 有什么主要区别?",
"previous_response_id": "第一轮返回的响应id"
}'
缓存命中规则Session 缓存按精确匹配命中,规则如下:
- 不支持前缀匹配:在原有 user prompt 之后追加内容不会命中缓存。
- 不支持语义匹配:只有内容完全相同才会命中缓存,语义相同但文字不同不会命中。
- 最小可缓存 Token 数:1024 Token。低于该阈值的输入不会触发缓存创建;多轮对话中累积上下文超过 1024 Token 后才会开始创建缓存。
您可以通过 usage.input_tokens_details.cached_tokens 查看命中缓存的 Token 数,通过 cache_creation_input_tokens 查看本次请求新创建缓存的 Token 数。 |