通義千問VL模型可以根據您傳入的圖片或視頻進行回答,支援單圖或多圖的輸入,適用於映像描述、視覺問答、物體定位等多種任務。
快速開始
前提條件
如果通過 SDK 進行調用,需安裝SDK,其中 DashScope Python SDK 版本不低於1.24.6,DashScope Java SDK 版本不低於 2.21.10。
以下樣本示範了如何調用模型描述映像內容。關於本地檔案和映像限制的說明,請參見如何傳入本地檔案、映像限制章節。
OpenAI相容
Python
from openai import OpenAI
import os
client = OpenAI(
# 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
api_key=os.getenv("DASHSCOPE_API_KEY"),
# 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1
base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
)
completion = client.chat.completions.create(
model="qwen3-vl-plus", # 此處以qwen3-vl-plus為例,可按需更換模型名稱。模型列表:https://www.alibabacloud.com/help/model-studio/getting-started/models
messages=[
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {
"url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241022/emyrja/dog_and_girl.jpeg"
},
},
{"type": "text", "text": "圖中描繪的是什麼景象?"},
],
},
],
)
print(completion.choices[0].message.content)返回結果
這是一張在海灘上拍攝的照片。照片中,一個人和一隻狗坐在沙灘上,背景是大海和天空。人和狗似乎在互動,狗的前爪搭在人的手上。陽光從畫面的右側照射過來,給整個情境增添了一種溫暖的氛圍。Node.js
import OpenAI from "openai";
const openai = new OpenAI({
// 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
// 若沒有配置環境變數,請用百鍊API Key將下行替換為:apiKey: "sk-xxx"
apiKey: process.env.DASHSCOPE_API_KEY,
// 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為https://dashscope.aliyuncs.com/compatible-mode/v1
baseURL: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
});
async function main() {
const response = await openai.chat.completions.create({
model: "qwen3-vl-plus", // 此處以qwen3-vl-plus為例,可按需更換模型名稱。模型列表:https://www.alibabacloud.com/help/model-studio/getting-started/models
messages: [
{
role: "user",
content: [{
type: "image_url",
image_url: {
"url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241022/emyrja/dog_and_girl.jpeg"
}
},
{
type: "text",
text: "圖中描繪的是什麼景象?"
}
]
}
]
});
console.log(response.choices[0].message.content);
}
main()返回結果
這是一張在海灘上拍攝的照片。照片中,一個人和一隻狗坐在沙灘上,背景是大海和天空。人和狗似乎在互動,狗的前爪搭在人的手上。陽光從畫面的右側照射過來,給整個情境增添了一種溫暖的氛圍。curl
# ======= 重要提示 =======
# 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
# 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# === 執行時請刪除該注釋 ===
curl --location 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"model": "qwen3-vl-plus",
"messages": [
{"role": "user",
"content": [
{"type": "image_url", "image_url": {"url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241022/emyrja/dog_and_girl.jpeg"}},
{"type": "text", "text": "圖中描繪的是什麼景象?"}
]
}]
}'返回結果
{
"choices": [
{
"message": {
"content": "這是一張在海灘上拍攝的照片。照片中,一個人和一隻狗坐在沙灘上,背景是大海和天空。人和狗似乎在互動,狗的前爪搭在人的手上。陽光從畫面的右側照射過來,給整個情境增添了一種溫暖的氛圍。",
"role": "assistant"
},
"finish_reason": "stop",
"index": 0,
"logprobs": null
}
],
"object": "chat.completion",
"usage": {
"prompt_tokens": 1270,
"completion_tokens": 54,
"total_tokens": 1324
},
"created": 1725948561,
"system_fingerprint": null,
"model": "qwen3-vl-plus",
"id": "chatcmpl-0fd66f46-b09e-9164-a84f-3ebbbedbac15"
}DashScope
Python
import os
import dashscope
# 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
messages = [
{
"role": "user",
"content": [
{"image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241022/emyrja/dog_and_girl.jpeg"},
{"text": "圖中描繪的是什麼景象?"}]
}]
response = dashscope.MultiModalConversation.call(
# 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# 若沒有配置環境變數,請用百鍊API Key將下行替換為:api_key="sk-xxx"
api_key=os.getenv('DASHSCOPE_API_KEY'),
model='qwen3-vl-plus', # 此處以qwen3-vl-plus為例,可按需更換模型名稱。模型列表:https://www.alibabacloud.com/help/model-studio/getting-started/models
messages=messages
)
print(response.output.choices[0].message.content[0]["text"])返回結果
是一張在海灘上拍攝的照片。照片中有一位女士和一隻狗。女士坐在沙灘上,微笑著與狗互動。狗戴著項圈,似乎在與女士握手。背景是大海和天空,陽光灑在她們身上,營造出溫馨的氛圍。Java
import java.util.Arrays;
import java.util.Collections;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;
public class Main {
// 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/api/v1
static {
Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
}
public static void simpleMultiModalConversationCall()
throws ApiException, NoApiKeyException, UploadFileException {
MultiModalConversation conv = new MultiModalConversation();
MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
.content(Arrays.asList(
Collections.singletonMap("image", "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241022/emyrja/dog_and_girl.jpeg"),
Collections.singletonMap("text", "圖中描繪的是什麼景象"))).build();
MultiModalConversationParam param = MultiModalConversationParam.builder()
// 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
// 若沒有配置環境變數,請用百鍊API Key將下行替換為:.apiKey("sk-xxx")
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.model("qwen3-vl-plus") // 此處以qwen3-vl-plus為例,可按需更換模型名稱。模型列表:https://www.alibabacloud.com/help/model-studio/getting-started/models
.messages(Arrays.asList(userMessage))
.build();
MultiModalConversationResult result = conv.call(param);
System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text"));
}
public static void main(String[] args) {
try {
simpleMultiModalConversationCall();
} catch (ApiException | NoApiKeyException | UploadFileException e) {
System.out.println(e.getMessage());
}
System.exit(0);
}
}返回結果
這是一張在海灘上拍攝的照片。照片中有一個穿著格子襯衫的人和一隻戴著項圈的狗。人和狗面對面坐著,似乎在互動。背景是大海和天空,陽光灑在他們身上,營造出溫暖的氛圍。curl
# ======= 重要提示 =======
# 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
# 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# === 執行時請刪除該注釋 ===
curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "qwen3-vl-plus",
"input":{
"messages":[
{
"role": "user",
"content": [
{"image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241022/emyrja/dog_and_girl.jpeg"},
{"text": "圖中描繪的是什麼景象?"}
]
}
]
}
}'返回結果
{
"output": {
"choices": [
{
"finish_reason": "stop",
"message": {
"role": "assistant",
"content": [
{
"text": "這是一張在海灘上拍攝的照片。照片中有一個穿著格子襯衫的人和一隻戴著項圈的狗。他們坐在沙灘上,背景是大海和天空。陽光從畫面的右側照射過來,給整個情境增添了一種溫暖的氛圍。"
}
]
}
}
]
},
"usage": {
"output_tokens": 55,
"input_tokens": 1271,
"image_tokens": 1247
},
"request_id": "ccf845a3-dc33-9cda-b581-20fe7dc23f70"
}模型選型
對於如高精度的物體識別與定位(包括 3D 定位)、 Agent 工具調用、文檔和網頁解析、複雜題目解答、長視頻理解等任務,首選 Qwen3-VL,系列內模型對比如下:
qwen3-vl-plus:效能最強的模型。qwen3-vl-flash:速度更快,成本更低,是兼顧效能與成本的高性價比選擇,適用於對響應速度敏感的情境。
對於簡單的映像描述、短視頻摘要提取等通用任務,可選 Qwen2.5-VL,系列內模型對比如下:
qwen-vl-max:Qwen2.5-VL 系列中效果最佳的模型。qwen-vl-plus:速度更快,在效果與成本之間實現良好平衡。
模型的名稱、上下文、價格、快照版本等資訊請參見模型列表;並發限流條件請參考限流。
效果概覽
映像問答
描述映像中的內容或者對其進行分類打標,如識別人物、地點、動植物等。
如果太陽很刺眼,我應該用這張圖中的什麼物品? | 當太陽很刺眼時,你應該使用圖中的粉色太陽鏡。太陽鏡可以有效阻擋強光、減少紫外線對眼睛的傷害,協助你在陽光強烈時保護視力並提升視覺舒適度。 |
創意寫作
根據圖片或視頻內容產生生動的文字描述,適用於故事創作、文案撰寫、短視頻指令碼等創意情境。
請根據圖片內容,幫我寫一段有意思的朋友圈文案。 | 好的,這張圖片充滿了濃鬱的中秋節日氛圍,古典與現代元素結合得非常巧妙。根據圖片中的主要元素,我為你準備了幾個不同風格的朋友圈文案,你可以根據自己的喜好選擇。 詩意唯美風 今夜月明人盡望,不知秋思落誰家。ECS Operations and Maintenance System奔月,玉兔搗藥,古人的浪漫在今夜被點亮。願這輪明月,能照亮你回家的路,也能寄去我最深的思念。中秋節快樂! 溫馨祝福風 月圓人團圓,中秋夜最溫柔。看煙花綻放,賞圓月當空,吃一口月餅,道一聲安康。願你我心中所念,皆能如願以償。祝大家中秋快樂,闔家幸福! |
文字識別與資訊抽取
識別映像中的文字、公式或抽取票據、證件、表單中的資訊,支援格式化輸出文本;Qwen3-VL模型支援的語言增加至33種,支援的語言可參見模型特性對比。
提取圖中的:['發票代碼','發票號碼','到站','燃油費','票價','乘車日期','開車時間','車次','座號'],請你以JSON格式輸出。 | { "發票代碼": "221021325353", "發票號碼": "10283819", "到站": "開發區", "燃油費": "2.0", "票價": "8.00<全>", "乘車日期": "2013-06-29", "開車時間": "流水", "車次": "040", "座號": "371" } |
多學科題目解答
解答映像中的數學、物理、化學等問題,適用於中小學、大學以及成人教育階段。
請你分步驟解答圖中的數學題。 |
|
視覺編碼
可通過映像或視頻產生代碼,可用於將設計圖、網站截圖等產生HTML、CSS、JS 代碼。
根據我的草圖設計使用HTML、CSS建立網頁,主色調為黑色。 |
網頁預覽效果 |
物體定位
支援二維和三維定位,可用於判斷物體方位、視角變化、遮擋關係。三維定位為Qwen3-VL模型新增能力。
Qwen2.5-VL模型 480*480 ~ 2560*2560 解析度範圍內,物體定位效果較為魯棒,在此範圍之外檢測精度可能會下降(偶發檢測框漂移現象)。
如需將定位結果繪製到原圖可參見常見問題。
二維定位
| 可視化展示二維定位效果
|
文檔解析
將映像類的文檔(如掃描件/圖片PDF)解析為 QwenVL HTML 或 QwenVL Markdown 格式,該格式不僅能精準識別文本,還能擷取映像、表格等元素的位置資訊。Qwen3-VL模型新增解析為 Markdown 格式的能力。
推薦提示詞如下:qwenvl html(解析為HTML格式)或qwenvl markdown(解析為Markdown格式)
qwenvl markdown。 |
可視化展示效果 |
視頻理解
分析視頻內容,如對具體事件進行定位並擷取時間戳記、產生關鍵時間段的摘要等。
請你描述下視頻中的人物的一系列動作,以JSON格式輸出開始時間(start_time)、結束時間(end_time)、事件(event),請使用HH:mm:ss表示 時間戳記。 | { "events": [ { "start_time": "00:00:00", "end_time": "00:00:05", "event": "人物手持一個紙箱走向桌子,並將紙箱放在桌上。" }, { "start_time": "00:00:05", "end_time": "00:00:15", "event": "人物拿起掃描槍,對準紙箱上的標籤進行掃描。" }, { "start_time": "00:00:15", "end_time": "00:00:21", "event": "人物將掃描槍放回原位,然後拿起筆在筆記本上記錄資訊。"}] } |
核心能力
開啟/關閉思考模式
qwen3-vl-plus、qwen3-vl-flash系列模型屬於混合思考模型,模型可以在思考後回複,也可直接回複;通過
enable_thinking參數控制是否開啟思考模式:true:開啟思考模式false(預設):關閉思考模式
qwen3-vl-235b-a22b-thinking等帶thinking尾碼的屬於僅思考模型,模型總會在回複前進行思考,且無法關閉。
模型配置:在非 Agent 工具調用的通用對話情境下,為保持最佳效果,建議不設定
System Message,可將模型角色設定、輸出格式要求等指令通過User Message傳入。優先使用流式輸出: 開啟思考模式時,支援流式和非流式兩種輸出方式。為避免因響應內容過長導致逾時,建議優先使用流式輸出方式。
限制思考長度:深度思考模型有時會輸出冗長的推理過程,可使用
thinking_budget參數限制思考過程的長度。若模型思考過程產生的 Token 數超過thinking_budget,推理內容會進行截斷並立刻開始產生最終回複內容。thinking_budget預設值為模型的最大思維鏈長度,請參見模型列表。
OpenAI 相容
enable_thinking非 OpenAI 標準參數,若使用 OpenAI Python SDK 請通過 extra_body傳入。
import os
from openai import OpenAI
client = OpenAI(
# 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
api_key=os.getenv("DASHSCOPE_API_KEY"),
# 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1
base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
)
reasoning_content = "" # 定義完整思考過程
answer_content = "" # 定義完整回複
is_answering = False # 判斷是否結束思考過程並開始回複
enable_thinking = True
# 建立聊天完成請求
completion = client.chat.completions.create(
model="qwen3-vl-plus",
messages=[
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {
"url": "https://img.alicdn.com/imgextra/i1/O1CN01gDEY8M1W114Hi3XcN_!!6000000002727-0-tps-1024-406.jpg"
},
},
{"type": "text", "text": "這道題怎麼解答?"},
],
},
],
stream=True,
# enable_thinking 參數開啟思考過程,thinking_budget 參數設定最大推理過程 Token 數
# qwen3-vl-plus、 qwen3-vl-flash可通過enable_thinking開啟或關閉思考、對於qwen3-vl-235b-a22b-thinking等帶thinking尾碼的模型,enable_thinking僅支援設定為開啟,對其他Qwen-VL模型均不適用
extra_body={
'enable_thinking': enable_thinking,
"thinking_budget": 81920},
# 解除以下注釋會在最後一個chunk返回Token使用量
# stream_options={
# "include_usage": True
# }
)
if enable_thinking:
print("\n" + "=" * 20 + "思考過程" + "=" * 20 + "\n")
for chunk in completion:
# 如果chunk.choices為空白,則列印usage
if not chunk.choices:
print("\nUsage:")
print(chunk.usage)
else:
delta = chunk.choices[0].delta
# 列印思考過程
if hasattr(delta, 'reasoning_content') and delta.reasoning_content != None:
print(delta.reasoning_content, end='', flush=True)
reasoning_content += delta.reasoning_content
else:
# 開始回複
if delta.content != "" and is_answering is False:
print("\n" + "=" * 20 + "完整回複" + "=" * 20 + "\n")
is_answering = True
# 列印回複過程
print(delta.content, end='', flush=True)
answer_content += delta.content
# print("=" * 20 + "完整思考過程" + "=" * 20 + "\n")
# print(reasoning_content)
# print("=" * 20 + "完整回複" + "=" * 20 + "\n")
# print(answer_content)import OpenAI from "openai";
// 初始化 openai 用戶端
const openai = new OpenAI({
// 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
// 若沒有配置環境變數,請用百鍊API Key將下行替換為:apiKey: "sk-xxx"
apiKey: process.env.DASHSCOPE_API_KEY,
// 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為https://dashscope.aliyuncs.com/compatible-mode/v1
baseURL: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
});
let reasoningContent = '';
let answerContent = '';
let isAnswering = false;
let enableThinking = true;
let messages = [
{
role: "user",
content: [
{ type: "image_url", image_url: { "url": "https://img.alicdn.com/imgextra/i1/O1CN01gDEY8M1W114Hi3XcN_!!6000000002727-0-tps-1024-406.jpg" } },
{ type: "text", text: "解答這道題" },
]
}]
async function main() {
try {
const stream = await openai.chat.completions.create({
model: 'qwen3-vl-plus',
messages: messages,
stream: true,
// 注意:在 Node.js SDK,enableThinking 這樣的非標準參數作為頂層屬性傳遞的,無需放在 extra_body 中
enable_thinking: enableThinking,
thinking_budget: 81920
});
if (enableThinking){console.log('\n' + '='.repeat(20) + '思考過程' + '='.repeat(20) + '\n');}
for await (const chunk of stream) {
if (!chunk.choices?.length) {
console.log('\nUsage:');
console.log(chunk.usage);
continue;
}
const delta = chunk.choices[0].delta;
// 處理思考過程
if (delta.reasoning_content) {
process.stdout.write(delta.reasoning_content);
reasoningContent += delta.reasoning_content;
}
// 處理正式回複
else if (delta.content) {
if (!isAnswering) {
console.log('\n' + '='.repeat(20) + '完整回複' + '='.repeat(20) + '\n');
isAnswering = true;
}
process.stdout.write(delta.content);
answerContent += delta.content;
}
}
} catch (error) {
console.error('Error:', error);
}
}
main();# ======= 重要提示 =======
# 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
# 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# === 執行時請刪除該注釋 ===
curl --location 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"model": "qwen3-vl-plus",
"messages": [
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {
"url": "https://img.alicdn.com/imgextra/i1/O1CN01gDEY8M1W114Hi3XcN_!!6000000002727-0-tps-1024-406.jpg"
}
},
{
"type": "text",
"text": "請解答這道題"
}
]
}
],
"stream":true,
"stream_options":{"include_usage":true},
"enable_thinking": true,
"thinking_budget": 81920
}'DashScope
import os
import dashscope
from dashscope import MultiModalConversation
# 若使用新加坡地區的模型,請取消下列注釋
# dashscope.base_http_api_url = "https://dashscope-intl.aliyuncs.com/api/v1"
enable_thinking=True
messages = [
{
"role": "user",
"content": [
{"image": "https://img.alicdn.com/imgextra/i1/O1CN01gDEY8M1W114Hi3XcN_!!6000000002727-0-tps-1024-406.jpg"},
{"text": "解答這道題?"}
]
}
]
response = MultiModalConversation.call(
# 若沒有配置環境變數,請用百鍊API Key將下行替換為:api_key="sk-xxx",
# 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
api_key=os.getenv('DASHSCOPE_API_KEY'),
model="qwen3-vl-plus",
messages=messages,
stream=True,
# enable_thinking 參數開啟思考過程
# qwen3-vl-plus、 qwen3-vl-flash可通過enable_thinking開啟或關閉思考,對於qwen3-vl-235b-a22b-thinking等帶thinking尾碼的模型,enable_thinking僅支援設定為開啟,對其他Qwen-VL模型均不適用
enable_thinking=enable_thinking,
# thinking_budget 參數設定最大推理過程 Token 數
thinking_budget=81920,
)
# 定義完整思考過程
reasoning_content = ""
# 定義完整回複
answer_content = ""
# 判斷是否結束思考過程並開始回複
is_answering = False
if enable_thinking:
print("=" * 20 + "思考過程" + "=" * 20)
for chunk in response:
# 如果思考過程與回複皆為空白,則忽略
message = chunk.output.choices[0].message
reasoning_content_chunk = message.get("reasoning_content", None)
if (chunk.output.choices[0].message.content == [] and
reasoning_content_chunk == ""):
pass
else:
# 如果當前為思考過程
if reasoning_content_chunk != None and chunk.output.choices[0].message.content == []:
print(chunk.output.choices[0].message.reasoning_content, end="")
reasoning_content += chunk.output.choices[0].message.reasoning_content
# 如果當前為回複
elif chunk.output.choices[0].message.content != []:
if not is_answering:
print("\n" + "=" * 20 + "完整回複" + "=" * 20)
is_answering = True
print(chunk.output.choices[0].message.content[0]["text"], end="")
answer_content += chunk.output.choices[0].message.content[0]["text"]
# 如果您需要列印完整思考過程與完整回複,請將以下代碼解除注釋後運行
# print("=" * 20 + "完整思考過程" + "=" * 20 + "\n")
# print(f"{reasoning_content}")
# print("=" * 20 + "完整回複" + "=" * 20 + "\n")
# print(f"{answer_content}")// dashscope SDK的版本 >= 2.21.10
import java.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import io.reactivex.Flowable;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.exception.InputRequiredException;
import java.lang.System;
import com.alibaba.dashscope.utils.Constants;
public class Main {
static {Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";}
private static final Logger logger = LoggerFactory.getLogger(Main.class);
private static StringBuilder reasoningContent = new StringBuilder();
private static StringBuilder finalContent = new StringBuilder();
private static boolean isFirstPrint = true;
private static void handleGenerationResult(MultiModalConversationResult message) {
String re = message.getOutput().getChoices().get(0).getMessage().getReasoningContent();
String reasoning = Objects.isNull(re)?"":re; // 預設值
List<Map<String, Object>> content = message.getOutput().getChoices().get(0).getMessage().getContent();
if (!reasoning.isEmpty()) {
reasoningContent.append(reasoning);
if (isFirstPrint) {
System.out.println("====================思考過程====================");
isFirstPrint = false;
}
System.out.print(reasoning);
}
if (Objects.nonNull(content) && !content.isEmpty()) {
Object text = content.get(0).get("text");
finalContent.append(content.get(0).get("text"));
if (!isFirstPrint) {
System.out.println("\n====================完整回複====================");
isFirstPrint = true;
}
System.out.print(text);
}
}
public static MultiModalConversationParam buildMultiModalConversationParam(MultiModalMessage Msg) {
return MultiModalConversationParam.builder()
// 若沒有配置環境變數,請用百鍊API Key將下行替換為:.apiKey("sk-xxx")
// 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.model("qwen3-vl-plus")
.messages(Arrays.asList(Msg))
.enableThinking(true)
.thinkingBudget(81920)
.incrementalOutput(true)
.build();
}
public static void streamCallWithMessage(MultiModalConversation conv, MultiModalMessage Msg)
throws NoApiKeyException, ApiException, InputRequiredException, UploadFileException {
MultiModalConversationParam param = buildMultiModalConversationParam(Msg);
Flowable<MultiModalConversationResult> result = conv.streamCall(param);
result.blockingForEach(message -> {
handleGenerationResult(message);
});
}
public static void main(String[] args) {
try {
MultiModalConversation conv = new MultiModalConversation();
MultiModalMessage userMsg = MultiModalMessage.builder()
.role(Role.USER.getValue())
.content(Arrays.asList(Collections.singletonMap("image", "https://img.alicdn.com/imgextra/i1/O1CN01gDEY8M1W114Hi3XcN_!!6000000002727-0-tps-1024-406.jpg"),
Collections.singletonMap("text", "請解答這道題")))
.build();
streamCallWithMessage(conv, userMsg);
// 列印最終結果
// if (reasoningContent.length() > 0) {
// System.out.println("\n====================完整回複====================");
// System.out.println(finalContent.toString());
// }
} catch (ApiException | NoApiKeyException | UploadFileException | InputRequiredException e) {
logger.error("An exception occurred: {}", e.getMessage());
}
System.exit(0);
}
}# ======= 重要提示 =======
# 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
# === 執行時請刪除該注釋 ===
curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-H 'X-DashScope-SSE: enable' \
-d '{
"model": "qwen3-vl-plus",
"input":{
"messages":[
{
"role": "user",
"content": [
{"image": "https://img.alicdn.com/imgextra/i1/O1CN01gDEY8M1W114Hi3XcN_!!6000000002727-0-tps-1024-406.jpg"},
{"text": "請解答這道題"}
]
}
]
},
"parameters":{
"enable_thinking": true,
"incremental_output": true,
"thinking_budget": 81920
}
}'多映像輸入
通義千問VL 模型支援在單次請求中傳入多張圖片,可用於商品對比、多頁文檔處理等任務。實現時只需在user message 的content數組中包含多個圖片對象即可。
圖片數量受模型圖文總 Token 上限的限制,所有圖片和文本的總 Token 數必須小於模型的最大輸入。
OpenAI相容
Python
import os
from openai import OpenAI
client = OpenAI(
# 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
api_key=os.getenv("DASHSCOPE_API_KEY"),
# 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1
base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
model="qwen3-vl-plus", # 此處以qwen3-vl-plus為例,可按需更換模型名稱。模型列表:https://www.alibabacloud.com/help/model-studio/getting-started/models
messages=[
{"role": "user","content": [
{"type": "image_url","image_url": {"url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241022/emyrja/dog_and_girl.jpeg"},},
{"type": "image_url","image_url": {"url": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/tiger.png"},},
{"type": "text", "text": "這些圖描繪了什麼內容?"},
],
}
],
)
print(completion.choices[0].message.content)返回結果
圖1中是一位女士和一隻拉布拉多犬在海灘上互動的情境。女士穿著格子襯衫,坐在沙灘上,與狗進行握手的動作,背景是海浪和天空,整個畫面充滿了溫馨和愉快的氛圍。
圖2中是一隻老虎在森林中行走的情境。老虎的毛色是橙色和黑色條紋相間,它正向前邁步,周圍是茂密的樹木和植被,地面上覆蓋著落葉,整個畫面給人一種野生自然的感覺。Node.js
import OpenAI from "openai";
const openai = new OpenAI(
{
// 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
// 若沒有配置環境變數,請用百鍊API Key將下行替換為:apiKey: "sk-xxx"
apiKey: process.env.DASHSCOPE_API_KEY,
// 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1
baseURL: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
}
);
async function main() {
const response = await openai.chat.completions.create({
model: "qwen3-vl-plus", // 此處以qwen3-vl-plus為例,可按需更換模型名稱。模型列表:https://www.alibabacloud.com/help/model-studio/getting-started/models
messages: [
{role: "user",content: [
{type: "image_url",image_url: {"url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241022/emyrja/dog_and_girl.jpeg"}},
{type: "image_url",image_url: {"url": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/tiger.png"}},
{type: "text", text: "這些圖描繪了什麼內容?" },
]}]
});
console.log(response.choices[0].message.content);
}
main()返回結果
第一張圖片中,一個人和一隻狗在海灘上互動。人穿著格子襯衫,狗戴著項圈,他們似乎在握手或擊掌。
第二張圖片中,一隻老虎在森林中行走。老虎的毛色是橙色和黑色條紋,背景是綠色的樹木和植被。curl
# ======= 重要提示 =======
# 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
# === 執行時請刪除該注釋 ===
curl -X POST https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "qwen3-vl-plus",
"messages": [
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {
"url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241022/emyrja/dog_and_girl.jpeg"
}
},
{
"type": "image_url",
"image_url": {
"url": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/tiger.png"
}
},
{
"type": "text",
"text": "這些圖描繪了什麼內容?"
}
]
}
]
}'返回結果
{
"choices": [
{
"message": {
"content": "圖1中是一位女士和一隻拉布拉多犬在海灘上互動的情境。女士穿著格子襯衫,坐在沙灘上,與狗進行握手的動作,背景是海景和日落的天空,整個畫面顯得非常溫馨和諧。\n\n圖2中是一隻老虎在森林中行走的情境。老虎的毛色是橙色和黑色條紋相間,它正向前邁步,周圍是茂密的樹木和植被,地面上覆蓋著落葉,整個畫面充滿了自然的野性和生機。",
"role": "assistant"
},
"finish_reason": "stop",
"index": 0,
"logprobs": null
}
],
"object": "chat.completion",
"usage": {
"prompt_tokens": 2497,
"completion_tokens": 109,
"total_tokens": 2606
},
"created": 1725948561,
"system_fingerprint": null,
"model": "qwen3-vl-plus",
"id": "chatcmpl-0fd66f46-b09e-9164-a84f-3ebbbedbac15"
}DashScope
Python
import os
import dashscope
# 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
messages = [
{
"role": "user",
"content": [
{"image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241022/emyrja/dog_and_girl.jpeg"},
{"image": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/tiger.png"},
{"text": "這些圖描繪了什麼內容?"}
]
}
]
response = dashscope.MultiModalConversation.call(
# 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# 若沒有配置環境變數,請用百鍊API Key將下行替換為:api_key="sk-xxx"
api_key=os.getenv('DASHSCOPE_API_KEY'),
model='qwen3-vl-plus', # 此處以qwen3-vl-plus為例,可按需更換模型名稱。模型列表:https://www.alibabacloud.com/help/zh/model-studio/getting-started/models
messages=messages
)
print(response.output.choices[0].message.content[0]["text"])返回結果
這些圖片展示了一些動物和自然情境。第一張圖片中,一個人和一隻狗在海灘上互動。第二張圖片是一隻老虎在森林中行走Java
import java.util.Arrays;
import java.util.Collections;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;
public class Main {
static {
// 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/api/v1
Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
}
public static void simpleMultiModalConversationCall()
throws ApiException, NoApiKeyException, UploadFileException {
MultiModalConversation conv = new MultiModalConversation();
MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
.content(Arrays.asList(
Collections.singletonMap("image", "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241022/emyrja/dog_and_girl.jpeg"),
Collections.singletonMap("image", "https://dashscope.oss-cn-beijing.aliyuncs.com/images/tiger.png"),
Collections.singletonMap("text", "這些圖描繪了什麼內容?"))).build();
MultiModalConversationParam param = MultiModalConversationParam.builder()
// 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.model("qwen3-vl-plus") // 此處以qwen3-vl-plus為例,可按需更換模型名稱。模型列表:https://www.alibabacloud.com/help/model-studio/getting-started/models
.messages(Arrays.asList(userMessage))
.build();
MultiModalConversationResult result = conv.call(param);
System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text")); }
public static void main(String[] args) {
try {
simpleMultiModalConversationCall();
} catch (ApiException | NoApiKeyException | UploadFileException e) {
System.out.println(e.getMessage());
}
System.exit(0);
}
}返回結果
這些圖片展示了一些動物和自然情境。
1. 第一張圖片:一個女人和一隻狗在海灘上互動。女人穿著格子襯衫,坐在沙灘上,狗戴著項圈,伸出爪子與女人握手。
2. 第二張圖片:一隻老虎在森林中行走。老虎的毛色是橙色和黑色條紋,背景是樹木和樹葉。curl
# ======= 重要提示 =======
# 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
# 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# === 執行時請刪除該注釋 ===
curl --location 'https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"model": "qwen3-vl-plus",
"input":{
"messages":[
{
"role": "user",
"content": [
{"image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241022/emyrja/dog_and_girl.jpeg"},
{"image": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/tiger.png"},
{"text": "這些圖展現了什麼內容?"}
]
}
]
}
}'返回結果
{
"output": {
"choices": [
{
"finish_reason": "stop",
"message": {
"role": "assistant",
"content": [
{
"text": "這些圖片展示了一些動物和自然情境。第一張圖片中,一個人和一隻狗在海灘上互動。第二張圖片是一隻老虎在森林中行走。"
}
]
}
}
]
},
"usage": {
"output_tokens": 81,
"input_tokens": 1277,
"image_tokens": 2497
},
"request_id": "ccf845a3-dc33-9cda-b581-20fe7dc23f70"
}視頻理解
通義千問VL模型支援對視頻內容進行理解,檔案形式包括映像列表(視訊框架)或視頻檔案。
建議使用效能較優的最新版或近期快照版模型理解視頻檔案。
視頻檔案
視頻抽幀說明
通義千問VL 模型通過從視頻中提取幀序列進行內容分析,抽幀的頻率決定了模型分析的精細度,不同 SDK 抽幀頻率不同:
使用
DashScope SDK:可通過
fps參數來控制抽幀間隔(每隔秒抽取一幀),該參數範圍為 [0.1, 10]且預設值為2.0。建議為高速運動情境設定較高fps,為靜態或長視頻設定較低fps。
使用
OpenAI相容SDK:採用固定頻率抽幀(每0.5秒1幀),不支援自訂。
以下是理解線上視頻(通過URL指定)的範例程式碼。瞭解如何傳入本地檔案。
OpenAI相容
使用OpenAI SDK或HTTP方式向通義千問VL模型直接輸入視頻檔案時,需要將使用者訊息中的"type"參數設為"video_url"。
Python
import os
from openai import OpenAI
client = OpenAI(
# 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# 若沒有配置環境變數,請用百鍊API Key將下行替換為:api_key="sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
# 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1
base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
model="qwen3-vl-plus",
messages=[
{"role": "user","content": [{
# 直接傳入的視訊檔案時,請將type的值設定為video_url
# 使用OpenAI SDK時,視頻檔案預設每間隔0.5秒抽取一幀,且不支援修改,如需自訂抽幀頻率,請使用DashScope SDK.
"type": "video_url",
"video_url": {"url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241115/cqqkru/1.mp4"}},
{"type": "text","text": "這段視頻的內容是什麼?"}]
}]
)
print(completion.choices[0].message.content)Node.js
import OpenAI from "openai";
const openai = new OpenAI(
{
// 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
// 若沒有配置環境變數,請用百鍊API Key將下行替換為:apiKey: "sk-xxx"
apiKey: process.env.DASHSCOPE_API_KEY,
// 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1
baseURL: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
}
);
async function main() {
const response = await openai.chat.completions.create({
model: "qwen3-vl-plus",
messages: [
{role: "user",content: [
// 直接傳入的視訊檔案時,請將type的值設定為video_url
// 使用OpenAI SDK時,視頻檔案預設每間隔0.5秒抽取一幀,且不支援修改,如需自訂抽幀頻率,請使用DashScope SDK.
{type: "video_url", video_url: {"url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241115/cqqkru/1.mp4"}},
{type: "text", text: "這段視頻的內容是什麼?" },
]}]
});
console.log(response.choices[0].message.content);
}
main()curl
# ======= 重要提示 =======
# 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
# === 執行時請刪除該注釋 ===
curl -X POST https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "qwen3-vl-plus",
"messages": [
{"role": "user","content": [{"type": "video_url","video_url": {"url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241115/cqqkru/1.mp4"}},
{"type": "text","text": "這段視頻的內容是什麼?"}]}]
}'DashScope
Python
import dashscope
import os
# 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
messages = [
{"role": "user",
"content": [
# fps 可參數控制視頻抽幀頻率,表示每隔 1/fps 秒抽取一幀,完整用法請參見:https://www.alibabacloud.com/help/zh/model-studio/use-qwen-by-calling-api?#2ed5ee7377fum
{"video": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241115/cqqkru/1.mp4","fps":2},
{"text": "這段視頻的內容是什麼?"}
]
}
]
response = dashscope.MultiModalConversation.call(
# 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# 若沒有配置環境變數, 請用百鍊API Key將下行替換為: api_key ="sk-xxx"
api_key=os.getenv('DASHSCOPE_API_KEY'),
model='qwen3-vl-plus',
messages=messages
)
print(response.output.choices[0].message.content[0]["text"])Java
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;
public class Main {
static {
// 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/api/v1
Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
}
public static void simpleMultiModalConversationCall()
throws ApiException, NoApiKeyException, UploadFileException {
MultiModalConversation conv = new MultiModalConversation();
// fps參數控制視頻抽幀頻率,表示每隔 1/fps 秒抽取一幀,完整用法請參見:https://www.alibabacloud.com/help/zh/model-studio/use-qwen-by-calling-api?#2ed5ee7377fum
Map<String, Object> params = new HashMap<>();
params.put("video", "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241115/cqqkru/1.mp4");
params.put("fps", 2);
MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
.content(Arrays.asList(
params,
Collections.singletonMap("text", "這段視頻的內容是什麼?"))).build();
MultiModalConversationParam param = MultiModalConversationParam.builder()
// 如果使用華北2(北京)地區的模型,需要使用華北2(北京)地區的 API Key,擷取連結:https://bailian.console.alibabacloud.com/?tab=model#/api-key
// 若沒有配置環境變數,請用百鍊API Key將下行替換為:.apiKey("sk-xxx")
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.model("qwen3-vl-plus")
.messages(Arrays.asList(userMessage))
.build();
MultiModalConversationResult result = conv.call(param);
System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text"));
}
public static void main(String[] args) {
try {
simpleMultiModalConversationCall();
} catch (ApiException | NoApiKeyException | UploadFileException e) {
System.out.println(e.getMessage());
}
System.exit(0);
}
}curl
# ======= 重要提示 =======
# 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
# 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# === 執行時請刪除該注釋 ===
curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "qwen3-vl-plus",
"input":{
"messages":[
{"role": "user","content": [{"video": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241115/cqqkru/1.mp4","fps":2},
{"text": "這段視頻的內容是什麼?"}]}]}
}'映像列表
映像列表數量限制
qwen3-vl-plus系列:最少傳入 4 張圖片,最多 2000 張圖片qwen3-vl-flash系列、Qwen2.5-VL、QVQ系列模型:最少傳入 4 張圖片,最多 512 張圖片其他模型:最少傳入 4 張圖片,最多 80 張圖片
視頻抽幀說明
當視頻以映像列表(即預先抽取的視訊框架)傳入時,可通過fps參數告知模型視訊框架之間的時間間隔,這能協助模型更準確地理解事件的順序、期間和動態變化。
DashScope SDK:
支援通過
fps參數指定原始視頻的抽幀率,表示視訊框架是每隔秒從原始視頻中抽取的。該參數支援 Qwen2.5-VL、Qwen3-VL模型。 OpenAI 相容 SDK:
不支援
fps參數。模型將預設視訊框架是按照每 0.5 秒一幀的頻率抽取的。
以下是理解線上視訊框架(通過URL指定)的範例程式碼。瞭解如何傳入本地檔案。
OpenAI相容
使用OpenAI SDK或HTTP方式向通義千問VL模型輸入圖片列表形式的視頻時,需要將使用者訊息中的"type"參數設為"video"。
Python
import os
from openai import OpenAI
client = OpenAI(
# 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# 若沒有配置環境變數,請用百鍊API Key將下行替換為:api_key="sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
# 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1
base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
model="qwen3-vl-plus", # 此處以qwen3-vl-plus為例,可按需更換模型名稱。模型列表:https://www.alibabacloud.com/help/model-studio/getting-started/models
messages=[{"role": "user","content": [
# 傳入映像列表時,使用者訊息中的"type"參數為"video"
# 使用OpenAI SDK時,映像列表預設是以每隔0.5秒從視頻中抽取出來的,且不支援修改。如需自訂抽幀頻率,請使用DashScope SDK.
{"type": "video","video": ["https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/xzsgiz/football1.jpg",
"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/tdescd/football2.jpg",
"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/zefdja/football3.jpg",
"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/aedbqh/football4.jpg"]},
{"type": "text","text": "描述這個視頻的具體過程"},
]}]
)
print(completion.choices[0].message.content)Node.js
// 確保之前在 package.json 中指定了 "type": "module"
import OpenAI from "openai";
const openai = new OpenAI({
// 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
// 若沒有配置環境變數,請用百鍊API Key將下行替換為:apiKey: "sk-xxx",
apiKey: process.env.DASHSCOPE_API_KEY,
// 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1
baseURL: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
});
async function main() {
const response = await openai.chat.completions.create({
model: "qwen3-vl-plus", // 此處以qwen3-vl-plus為例,可按需更換模型名稱。模型列表:https://www.alibabacloud.com/help/model-studio/getting-started/models
messages: [{
role: "user",
content: [
{
// 傳入映像列表時,使用者訊息中的"type"參數為"video"
// 使用OpenAI SDK時,映像列表預設是以每隔0.5秒從視頻中抽取出來的,且不支援修改。如需自訂抽幀頻率,請使用DashScope SDK.
type: "video",
video: [
"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/xzsgiz/football1.jpg",
"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/tdescd/football2.jpg",
"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/zefdja/football3.jpg",
"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/aedbqh/football4.jpg"
]
},
{
type: "text",
text: "描述這個視頻的具體過程"
}
]
}]
});
console.log(response.choices[0].message.content);
}
main();curl
# ======= 重要提示 =======
# 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
# === 執行時請刪除該注釋 ===
curl -X POST https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "qwen3-vl-plus",
"messages": [{"role": "user",
"content": [{"type": "video",
"video": ["https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/xzsgiz/football1.jpg",
"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/tdescd/football2.jpg",
"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/zefdja/football3.jpg",
"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/aedbqh/football4.jpg"]},
{"type": "text",
"text": "描述這個視頻的具體過程"}]}]
}'DashScope
Python
import os
import dashscope
# 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
messages = [{"role": "user",
"content": [
# 若模型屬於Qwen2.5-VL、Qwen3-VL系列且傳入的是映像列表時,可設定fps參數,表示映像列表是由原視頻每隔 1/fps 秒抽取的
{"video":["https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/xzsgiz/football1.jpg",
"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/tdescd/football2.jpg",
"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/zefdja/football3.jpg",
"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/aedbqh/football4.jpg"],
"fps":2},
{"text": "描述這個視頻的具體過程"}]}]
response = dashscope.MultiModalConversation.call(
# 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# 若沒有配置環境變數,請用百鍊API Key將下行替換為:api_key="sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
model='qwen3-vl-plus', # 此處以qwen3-vl-plus為例,可按需更換模型名稱。模型列表:https://www.alibabacloud.com/help/model-studio/getting-started/models
messages=messages
)
print(response.output.choices[0].message.content[0]["text"])Java
// DashScope SDK版本需要不低於2.18.3
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;
public class Main {
static {
// 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/api/v1
Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
}
private static final String MODEL_NAME = "qwen3-vl-plus"; // 此處以qwen3-vl-plus為例,可按需更換模型名稱。模型列表:https://www.alibabacloud.com/help/model-studio/getting-started/models
public static void videoImageListSample() throws ApiException, NoApiKeyException, UploadFileException {
MultiModalConversation conv = new MultiModalConversation();
// 若模型屬於Qwen2.5-VL、Qwen3-VL系列且傳入的是映像列表時,可設定fps參數,表示映像列表是由原視頻每隔 1/fps 秒抽取的
Map<String, Object> params = new HashMap<>();
params.put("video", Arrays.asList("https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/xzsgiz/football1.jpg",
"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/tdescd/football2.jpg",
"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/zefdja/football3.jpg",
"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/aedbqh/football4.jpg"));
params.put("fps", 2);
MultiModalMessage userMessage = MultiModalMessage.builder()
.role(Role.USER.getValue())
.content(Arrays.asList(
params,
Collections.singletonMap("text", "描述這個視頻的具體過程")))
.build();
MultiModalConversationParam param = MultiModalConversationParam.builder()
// 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
// 若沒有配置環境變數,請用百鍊API Key將下行替換為:.apiKey("sk-xxx")
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.model(MODEL_NAME)
.messages(Arrays.asList(userMessage)).build();
MultiModalConversationResult result = conv.call(param);
System.out.print(result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text"));
}
public static void main(String[] args) {
try {
videoImageListSample();
} catch (ApiException | NoApiKeyException | UploadFileException e) {
System.out.println(e.getMessage());
}
System.exit(0);
}
}curl
# ======= 重要提示 =======
# 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
# 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# === 執行時請刪除該注釋 ===
curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "qwen3-vl-plus",
"input": {
"messages": [
{
"role": "user",
"content": [
{
"video": [
"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/xzsgiz/football1.jpg",
"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/tdescd/football2.jpg",
"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/zefdja/football3.jpg",
"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/aedbqh/football4.jpg"
],
"fps":2
},
{
"text": "描述這個視頻的具體過程"
}
]
}
]
}
}'傳入本地檔案(Base 64 編碼或檔案路徑)
通義千問VL 提供兩種本地檔案上傳方式:Base 64 編碼上傳和檔案路徑直接上傳。可根據檔案大小、SDK類型選擇上傳方式,具體建議請參見如何選擇檔案上傳方式;兩種方式均需滿足映像限制中對檔案的要求。
Base64 編碼上傳
將檔案轉換為 Base 64 編碼字串,再傳入模型。適用於 OpenAI 和 DashScope SDK 及 HTTP 方式
檔案路徑上傳
直接向模型傳入本地檔案路徑。僅 DashScope Python 和 Java SDK 支援,不支援 DashScope HTTP 和OpenAI 相容方式。
請您參考下表,結合您的程式設計語言與作業系統指定檔案的路徑。
映像
檔案路徑傳入
Python
import os
import dashscope
# 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
# 將xxx/eagle.png替換為你本地映像的絕對路徑
local_path = "xxx/eagle.png"
image_path = f"file://{local_path}"
messages = [
{'role':'user',
'content': [{'image': image_path},
{'text': '圖中描繪的是什麼景象?'}]}]
response = dashscope.MultiModalConversation.call(
# 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# 若沒有配置環境變數,請用百鍊API Key將下行替換為:api_key="sk-xxx"
api_key=os.getenv('DASHSCOPE_API_KEY'),
model='qwen3-vl-plus', # 此處以qwen3-vl-plus為例,可按需更換模型名稱。模型列表:https://www.alibabacloud.com/help/model-studio/getting-started/models
messages=messages)
print(response.output.choices[0].message.content[0]["text"])Java
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;
public class Main {
static {
// 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/api/v1
Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
}
public static void callWithLocalFile(String localPath)
throws ApiException, NoApiKeyException, UploadFileException {
String filePath = "file://"+localPath;
MultiModalConversation conv = new MultiModalConversation();
MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
.content(Arrays.asList(new HashMap<String, Object>(){{put("image", filePath);}},
new HashMap<String, Object>(){{put("text", "圖中描繪的是什麼景象?");}})).build();
MultiModalConversationParam param = MultiModalConversationParam.builder()
// 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
// 若沒有配置環境變數,請用百鍊API Key將下行替換為:.apiKey("sk-xxx")
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.model("qwen3-vl-plus") // 此處以qwen3-vl-plus為例,可按需更換模型名稱。模型列表:https://www.alibabacloud.com/help/model-studio/getting-started/models
.messages(Arrays.asList(userMessage))
.build();
MultiModalConversationResult result = conv.call(param);
System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text"));}
public static void main(String[] args) {
try {
// 將xxx/eagle.png替換為你本地映像的絕對路徑
callWithLocalFile("xxx/eagle.png");
} catch (ApiException | NoApiKeyException | UploadFileException e) {
System.out.println(e.getMessage());
}
System.exit(0);
}
}Base 64 編碼傳入
OpenAI相容
Python
from openai import OpenAI
import os
import base64
# 編碼函數: 將本地檔案轉換為 Base 64 編碼的字串
def encode_image(image_path):
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode("utf-8")
# 將xxxx/eagle.png替換為你本地映像的絕對路徑
base64_image = encode_image("xxx/eagle.png")
client = OpenAI(
# 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# 若沒有配置環境變數,請用百鍊API Key將下行替換為:api_key="sk-xxx"
api_key=os.getenv('DASHSCOPE_API_KEY'),
# 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1
base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
model="qwen3-vl-plus", # 此處以qwen3-vl-plus為例,可按需更換模型名稱。模型列表:https://www.alibabacloud.com/help/model-studio/getting-started/models
messages=[
{
"role": "user",
"content": [
{
"type": "image_url",
# 傳入Base64映像資料, 需要注意,映像格式(即image/{format})需要與支援的圖片列表中的Content Type保持一致。"f"是字串格式化的方法。
# PNG映像: f"data:image/png;base64,{base64_image}"
# JPEG映像: f"data:image/jpeg;base64,{base64_image}"
# WEBP映像: f"data:image/webp;base64,{base64_image}"
"image_url": {"url": f"data:image/png;base64,{base64_image}"},
},
{"type": "text", "text": "圖中描繪的是什麼景象?"},
],
}
],
)
print(completion.choices[0].message.content)Node.js
import OpenAI from "openai";
import { readFileSync } from 'fs';
const openai = new OpenAI(
{
// 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
// 若沒有配置環境變數,請用百鍊API Key將下行替換為:apiKey: "sk-xxx"
apiKey: process.env.DASHSCOPE_API_KEY,
// 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1
baseURL: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
}
);
const encodeImage = (imagePath) => {
const imageFile = readFileSync(imagePath);
return imageFile.toString('base64');
};
// 將xxx/eagle.png替換為你本地映像的絕對路徑
const base64Image = encodeImage("xxx/eagle.png")
async function main() {
const completion = await openai.chat.completions.create({
model: "qwen3-vl-plus", // 此處以qwen3-vl-plus為例,可按需更換模型名稱。模型列表:https://www.alibabacloud.com/help/model-studio/getting-started/models
messages: [
{"role": "user",
"content": [{"type": "image_url",
// 需要注意,傳入Base64,映像格式(即image/{format})需要與支援的圖片列表中的Content Type保持一致。
// PNG映像: data:image/png;base64,${base64Image}
// JPEG映像: data:image/jpeg;base64,${base64Image}
// WEBP映像: data:image/webp;base64,${base64Image}
"image_url": {"url": `data:image/png;base64,${base64Image}`},},
{"type": "text", "text": "圖中描繪的是什麼景象?"}]}]
});
console.log(completion.choices[0].message.content);
}
main();curl
將檔案轉換為 Base 64 編碼的字串的方法可參見範例程式碼;
為了便於展示,代碼中的
"data:image/jpg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAA...",該Base 64 編碼字串是截斷的。在實際使用中,請務必傳入完整的編碼字串。
# ======= 重要提示 =======
# 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
# === 執行時請刪除該注釋 ===
curl --location 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"model": "qwen3-vl-plus",
"messages": [
{
"role": "user",
"content": [
{"type": "image_url", "image_url": {"url": "data:image/jpg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAA"}},
{"type": "text", "text": "圖中描繪的是什麼景象?"}
]
}]
}'DashScope
Python
import base64
import os
import dashscope
# 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
# 編碼函數: 將本地檔案轉換為 Base 64 編碼的字串
def encode_image(image_path):
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode("utf-8")
# 將xxxx/eagle.png替換為你本地映像的絕對路徑
base64_image = encode_image("xxxx/eagle.png")
messages = [
{
"role": "user",
"content": [
# 需要注意,傳入Base64,映像格式(即image/{format})需要與支援的圖片列表中的Content Type保持一致。"f"是字串格式化的方法。
# PNG映像: f"data:image/png;base64,{base64_image}"
# JPEG映像: f"data:image/jpeg;base64,{base64_image}"
# WEBP映像: f"data:image/webp;base64,{base64_image}"
{"image": f"data:image/png;base64,{base64_image}"},
{"text": "圖中描繪的是什麼景象?"},
],
},
]
response = dashscope.MultiModalConversation.call(
# 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# 若沒有配置環境變數,請用百鍊API Key將下行替換為:api_key="sk-xxx"
api_key=os.getenv("DASHSCOPE_API_KEY"),
model="qwen3-vl-plus", # 此處以qwen3-vl-plus為例,可按需更換模型名稱。模型列表:https://www.alibabacloud.com/help/model-studio/getting-started/models
messages=messages,
)
print(response.output.choices[0].message.content[0]["text"])Java
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Base64;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import com.alibaba.dashscope.aigc.multimodalconversation.*;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;
public class Main {
static {
// 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/api/v1
Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
}
private static String encodeImageToBase64(String imagePath) throws IOException {
Path path = Paths.get(imagePath);
byte[] imageBytes = Files.readAllBytes(path);
return Base64.getEncoder().encodeToString(imageBytes);
}
public static void callWithLocalFile(String localPath) throws ApiException, NoApiKeyException, UploadFileException, IOException {
String base64Image = encodeImageToBase64(localPath); // Base64編碼
MultiModalConversation conv = new MultiModalConversation();
MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
.content(Arrays.asList(
new HashMap<String, Object>() {{ put("image", "data:image/png;base64," + base64Image); }},
new HashMap<String, Object>() {{ put("text", "圖中描繪的是什麼景象?"); }}
)).build();
MultiModalConversationParam param = MultiModalConversationParam.builder()
// 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.model("qwen3-vl-plus")
.messages(Arrays.asList(userMessage))
.build();
MultiModalConversationResult result = conv.call(param);
System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text"));
}
public static void main(String[] args) {
try {
// 將 xxx/eagle.png 替換為你本地映像的絕對路徑
callWithLocalFile("xxx/eagle.png");
} catch (ApiException | NoApiKeyException | UploadFileException | IOException e) {
System.out.println(e.getMessage());
}
System.exit(0);
}
}curl
將檔案轉換為 Base 64 編碼的字串的方法可參見範例程式碼;
為了便於展示,代碼中的
"data:image/jpg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAA...",該Base 64 編碼字串是截斷的。在實際使用中,請務必傳入完整的編碼字串。
# ======= 重要提示 =======
# 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
# 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# === 執行時請刪除該注釋 ===
curl -X POST https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "qwen3-vl-plus",
"input":{
"messages":[
{
"role": "user",
"content": [
{"image": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAA..."},
{"text": "圖中描繪的是什麼景象?"}
]
}
]
}
}'視頻檔案
以儲存在本地的test.mp4為例。
檔案路徑傳入
Python
import os
import dashscope
# 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
# 將xxxx/test.mp4替換為你本地視頻的絕對路徑
local_path = "xxx/test.mp4"
video_path = f"file://{local_path}"
messages = [
{'role':'user',
# fps參數控制視頻抽幀數量,表示每隔1/fps 秒抽取一幀
'content': [{'video': video_path,"fps":2},
{'text': '這段視頻描繪的是什麼景象?'}]}]
response = MultiModalConversation.call(
# 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# 若沒有配置環境變數,請用百鍊API Key將下行替換為:api_key="sk-xxx"
api_key=os.getenv('DASHSCOPE_API_KEY'),
model='qwen3-vl-plus',
messages=messages)
print(response.output.choices[0].message.content[0]["text"])Java
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;
public class Main {
static {
// 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/api/v1
Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
}
public static void callWithLocalFile(String localPath)
throws ApiException, NoApiKeyException, UploadFileException {
String filePath = "file://"+localPath;
MultiModalConversation conv = new MultiModalConversation();
MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
.content(Arrays.asList(new HashMap<String, Object>()
{{
put("video", filePath);// fps參數控制視頻抽幀數量,表示每隔1/fps 秒抽取一幀
put("fps", 2);
}},
new HashMap<String, Object>(){{put("text", "這段視頻描繪的是什麼景象?");}})).build();
MultiModalConversationParam param = MultiModalConversationParam.builder()
// 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
// 若沒有配置環境變數,請用百鍊API Key將下行替換為:.apiKey("sk-xxx")
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.model("qwen3-vl-plus")
.messages(Arrays.asList(userMessage))
.build();
MultiModalConversationResult result = conv.call(param);
System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text"));}
public static void main(String[] args) {
try {
// 將xxxx/test.mp4替換為你本地視頻的絕對路徑
callWithLocalFile("xxx/test.mp4");
} catch (ApiException | NoApiKeyException | UploadFileException e) {
System.out.println(e.getMessage());
}
System.exit(0);
}
}Base 64 編碼傳入
OpenAI相容
Python
from openai import OpenAI
import os
import base64
# 編碼函數: 將本地檔案轉換為 Base 64 編碼的字串
def encode_video(video_path):
with open(video_path, "rb") as video_file:
return base64.b64encode(video_file.read()).decode("utf-8")
# 將xxxx/test.mp4替換為你本地視頻的絕對路徑
base64_video = encode_video("xxx/test.mp4")
client = OpenAI(
# 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# 若沒有配置環境變數,請用百鍊API Key將下行替換為:api_key="sk-xxx"
api_key=os.getenv('DASHSCOPE_API_KEY'),
# 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1
base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
model="qwen3-vl-plus",
messages=[
{
"role": "user",
"content": [
{
# 直接傳入的視訊檔案時,請將type的值設定為video_url
"type": "video_url",
"video_url": {"url": f"data:video/mp4;base64,{base64_video}"},
},
{"type": "text", "text": "這段視頻描繪的是什麼景象?"},
],
}
],
)
print(completion.choices[0].message.content)Node.js
import OpenAI from "openai";
import { readFileSync } from 'fs';
const openai = new OpenAI(
{
// 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
// 若沒有配置環境變數,請用百鍊API Key將下行替換為:apiKey: "sk-xxx"
apiKey: process.env.DASHSCOPE_API_KEY,
// 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1
baseURL: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
}
);
const encodeVideo = (videoPath) => {
const videoFile = readFileSync(videoPath);
return videoFile.toString('base64');
};
// 將xxxx/test.mp4替換為你本地視頻的絕對路徑
const base64Video = encodeVideo("xxx/test.mp4")
async function main() {
const completion = await openai.chat.completions.create({
model: "qwen3-vl-plus",
messages: [
{"role": "user",
"content": [{
// 直接傳入的視訊檔案時,請將type的值設定為video_url
"type": "video_url",
"video_url": {"url": `data:video/mp4;base64,${base64Video}`}},
{"type": "text", "text": "這段視頻描繪的是什麼景象?"}]}]
});
console.log(completion.choices[0].message.content);
}
main();
curl
將檔案轉換為 Base 64 編碼的字串的方法可參見範例程式碼;
為了便於展示,代碼中的
"data:video/mp4;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAA...",該Base 64 編碼字串是截斷的。在實際使用中,請務必傳入完整的編碼字串。
# ======= 重要提示 =======
# 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
# === 執行時請刪除該注釋 ===
curl --location 'https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"model": "qwen3-vl-plus",
"messages": [
{
"role": "user",
"content": [
{"type": "video_url", "video_url": {"url": "data:video/mp4;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAA..."}},
{"type": "text", "text": "圖中描繪的是什麼景象?"}
]
}]
}'DashScope
Python
import base64
import os
import dashscope
# 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
# 編碼函數: 將本地檔案轉換為 Base 64 編碼的字串
def encode_video(video_path):
with open(video_path, "rb") as video_file:
return base64.b64encode(video_file.read()).decode("utf-8")
# 將xxxx/test.mp4替換為你本地視頻的絕對路徑
base64_video = encode_video("xxxx/test.mp4")
messages = [{'role':'user',
# fps參數控制視頻抽幀數量,表示每隔1/fps 秒抽取一幀
'content': [{'video': f"data:video/mp4;base64,{base64_video}","fps":2},
{'text': '這段視頻描繪的是什麼景象?'}]}]
response = dashscope.MultiModalConversation.call(
# 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# 若沒有配置環境變數,請用百鍊API Key將下行替換為:api_key="sk-xxx"
api_key=os.getenv('DASHSCOPE_API_KEY'),
model='qwen3-vl-plus',
messages=messages)
print(response.output.choices[0].message.content[0]["text"])Java
import java.io.IOException;
import java.util.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import com.alibaba.dashscope.aigc.multimodalconversation.*;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;
public class Main {
static {
// 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/api/v1
Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
}
private static String encodeVideoToBase64(String videoPath) throws IOException {
Path path = Paths.get(videoPath);
byte[] videoBytes = Files.readAllBytes(path);
return Base64.getEncoder().encodeToString(videoBytes);
}
public static void callWithLocalFile(String localPath)
throws ApiException, NoApiKeyException, UploadFileException, IOException {
String base64Video = encodeVideoToBase64(localPath); // Base64編碼
MultiModalConversation conv = new MultiModalConversation();
MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
.content(Arrays.asList(new HashMap<String, Object>()
{{
put("video", "data:video/mp4;base64," + base64Video);// fps參數控制視頻抽幀數量,表示每隔1/fps 秒抽取一幀
put("fps", 2);
}},
new HashMap<String, Object>(){{put("text", "這段視頻描繪的是什麼景象?");}})).build();
MultiModalConversationParam param = MultiModalConversationParam.builder()
// 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
// 若沒有配置環境變數,請用百鍊API Key將下行替換為:.apiKey("sk-xxx")
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.model("qwen3-vl-plus")
.messages(Arrays.asList(userMessage))
.build();
MultiModalConversationResult result = conv.call(param);
System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text"));
}
public static void main(String[] args) {
try {
// 將 xxx/test.mp4 替換為你本地映像的絕對路徑
callWithLocalFile("xxx/test.mp4");
} catch (ApiException | NoApiKeyException | UploadFileException | IOException e) {
System.out.println(e.getMessage());
}
System.exit(0);
}
}curl
將檔案轉換為 Base 64 編碼的字串的方法可參見範例程式碼;
為了便於展示,代碼中的
"f"data:video/mp4;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAA...",該Base 64 編碼字串是截斷的。在實際使用中,請務必傳入完整的編碼字串。
# ======= 重要提示 =======
# 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
# 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# === 執行時請刪除該注釋 ===
curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "qwen3-vl-plus",
"input":{
"messages":[
{
"role": "user",
"content": [
{"video": "data:video/mp4;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAA..."},
{"text": "圖中描繪的是什麼景象?"}
]
}
]
}
}'映像列表
以儲存在本地的football1.jpg、football2.jpg、football3.jpg、football4.jpg為例。
檔案路徑傳入
Python
import os
import dashscope
# 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
local_path1 = "football1.jpg"
local_path2 = "football2.jpg"
local_path3 = "football3.jpg"
local_path4 = "football4.jpg"
image_path1 = f"file://{local_path1}"
image_path2 = f"file://{local_path2}"
image_path3 = f"file://{local_path3}"
image_path4 = f"file://{local_path4}"
messages = [{'role':'user',
# 若模型屬於Qwen2.5-VL系列且傳入映像列表時,可設定fps參數,表示映像列表是由原視頻每隔 1/fps 秒抽取的,其他模型設定則不生效
'content': [{'video': [image_path1,image_path2,image_path3,image_path4],"fps":2},
{'text': '這段視頻描繪的是什麼景象?'}]}]
response = MultiModalConversation.call(
# 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# 若沒有配置環境變數,請用百鍊API Key將下行替換為:api_key="sk-xxx"
api_key=os.getenv('DASHSCOPE_API_KEY'),
model='qwen3-vl-plus', # 此處以qwen3-vl-plus為例,可按需更換模型名稱。模型列表:https://www.alibabacloud.com/help/model-studio/getting-started/models
messages=messages)
print(response.output.choices[0].message.content[0]["text"])Java
// DashScope SDK版本需要不低於2.18.3
import java.util.Arrays;
import java.util.Map;
import java.util.Collections;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;
public class Main {
static {
// 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/api/v1
Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
}
private static final String MODEL_NAME = "qwen3-vl-plus"; // 此處以qwen3-vl-plus為例,可按需更換模型名稱。模型列表:https://www.alibabacloud.com/help/model-studio/getting-started/models
public static void videoImageListSample(String localPath1, String localPath2, String localPath3, String localPath4)
throws ApiException, NoApiKeyException, UploadFileException {
MultiModalConversation conv = new MultiModalConversation();
String filePath1 = "file://" + localPath1;
String filePath2 = "file://" + localPath2;
String filePath3 = "file://" + localPath3;
String filePath4 = "file://" + localPath4;
Map<String, Object> params = new HashMap<>();
params.put("video", Arrays.asList(filePath1,filePath2,filePath3,filePath4));
// 若模型屬於Qwen2.5-VL系列且傳入映像列表時,可設定fps參數,表示映像列表是由原視頻每隔 1/fps 秒抽取的,其他模型設定則不生效
params.put("fps", 2);
MultiModalMessage userMessage = MultiModalMessage.builder()
.role(Role.USER.getValue())
.content(Arrays.asList(params,
Collections.singletonMap("text", "描述這個視頻的具體過程")))
.build();
MultiModalConversationParam param = MultiModalConversationParam.builder()
// 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
// 若沒有配置環境變數,請用百鍊API Key將下行替換為:.apiKey("sk-xxx")
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.model(MODEL_NAME)
.messages(Arrays.asList(userMessage)).build();
MultiModalConversationResult result = conv.call(param);
System.out.print(result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text"));
}
public static void main(String[] args) {
try {
videoImageListSample(
"xxx/football1.jpg",
"xxx/football2.jpg",
"xxx/football3.jpg",
"xxx/football4.jpg");
} catch (ApiException | NoApiKeyException | UploadFileException e) {
System.out.println(e.getMessage());
}
System.exit(0);
}
}Base 64 編碼傳入
OpenAI相容
Python
import os
from openai import OpenAI
import base64
# 編碼函數: 將本地檔案轉換為 Base 64 編碼的字串
def encode_image(image_path):
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode("utf-8")
base64_image1 = encode_image("football1.jpg")
base64_image2 = encode_image("football2.jpg")
base64_image3 = encode_image("football3.jpg")
base64_image4 = encode_image("football4.jpg")
client = OpenAI(
# 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# 若沒有配置環境變數,請用百鍊API Key將下行替換為:api_key="sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
# 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1
base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
model="qwen3-vl-plus", # 此處以qwen3-vl-plus為例,可按需更換模型名稱。模型列表:https://www.alibabacloud.com/help/model-studio/getting-started/models
messages=[
{"role": "user","content": [
{"type": "video","video": [
f"data:image/jpeg;base64,{base64_image1}",
f"data:image/jpeg;base64,{base64_image2}",
f"data:image/jpeg;base64,{base64_image3}",
f"data:image/jpeg;base64,{base64_image4}",]},
{"type": "text","text": "描述這個視頻的具體過程"},
]}]
)
print(completion.choices[0].message.content)Node.js
import OpenAI from "openai";
import { readFileSync } from 'fs';
const openai = new OpenAI(
{
// 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
// 若沒有配置環境變數,請用百鍊API Key將下行替換為:apiKey: "sk-xxx"
apiKey: process.env.DASHSCOPE_API_KEY,
// 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1
baseURL: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
}
);
const encodeImage = (imagePath) => {
const imageFile = readFileSync(imagePath);
return imageFile.toString('base64');
};
const base64Image1 = encodeImage("football1.jpg")
const base64Image2 = encodeImage("football2.jpg")
const base64Image3 = encodeImage("football3.jpg")
const base64Image4 = encodeImage("football4.jpg")
async function main() {
const completion = await openai.chat.completions.create({
model: "qwen3-vl-plus", // 此處以qwen3-vl-plus為例,可按需更換模型名稱。模型列表:https://www.alibabacloud.com/help/model-studio/getting-started/models
messages: [
{"role": "user",
"content": [{"type": "video",
// 需要注意,傳入Base64,映像格式(即image/{format})需要與支援的圖片列表中的Content Type保持一致。
// PNG映像: data:image/png;base64,${base64Image}
// JPEG映像: data:image/jpeg;base64,${base64Image}
// WEBP映像: data:image/webp;base64,${base64Image}
"video": [
`data:image/jpeg;base64,${base64Image1}`,
`data:image/jpeg;base64,${base64Image2}`,
`data:image/jpeg;base64,${base64Image3}`,
`data:image/jpeg;base64,${base64Image4}`]},
{"type": "text", "text": "這段視頻描繪的是什麼景象?"}]}]
});
console.log(completion.choices[0].message.content);
}
main();curl
將檔案轉換為 Base 64 編碼的字串的方法可參見範例程式碼;
為了便於展示,代碼中的
"data:image/jpg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAA...",該Base 64 編碼字串是截斷的。在實際使用中,請務必傳入完整的編碼字串。
# ======= 重要提示 =======
# 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
# 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# === 執行時請刪除該注釋 ===
curl -X POST https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "qwen3-vl-plus",
"messages": [{"role": "user",
"content": [{"type": "video",
"video": [
"data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAA...",
"data:image/jpeg;base64,nEpp6jpnP57MoWSyOWwrkXMJhHRCWYeFYb...",
"data:image/jpeg;base64,JHWQnJPc40GwQ7zERAtRMK6iIhnWw4080s...",
"data:image/jpeg;base64,adB6QOU5HP7dAYBBOg/Fb7KIptlbyEOu58..."
]},
{"type": "text",
"text": "描述這個視頻的具體過程"}]}]
}'DashScope
Python
import base64
import os
import dashscope
# 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
# 編碼函數: 將本地檔案轉換為 Base 64 編碼的字串
def encode_image(image_path):
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode("utf-8")
base64_image1 = encode_image("football1.jpg")
base64_image2 = encode_image("football2.jpg")
base64_image3 = encode_image("football3.jpg")
base64_image4 = encode_image("football4.jpg")
messages = [{'role':'user',
'content': [
{'video':
[f"data:image/png;base64,{base64_image1}",
f"data:image/png;base64,{base64_image2}",
f"data:image/png;base64,{base64_image3}",
f"data:image/png;base64,{base64_image4}"
]
},
{'text': '請描繪這個視頻的具體過程?'}]}]
response = dashscope.MultiModalConversation.call(
# 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
api_key=os.getenv("DASHSCOPE_API_KEY"),
model='qwen3-vl-plus', # 此處以qwen3-vl-plus為例,可按需更換模型名稱。模型列表:https://www.alibabacloud.com/help/model-studio/getting-started/models
messages=messages)
print(response.output.choices[0].message.content[0]["text"])Java
import java.io.IOException;
import java.util.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import com.alibaba.dashscope.aigc.multimodalconversation.*;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;
public class Main {
static {
// 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/api/v1
Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
}
private static String encodeImageToBase64(String imagePath) throws IOException {
Path path = Paths.get(imagePath);
byte[] imageBytes = Files.readAllBytes(path);
return Base64.getEncoder().encodeToString(imageBytes);
}
public static void videoImageListSample(String localPath1,String localPath2,String localPath3,String localPath4)
throws ApiException, NoApiKeyException, UploadFileException, IOException {
String base64Image1 = encodeImageToBase64(localPath1); // Base64編碼
String base64Image2 = encodeImageToBase64(localPath2);
String base64Image3 = encodeImageToBase64(localPath3);
String base64Image4 = encodeImageToBase64(localPath4);
MultiModalConversation conv = new MultiModalConversation();
Map<String, Object> params = new HashMap<>();
params.put("video", Arrays.asList(
"data:image/jpeg;base64," + base64Image1,
"data:image/jpeg;base64," + base64Image2,
"data:image/jpeg;base64," + base64Image3,
"data:image/jpeg;base64," + base64Image4));
// 若模型屬於Qwen2.5-VL系列且傳入映像列表時,可設定fps參數,表示映像列表是由原視頻每隔 1/fps 秒抽取的,其他模型設定則不生效
params.put("fps", 2);
MultiModalMessage userMessage = MultiModalMessage.builder()
.role(Role.USER.getValue())
.content(Arrays.asList(params,
Collections.singletonMap("text", "描述這個視頻的具體過程")))
.build();
MultiModalConversationParam param = MultiModalConversationParam.builder()
// 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.model("qwen3-vl-plus")
.messages(Arrays.asList(userMessage))
.build();
MultiModalConversationResult result = conv.call(param);
System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text"));
}
public static void main(String[] args) {
try {
// 將 xxx/football1.png 等替換為你本地映像的絕對路徑
videoImageListSample(
"xxx/football1.jpg",
"xxx/football2.jpg",
"xxx/football3.jpg",
"xxx/football4.jpg"
);
} catch (ApiException | NoApiKeyException | UploadFileException | IOException e) {
System.out.println(e.getMessage());
}
System.exit(0);
}
}curl
將檔案轉換為 Base 64 編碼的字串的方法可參見範例程式碼;
為了便於展示,代碼中的
"data:image/jpg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAA...",該Base 64 編碼字串是截斷的。在實際使用中,請務必傳入完整的編碼字串。
# ======= 重要提示 =======
# 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
# 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# === 執行時請刪除該注釋 ===
curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "qwen3-vl-plus",
"input": {
"messages": [
{
"role": "user",
"content": [
{
"video": [
"data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAA...",
"data:image/jpeg;base64,nEpp6jpnP57MoWSyOWwrkXMJhHRCWYeFYb...",
"data:image/jpeg;base64,JHWQnJPc40GwQ7zERAtRMK6iIhnWw4080s...",
"data:image/jpeg;base64,adB6QOU5HP7dAYBBOg/Fb7KIptlbyEOu58..."
],
"fps":2
},
{
"text": "描述這個視頻的具體過程"
}
]
}
]
}
}'處理高解析度映像
通義千問VL API對單張映像編碼後的視覺 Token 數量設有限制,預設配置下,高解析度映像會被壓縮,可能丟失細節,影響理解準確性。啟用 vl_high_resolution_images 或調整 max_pixels 可增加視覺 Token 數量,從而保留更多映像細節,提升理解效果。
不同模型,每個視覺 Token 對應的像素與 Token 、像素上限不同。具體參數如下:
模型 | 每Token 對應像素 | vl_high_resolution_images | max_pixels | Token 上限 | 像素上限 若超過像素上限,則將映像的總像素縮小至此上限內。 |
|
|
|
|
|
|
| 可自訂,最大值是 |
|
| ||
|
|
|
|
|
|
| 可自訂,最大值是 |
|
| ||
|
|
|
|
|
|
| 可自訂,最大值是 |
|
|
當
vl_high_resolution_images=true時,API使用固定解析度策略,忽略max_pixels設定。適合用於識別映像中的精細文本、微小物體或豐富細節。當
vl_high_resolution_images=false時,實際解析度由max_pixels與預設上限共同決定,取二者計算結果的最大值。對處理速度要求高或成本敏感:使用
max_pixels的預設值或設定為更小的值需要關注一定的細節,可接受較低的處理速度:適當提高
max_pixels的值
OpenAI 相容
vl_high_resolution_images非 OpenAI 標準參數,若使用 OpenAI Python SDK 請通過 extra_body傳入。
Python
import os
import time
from openai import OpenAI
client = OpenAI(
# 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
api_key=os.getenv("DASHSCOPE_API_KEY"),
# 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1
base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
model="qwen3-vl-plus",
messages=[
{"role": "user","content": [
{"type": "image_url","image_url": {"url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250212/earbrt/vcg_VCG211286867973_RF.jpg"},
# max_pixels表示輸入映像的最大像素閾值,在vl_high_resolution_images=True,無效,vl_high_resolution_images=False,支援自訂,不同模型最大值不同
# "max_pixels": 16384 * 32 * 32
},
{"type": "text", "text": "這張圖表現的是哪個節日的氛圍"},
],
}
],
extra_body={"vl_high_resolution_images":True}
)
print(f"模型輸出結果: {completion.choices[0].message.content}")
print(f"輸入總Tokens: {completion.usage.prompt_tokens}")Node.js
import OpenAI from "openai";
const openai = new OpenAI(
{
// 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
// 若沒有配置環境變數,請用百鍊API Key將下行替換為:apiKey: "sk-xxx"
apiKey: process.env.DASHSCOPE_API_KEY,
// 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1
baseURL: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
}
);
const response = await openai.chat.completions.create({
model: "qwen3-vl-plus",
messages: [
{role: "user",content: [
{type: "image_url",
image_url: {"url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250212/earbrt/vcg_VCG211286867973_RF.jpg"},
// max_pixels表示輸入映像的最大像素閾值,在vl_high_resolution_images=True,不生效,vl_high_resolution_images=False,支援自訂,不同模型最大值不同
// "max_pixels": 2560 * 32 * 32
},
{type: "text", text: "這張圖表現的是哪個節日的氛圍?" },
]}],
vl_high_resolution_images:true
})
console.log("模型輸出結果:",response.choices[0].message.content);
console.log("輸入總Tokens",response.usage.prompt_tokens);
curl
# ======= 重要提示 =======
# 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
# === 執行時請刪除該注釋 ===
curl -X POST https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "qwen3-vl-plus",
"messages": [
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {
"url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250212/earbrt/vcg_VCG211286867973_RF.jpg"
}
},
{
"type": "text",
"text": "這張圖表現的是哪個節日的氛圍?"
}
]
}
],
"vl_high_resolution_images":true
}'DashScope
Python
import os
import time
import dashscope
# 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
messages = [
{
"role": "user",
"content": [
{"image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250212/earbrt/vcg_VCG211286867973_RF.jpg",
# max_pixels表示輸入映像的最大像素閾值,在vl_high_resolution_images=True,無效,vl_high_resolution_images=False,支援自訂,不同模型最大值不同
# "max_pixels": 16384 * 32 * 32
},
{"text": "這張圖表現的是哪個節日的氛圍?"}
]
}
]
response = dashscope.MultiModalConversation.call(
# 若沒有配置環境變數,請用百鍊API Key將下行替換為:api_key="sk-xxx"
# 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
api_key=os.getenv('DASHSCOPE_API_KEY'),
model='qwen3-vl-plus',
messages=messages,
vl_high_resolution_images=True
)
print("模型輸出",response.output.choices[0].message.content[0]["text"])
print("輸入總Tokens:",response.usage.input_tokens)Java
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import java.util.HashMap;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;
public class Main {
static {
// 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/api/v1
Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
}
public static void simpleMultiModalConversationCall()
throws ApiException, NoApiKeyException, UploadFileException {
MultiModalConversation conv = new MultiModalConversation();
Map<String, Object> map = new HashMap<>();
map.put("image", "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250212/earbrt/vcg_VCG211286867973_RF.jpg");
// max_pixels表示輸入映像的最大像素閾值,在vl_high_resolution_images=True,無效,vl_high_resolution_images=False,支援自訂,不同模型最大值不同
// map.put("min_pixels", 2621440);
MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
.content(Arrays.asList(
map,
Collections.singletonMap("text", "這張圖表現的是哪個節日的氛圍?"))).build();
MultiModalConversationParam param = MultiModalConversationParam.builder()
// 若沒有配置環境變數,請用百鍊API Key將下行替換為:.apiKey("sk-xxx")
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.model("qwen3-vl-plus")
.message(userMessage)
.vlHighResolutionImages(true)
.build();
MultiModalConversationResult result = conv.call(param);
System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text"));
System.out.println(result.getUsage().getInputTokens());
}
public static void main(String[] args) {
try {
simpleMultiModalConversationCall();
} catch (ApiException | NoApiKeyException | UploadFileException e) {
System.out.println(e.getMessage());
}
System.exit(0);
}
}curl
# ======= 重要提示 =======
# 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
# === 執行時請刪除該注釋 ===
curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "qwen3-vl-plus",
"input":{
"messages":[
{
"role": "user",
"content": [
{"image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250212/earbrt/vcg_VCG211286867973_RF.jpg"},
{"text": "這張圖表現的是哪個節日的氛圍?"}
]
}
]
},
"parameters": {
"vl_high_resolution_images": true
}
}'更多用法
使用限制
輸入檔案限制
映像限制
映像解析度:
最小尺寸:映像的寬度和高度均須大於
10像素。寬高比:映像長邊與短邊的比值不得超過
200:1。像素上限:
推薦將映像解析度控制在
8K(7680x4320)以內。超過此解析度的映像可能因檔案過大、網路傳輸耗時過長而導致 API 呼叫逾時。自動縮放機制:模型在處理前會自動縮放輸入映像。因此,提供超高解析度的映像並不會提升識別精度,反而會增加調用失敗的風險,建議在用戶端提前將映像縮放至合理大小。
支援的映像格式
解析度在4K
(3840x2160)以下,支援的映像格式如下:映像格式
常見副檔名
MIME Type
BMP
.bmp
image/bmp
JPEG
.jpe, .jpeg, .jpg
image/jpeg
PNG
.png
image/png
TIFF
.tif, .tiff
image/tiff
WEBP
.webp
image/webp
HEIC
.heic
image/heic
解析度處於
4K(3840x2160)到8K(7680x4320)範圍,僅支援 JPEG、JPG 、 PNG 格式。
映像大小:
以公網 URL 和本地路徑傳入時:單個映像的大小不超過
10MB。以 Base 64 編碼傳入時:編碼後的字串不超過
10MB。
如需壓縮檔體積請參見如何將映像或視頻壓縮到滿足要求的大小。
支援傳入的圖片數量:傳入多張映像時,圖片數量受模型的最大輸入的限制,所有圖片和文本的總 Token 數必須小於模型的最大輸入。
舉例說明:使用的模型為
qwen3-vl-plus,思考模式下模型的最大輸入為258048個Token,若傳入的文本轉換為100個Token,映像轉換為2560個Token(計算映像的 Token 請參見計費與限流),則最大能傳入(258048-100)/ 2560 = 100張。
視頻限制
視頻大小:
以公網 URL 傳入時:
Qwen3-VL系列、qwen-vl-max(包含qwen-vl-max-latest、qwen-vl-max-2025-04-08之後的所有版本):不超過 2GB;qwen-vl-plus系列、其他qwen-vl-max模型、Qwen2.5-VL開源系列及QVQ系列模型:不超過 1GB;其他模型不超過 150MB
以 Base 64 編碼傳入時:編碼後的字串小於 10MB;
以本地檔案路徑傳入時:視頻本身不超過 100MB。
如需壓縮檔體積請參見如何將映像或視頻壓縮到滿足要求的大小。
視頻時間長度:
qwen3-vl-plus系列:2 秒至 1 小時;qwen3-vl-flash系列、Qwen3-VL開源系列、qwen-vl-max(包含qwen-vl-max-latest、qwen-vl-max-2025-04-08之後的所有版本):2 秒至 20 分鐘;qwen-vl-plus系列、 其他qwen-vl-max模型、Qwen2.5-VL開源系列及QVQ系列模型:2 秒至 10 分鐘;其他模型:2 秒至 40 秒。
視頻格式: MP4、AVI、MKV、MOV、FLV、WMV 等。
視頻尺寸:無特定限制,模型處理前會被調整到約 60萬 像素數,更大尺寸的視頻檔案不會有更好的理解效果。
音頻理解:不支援對視頻檔案的音頻進行理解。
檔案傳入方式
公網URL:提供一個公網可訪問的檔案地址,支援 HTTP 或 HTTPS 協議。為獲得最佳穩定性和效能,可將檔案上傳至OSS,擷取公網 URL。
重要為確保模型能成功下載檔案,提供的公網 URL的要求標頭中必須包含 Content-Length(檔案大小)和 Content-Type(媒體類型,如 image/jpeg)。任一欄位缺失或者錯誤將會導致檔案下載失敗。
Base64編碼傳入:將檔案轉換為 Base 64 編碼字串再傳入。
本地檔案路徑傳入(僅限 DashScope SDK):傳入本地檔案的路徑。
關於檔案傳入方式的建議,請參見如何選擇檔案上傳方式?
應用於生產環境
映像/視頻預先處理:通義千問VL 對輸入的檔案有大小限制,如需壓縮檔請參見映像或視頻壓縮方法。
處理文字檔:通義千問VL 僅支援處理映像格式的檔案,無法直接處理文字檔。但可使用以下替代方案:
容錯與穩定性
逾時處理:在非流式調用中,180 秒內模型沒有結束輸出通常會觸發逾時報錯。為了提升使用者體驗,逾時後響應體中會將已產生的內容返回。如果回應標頭包含
x-dashscope-partialresponse:true,表示本次響應觸發了逾時。您可以使用首碼續寫功能(支援部分模型),將已產生的內容添加到 messages 數組並再次發出請求,使大模型繼續產生內容。詳情請參見:基於不完整輸出進行續寫。重試機制:設計合理的API調用重試邏輯(如指數退避),以應對網路波動或服務瞬時停用情況。
計費與限流
計費 :總費用根據輸入和輸出的總 Token 數計算;輸入和輸出價格可參見模型列表。
Token 構成:輸入 Token 由文本 Token 和映像或視頻轉換後的 Token 組成;輸出 Token 為模型產生的文本。在思考模式下,模型的思考過程也會計入輸出 Token。若思考模式下未輸出思考過程,按照非思考模式價格計費。
計算映像與視頻 Token:可通過以下代碼計算映像或視頻的 Token 消耗。估算結果僅供參考,實際用量以 API 響應為準。
API參考
關於通義千問VL模型的輸入輸出參數,請參見通義千問。
常見問題
如何選擇檔案上傳方式?
如何將映像或視頻壓縮到滿足要求的大小?
模型輸出物體定位的結果後,如何將檢測框繪製到原圖上?
錯誤碼
如果模型調用失敗並返回報錯資訊,請參見錯誤資訊進行解決。












