Utilice Qwen-Omni mediante HTTP para comprender texto, imágenes, audio y video. Elija Qwen3.8-Omni-Flash para análisis de texto y Qwen3.5-Omni para salida de voz.
Introducción
Elija un ejemplo según el tipo de salida: Qwen3.8-Omni-Flash para análisis de texto o Qwen3.5-Omni para generación de voz.
Salida de texto (Qwen3.8-Omni-Flash)
Configure su clave de API e instale el SDK de OpenAI. Establezca la variable de entorno DASHSCOPE_BASE_URL en la base_url de su espacio de trabajo desde los endpoints de Chat Completions. Configure AUDIO_URL con una URL de audio WAV accesible. Utilice una clave de API de la región seleccionada.
En una terminal de macOS o Linux, instale la dependencia y configure las siguientes variables. Reemplace el endpoint y la URL de audio con sus valores; configure DASHSCOPE_API_KEY siguiendo las instrucciones vinculadas anteriormente.
python3 -m pip install openai
export DASHSCOPE_BASE_URL="<workspace-base-url>"
export AUDIO_URL="<accessible-wav-url>"
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ["DASHSCOPE_API_KEY"],
base_url=os.environ["DASHSCOPE_BASE_URL"],
)
completion = client.chat.completions.create(
model="qwen3.8-omni-flash",
messages=[{
"role": "user",
"content": [
{"type": "text", "text": "Summarize the main points of this recording."},
{"type": "input_audio", "input_audio": {
"data": os.environ["AUDIO_URL"],
"format": "wav",
}},
],
}],
stream=True,
stream_options={"include_usage": True},
)
output_section = None
for chunk in completion:
if not chunk.choices:
if chunk.usage:
print("\nUsage:", chunk.usage)
continue
delta = chunk.choices[0].delta
if getattr(delta, "reasoning_content", None):
if output_section != "thinking":
print("\nThinking:")
output_section = "thinking"
print(delta.reasoning_content, end="", flush=True)
if delta.content:
if output_section != "answer":
print("\nAnswer:")
output_section = "answer"
print(delta.content, end="", flush=True)
Salida de audio (Qwen3.5-Omni)
Requisitos previos- Obtener una clave de API y configurar la clave de API como variable de entorno.
- Los siguientes ejemplos de salida de audio utilizan invocación compatible con OpenAI. Debe instalar el SDK más reciente. Las versiones mínimas requeridas son 1.52.0 para el SDK de Python de OpenAI y 4.68.0 para el SDK de Node.js.
Este ejemplo envía un prompt de texto a la API de Qwen-Omni y devuelve una respuesta en streaming con texto y audio.
import os
import base64
import soundfile as sf
import numpy as np
from openai import OpenAI
# 1. Initialize the client
client = OpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"), # Confirm that the environment variable is set
# Singapore region. Replace {WorkspaceId} with your Bailian workspace ID. URLs vary by region.
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
# 2. Send the request
try:
completion = client.chat.completions.create(
model="qwen3.5-omni-plus",
messages=[{"role": "user", "content": "Who are you?"}],
modalities=["text", "audio"], # Specify text and audio output
audio={"voice": "Tina", "format": "wav"},
stream=True, # Must be set to True
stream_options={"include_usage": True},
)
# 3. Process the streaming response and decode the audio
print("Model response:")
audio_base64_string = ""
for chunk in completion:
# Process the text part
if chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="")
# Collect the audio part
if chunk.choices and hasattr(chunk.choices[0].delta, "audio") and chunk.choices[0].delta.audio:
audio_base64_string += chunk.choices[0].delta.audio.get("data", "")
# 4. Save the audio file
if audio_base64_string:
wav_bytes = base64.b64decode(audio_base64_string)
audio_np = np.frombuffer(wav_bytes, dtype=np.int16)
sf.write("audio_assistant.wav", audio_np, samplerate=24000)
print("\nAudio file saved to: audio_assistant.wav")
except Exception as e:
print(f"Request failed: {e}")
// Before you run this code:
// For Windows/Mac/Linux:
// 1. Ensure Node.js version >= 14 is installed.
// 2. Run the following command to install necessary dependencies:
// npm install openai wav
import OpenAI from "openai";
import { createWriteStream } from 'node:fs';
import { Writer } from 'wav';
// Define a function to convert a Base64 string and save it as a standard WAV audio file
async function convertAudio(audioString, audioPath) {
try {
// Decode the Base64 string into a Buffer
const wavBuffer = Buffer.from(audioString, 'base64');
// Create a WAV file write stream
const writer = new Writer({
sampleRate: 24000, // Sample rate
channels: 1, // Mono
bitDepth: 16 // 16-bit depth
});
// Create an output file stream and establish a pipe connection
const outputStream = createWriteStream(audioPath);
writer.pipe(outputStream);
// Write PCM data and end writing
writer.write(wavBuffer);
writer.end();
// Use a Promise to wait for the file to finish writing
await new Promise((resolve, reject) => {
outputStream.on('finish', resolve);
outputStream.on('error', reject);
});
// Add extra wait time to ensure audio integrity
await new Promise(resolve => setTimeout(resolve, 800));
console.log(`\nAudio file saved to: ${audioPath}`);
} catch (error) {
console.error('Error during processing:', error);
}
}
// 1. Initialize the client
const openai = new OpenAI(
{
// API keys for the Singapore and Beijing regions are different. Get an API key: https://www.alibabacloud.com/help/model-studio/get-api-key
apiKey: process.env.DASHSCOPE_API_KEY,
// The following URL is for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
}
);
// 2. Send the request
const completion = await openai.chat.completions.create({
model: "qwen3.5-omni-plus",
messages: [
{
"role": "user",
"content": "Who are you?"
}],
stream: true,
stream_options: {
include_usage: true
},
modalities: ["text", "audio"],
audio: { voice: "Tina", format: "wav" }
});
let audioString = "";
console.log("Model response:")
// 3. Process the streaming response and decode the audio
for await (const chunk of completion) {
if (Array.isArray(chunk.choices) && chunk.choices.length > 0) {
// Process text content
if (chunk.choices[0].delta.content) {
process.stdout.write(chunk.choices[0].delta.content);
}
// Process audio content
if (chunk.choices[0].delta.audio) {
if (chunk.choices[0].delta.audio["data"]) {
audioString += chunk.choices[0].delta.audio["data"];
}
}
}
}
// 4. Save the audio file
convertAudio(audioString, "audio_assistant.wav");
# ======= Important note =======
# API keys for the Singapore and Beijing regions are different. Get an API key: https://www.alibabacloud.com/help/model-studio/get-api-key
# The following URL is for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
# === Delete this comment before execution ===
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen3.5-omni-plus",
"messages": [
{
"role": "user",
"content": "Who are you?"
}
],
"stream":true,
"stream_options":{
"include_usage":true
},
"modalities":["text","audio"],
"audio":{"voice":"Tina","format":"wav"}
}'
Respuesta
Después de ejecutar el código Python o Node.js, la respuesta de texto aparece en la consola y se guarda un archivo de audio llamado audio_assistant.wav en el mismo directorio que su archivo de código.
Model response:
I am a large language model developed by Alibaba Cloud. My name is Qwen. How can I help you?
Ejecutar código HTTP devuelve texto y datos de audio codificados en Base64 directamente en el campo audio.
data: {"choices":[{"delta":{"content":"I"},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1757647879,"system_fingerprint":null,"model":"qwen3.5-omni-plus","id":"chatcmpl-a68eca3b-c67e-4666-a72f-73c0b4919860"}
data: {"choices":[{"delta":{"content":"am"},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1757647879,"system_fingerprint":null,"model":"qwen3.5-omni-plus","id":"chatcmpl-a68eca3b-c67e-4666-a72f-73c0b4919860"}
......
data: {"choices":[{"delta":{"audio":{"data":"/v8AAAAAAAAAAAAAAA...","expires_at":1757647879,"id":"audio_a68eca3b-c67e-4666-a72f-73c0b4919860"}},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1757647879,"system_fingerprint":null,"model":"qwen3.5-omni-plus","id":"chatcmpl-a68eca3b-c67e-4666-a72f-73c0b4919860"}
data: {"choices":[{"finish_reason":"stop","delta":{"content":""},"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1764763585,"system_fingerprint":null,"model":"qwen3.5-omni-plus","id":"chatcmpl-e8c82e9e-073e-4289-a786-a20eb444ac9c"}
data: {"choices":[],"object":"chat.completion.chunk","usage":{"prompt_tokens":207,"completion_tokens":103,"total_tokens":310,"completion_tokens_details":{"audio_tokens":83,"text_tokens":20},"prompt_tokens_details":{"text_tokens":207}},"created":1757940330,"system_fingerprint":null,"model":"qwen3.5-omni-plus","id":"chatcmpl-9cdd5a26-f9e9-4eff-9dcc-93a878165afc"}
Selección de modelo
Para comprensión de audio/video, resúmenes de reuniones, subtítulos y respuestas de texto, utilice Qwen3.8-Omni-Flash. Admite pensamiento, llamada de herramientas y búsqueda web; consulte los ejemplos de invocación. Para respuestas de voz generadas, utilice Qwen3.5-Omni a continuación.
Qwen3.8-Omni-Flash
Regiones admitidas: China (Pekín), Singapur, China (Hong Kong), Japón (Tokio), Alemania (Fráncfort) y EE. UU. (Virginia). Utilice una clave de API de la región seleccionada.
qwen3.8-omni-flash está diseñado para la comprensión de audio y video, resúmenes de reuniones y análisis de contenido.
| Modelo | Entrada | Salida | APIs |
|---|---|---|---|
qwen3.8-omni-flash | Texto, imágenes, audio, video | Text | Chat Completions, Responses |
- La longitud del contexto es de 1M tokens.
- La entrada de audio admite 113 idiomas y dialectos, igual que Qwen3.5-Omni. Consulte los idiomas de entrada de audio de Qwen3.5-Omni en Selección de modelos para obtener la lista completa.
- Admite Function Calling y búsqueda web. La única herramienta integrada de Responses admitida actualmente es
web_search.
Qwen3.5-Omni: salida de audio e interacción multimodal
Regiones admitidas: China (Pekín) y Singapur. Utilice una clave de API de la región seleccionada.
-
Serie Qwen3.5-Omni: Admite comprensión de audio/video, respuestas de voz y control de audio.
- Límites de entrada: Hasta 3 horas de audio o 1 hora de video
- Control de audio: Admite el ajuste de volumen, velocidad de habla y emoción mediante instrucciones
- Capacidad visual: Coincide con el nivel de Qwen3.5. Comprende imágenes, voz, efectos de sonido y otras entradas multimodales
- Entrada multimodal combinada: Admite cualquier combinación de texto con imágenes, audio y video en una sola solicitud
- Clonación de voz: Admite voces personalizadas (solo qwen3.5-omni-plus y qwen3.5-omni-flash; no se admiten versiones snapshot). Para más detalles, consulte Clonación de voz
Otros modelos y especificaciones
-
Serie Qwen3-Omni-Flash:
- Límites de entrada: Entrada de audio y video de hasta 150 segundos
- Modo de pensamiento: Use
enable_thinkingpara activar o desactivar el pensamiento - Modalidad de entrada: Admite únicamente una combinación de texto con una sola modalidad adicional (imagen, audio o video).
| Serie | Descripción de audio y video | Pensamiento profundo | Búsqueda web | Idiomas de audio de entrada | Idiomas de audio de salida | Voces admitidas |
Qwen3.5-Omni Modelo omnimodal con salida de audio | Fuerte | No compatible | Compatible | 113 74 idiomas y 39 dialectos Idiomas: Chino, inglés, alemán, francés, italiano, checo, indonesio, tailandés, coreano, polaco, japonés, vietnamita, finés, portugués, español, neerlandés, ruso, malayo, catalán, sueco, turco, ucraniano, rumano, eslovaco, danés, islandés, noruego (bokmål), macedonio, griego, húngaro, gallego, filipino, croata, bosnio, esloveno, búlgaro, kazajo, bielorruso, letón, estonio, azerbaiyano, uigur, suajili, hindi, esperanto, kirguís, tayiko, cebuano, afrikáans, árabe, lituano, javanés, bengalí, persa, hebreo, panyabí, guyaratí, mongol, asturiano, canarés, maratí, interlingua, malayalam, maltés, nynorsk noruego, telugu, urdu, georgiano, vasco, tamil, odia, serbio, maorí Dialectos: | 36 29 idiomas y 7 dialectos Idiomas:Chino, inglés, alemán, italiano, portugués, español, japonés, coreano, francés, ruso, tailandés, indonesio, árabe, vietnamita, turco, finés, polaco, hindi, neerlandés, checo, urdu, tagalo, sueco, danés, hebreo, islandés, malayo, noruego, persa Dialectos:Dialecto de Sichuan, dialecto de Pekín, dialecto de Tianjin, dialecto de Nanjing, dialecto de Shaanxi, cantonés, min del sur | 55 |
Qwen3-Omni-Flash Modelo de pensamiento híbrido | Más débil | Compatible | No compatible | 19 11 idiomas y 8 dialectos Idioma: Chino, inglés, alemán, francés, italiano, tailandés, coreano, japonés, ruso, español, portugués Dialectos:Dialecto de Sichuan, shanghainés, cantonés, min del sur, dialecto de Shaanxi, dialecto de Nanjing, dialecto de Tianjin, dialecto de Pekín | 19 11 idiomas y 8 dialectos Idioma: Chino, inglés, alemán, francés, italiano, tailandés, coreano, japonés, ruso, español, portugués Dialectos:Sichuanés, shanghainés, cantonés, hokkien, dialecto de Shaanxi, dialecto de Nanjing, dialecto de Tianjin, dialecto de Pekín | 17 a 49
|
Para nombres de modelos, ventanas de contexto, precios y versiones snapshot, consulte la consola de Model Studio. Para límites de tasa, consulte Limitación de tasa.
Rendimiento del modelo
Análisis de contenido de audio y video
| 00:00.000 – 00:02.500 Una calle urbana empapada por la lluvia llena el encuadre panorámico. La fotografía de larga exposición crea estelas de luces rojas y azules de autos sobre el pavimento mojado. Un hombre solitario con una gabardina oscura hasta la rodilla y una camisa clara con corbata camina hacia la cámara por la acera derecha. Gotas de lluvia se adhieren a sus hombros y cabello. Cada paso produce un sonido sordo sobre el concreto húmedo. Un zumbido electrónico bajo y ominoso subraya los sonidos ambientales, mientras la lluvia constante crepita a su alrededor. Grafitis coloridos cubren la pared de ladrillos a su lado, y letreros de neón brillan a lo lejos: uno muestra claramente una escritura cursiva en rojo anaranjado que dice "Nice", mientras que otro letrero vertical muestra las letras "AT" en su parte inferior. ...... 00:12.300 – 00:14.533La cámara se inclina hacia abajo. Dentro del haz de una linterna, una hoja individual amarillenta y envejecida yace en un charco poco profundo, con los bordes carbonizados y las esquinas enrolladas. Párrafos escritos con tinta cubren la mayor parte de su superficie, pero la humedad y las marcas de quemaduras hacen que el texto sea ilegible. El hombre se arrodilla, extendiendo sus dedos enguantados hacia el documento. Se forman ondas que se expanden hacia afuera cuando su mano se acerca. Las sirenas alcanzan su punto máximo y luego comienzan a desvanecerse ligeramente, mientras el zumbido ambiental permanece constante. La escena se congela justo antes de que se toque el papel tembloroso, terminando el clip.
|
Comprensión multidialectal
| Este audio presenta interpretaciones de rap de cantantes de diversas regiones de China, mostrando una rica diversidad dialectal. A continuación se presentan descripciones detalladas de los rasgos vocales, el estado emocional y la letra correspondiente de cada cantante: Dialecto de Hangzhou (Wu)Rasgos vocales:La voz del cantante masculino es suave y delicada, con la suavidad y calidez distintivas del dialecto Wu. Su entonación sube y baja suavemente, y su ritmo es ligero y rápido, creando un efecto narrativo relajado. Estado emocional:Relajado, cómodo y lleno de vida cotidiana. Describe el estilo de vida pausado de Hangzhou y los cambios urbanos, expresando afecto por su ciudad natal y reflexiones sobre el desarrollo moderno. En general, se siente acogedor y familiar. Letra:> ¡Dialecto de Hangzhou, escuchen! Nuestra cultura incluye la pronunciación local erhua. > Como flores floreciendo junto al Lago del Oeste, no hace falta encuesta cultural; lo entendemos mejor. > None de ustedes entienden. 'San bu da men', 'ge'r', 'lao'r', 'fen'r', 'ya'r'... ¿cómo se supone que alguien de fuera distinga todo esto? > ¡Vamos! El transporte es rápido, hay metro por todas partes. Lo comprobaremos. > Dando la bienvenida al Sudeste Asiático y Tailandia, viendo espectáculos de "Thirteen Ta". Orgullosos de nuestra ciudad, directos de personalidad. > ¿Así que solo viniste por la experiencia de "cruzar el puente" y, como el sabor es diferente, no vas a volver?
|
Generación de subtítulos líricos
| [00:00:12,680 --> 00:00:16,960] Un hilo felino se mece bajo la luz de la luna en los árboles. [00:00:18,400 --> 00:00:22,800] Los radiadores zumban éxitos de listas de 1998. [00:00:24.160 → 00:00:28.080] El tiempo separa las ondas de calor similares a la niebla. [00:00:28,920 --> 00:00:33,000] El neón de la pantalla brilla sobre el puente de mi nariz. ...... [00:03:16,720 --> 00:03:21,680] Nos acurrucamos en el anillo más suave del tronco del árbol. [00:03:22,400 --> 00:03:27,000] La respiración convierte el calor residual en miel. [00:03:28,160 --> 00:03:33,200] El sofá se hunde en forma de nube esponjosa. [00:03:34,000 --> 00:03:38,800] Cada poro se empapa de sol. [00:04:09,000 --> 00:04:10,020] (Fin)
|
Programación de audio y video
Uso
Salida por secuencias
Los ejemplos de Qwen3.5-Omni y Qwen3-Omni-Flash a continuación requieren stream=True.
Responses: entrada de audio y video
Los siguientes ejemplos utilizan Qwen3.8-Omni-Flash con la API de Responses para procesar entradas de audio y video y generar respuestas de texto.
Reutilice la clave de API, DASHSCOPE_BASE_URL y AUDIO_URL del ejemplo de inicio rápido. Responses utiliza input, con la URL de audio en audio_url, en lugar de la estructura input_audio.data de Chat Completions. La entrada de audio y video solo se permite en mensajes de user.
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ["DASHSCOPE_API_KEY"],
base_url=os.environ["DASHSCOPE_BASE_URL"],
)
response = client.responses.create(
model="qwen3.8-omni-flash",
input=[{
"role": "user",
"content": [
{"type": "input_text", "text": "Summarize the main points of this recording."},
{"type": "input_audio", "audio_url": os.environ["AUDIO_URL"], "format": "wav"},
],
}],
stream=False,
)
print(response.output_text)
Para analizar un video, establezca VIDEO_URL en una URL de video accesible y reemplace input[0].content en el ejemplo de inicio rápido con:
[
{"type": "input_text", "text": "Describe the visuals and sounds in the video."},
{"type": "input_video", "video_url": os.environ["VIDEO_URL"]},
]
Para audio espacial de dos o cuatro canales, agregue "use_multichannel": True (Python) al objeto de contenido de audio anterior, junto con audio_url y format. El valor predeterminado es False, que procesa el audio como audio de un solo canal.
Para entrada de audio Base64, definiciones de campos y alcance de herramientas, consulte Crear una respuesta.
Configuración del modelo
Las siguientes recomendaciones de configuración se aplican a Qwen3.5-Omni. Ajuste los parámetros, prompts y duraciones de medios según su caso de uso. Para Qwen3.8-Omni-Flash, consulte Prompts recomendados.
Comprensión de audio y video
| Caso de uso | Duración de video recomendada | Prompt recomendado | max_pixels recomendado |
Revisión rápida, bajo costo | ≤60 minutos | Prompt simple de hasta 50 palabras | 230,400 |
Extracción de contenido (segmentación de video largo) | ≤60 minutos | 921,600~2,073,600 | |
Análisis estándar (etiquetado de video corto) | ≤4 minutos | Use el prompt estructurado a continuación Prompt recomendado | 921,600~2,073,600 |
Análisis detallado (múltiples hablantes/escenas complejas) | ≤2 minutos | 2,073,600 |
NotaPuede segmentar primero los videos largos para obtener descripciones detalladas.
Comprensión de audio
Puede equilibrar el costo y la calidad controlando la duración del audio y la complejidad del prompt.
| Caso de uso | Duración de audio recomendada | Prompt recomendado |
Revisión rápida, bajo costo | ≤60 minutos | Prompt simple de hasta 50 palabras |
Extracción de contenido (segmentación de audio largo) | ≤60 minutos | |
Análisis estándar (etiquetado de audio) | ≤2 minutos | Use un prompt estructurado Prompt estructurado |
Análisis detallado (múltiples hablantes/escenas complejas) | ≤1 minuto |
NotaPuede segmentar primero el audio largo para obtener descripciones detalladas.
Prompts recomendados
Estos prompts se aplican a qwen3.8-omni-flash. Elija un prompt para su tarea y colóquelo en el campo text de un elemento type="text" dentro del arreglo content del mensaje de user. Incluya el audio o video a analizar en el mismo mensaje. Las instrucciones de formato de salida en los prompts guían el contenido generado.
Descripción audiovisual detallada: narrativa cronológica
Combine la información visual y de audio en un relato cronológico con rangos de tiempo para localizar eventos en el video.
You are a rigorous audio-visual description expert. Your task is to watch and analyze the entire video and produce a highly detailed, coherent, evidence-grounded description that reconstructs, as accurately as possible, what is actually visible, audible, and readable in the video.
Produce a complete, directly usable video description — not an analysis report, not a checklist, not a rough summary. The description must cover the main content of the video from beginning to end, organized in chronological order into naturally coherent, information-dense paragraphs. Level of detail must always yield to factual accuracy: details that cannot be confirmed may be omitted, but you must never guess, fill in, or fabricate anything in order to make the description richer.
## Core Principles
1. Cover the main content of the video from beginning to end, including the opening, the main process, scene changes, important actions, speech, on-screen text, sound, and the ending. Removing redundancy applies only to attributes that have not changed — clothing, room layout, aspect ratio, a continuing music bed — which are described once and then revisited only when they change. It does not license coarser event granularity: you must not skip or compress new actions, text, sounds, or state changes.
2. Every statement must be grounded in what is actually visible, audible, or readable in the video. Do not add background knowledge, common sense, prior assumptions, or speculation from outside the video. Do not treat "seems plausible" as "the video has proven it."
3. Prioritize preserving clearly discernible concrete facts, including people, animals, objects, appearance, clothing, colors, quantities, positions, actions, interactions, on-screen text, subtitles, speech, ambient sound, music, sound effects, camera changes, scene cuts, and state changes.
4. Track people, animals, and objects continuously. Once an entity has been clearly identified, keep its identity consistent in later appearances; if multiple similar entities cannot be reliably distinguished, use positional descriptions such as "the device on the left" or "the person in the center of the frame" rather than forcing a name onto them. Avoid ambiguous references such as "he," "she," "it," "this person," or "that thing."
5. Do not invent a person's identity, age, occupation, emotion, intention, relationship, or the reason behind an action. You may describe visible facial expressions and body movements, but do not interpret an expression directly as a mental state. For example, write "the corners of his mouth turn up and he smiles" rather than "he feels happy."
6. When the identity of an entity, an action, a quantity, text, speech, a temporal relationship, a sound source, or a causal relationship cannot be confirmed, and that uncertainty affects understanding, use brief, specific, conservative wording, for example "the on-screen text is small and cannot be fully made out" or "voices can be heard, but the exact lines are unclear." For unimportant unclear details, simply omit them; do not repeatedly pile up "possibly," "seemingly," and "appears to be."
7. When speech, subtitles, or on-screen text are clearly discernible, preserve the original wording as far as possible, especially for personal names, place names, numbers, brands, labels, proper nouns, formulas, code, and key statements. Do not translate, rewrite, or correct the original text on your own initiative.
8. Distinguish facts directly observed in the footage from opinions expressed by people in the video, by narration, or by subtitles. If a host or narrator offers an evaluation, explanation, recommendation, or causal judgment, write it explicitly as "the host states," "the narration explains," or "the subtitle says"; do not rewrite an opinion voiced in the video as the describer's own objective conclusion.
9. When level of detail and reliability conflict, reliability comes first. It is better to write fewer unconfirmable details than to hallucinate in order to fill up information.
## Description Granularity
The unit of segmentation is a change in information, not a fixed number of seconds. Begin a new event wherever the subject, object, or goal changes; an action enters a new stage; contact is made or released; direction, speed, or trajectory changes noticeably; an observable state change occurs; the speaker turn changes; the sound or music structure changes; the scene, shot, or narrative layer changes; or the interface focus, control, parameter, or result state changes.
For each significant action, write as much of the following as the video actually supports: the subject, its state before the action, the action itself, the object or point of contact, which hand, body part, or tool is used, the direction and trajectory, the speed or manner, any intermediate stage, the resulting state, and the observable consequence. A named action on its own is a label, not a description. "She opens the bottle" is insufficient; "she steadies the bottle with her left hand, then twists the metal cap counter-clockwise with her right, and once the cap is free she sets it down to the right of the bottle" carries the actual granularity. The same applies to a state change: give both ends of it, since "the waveform is narrower after he applies the setting" carries the change while "he adjusts the audio" does not.
Granularity does not degrade with video length. A long or repetitive video receives the same local event granularity as a short one. Length may add chapter-level organization, but it must never replace a sequence of distinct actions with a single coarser generalizing verb.
Before using left, right, in front, or behind, make the frame of reference unambiguous, distinguishing the viewer's left and right within the frame, a person's own left and right, and the left and right inside a software window or interface. When a visual event and a sound belong to the same occurrence, write them together and make the relation explicit rather than listing picture and sound separately for the reader to pair up. Whenever you give a number, make the basis of the count explicit: what is being counted, over which time window, and whether you are counting instantaneous on-screen quantity, distinct entities across the whole video, completed actions, attempts, or sound occurrences.
## Scope of Content Coverage
Describe the following whenever the video actually contains them:
* the video type, subject, narrative line, and overall visual form;
* the main people, animals, and objects, and their identities or roles;
* appearance, clothing, colors, materials, quantities, and spatial positions;
* actions, interactions, operating steps, and their order;
* the scene environment, foreground, middle ground, background, lighting, left-right relationships, and spatial changes;
* camera viewpoint, shot size, focus, push/pull/pan/tilt, following shots, transitions, and frame layout;
* titles, subtitles, labels, interface text, numbers, formulas, code, tables, and charts;
* speech, narration, language, speakers, discernible original spoken content, and obvious tonal characteristics;
* background music, ambient sound, sound effects, and the onset, end, and obvious changes of sounds;
* the entrance, exit, movement, contact, operation, and state changes of the subjects;
* professional procedures, tools, terminology, and conclusions explicitly demonstrated or explicitly stated in the video;
* temporal continuity, location changes, and time jumps between different scenes.
Do not infer a music track's specific BPM, genre, instrumentation, key, mixing, compression, or reverb from listening impression alone. When the sound source cannot be confirmed, use neutral wording such as "an impact sound is heard" or "a short electronic sound effect occurs." Attribute a sound to a specific object only when the sound clearly corresponds to an action visible in the frame.
For OCR, numbers, and charts, transcribe verbatim only when the content is clear enough. Do not guess content from blurry text, and do not estimate values from the heights of bars or lines in a chart. If it cannot be read reliably, omit the specific value or state that part of the text cannot be made out.
## Timestamp Rules
Describe the video in chronological order, and start a new paragraph at shot cuts, scene changes, changes of main activity, the appearance of a new subject, speaker changes, the appearance of key text, or obvious state changes.
Begin each time segment with the following format:
[hh:mm:ss:xxx-hh:mm:ss:xxx]
For example:
[00:00:04:000-00:00:12:000] The shot cuts to ...
Timestamps must be safe time intervals backed by evidence. Timing may be determined from clear shot cuts, subtitle appearances, speech onset and offset points, ASR timestamps, or stably locatable visual events. Do not generate timings from paragraph length, average shot duration, or guesswork, and do not fabricate millisecond-level precision merely to satisfy the millisecond format.
Match precision to the evidence available. Chapters and long scenes take ranges of seconds to minutes; shot boundaries and ordinary actions are locatable to roughly half a second to a second; dialogue turns to a few tenths of a second; clicks, contacts, impacts, and cue tones to around a tenth of a second. If an event can only be confirmed as falling somewhere near a given second, write an approximate range rather than a fabricated millisecond timestamp.
Write an additional precise time point inside a paragraph only when that event can genuinely be located reliably. Otherwise, describe only the order in which events occur and the time segment they fall in. Adjacent time segments must not overlap, and do not manufacture unreliable time boundaries in the pursuit of precision.
Distinguish a new event from a repeated action, a slow-motion pass, a replay, or a flashback. A replayed sequence keeps the same clothing, action order, and target, and should be identified as a replay rather than described as further new events.
## Output Format
Write one concise overview paragraph followed by multiple chronologically ordered description paragraphs.
Open with a short overview introducing the video type, core subjects, main scenes, visual style, and overall auditory environment. Then describe the concrete content in chronological order, integrating visuals, speech, on-screen text, and audio within the same time segment; do not mechanically split by modality into "visual," "audio," "OCR," and so on.
Add a brief closing paragraph only when the video genuinely has a clear overall outcome or concluding development. The closing must not introduce new information absent from the preceding text, and must not offer your own evaluation of the video.
Do not use tables, bullet points, numbered lists, XML, JSON, analytical subheadings, or mechanical headings such as "Scene 1" or "Shot 2.3." Do not output your analysis process, observation process, evidence lists, tool-call records, quality assessments, or any explanation unrelated to the video.
The final output should be natural, fluent, specific, coherent, and information-dense without excessive repetition, and must at all times obey the principles of "evidence first, timing grounded, details reliable."
Please describe this video in detail.
Descripción audiovisual detallada: transcripciones separadas y texto en pantalla
Devuelva secciones separadas para eventos, texto en pantalla y transcripciones de voz. Conserve la redacción original, los hablantes y los rangos de tiempo para búsqueda y verificación.
Provide a detailed description of the video.
Make sure your description covers every one of the following dimensions:
Visual
- Subjects and characters: appearance, clothing, gender/age cues, identity, distinctive features
- Actions and events in chronological order, and how the scene evolves over time
- Setting and background: location, environment, time of day
- Spatial layout and relations between subjects/objects; counts and quantities
- On-screen text: captions, titles, subtitles, logos, UI — exact content and appearance
- Visual style: colors, lighting, camera shots, angles, and camera movement
Audio
- Speech: the exact spoken content, transcribed verbatim
- Speakers: who is speaking (mapped to the on-screen person or voice-over), with accent, tone, gender/age cues
- Speaking state: prosody, emotion, volume, and speaking style
- Music: presence, genre/mood, and lyrics if any
- Sound effects and ambient/background sounds
- Non-speech vocalizations: laughter, crying, applause, etc.
Audio-visual correspondence
- Which speech or sound aligns with which on-screen person or visual event
- The timing of each event, expressed with timestamps
It should explicitly include three sections:
1. A structured chronological storyline of **every noticeable audio and visual details**
2. A structured list of all visible text. For each text element, include start timestamp, end timestamp, the exact text content, the appearance characteristics. If no text appears, explicitly state so.
3. A structured speech-to-text transcription, include speaker(Corresponding to the character or voice‑over in Section 1, including their accent and tone), exact spoken content, start timestamp, end timestamp, and speaking state (prosody, emotion, and style). If no speech appears, explicitly state so.
Aside from these three required sections, you are free to organize any additional content in any way you find helpful. This additional content can include global information about the entire video or localized information about specific moments. You may choose the topic of this extra content freely.
Rules:
- Add as much descriptive detail as possible.
- Do not use Markdown bold formatting.
- Carefully look at frames and listen to the audio, making sure no detail is overlooked.
Output Format:
Descripción audiovisual estructurada
Devuelva JSON organizado en escenas y eventos. Incluya tanto las instrucciones de la tarea como el esquema JSON completo en el prompt para definir campos, tipos, propiedades obligatorias y restricciones.
Describe the audio and visual content in detail in English, organized into scenes and events, following the JSON Schema below.
All timestamps must be relative to the beginning of the video. End times must not precede start times or exceed the video duration. Each event must fall within the time range of its parent scene.
Include only information directly supported by the audio or video. Do not guess or invent details. Do not infer causality merely because a sound and an action occur at the same time.
Return only valid JSON, without Markdown fences or commentary.
JSON Schema:
{
"$defs": {
"Event": {
"additionalProperties": false,
"properties": {
"time_range": {
"$ref": "#/$defs/TimeRange",
"description": "Time range of the event"
},
"participants": {
"description": "People, animals, or objects involved, named by observable features; use consistent names for the same participant",
"items": {
"type": "string"
},
"title": "Participants",
"type": "array"
},
"action": {
"description": "Specific actions, interactions, and observable outcomes",
"title": "Action",
"type": "string"
},
"sounds": {
"description": "Sounds heard during the event; use an empty list if none are discernible",
"items": {
"type": "string"
},
"title": "Sounds",
"type": "array"
}
},
"required": [
"time_range",
"participants",
"action",
"sounds"
],
"title": "Event"
,
"type": "object"
},
"Scene": {
"additionalProperties": false,
"properties": {
"time_range": {
"$ref": "#/$defs/TimeRange",
"description": "Time range of the scene"
},
"setting": {
"description": "Environment, spatial layout, and main visual features",
"title": "Setting",
"type": "string"
},
"events": {
"description": "Events in chronological order; use an empty list if there are none",
"items": {
"$ref": "#/$defs/Event"
},
"title": "Events",
"type": "array"
}
},
"required": [
"time_range",
"setting",
"events"
],
"title": "Scene",
"type": "object"
},
"TimeRange": {
"additionalProperties": false,
"properties": {
"start_seconds": {
"description": "Start time in seconds relative to the beginning of the video",
"minimum": 0,
"title": "Start Seconds",
"type": "number"
},
"end_seconds": {
"description": "End time in seconds; must not precede the start time",
"minimum": 0,
"title": "End Seconds",
"type": "number"
}
},
"required": [
"start_seconds",
"end_seconds"
],
"title": "TimeRange",
"type": "object"
}
},
"additionalProperties": false,
"properties": {
"summary": {
"description": "An overview of the main content of the video",
"title": "Summary",
"type": "string"
},
"scenes": {
"description": "Scenes in chronological order; group continuous footage with a consistent setting into one scene",
"items": {
"$ref": "#/$defs/Scene"
},
"title": "Scenes",
"type": "array"
}
},
"required": [
"summary",
"scenes"
],
"title": "CaptionResult",
"type": "object"
}
Contenido audiovisual altamente dinámico
Describa elementos visuales, acciones y eventos que cambian rápidamente. Ajuste la tasa de muestreo de cuadros del video a la dinámica del contenido. El modelo mantiene resultados estables con entradas muestreadas hasta 15 fps, capturando acciones más detalladas y cambios temporales. Tasas de cuadros más altas incrementan los costos de procesamiento, por lo que debe elegir una tasa adecuada para la tarea.
You are a rigorous audio-visual description expert. Your task is to watch and analyze the entire video and produce a highly detailed, coherent, evidence-grounded description that reconstructs, as accurately as possible, what is actually visible, audible, and readable in the video.
Produce a complete, directly usable video description — not an analysis report, not a checklist, not a rough summary. The description must cover the main content of the video from beginning to end, organized in chronological order into naturally coherent, information-dense paragraphs. Level of detail must always yield to factual accuracy: details that cannot be confirmed may be omitted, but you must never guess, fill in, or fabricate anything in order to make the description richer.
## Core Principles
1. Cover the main content of the video from beginning to end, including the opening, the main process, scene changes, important actions, speech, on-screen text, sound, and the ending. Removing redundancy applies only to attributes that have not changed — clothing, room layout, aspect ratio, a continuing music bed — which are described once and then revisited only when they change. It does not license coarser event granularity: you must not skip or compress new actions, text, sounds, or state changes.
2. Every statement must be grounded in what is actually visible, audible, or readable in the video. Do not add background knowledge, common sense, prior assumptions, or speculation from outside the video. Do not treat "seems plausible" as "the video has proven it."
3. Prioritize preserving clearly discernible concrete facts, including people, animals, objects, appearance, clothing, colors, quantities, positions, actions, interactions, on-screen text, subtitles, speech, ambient sound, music, sound effects, camera changes, scene cuts, and state changes.
4. Track people, animals, and objects continuously. Once an entity has been clearly identified, keep its identity consistent in later appearances; if multiple similar entities cannot be reliably distinguished, use positional descriptions such as "the device on the left" or "the person in the center of the frame" rather than forcing a name onto them. Avoid ambiguous references such as "he," "she," "it," "this person," or "that thing."
5. Do not invent a person's identity, age, occupation, emotion, intention, relationship, or the reason behind an action. You may describe visible facial expressions and body movements, but do not interpret an expression directly as a mental state. For example, write "the corners of his mouth turn up and he smiles" rather than "he feels happy."
6. When the identity of an entity, an action, a quantity, text, speech, a temporal relationship, a sound source, or a causal relationship cannot be confirmed, and that uncertainty affects understanding, use brief, specific, conservative wording, for example "the on-screen text is small and cannot be fully made out" or "voices can be heard, but the exact lines are unclear." For unimportant unclear details, simply omit them; do not repeatedly pile up "possibly," "seemingly," and "appears to be."
7. When speech, subtitles, or on-screen text are clearly discernible, preserve the original wording as far as possible, especially for personal names, place names, numbers, brands, labels, proper nouns, formulas, code, and key statements. Do not translate, rewrite, or correct the original text on your own initiative.
8. Distinguish facts directly observed in the footage from opinions expressed by people in the video, by narration, or by subtitles. If a host or narrator offers an evaluation, explanation, recommendation, or causal judgment, write it explicitly as "the host states," "the narration explains," or "the subtitle says"; do not rewrite an opinion voiced in the video as the describer's own objective conclusion.
9. When level of detail and reliability conflict, reliability comes first. It is better to write fewer unconfirmable details than to hallucinate in order to fill up information.
## Description Granularity
The unit of segmentation is a change in information, not a fixed number of seconds. Begin a new event wherever the subject, object, or goal changes; an action enters a new stage; contact is made or released; direction, speed, or trajectory changes noticeably; an observable state change occurs; the speaker turn changes; the sound or music structure changes; the scene, shot, or narrative layer changes; or the interface focus, control, parameter, or result state changes.
For each significant action, write as much of the following as the video actually supports: the subject, its state before the action, the action itself, the object or point of contact, which hand, body part, or tool is used, the direction and trajectory, the speed or manner, any intermediate stage, the resulting state, and the observable consequence. A named action on its own is a label, not a description. "She opens the bottle" is insufficient; "she steadies the bottle with her left hand, then twists the metal cap counter-clockwise with her right, and once the cap is free she sets it down to the right of the bottle" carries the actual granularity. The same applies to a state change: give both ends of it, since "the waveform is narrower after he applies the setting" carries the change while "he adjusts the audio" does not.
Granularity does not degrade with video length. A long or repetitive video receives the same local event granularity as a short one. Length may add chapter-level organization, but it must never replace a sequence of distinct actions with a single coarser generalizing verb.
Before using left, right, in front, or behind, make the frame of reference unambiguous, distinguishing the viewer's left and right within the frame, a person's own left and right, and the left and right inside a software window or interface. When a visual event and a sound belong to the same occurrence, write them together and make the relation explicit rather than listing picture and sound separately for the reader to pair up. Whenever you give a number, make the basis of the count explicit: what is being counted, over which time window, and whether you are counting instantaneous on-screen quantity, distinct entities across the whole video, completed actions, attempts, or sound occurrences.
## Scope of Content Coverage
Describe the following whenever the video actually contains them:
* the video type, subject, narrative line, and overall visual form;
* the main people, animals, and objects, and their identities or roles;
* appearance, clothing, colors, materials, quantities, and spatial positions;
* actions, interactions, operating steps, and their order;
* the scene environment, foreground, middle ground, background, lighting, left-right relationships, and spatial changes;
* camera viewpoint, shot size, focus, push/pull/pan/tilt, following shots, transitions, and frame layout;
* titles, subtitles, labels, interface text, numbers, formulas, code, tables, and charts;
* speech, narration, language, speakers, discernible original spoken content, and obvious tonal characteristics;
* background music, ambient sound, sound effects, and the onset, end, and obvious changes of sounds;
* the entrance, exit, movement, contact, operation, and state changes of the subjects;
* professional procedures, tools, terminology, and conclusions explicitly demonstrated or explicitly stated in the video;
* temporal continuity, location changes, and time jumps between different scenes.
Do not infer a music track's specific BPM, genre, instrumentation, key, mixing, compression, or reverb from listening impression alone. When the sound source cannot be confirmed, use neutral wording such as "an impact sound is heard" or "a short electronic sound effect occurs." Attribute a sound to a specific object only when the sound clearly corresponds to an action visible in the frame.
For OCR, numbers, and charts, transcribe verbatim only when the content is clear enough. Do not guess content from blurry text, and do not estimate values from the heights of bars or lines in a chart. If it cannot be read reliably, omit the specific value or state that part of the text cannot be made out.
## Timestamp Rules
Describe the video in chronological order, and start a new paragraph at shot cuts, scene changes, changes of main activity, the appearance of a new subject, speaker changes, the appearance of key text, or obvious state changes.
Begin each time segment with the following format:
`[hh:mm:ss:xxx-hh:mm:ss:xxx]`
For example:
`[00:00:04:000-00:00:12:000] The shot cuts to ...`
Timestamps must be safe time intervals backed by evidence. Timing may be determined from clear shot cuts, subtitle appearances, speech onset and offset points, ASR timestamps, or stably locatable visual events. Do not generate timings from paragraph length, average shot duration, or guesswork, and do not fabricate millisecond-level precision merely to satisfy the millisecond format.
Match precision to the evidence available. Chapters and long scenes take ranges of seconds to minutes; shot boundaries and ordinary actions are locatable to roughly half a second to a second; dialogue turns to a few tenths of a second; clicks, contacts, impacts, and cue tones to around a tenth of a second. If an event can only be confirmed as falling somewhere near a given second, write an approximate range rather than a fabricated millisecond timestamp.
Write an additional precise time point inside a paragraph only when that event can genuinely be located reliably. Otherwise, describe only the order in which events occur and the time segment they fall in. Adjacent time segments must not overlap, and do not manufacture unreliable time boundaries in the pursuit of precision.
Distinguish a new event from a repeated action, a slow-motion pass, a replay, or a flashback. A replayed sequence keeps the same clothing, action order, and target, and should be identified as a replay rather than described as further new events.
## Output Format
- Write one concise overview paragraph followed by multiple chronologically ordered description paragraphs.
- Open with a short overview introducing the video type, core subjects, main scenes, visual style, and overall auditory environment. Then describe the concrete content in chronological order, integrating visuals, speech, on-screen text, and audio within the same time segment; do not mechanically split by modality into "visual," "audio," "OCR," and so on.
- Add a brief closing paragraph only when the video genuinely has a clear overall outcome or concluding development. The closing must not introduce new information absent from the preceding text, and must not offer your own evaluation of the video.
- Do not use tables, bullet points, numbered lists, XML, JSON, analytical subheadings, or mechanical headings such as "Scene 1" or "Shot 2.3." Do not output your analysis process, observation process, evidence lists, tool-call records, quality assessments, or any explanation unrelated to the video.
- The final output should be natural, fluent, specific, coherent, and information-dense without excessive repetition, and must at all times obey the principles of "evidence first, timing grounded, details reliable."
Please describe this video in a super detail manner.
Análisis audiovisual con múltiples hablantes
Utilice audio y video para identificar hablantes y producir una transcripción con marcas de tiempo. Cuando se proporciona video, el modelo puede usar información visual para analizar la correspondencia entre hablantes y habla.
Transcribe the dialogue with speaker identification and timestamps. Output format: <soc><sos><start_time>text<end_time><speakerX><eos>...<eoc>.
Localización de eventos de audio
Localice un evento de sonido específico. Reemplace [audio event label] en el prompt con el evento objetivo, como dog_barking. El resultado contiene el tipo de evento y los tiempos de inicio y fin en segundos.
Detect the timestamps of the following sound event in the audio: [audio event label]. Output the result strictly as a JSON array. Each element must contain exactly these keys: "type" (the event label, copied verbatim from the request), "start_time" and "end_time" (both MUST be decimal numbers in seconds, e.g. 4.5 or 12.0, NOT strings, and NOT in mm:ss or hh:mm:ss format). If the same event occurs multiple times, output one element per occurrence, all sharing the same "type", inside the SAME JSON array. Do not include any text outside the JSON array. Example: [{"type": "dog_barking", "start_time": 1.23, "end_time": 4.56}]
Entrada multimodal combinada
Qwen3.8-Omni-Flash y Qwen3.5-Omni admiten la combinación de texto, imágenes, audio y video en la misma solicitud. Los siguientes ejemplos utilizan Qwen3.8-Omni-Flash para analizar una imagen y audio, y generar una respuesta de texto. Para generar voz, utilice Qwen3.5-Omni. Consulte el ejemplo de salida de audio.
import os
from openai import OpenAI
client = OpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"),
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
model="qwen3.8-omni-flash",
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": "input_audio",
"input_audio": {
"data": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250211/tixcef/cherry.wav",
"format": "wav"
},
},
{"type": "text", "text": "Describe the image content and tell me what the audio is about."},
],
},
],
modalities=["text"],
stream=True,
stream_options={"include_usage": True},
)
for chunk in completion:
if chunk.choices:
print(chunk.choices[0].delta)
else:
print(chunk.usage)
import OpenAI from "openai";
const openai = new OpenAI(
{
// API keys for the Singapore and Beijing regions are different. Get an API key: https://www.alibabacloud.com/help/model-studio/get-api-key
apiKey: process.env.DASHSCOPE_API_KEY,
// The following URL is for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
}
);
const completion = await openai.chat.completions.create({
model: "qwen3.8-omni-flash",
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": "input_audio",
"input_audio": {
"data": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250211/tixcef/cherry.wav",
"format": "wav"
},
},
{ "type": "text", "text": "Describe the image content and tell me what the audio is about." }
]
}
],
stream: true,
stream_options: {
include_usage: true
},
modalities: ["text"],
});
for await (const chunk of completion) {
if (Array.isArray(chunk.choices) && chunk.choices.length > 0) {
console.log(chunk.choices[0].delta);
} else {
console.log(chunk.usage);
}
}
# API keys for the Singapore and Beijing regions are different. Get an API key: https://www.alibabacloud.com/help/model-studio/get-api-key
# The following URL is for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen3.8-omni-flash",
"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": "input_audio",
"input_audio": {
"data": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250211/tixcef/cherry.wav",
"format": "wav"
}
},
{
"type": "text",
"text": "Describe the image content and tell me what the audio is about."
}
]
}
],
"stream": true,
"stream_options": {
"include_usage": true
},
"modalities": ["text"]
}'
Entrada de modalidad única
Cada solicitud contiene texto y otra modalidad (video, audio o imagen). Los ejemplos utilizan Qwen3.8-Omni-Flash para devolver texto mediante Chat Completions.
Entrada de video y texto
Proporcione el video como una lista de imágenes o un archivo de video (con soporte de audio).
Archivo de video (admite audio en el video)
import os
from openai import OpenAI
client = OpenAI(
# API keys for the Singapore and Beijing regions are different. Get an API key: https://www.alibabacloud.com/help/model-studio/get-api-key
api_key=os.getenv("DASHSCOPE_API_KEY"),
# The following URL is for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
model="qwen3.8-omni-flash",
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": "What is the video about?"},
],
},
],
modalities=["text"],
stream=True,
stream_options={"include_usage": True},
)
for chunk in completion:
if chunk.choices:
print(chunk.choices[0].delta)
else:
print(chunk.usage)
import OpenAI from "openai";
const openai = new OpenAI(
{
// API keys for the Singapore and Beijing regions are different. Get an API key: https://www.alibabacloud.com/help/model-studio/get-api-key
apiKey: process.env.DASHSCOPE_API_KEY,
// The following URL is for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
}
);
const completion = await openai.chat.completions.create({
model: "qwen3.8-omni-flash",
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": "What is the video about?" }]
}],
stream: true,
stream_options: {
include_usage: true
},
modalities: ["text"],
});
for await (const chunk of completion) {
if (Array.isArray(chunk.choices) && chunk.choices.length > 0) {
console.log(chunk.choices[0].delta);
} else {
console.log(chunk.usage);
}
}
# ======= Important note =======
# API keys for the Singapore and Beijing regions are different. Get an API key: https://www.alibabacloud.com/help/model-studio/get-api-key
# The following URL is for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
# === Delete this comment before execution ===
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen3.8-omni-flash",
"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": "What is the video about"
}
]
}
],
"stream":true,
"stream_options": {
"include_usage": true
},
"modalities":["text"]
}'
Límites de entrada
-
Número de archivos:
- Qwen3.8-Omni-Flash: Hasta 64 archivos.
- Serie Qwen3.5-Omni: Hasta 512 archivos mediante URL públicas y hasta 250 archivos mediante codificación Base64.
- Serie Qwen3-Omni-Flash: Solo se permite un archivo.
-
Tamaño del archivo:
-
Uso de URL públicas:
- Series Qwen3.8-Omni-Flash y Qwen3.5-Omni: Hasta 2 GB
- Qwen3-Omni-Flash: Hasta 256 MB
-
Uso de codificación Base64: La cadena Base64 codificada debe ser menor que 10 MB
-
-
Límites de duración:
- Qwen3.8-Omni-Flash: 2 horas
- Serie Qwen3.5-Omni: 1 hora
- Qwen3-Omni-Flash: 150 segundos
-
Formatos de archivo: MP4, AVI, MKV, MOV, FLV y WMV.
-
La información visual y de audio en el archivo de video se facturan por separado.
Formato de lista de imágenes
import os
from openai import OpenAI
client = OpenAI(
# API keys for the Singapore and Beijing regions are different. Get an API key: https://www.alibabacloud.com/help/model-studio/get-api-key
api_key=os.getenv("DASHSCOPE_API_KEY"),
# The following URL is for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
model="qwen3.8-omni-flash",
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": "Describe the process shown in this video"},
],
}
],
modalities=["text"],
stream=True,
stream_options={"include_usage": True},
)
for chunk in completion:
if chunk.choices:
print(chunk.choices[0].delta)
else:
print(chunk.usage)
import OpenAI from "openai";
const openai = new OpenAI(
{
// API keys for the Singapore and Beijing regions are different. Get an API key: https://www.alibabacloud.com/help/model-studio/get-api-key
apiKey: process.env.DASHSCOPE_API_KEY,
// The following URL is for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
}
);
const completion = await openai.chat.completions.create({
model: "qwen3.8-omni-flash",
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: "Describe the process shown in this video"
}
]
}],
stream: true,
stream_options: {
include_usage: true
},
modalities: ["text"],
});
for await (const chunk of completion) {
if (Array.isArray(chunk.choices) && chunk.choices.length > 0) {
console.log(chunk.choices[0].delta);
} else {
console.log(chunk.usage);
}
}
# ======= Important note =======
# API keys for the Singapore and Beijing regions are different. Get an API key: https://www.alibabacloud.com/help/model-studio/get-api-key
# The following URL is for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
# === Delete this comment before execution ===
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen3.8-omni-flash",
"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": "Describe the process shown in this video"
}
]
}
],
"stream": true,
"stream_options": {
"include_usage": true
},
"modalities": ["text"]
}'
Límites de entrada
- Series Qwen3.8-Omni-Flash y Qwen3.5-Omni: Un mínimo de 2 imágenes y un máximo de 2048 imágenes
- Qwen3-Omni-Flash: Un mínimo de 2 imágenes y un máximo de 128 imágenes
Entrada de audio y texto
Este ejemplo utiliza una URL pública de audio. Para usar un archivo local, consulte Enviar archivos locales con codificación Base64. El siguiente ejemplo utiliza salida en streaming.
import os
from openai import OpenAI
client = OpenAI(
# API keys for the Singapore and Beijing regions are different. Get an API key: https://www.alibabacloud.com/help/model-studio/get-api-key
api_key=os.getenv("DASHSCOPE_API_KEY"),
# The following URL is for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
model="qwen3.8-omni-flash",
messages=[
{
"role": "user",
"content": [
{
"type": "input_audio",
"input_audio": {
"data": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250211/tixcef/cherry.wav",
"format": "wav",
},
},
{"type": "text", "text": "What is this audio about"},
],
},
],
modalities=["text"],
stream=True,
stream_options={"include_usage": True},
)
for chunk in completion:
if chunk.choices:
print(chunk.choices[0].delta)
else:
print(chunk.usage)
import OpenAI from "openai";
const openai = new OpenAI(
{
// API keys for the Singapore and Beijing regions are different. Get an API key: https://www.alibabacloud.com/help/model-studio/get-api-key
apiKey: process.env.DASHSCOPE_API_KEY,
// The following URL is for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
}
);
const completion = await openai.chat.completions.create({
model: "qwen3.8-omni-flash",
messages: [
{
"role": "user",
"content": [{
"type": "input_audio",
"input_audio": { "data": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250211/tixcef/cherry.wav", "format": "wav" },
},
{ "type": "text", "text": "What is this audio about" }]
}],
stream: true,
stream_options: {
include_usage: true
},
modalities: ["text"],
});
for await (const chunk of completion) {
if (Array.isArray(chunk.choices) && chunk.choices.length > 0) {
console.log(chunk.choices[0].delta);
} else {
console.log(chunk.usage);
}
}
# ======= Important note =======
# API keys for the Singapore and Beijing regions are different. Get an API key: https://www.alibabacloud.com/help/model-studio/get-api-key
# The following URL is for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
# === Delete this comment before execution ===
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen3.8-omni-flash",
"messages": [
{
"role": "user",
"content": [
{
"type": "input_audio",
"input_audio": {
"data": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250211/tixcef/cherry.wav",
"format": "wav"
}
},
{
"type": "text",
"text": "What is this audio about"
}
]
}
],
"stream":true,
"stream_options":{
"include_usage":true
},
"modalities":["text"]
}'
Límites de entrada
-
Número de archivos:
- Series Qwen3.8-Omni-Flash y Qwen3.5-Omni: Hasta 2048 archivos mediante URL públicas y hasta 250 archivos mediante codificación Base64.
- Serie Qwen3-Omni-Flash: Solo se permite un archivo.
-
Tamaño del archivo:
-
Uso de URL públicas:
- Series Qwen3.8-Omni-Flash y Qwen3.5-Omni: Hasta 2 GB
- Qwen3-Omni-Flash: Hasta 100 MB
-
Uso de codificación Base64: La cadena Base64 codificada debe ser menor que 10 MB
-
-
Límites de duración:
- Series Qwen3.8-Omni-Flash y Qwen3.5-Omni: Hasta 3 horas
- Qwen3-Omni-Flash: Hasta 20 minutos
-
Formatos de archivo: AMR, WAV, 3GP, 3GPP, AAC y MP3.
Entrada de imagen y texto
Este ejemplo utiliza una URL pública de imagen. Para usar un archivo local, consulte Archivo local codificado en Base64 de entrada. El siguiente ejemplo utiliza salida en streaming.
import os
from openai import OpenAI
client = OpenAI(
# API keys for the Singapore and Beijing regions are different. Get an API key: https://www.alibabacloud.com/help/model-studio/get-api-key
api_key=os.getenv("DASHSCOPE_API_KEY"),
# The following URL is for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
model="qwen3.8-omni-flash",
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": "What scene is depicted in the image?"},
],
},
],
modalities=["text"],
stream=True,
stream_options={
"include_usage": True
}
)
for chunk in completion:
if chunk.choices:
print(chunk.choices[0].delta)
else:
print(chunk.usage)
import OpenAI from "openai";
const openai = new OpenAI(
{
// API keys for the Singapore and Beijing regions are different. Get an API key: https://www.alibabacloud.com/help/model-studio/get-api-key
apiKey: process.env.DASHSCOPE_API_KEY,
// The following URL is for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
}
);
const completion = await openai.chat.completions.create({
model: "qwen3.8-omni-flash",
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": "What scene is depicted in the image?" }]
}],
stream: true,
stream_options: {
include_usage: true
},
modalities: ["text"],
});
for await (const chunk of completion) {
if (Array.isArray(chunk.choices) && chunk.choices.length > 0) {
console.log(chunk.choices[0].delta);
} else {
console.log(chunk.usage);
}
}
# ======= Important note =======
# API keys for the Singapore and Beijing regions are different. Get an API key: https://www.alibabacloud.com/help/model-studio/get-api-key
# The following URL is for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
# === Delete this comment before execution ===
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen3.8-omni-flash",
"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": "What scene is depicted in the image?"
}
]
}
],
"stream":true,
"stream_options":{
"include_usage":true
},
"modalities":["text"]
}'
Límites de entrada
Los modelos Qwen-Omni admiten múltiples imágenes por solicitud. Requisitos de imagen:
-
Número de imágenes:
- Uso de una URL pública: Hasta 2048 imágenes
- Uso de codificación Base64: Hasta 250 imágenes
-
Tamaño de imagen:
-
Uso de URL públicas:
- Series Qwen3.8-Omni-Flash y Qwen3.5-Omni: Cada archivo de imagen no debe exceder 20 MB
- Serie Qwen3-Omni-Flash: Cada archivo de imagen no debe exceder 10 MB
-
Qwen3.5-Omni y Qwen3-Omni-Flash mediante codificación Base64: La cadena Base64 codificada debe ser menor que 10 MB.
-
-
Tanto el ancho como la altura deben superar los 10 píxeles. La relación de aspecto no debe exceder 200:1 o 1:200.
-
Tipos de imagen admitidos: Consulte Comprensión de imágenes y video.
Audio multicanal
qwen3.8-omni-flash admite estéreo de dos canales y audio espacial FOA de cuatro canales (orden de canales WYZX). Estas entradas conservan la información espacial para la comprensión del audio.
use_multichannel tiene como valor predeterminado false, lo que analiza todo el audio como mono. Cuando es true y la entrada tiene dos canales (izquierdo y derecho) o cuatro canales (FOA, en orden WYZX), el modelo analiza la información de audio espacial.
En el ejemplo de inicio rápido de Chat Completions, configure AUDIO_URL con el audio WAV multicanal correspondiente y agregue el siguiente argumento a client.chat.completions.create(). En una solicitud HTTP, use_multichannel es un campo de nivel superior del cuerpo de la solicitud.
extra_body={"use_multichannel": True},
El siguiente ejemplo completo utiliza un WAV estéreo de dos canales para llamar a qwen3.8-omni-flash para la comprensión de audio espacial. Para audio FOA de cuatro canales, la llamada es idéntica; simplemente establezca AUDIO_URL en un WAV de cuatro canales en orden de canales WYZX.
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ["DASHSCOPE_API_KEY"],
base_url=os.environ["DASHSCOPE_BASE_URL"],
)
completion = client.chat.completions.create(
model="qwen3.8-omni-flash",
messages=[{
"role": "user",
"content": [
{"type": "text", "text": "Describe the spatial audio information in this recording."},
{"type": "input_audio", "input_audio": {
"data": os.environ["AUDIO_URL"],
"format": "wav",
}},
],
}],
extra_body={"use_multichannel": True},
stream=True,
stream_options={"include_usage": True},
)
for chunk in completion:
if not chunk.choices:
if chunk.usage:
print("\nUsage:", chunk.usage)
continue
delta = chunk.choices[0].delta
if getattr(delta, "reasoning_content", None):
print(delta.reasoning_content, end="", flush=True)
if delta.content:
print(delta.content, end="", flush=True)
NotaEl audio multicanal debe tener 2 canales (estéreo de dos canales, izquierdo y derecho) o 4 canales (FOA de cuatro canales, orden de canales WYZX). Puede verificar el número de canales con soundfile:
python3 -c "import soundfile as sf; print(sf.info('audio.wav').channels)"
Búsqueda web
Qwen3.8-Omni-Flash admite la búsqueda web para recuperar información actualizada y generar respuestas de texto.
Qwen3.8-Omni-Flash utiliza la herramienta web_search a través de Responses. Qwen3.8-Omni-Flash y Qwen3.5-Omni utilizan la estrategia de búsqueda agent a través de Chat Completions. Para tarifas, consulte Facturación de búsqueda web.
Los siguientes ejemplos de Chat Completions utilizan Qwen3.8-Omni-Flash con enable_search=True y search_options={"search_strategy": "agent"} para habilitar la búsqueda web y reasoning_effort="none" para desactivar el pensamiento, y luego leen respuestas de texto en streaming.
# Prerequisites:
# pip install openai
import os
from openai import OpenAI
# Initialize the client
client = OpenAI(
# API Keys differ between Singapore and Beijing regions. Get API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
api_key=os.getenv("DASHSCOPE_API_KEY"),
# The following URL is for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
# Send request (with web search enabled)
try:
completion = client.chat.completions.create(
model="qwen3.8-omni-flash",
reasoning_effort="none",
messages=[{
"role": "user",
"content": "What is today's date and day of the week, and what important holidays are there today?"
}],
stream=True,
stream_options={"include_usage": True},
# Enable web search
extra_body={
"enable_search": True,
"search_options": {"search_strategy": "agent"}
}
)
print("Model response (with real-time information):")
for chunk in completion:
if chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="")
print()
except Exception as e:
print(f"Request failed:{e}")
// Prerequisites:
// npm install openai
import OpenAI from "openai";
// Initialize the client
const openai = new OpenAI({
// API Keys differ between Singapore and Beijing regions. Get API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
apiKey: process.env.DASHSCOPE_API_KEY,
// The following URL is for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
});
// Send request (with web search enabled)
const completion = await openai.chat.completions.create({
model: "qwen3.8-omni-flash",
reasoning_effort: "none",
messages: [{
"role": "user",
"content": "What is today's date and day of the week, and what important holidays are there today?"
}],
stream: true,
stream_options: {
include_usage: true
},
// Enable web search
enable_search: true,
search_options: { search_strategy: "agent" }
});
console.log("Model response (with real-time information):");
for await (const chunk of completion) {
if (Array.isArray(chunk.choices) && chunk.choices.length > 0) {
if (chunk.choices[0].delta.content) {
process.stdout.write(chunk.choices[0].delta.content);
}
}
}
console.log();
# ======= Important =======
# API Keys differ between Singapore and Beijing regions. Get API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
# The following URL is for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
# === Remove this comment before running ===
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen3.8-omni-flash",
"reasoning_effort": "none",
"messages": [
{
"role": "user",
"content": "What is today\u0027s date and day of the week, and what important holidays are there today?"
}
],
"stream": true,
"stream_options": {
"include_usage": true
},
"enable_search": true,
"search_options": {"search_strategy": "agent"}
}'
Activar/desactivar el modo de pensamiento
Qwen3.8-Omni-Flash
El razonamiento está activado de forma predeterminada para qwen3.8-omni-flash, con reasoning_effort establecido por defecto en xhigh. El campo de solicitud de nivel superior de Chat Completions reasoning_effort acepta none, minimal, low, medium, high, xhigh y max. No configure reasoning_effort y thinking_budget simultáneamente: la solicitud devolverá un error.
Elija low, medium o xhigh para el esfuerzo de pensamiento. Por compatibilidad, minimal se asigna a low, high y max se asignan a xhigh, y none deshabilita el pensamiento.
Agregue el siguiente argumento a client.chat.completions.create() en el ejemplo de inicio rápido de Chat Completions. Pase reasoning_effort directamente como argumento del SDK.
reasoning_effort="low",
Qwen3-Omni-Flash
Esta sección describe el pensamiento híbrido para Qwen3-Omni-Flash. Puede utilizar el parámetro enable_thinking para activar o desactivar el modo de pensamiento:
truefalse(predeterminado)
En el modo de pensamiento, no se admite la salida de audio.
import os
from openai import OpenAI
client = OpenAI(
# API keys for the Singapore and Beijing regions are different. Get an API key: https://www.alibabacloud.com/help/model-studio/get-api-key
api_key=os.getenv("DASHSCOPE_API_KEY"),
# The following URL is for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
model="qwen3-omni-flash",
messages=[{"role": "user", "content": "Who are you?"}],
extra_body={'enable_thinking': True},
# Set the output modality. Two options are supported in non-thinking mode: ["text","audio"] and ["text"]. Only ["text"] is supported in thinking mode.
modalities=["text"],
# Set the voice. The audio parameter is not supported in thinking mode.
# audio={"voice": "Tina", "format": "wav"},
# stream must be set to True, otherwise an error occurs.
stream=True,
stream_options={"include_usage": True},
)
for chunk in completion:
if chunk.choices:
print(chunk.choices[0].delta)
else:
print(chunk.usage)
import OpenAI from "openai";
const openai = new OpenAI(
{
// API keys for the Singapore and Beijing regions are different. Get an API key: https://www.alibabacloud.com/help/model-studio/get-api-key
apiKey: process.env.DASHSCOPE_API_KEY,
// The following URL is for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
}
);
const completion = await openai.chat.completions.create({
model: "qwen3-omni-flash",
messages: [
{ role: "user", content: "Who are you?" }
],
// stream must be set to True, otherwise an error occurs.
stream: true,
stream_options: {
include_usage: true
},
// Enable or disable thinking mode. Audio output is not supported in thinking mode
enable_thinking: true,
// Set the output modality. Two options are supported in non-thinking mode: ["text","audio"] and ["text"]. Only ["text"] is supported in thinking mode.
modalities: ["text"],
// Set the voice. The audio parameter is not supported in thinking mode.
//audio: { voice: "Tina", format: "wav" }
});
for await (const chunk of completion) {
if (Array.isArray(chunk.choices) && chunk.choices.length > 0) {
console.log(chunk.choices[0].delta);
} else {
console.log(chunk.usage);
}
}
# ======= Important note =======
# API keys for the Singapore and Beijing regions are different. Get an API key: https://www.alibabacloud.com/help/model-studio/get-api-key
# The following URL is for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
# === Delete this comment before execution ===
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen3-omni-flash",
"messages": [
{
"role": "user",
"content": "Who are you?"
}
],
"stream":true,
"stream_options":{
"include_usage":true
},
"modalities":["text"],
"enable_thinking": true
}'
Respuesta
data: {"choices":[{"delta":{"content":null,"role":"assistant","reasoning_content":""},"index":0,"logprobs":null,"finish_reason":null}],"object":"chat.completion.chunk","usage":null,"created":1757937336,"system_fingerprint":null,"model":"qwen3-omni-flash","id":"chatcmpl-ce3d6fe5-e717-4b7e-8b40-3aef12288d4c"}
data: {"choices":[{"finish_reason":null,"logprobs":null,"delta":{"content":null,"reasoning_content":"Hmm"},"index":0}],"object":"chat.completion.chunk","usage":null,"reated":1757937336,"system_fingerprint":null,"model":"qwen3-omni-flash","id":"chatcmpl-ce3d6fe5-e717-4b7e-8b40-3aef12288d4c"}
data: {"choices":[{"delta":{"content":null,"reasoning_content":","},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"reated":1757937336,"system_fingerprint":null,"model":"qwen3-omni-flash","id":"chatcmpl-ce3d6fe5-e717-4b7e-8b40-3aef12288d4c"}
......
data: {"choices":[{"delta":{"content":"Tell me"},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1757937336,"tem_fingerprint":null,"model":"qwen3-omni-flash","id":"chatcmpl-ce3d6fe5-e717-4b7e-8b40-3aef12288d4c"}
data: {"choices":[{"delta":{"content":"!"},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1757937336,"systm_fingerprint":null,"model":"qwen3-omni-flash","id":"chatcmpl-ce3d6fe5-e717-4b7e-8b40-3aef12288d4c"}
data: {"choices":[{"finish_reason":"stop","delta":{"content":"","reasoning_content":null},"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1757937336,"system_fingerprint":null,"model":"qwen3-omni-flash","id":"chatcmpl-ce3d6fe5-e717-4b7e-8b40-3aef12288d4c"}
data: {"choices":[],"object":"chat.completion.chunk","usage":{"prompt_tokens":11,"completion_tokens":363,"total_tokens":374,"completion_tokens_details":{"reasoning_tokens":195,"text_tokens":168},"prompt_tokens_details":{"text_tokens":11}},"created":1757937336,"system_fingerprint":null,"model":"qwen3-omni-flash","id":"chatcmpl-ce3d6fe5-e717-4b7e-8b40-3aef12288d4c"}
Conversación multironda
Para conversaciones de múltiples turnos con Qwen3.8-Omni-Flash, preserve_thinking está activado de forma predeterminada. Coloque la respuesta anterior y el razonamiento en los campos content y reasoning_content del mensaje histórico del asistente, respectivamente, e incluya ese mensaje en messages para la siguiente solicitud. Cuando se proporciona y está activado, el razonamiento histórico cuenta para los tokens de entrada y la facturación. Para un ejemplo completo de múltiples turnos, consulte Pasar el proceso de razonamiento.
El siguiente ejemplo de múltiples turnos utiliza Qwen3.8-Omni-Flash con reasoning_effort="none" para desactivar el razonamiento. Pasa las respuestas de texto en los mensajes históricos del asistente y texto más una modalidad en cada mensaje de usuario. Para entradas combinadas, consulte Entrada multimodal combinada:
-
Mensaje del asistente
Los mensajes del asistente en el arreglo messages solo pueden contener datos de texto.
-
Mensaje de usuario
En este ejemplo, cada mensaje de usuario contiene texto y otra modalidad. En conversaciones de múltiples turnos, puede introducir diferentes modalidades en distintos mensajes de usuario.
import os
from openai import OpenAI
client = OpenAI(
# API keys for the Singapore and Beijing regions are different. Get an API key: https://www.alibabacloud.com/help/model-studio/get-api-key
api_key=os.getenv("DASHSCOPE_API_KEY"),
# The following URL is for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
model="qwen3.8-omni-flash",
reasoning_effort="none",
messages=[
{
"role": "user",
"content": [
{
"type": "input_audio",
"input_audio": {
"data": "https://dashscope.oss-cn-beijing.aliyuncs.com/audios/welcome.mp3",
"format": "mp3",
},
},
{"type": "text", "text": "What is this audio about"},
],
},
{
"role": "assistant",
"content": [{"type": "text", "text": "This audio says: Welcome to Alibaba Cloud"}],
},
{
"role": "user",
"content": [{"type": "text", "text": "Tell me about this company."}],
},
],
modalities=["text"],
stream=True,
stream_options={"include_usage": True},
)
for chunk in completion:
if chunk.choices:
print(chunk.choices[0].delta)
else:
print(chunk.usage)
import OpenAI from "openai";
const openai = new OpenAI(
{
// API keys for the Singapore and Beijing regions are different. Get an API key: https://www.alibabacloud.com/help/model-studio/get-api-key
apiKey: process.env.DASHSCOPE_API_KEY,
// The following URL is for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
}
);
const completion = await openai.chat.completions.create({
model: "qwen3.8-omni-flash",
reasoning_effort: "none",
messages: [
{
"role": "user",
"content": [
{
"type": "input_audio",
"input_audio": {
"data": "https://dashscope.oss-cn-beijing.aliyuncs.com/audios/welcome.mp3",
"format": "mp3",
},
},
{ "type": "text", "text": "What is this audio about" },
],
},
{
"role": "assistant",
"content": [{ "type": "text", "text": "This audio says: Welcome to Alibaba Cloud" }],
},
{
"role": "user",
"content": [{ "type": "text", "text": "Tell me about this company." }]
}],
stream: true,
stream_options: {
include_usage: true
},
modalities: ["text"]
});
for await (const chunk of completion) {
if (Array.isArray(chunk.choices) && chunk.choices.length > 0) {
console.log(chunk.choices[0].delta);
} else {
console.log(chunk.usage);
}
}
# ======= Important note =======
# API keys for the Singapore and Beijing regions are different. Get an API key: https://www.alibabacloud.com/help/model-studio/get-api-key
# The following URL is for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
# === Delete this comment before execution ===
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen3.8-omni-flash",
"reasoning_effort": "none",
"messages": [
{
"role": "user",
"content": [
{
"type": "input_audio",
"input_audio": {
"data": "https://dashscope.oss-cn-beijing.aliyuncs.com/audios/welcome.mp3"
}
},
{
"type": "text",
"text": "What is this audio about"
}
]
},
{
"role": "assistant",
"content": [
{
"type": "text",
"text": "This audio says: Welcome to Alibaba Cloud"
}
]
},
{
"role": "user",
"content": [
{
"type": "text",
"text": "Tell me about this company."
}
]
}
],
"stream": true,
"stream_options": {
"include_usage": true
},
"modalities": ["text"]
}'
Análisis de datos de audio de salida codificados en Base64
Los modelos Qwen-Omni generan audio como datos codificados en Base64 en streaming. Durante la generación, mantenga una variable de cadena y añada los datos codificados en Base64 de cada fragmento devuelto. Una vez completada la generación, decodifique en Base64 la cadena completa para obtener el archivo de audio. Alternativamente, decodifique y reproduzca cada fragmento en tiempo real.
# Installation instructions for pyaudio:
# APPLE Mac OS X
# brew install portaudio
# pip install pyaudio
# Debian/Ubuntu
# sudo apt-get install python-pyaudio python3-pyaudio
# or
# pip install pyaudio
# CentOS
# sudo yum install -y portaudio portaudio-devel && pip install pyaudio
# Microsoft Windows
# python -m pip install pyaudio
import os
from openai import OpenAI
import base64
import numpy as np
import soundfile as sf
client = OpenAI(
# API keys for the Singapore and Beijing regions are different. Get an API key: https://www.alibabacloud.com/help/model-studio/get-api-key
api_key=os.getenv("DASHSCOPE_API_KEY"),
# The following URL is for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
model="qwen3.5-omni-plus", # For Qwen3-Omni-Flash, run in non-thinking mode.
messages=[{"role": "user", "content": "Who are you?"}],
# Set the output modality. Two options are currently supported: ["text","audio"] and ["text"]
modalities=["text", "audio"],
audio={"voice": "Tina", "format": "wav"},
# stream must be set to True, otherwise an error occurs.
stream=True,
stream_options={"include_usage": True},
)
# Method 1: Decode after generation is complete
audio_string = ""
for chunk in completion:
if chunk.choices:
if hasattr(chunk.choices[0].delta, "audio"):
try:
audio_string += chunk.choices[0].delta.audio["data"]
except Exception as e:
print(chunk.choices[0].delta.content)
else:
print(chunk.usage)
wav_bytes = base64.b64decode(audio_string)
audio_np = np.frombuffer(wav_bytes, dtype=np.int16)
sf.write("audio_assistant_py.wav", audio_np, samplerate=24000)
# Method 2: Decode while generating (comment out the code for Method 1 to use Method 2)
# # Initialize PyAudio
# import pyaudio
# import time
# p = pyaudio.PyAudio()
# # Create an audio stream
# stream = p.open(format=pyaudio.paInt16,
# channels=1,
# rate=24000,
# output=True)
# for chunk in completion:
# if chunk.choices:
# if hasattr(chunk.choices[0].delta, "audio"):
# try:
# audio_string = chunk.choices[0].delta.audio["data"]
# wav_bytes = base64.b64decode(audio_string)
# audio_np = np.frombuffer(wav_bytes, dtype=np.int16)
# # Play the audio data directly
# stream.write(audio_np.tobytes())
# except Exception as e:
# print(chunk.choices[0].delta.content)
# time.sleep(0.8)
# # Clean up resources
# stream.stop_stream()
# stream.close()
# p.terminate()
// Before running:
// For Windows/Mac/Linux:
// 1. Ensure Node.js version >= 14 is installed.
// 2. Run the following command to install necessary dependencies:
// npm install openai wav
//
// To use the real-time playback feature (Method 2), you also need:
// Windows:
// npm install speaker
// Mac:
// brew install portaudio
// npm install speaker
// Linux (Ubuntu/Debian):
// sudo apt-get install libasound2-dev
// npm install speaker
import OpenAI from "openai";
const openai = new OpenAI(
{
// API keys for the Singapore and Beijing regions are different. Get an API key: https://www.alibabacloud.com/help/model-studio/get-api-key
apiKey: process.env.DASHSCOPE_API_KEY,
// The following URL is for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
}
);
const completion = await openai.chat.completions.create({
model: "qwen3.5-omni-plus", // For Qwen3-Omni-Flash, run in non-thinking mode.
messages: [
{
"role": "user",
"content": "Who are you?"
}],
stream: true,
stream_options: {
include_usage: true
},
modalities: ["text", "audio"],
audio: { voice: "Tina", format: "wav" }
});
// Method 1: Decode after generation is complete
// Requires installation: npm install wav
import { createWriteStream } from 'node:fs'; // node:fs is a built-in Node.js module, no installation required
import { Writer } from 'wav';
async function convertAudio(audioString, audioPath) {
try {
// Decode the Base64 string into a Buffer
const wavBuffer = Buffer.from(audioString, 'base64');
// Create a WAV file write stream
const writer = new Writer({
sampleRate: 24000, // Sample rate
channels: 1, // Mono
bitDepth: 16 // 16-bit depth
});
// Create an output file stream and establish a pipe connection
const outputStream = createWriteStream(audioPath);
writer.pipe(outputStream);
// Write PCM data and end writing
writer.write(wavBuffer);
writer.end();
// Use a Promise to wait for the file to finish writing
await new Promise((resolve, reject) => {
outputStream.on('finish', resolve);
outputStream.on('error', reject);
});
// Add extra wait time to ensure audio integrity
await new Promise(resolve => setTimeout(resolve, 800));
console.log(`Audio file successfully saved as ${audioPath}`);
} catch (error) {
console.error('An error occurred during processing:', error);
}
}
let audioString = "";
for await (const chunk of completion) {
if (Array.isArray(chunk.choices) && chunk.choices.length > 0) {
if (chunk.choices[0].delta.audio) {
if (chunk.choices[0].delta.audio["data"]) {
audioString += chunk.choices[0].delta.audio["data"];
}
}
} else {
console.log(chunk.usage);
}
}
// Execute the conversion
convertAudio(audioString, "audio_assistant_mjs.wav");
// Method 2: Generate and play in real time
// Install necessary components according to your system's instructions above.
// import Speaker from 'speaker'; // Import the audio playback library
// // Create a speaker instance (configuration matches WAV file parameters)
// const speaker = new Speaker({
// sampleRate: 24000, // Sample rate
// channels: 1, // Number of sound channels
// bitDepth: 16, // Bit depth
// signed: true // Signed PCM
// });
// for await (const chunk of completion) {
// if (Array.isArray(chunk.choices) && chunk.choices.length > 0) {
// if (chunk.choices[0].delta.audio) {
// if (chunk.choices[0].delta.audio["data"]) {
// const pcmBuffer = Buffer.from(chunk.choices[0].delta.audio.data, 'base64');
// // Write directly to the speaker for playback
// speaker.write(pcmBuffer);
// }
// }
// } else {
// console.log(chunk.usage);
// }
// }
// speaker.on('finish', () => console.log('Playback complete'));
// speaker.end(); // Call based on the actual end of the API stream
Archivo local codificado en Base64 de entrada
Los siguientes ejemplos utilizan Qwen3.8-Omni-Flash para analizar archivos locales codificados en Base64 y devolver texto. Para audio y video, la cadena Base64 codificada debe ser menor que 10 MB. Este límite también se aplica a la entrada de imágenes para Qwen3.5-Omni y Qwen3-Omni-Flash.
Imágenes
Este ejemplo utiliza el archivo guardado localmente eagle.png.
import os
from openai import OpenAI
import base64
client = OpenAI(
# API keys for the Singapore and Beijing regions are different. Get an API key: https://www.alibabacloud.com/help/model-studio/get-api-key
api_key=os.getenv("DASHSCOPE_API_KEY"),
# The following URL is for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
# Base64 encoding format
def encode_image(image_path):
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode("utf-8")
base64_image = encode_image("eagle.png")
completion = client.chat.completions.create(
model="qwen3.8-omni-flash",
messages=[
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {"url": f"data:image/png;base64,{base64_image}"},
},
{"type": "text", "text": "What scene is depicted in the image?"},
],
},
],
modalities=["text"],
stream=True,
stream_options={"include_usage": True},
)
for chunk in completion:
if chunk.choices:
print(chunk.choices[0].delta)
else:
print(chunk.usage)
import OpenAI from "openai";
import { readFileSync } from 'fs';
const openai = new OpenAI(
{
// API keys for the Singapore and Beijing regions are different. Get an API key: https://www.alibabacloud.com/help/model-studio/get-api-key
apiKey: process.env.DASHSCOPE_API_KEY,
// The following URL is for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
}
);
const encodeImage = (imagePath) => {
const imageFile = readFileSync(imagePath);
return imageFile.toString('base64');
};
const base64Image = encodeImage("eagle.png")
const completion = await openai.chat.completions.create({
model: "qwen3.8-omni-flash",
messages: [
{
"role": "user",
"content": [{
"type": "image_url",
"image_url": { "url": `data:image/png;base64,${base64Image}` },
},
{ "type": "text", "text": "What scene is depicted in the image?" }]
}],
stream: true,
stream_options: {
include_usage: true
},
modalities: ["text"],
});
for await (const chunk of completion) {
if (Array.isArray(chunk.choices) && chunk.choices.length > 0) {
console.log(chunk.choices[0].delta);
} else {
console.log(chunk.usage);
}
}
Audio
Este ejemplo utiliza el archivo guardado localmente welcome.mp3.
import os
from openai import OpenAI
import base64
import numpy as np
import soundfile as sf
import requests
client = OpenAI(
# API keys for the Singapore and Beijing regions are different. Get an API key: https://www.alibabacloud.com/help/model-studio/get-api-key
api_key=os.getenv("DASHSCOPE_API_KEY"),
# The following URL is for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
def encode_audio(audio_path):
with open(audio_path, "rb") as audio_file:
return base64.b64encode(audio_file.read()).decode("utf-8")
base64_audio = encode_audio("welcome.mp3")
completion = client.chat.completions.create(
model="qwen3.8-omni-flash",
messages=[
{
"role": "user",
"content": [
{
"type": "input_audio",
"input_audio": {
"data": f"data:;base64,{base64_audio}",
"format": "mp3",
},
},
{"type": "text", "text": "What is this audio about"},
],
},
],
modalities=["text"],
stream=True,
stream_options={"include_usage": True},
)
for chunk in completion:
if chunk.choices:
print(chunk.choices[0].delta)
else:
print(chunk.usage)
import OpenAI from "openai";
import { readFileSync } from 'fs';
const openai = new OpenAI(
{
// API keys for the Singapore and Beijing regions are different. Get an API key: https://www.alibabacloud.com/help/model-studio/get-api-key
apiKey: process.env.DASHSCOPE_API_KEY,
// The following URL is for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
}
);
const encodeAudio = (audioPath) => {
const audioFile = readFileSync(audioPath);
return audioFile.toString('base64');
};
const base64Audio = encodeAudio("welcome.mp3")
const completion = await openai.chat.completions.create({
model: "qwen3.8-omni-flash",
messages: [
{
"role": "user",
"content": [{
"type": "input_audio",
"input_audio": { "data": `data:;base64,${base64Audio}`, "format": "mp3" },
},
{ "type": "text", "text": "What is this audio about" }]
}],
stream: true,
stream_options: {
include_usage: true
},
modalities: ["text"],
});
for await (const chunk of completion) {
if (Array.isArray(chunk.choices) && chunk.choices.length > 0) {
console.log(chunk.choices[0].delta);
} else {
console.log(chunk.usage);
}
}
Video
Archivo de video
Este ejemplo utiliza el archivo guardado localmente spring_mountain.mp4.
import os
from openai import OpenAI
import base64
import numpy as np
import soundfile as sf
client = OpenAI(
# API keys for the Singapore and Beijing regions are different. Get an API key: https://www.alibabacloud.com/help/model-studio/get-api-key
api_key=os.getenv("DASHSCOPE_API_KEY"),
# The following URL is for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
# Base64 encoding format
def encode_video(video_path):
with open(video_path, "rb") as video_file:
return base64.b64encode(video_file.read()).decode("utf-8")
base64_video = encode_video("spring_mountain.mp4")
completion = client.chat.completions.create(
model="qwen3.8-omni-flash",
messages=[
{
"role": "user",
"content": [
{
"type": "video_url",
"video_url": {"url": f"data:;base64,{base64_video}"},
},
{"type": "text", "text": "What is she singing?"},
],
},
],
modalities=["text"],
stream=True,
stream_options={"include_usage": True},
)
for chunk in completion:
if chunk.choices:
print(chunk.choices[0].delta)
else:
print(chunk.usage)
import OpenAI from "openai";
import { readFileSync } from 'fs';
const openai = new OpenAI(
{
// API keys for the Singapore and Beijing regions are different. Get an API key: https://www.alibabacloud.com/help/model-studio/get-api-key
apiKey: process.env.DASHSCOPE_API_KEY,
// The following URL is for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
}
);
const encodeVideo = (videoPath) => {
const videoFile = readFileSync(videoPath);
return videoFile.toString('base64');
};
const base64Video = encodeVideo("spring_mountain.mp4")
const completion = await openai.chat.completions.create({
model: "qwen3.8-omni-flash",
messages: [
{
"role": "user",
"content": [{
"type": "video_url",
"video_url": { "url": `data:;base64,${base64Video}` },
},
{ "type": "text", "text": "What is she singing?" }]
}],
stream: true,
stream_options: {
include_usage: true
},
modalities: ["text"],
});
for await (const chunk of completion) {
if (Array.isArray(chunk.choices) && chunk.choices.length > 0) {
console.log(chunk.choices[0].delta);
} else {
console.log(chunk.usage);
}
}
Lista de imágenes
Por ejemplo, considere los archivos guardados localmente football1.jpg, football2.jpg, football3.jpg y football4.jpg.
import os
from openai import OpenAI
import base64
import numpy as np
import soundfile as sf
client = OpenAI(
# API keys for the Singapore and Beijing regions are different. Get an API key: https://www.alibabacloud.com/help/model-studio/get-api-key
api_key=os.getenv("DASHSCOPE_API_KEY"),
# The following URL is for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
)
# Base64 encoding format
def encode_image(image_path):
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode("utf-8")
base64_image_1 = encode_image("football1.jpg")
base64_image_2 = encode_image("football2.jpg")
base64_image_3 = encode_image("football3.jpg")
base64_image_4 = encode_image("football4.jpg")
completion = client.chat.completions.create(
model="qwen3.8-omni-flash",
messages=[
{
"role": "user",
"content": [
{
"type": "video",
"video": [
f"data:image/jpeg;base64,{base64_image_1}",
f"data:image/jpeg;base64,{base64_image_2}",
f"data:image/jpeg;base64,{base64_image_3}",
f"data:image/jpeg;base64,{base64_image_4}",
],
},
{"type": "text", "text": "Describe the process shown in this video"},
],
}
],
modalities=["text"],
stream=True,
stream_options={"include_usage": True},
)
for chunk in completion:
if chunk.choices:
print(chunk.choices[0].delta)
else:
print(chunk.usage)
import OpenAI from "openai";
import { readFileSync } from 'fs';
const openai = new OpenAI(
{
// API keys for the Singapore and Beijing regions are different. Get an API key: https://www.alibabacloud.com/help/model-studio/get-api-key
apiKey: process.env.DASHSCOPE_API_KEY,
// The following URL is for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.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")
const completion = await openai.chat.completions.create({
model: "qwen3.8-omni-flash",
messages: [{
role: "user",
content: [
{
type: "video",
video: [
`data:image/jpeg;base64,${base64Image1}`,
`data:image/jpeg;base64,${base64Image2}`,
`data:image/jpeg;base64,${base64Image3}`,
`data:image/jpeg;base64,${base64Image4}`
]
},
{
type: "text",
text: "Describe the process shown in this video"
}
]
}],
stream: true,
stream_options: {
include_usage: true
},
modalities: ["text"],
});
for await (const chunk of completion) {
if (Array.isArray(chunk.choices) && chunk.choices.length > 0) {
console.log(chunk.choices[0].delta);
} else {
console.log(chunk.usage);
}
}
Referencia de API
- Chat Completions: Parámetros de entrada y salida para los modelos en esta página.
- Responses: Parámetros de entrada y salida para Qwen3.8-Omni-Flash.
Facturación y límites de tasa
Qwen3.8-Omni-Flash admite el almacenamiento en caché implícito automático. qwen3.8-omni-flash admite el almacenamiento en caché de sesiones de Responses. Para la configuración, consulte Caché de sesión.
Qwen-Omni se factura según los tokens consumidos en todas las modalidades (audio, imagen y video). Consulte los detalles de facturación en la consola.
Reglas de conversión de tokens para audio, imágenes y videos
Las reglas de conversión de tokens y los modelos aplicables se enumeran a continuación por modalidad.
Audio
-
Qwen3.8-Omni-Flash: Fórmula de audio de entrada:Total tokens = Audio duration (seconds) * 7. -
Qwen3.5-Omni series:- Fórmula de audio de entrada:
Total tokens = Audio duration (seconds) * 7 - Fórmula de audio de salida:
Total tokens = Audio duration (seconds) * 12.5
- Fórmula de audio de entrada:
-
Qwen3-Omni-Flash: Para el audio de entrada y salida,Total tokens = Audio duration (seconds) * 12.5
Si la duración del audio es inferior a 1 segundo, se cuenta como 1 segundo.
Imágenes
Qwen3.8-Omni-Flash,Qwen3.5-Omni seriesyQwen3-Omni-Flash: 1 token por cada32x32píxeles
Para Qwen3.8-Omni-Flash y la serie Qwen3.5-Omni, cada imagen requiere un mínimo de 24 tokens; para Qwen3-Omni-Flash, el mínimo es de 4 tokens. El máximo predeterminado es de 1280 tokens. Qwen3.8-Omni-Flash y la serie Qwen3.5-Omni admiten el parámetro vl_high_resolution_images para aumentar el máximo a 16384 tokens (Qwen3-Omni-Flash no admite este parámetro). Utilice el siguiente código para estimar el recuento de tokens para una sola imagen:
import math
from PIL import Image # pip install Pillow
# ============ Model configuration (modify as needed) ============
# Image factor: 32 for Qwen3.8-Omni-Flash, Qwen3.5-Omni series, and Qwen3-Omni-Flash
IMAGE_FACTOR = 32
# Min tokens: 24 for Qwen3.8-Omni-Flash and Qwen3.5-Omni series; 4 for Qwen3-Omni-Flash
MIN_TOKENS = 24
# High-resolution mode (Qwen3.8-Omni-Flash and Qwen3.5-Omni series; not supported by Qwen3-Omni-Flash)
# True → max tokens = 16384
# False → max tokens = 1280 (default)
VL_HIGH_RESOLUTION_IMAGES = False
# ============ Pixel range (auto-calculated from above) ============
MIN_PIXELS = MIN_TOKENS * IMAGE_FACTOR * IMAGE_FACTOR
MAX_PIXELS = (16384 if VL_HIGH_RESOLUTION_IMAGES else 1280) * IMAGE_FACTOR * IMAGE_FACTOR
def smart_resize(height, width, factor=IMAGE_FACTOR,
min_pixels=MIN_PIXELS, max_pixels=MAX_PIXELS):
"""Align image dimensions to multiples of factor and scale to [min_pixels, max_pixels]."""
h_bar = max(factor, round(height / factor) * factor)
w_bar = max(factor, round(width / factor) * factor)
if h_bar * w_bar > max_pixels:
beta = math.sqrt((height * width) / max_pixels)
h_bar = math.floor(height / beta / factor) * factor
w_bar = math.floor(width / beta / factor) * factor
elif h_bar * w_bar < min_pixels:
beta = math.sqrt(min_pixels / (height * width))
h_bar = math.ceil(height * beta / factor) * factor
w_bar = math.ceil(width * beta / factor) * factor
return h_bar, w_bar
if __name__ == "__main__":
image = Image.open("xxx/test.jpg")
print(f"Original size: {image.width}x{image.height}")
resized_h, resized_w = smart_resize(image.height, image.width)
token = int(resized_h * resized_w / (IMAGE_FACTOR * IMAGE_FACTOR)) + 2
print(f"Resized: {resized_w}x{resized_h}, tokens: {token}")
Video
Los tokens para archivos de video se dividen en video_tokens y audio_tokens.
-
video_tokensUtilice el siguiente código para estimar los tokens correspondientes a la parte visual de un video. Qwen3.8-Omni-Flash y Qwen3.5-Omni utilizan el mismo método de cálculo y parámetros de modelo:
# pip install opencv-python
import math
import cv2
# ============ Model configuration (modify as needed) ============
# Image factor: 32 for Qwen3.8-Omni-Flash, Qwen3.5-Omni series, and Qwen3-Omni-Flash
IMAGE_FACTOR = 32
FRAME_FACTOR = 2
FPS = 2
MAX_RATIO = 200
# Min pixels per video frame
VIDEO_MIN_PIXELS = 64 * IMAGE_FACTOR * IMAGE_FACTOR
# Max pixels per video frame
# Qwen3.8-Omni-Flash and Qwen3.5-Omni series: 640 * 32 * 32
# Qwen3-Omni-Flash: 768 * 32 * 32
VIDEO_MAX_PIXELS = 640 * IMAGE_FACTOR * IMAGE_FACTOR
# Min extracted frames: 2 for Qwen3.8-Omni-Flash, Qwen3.5-Omni series, and Qwen3-Omni-Flash
FPS_MIN_FRAMES = 2
# Max extracted frames: 2048 for Qwen3.8-Omni-Flash and Qwen3.5-Omni series; 128 for Qwen3-Omni-Flash
FPS_MAX_FRAMES = 2048
# Max total pixels for video input
# Qwen3.8-Omni-Flash and Qwen3.5-Omni series: 180224 * 32 * 32
# Qwen3-Omni-Flash: 16384 * 32 * 32
VIDEO_TOTAL_PIXELS = 180224 * IMAGE_FACTOR * IMAGE_FACTOR
# ============ Core functions ============
def get_video_info(video_path):
"""Read basic video info: height, width, total frames, fps."""
cap = cv2.VideoCapture(video_path)
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
fps = cap.get(cv2.CAP_PROP_FPS)
cap.release()
return height, width, total_frames, fps
def smart_nframes(total_frames, video_fps):
"""Calculate the number of frames to extract based on video duration and fps."""
min_frames = math.ceil(FPS_MIN_FRAMES / FRAME_FACTOR) * FRAME_FACTOR
max_frames = min(FPS_MAX_FRAMES, total_frames) // FRAME_FACTOR * FRAME_FACTOR
duration = total_frames / video_fps if video_fps else 0
if duration - int(duration) > (1 / FPS):
total_frames = math.ceil(duration * video_fps)
else:
total_frames = math.ceil(int(duration) * video_fps)
nframes = total_frames / video_fps * FPS
nframes = int(min(max(nframes, min_frames), max_frames, total_frames))
if not (FRAME_FACTOR <= nframes <= total_frames):
raise ValueError(f"nframes should in [{FRAME_FACTOR}, {total_frames}], got {nframes}")
return nframes
def smart_resize(height, width, nframes, factor=IMAGE_FACTOR):
"""Scale video frames to a reasonable pixel range, aligning to multiples of factor."""
max_pixels = max(
min(VIDEO_MAX_PIXELS, VIDEO_TOTAL_PIXELS / nframes * FRAME_FACTOR),
int(VIDEO_MIN_PIXELS * 1.05)
)
if max(height, width) / min(height, width) > MAX_RATIO:
raise ValueError(f"aspect ratio exceeds {MAX_RATIO}")
h_bar = max(factor, round(height / factor) * factor)
w_bar = max(factor, round(width / factor) * factor)
if h_bar * w_bar > max_pixels:
beta = math.sqrt((height * width) / max_pixels)
h_bar = math.floor(height / beta / factor) * factor
w_bar = math.floor(width / beta / factor) * factor
elif h_bar * w_bar < VIDEO_MIN_PIXELS:
beta = math.sqrt(VIDEO_MIN_PIXELS / (height * width))
h_bar = math.ceil(height * beta / factor) * factor
w_bar = math.ceil(width * beta / factor) * factor
return h_bar, w_bar
# ============ Calculate tokens ============
if __name__ == "__main__":
video_path = "spring_mountain.mp4"
height, width, total_frames, video_fps = get_video_info(video_path)
print(f"Video info: {width}x{height}, {total_frames} frames, {video_fps:.1f} fps")
nframes = smart_nframes(total_frames, video_fps)
resized_h, resized_w = smart_resize(height, width, nframes)
video_tokens = int(
math.ceil(nframes / FPS) * resized_h / IMAGE_FACTOR * resized_w / IMAGE_FACTOR
) + 2
print(f"Extracted frames: {nframes}, resized: {resized_w}x{resized_h}, video_tokens: {video_tokens}")
-
audio_tokens-
Qwen3.8-Omni-Flash: Fórmula de audio de entrada:Total tokens = Audio duration (seconds) * 7. -
Qwen3.5-Omni series:- Audio de entrada:
Total tokens = Audio duration (seconds) * 7 - Audio de salida:
Total tokens = Audio duration (seconds) * 12.5
- Audio de entrada:
-
Qwen3-Omni-Flash: Para el audio de entrada y salida,Total tokens = Audio duration (seconds) * 12.5
El audio con una duración inferior a 1 segundo se calcula como 1 segundo.
-
Para reclamar, consultar o utilizar su cuota gratuita, consulte Cuota gratuita para nuevos usuarios.
Límites de tasaPara reglas de limitación de tasa y preguntas frecuentes, consulte Limitación de tasa.
Códigos de error
Si la llamada al modelo falla y devuelve un mensaje de error, consulte Códigos de error para su resolución.
Lista de voces
Para las voces disponibles en los modelos Qwen-Omni que admiten salida de audio, consulte Lista de voces.