Extract text, structured data, and key information from images using the Qwen-OCR model. Qwen-OCR supports two API protocols: the OpenAI-compatible API and the DashScope API.
This topic describes the input and output parameters for calling the Qwen OCR models through the OpenAI-compatible API or the DashScope API.
The base_url for SDK calls: https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1
The endpoint for HTTP calls: POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/chat/completions
Singapore region
The base_url for SDK calls: https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1
The endpoint for HTTP calls: POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions
US (Virginia) region
The base_url for SDK calls: https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/compatible-mode/v1
The endpoint for HTTP calls: POST https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions
ImportantAlibaba Cloud Model Studio has released workspace-specific domains for the China (Beijing) and Singapore regions, which deliver superior performance and higher stability for inference requests. We recommend migrating to the new domains:
China (Beijing): from https://dashscope.aliyuncs.com to https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com
Singapore: from https://dashscope-intl.aliyuncs.com to https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com
{WorkspaceId} is your workspace ID, which you can view on the Workspace Details page in the Alibaba Cloud Model Studio console. The existing domains remain fully functional.
The model name. For supported models, see Select a model.
messagesarray (required)
The context passed to the model, arranged in conversation order.
Message types
User Messageobject (required)
The user message, used to pass instructions and the images to recognize to the model.
Attributes
contentarray (required)
The message content.
Attributes
typestring (required)
Valid values:
text
Set to text when inputting text.
image_url
Set to image_url when inputting an image.
textstring (optional)
The input text.
Default value: Please output only the text content from the image without any additional descriptions or formatting., that is, by default the model extracts all text from the image.
image_urlobject
Information about the input image. Required when type is image_url.
Attributes
urlstring (required)
The image URL or Base64 Data URL. To pass a local file, see Text extraction.
min_pixelsinteger (optional)
Sets the minimum pixel threshold for the input image, in pixels.
When the input image has fewer pixels than min_pixels, the image is enlarged until the total number of pixels exceeds min_pixels.
Conversion between image tokens and pixels
The number of pixels corresponding to each image token varies by model:
qwen3.5-ocr, qwen-vl-ocr-2025-11-20: each token corresponds to 32*32 pixels.
qwen-vl-ocr and earlier models: each token corresponds to 28*28 pixels.
min_pixels value range
qwen3.5-ocr, qwen-vl-ocr-2025-11-20: the default and minimum values are both 3072 (that is, 3×32×32)
qwen-vl-ocr and earlier models: the default and minimum values are both 3136 (that is, 4×28×28).
Example value: {"type": "image_url","image_url": {"url":"https://xxxx.jpg"},"min_pixels": 3072}
max_pixelsinteger (optional)
Sets the maximum pixel threshold for the input image, in pixels.
When the input image is within the [min_pixels, max_pixels] range, the model recognizes the original image. When the input image has more pixels than max_pixels, the image is reduced until the total number of pixels falls below max_pixels.
Conversion between image tokens and pixels
The number of pixels corresponding to each image token varies by model:
qwen3.5-ocr, qwen-vl-ocr-2025-11-20: each token corresponds to 32*32 pixels.
qwen-vl-ocr and earlier models: each token corresponds to 28*28 pixels.
max_pixels value range
qwen3.5-ocr, qwen-vl-ocr-2025-11-20
Default value: 8388608 (that is, 8192x32x32)
Maximum value: 30720000 (that is, 30000x32x32)
qwen-vl-ocr and earlier models
Default value: 6422528 (that is, 8192x28x28)
Maximum value: 23520000 (that is, 30000x28x28)
Example value: {"type": "image_url","image_url": {"url":"https://xxxx.jpg"},"max_pixels": 8388608}
rolestring (required)
The role of the user message, fixed to user.
streamboolean (optional) Default value: false
Whether to return responses in streaming mode.
Valid values:
false: waits until the model has generated the complete response and returns it all at once.
true: the model returns data chunks as it generates. The client must read the chunks one by one to reassemble the complete response.
stream_optionsobject (optional)
Configuration items for streaming output, effective only when stream is true.
Whether to include token usage information in the last data chunk.
Valid values:
true: included;
false: not included.
max_tokensinteger (optional)
Limits the maximum number of tokens the model generates. If the generated content exceeds this value, the response is truncated.
qwen3.5-ocr: the default and maximum values are both 32768.
qwen-vl-ocr-2025-11-20, qwen-vl-ocr-2024-10-28: the default and maximum values are both the model's maximum output length. See Model selection.
qwen-vl-ocr: the default and maximum values are both 4096.
To increase this value (within the 4097~8192 range), contact your business manager to apply, and provide the following information: primary account ID, image type (such as document images, e-commerce images, and contracts), model name, estimated QPS and total daily requests, and the percentage of requests whose model output length exceeds 4096.
logprobsboolean (optional) Default value: false
Whether to return the log probabilities of output tokens. Valid values:
true
Return
false
Do not return
top_logprobsinteger (optional) Default value: 0
Specifies the number of the most likely candidate tokens to return at each generation step.
Value range: [0,5]
Effective only when logprobs is true.
temperaturefloat (optional) Default value: 0.01
The sampling temperature, which controls the diversity of the text generated by the model.
A higher temperature produces more diverse text, while a lower temperature produces more deterministic text.
Value range: [0, 2)
Both temperature and top_p control the diversity of generated text. We recommend setting only one of them.
We recommend keeping the default value.
top_pfloat (optional) Default value: 0.001
The probability threshold for nucleus sampling, which controls the diversity of the text generated by the model.
A higher top_p produces more diverse text, while a lower top_p produces more deterministic text.
Value range: (0,1.0]
Both temperature and top_p control the diversity of generated text. We recommend setting only one of them.
We recommend keeping the default value.
top_kinteger (optional) Default value: 1
The size of the candidate set sampled during generation. For example, when set to 50, only the 50 highest-scoring tokens from a single generation form the random sampling candidate set. A larger value increases randomness, while a smaller value increases determinism. When set to None or greater than 100, the top_k policy is not enabled and only the top_p policy takes effect.
The value must be greater than or equal to 0.
This is not an OpenAI standard parameter. When calling through the Python SDK, put it in the extra_body object, configured as: extra_body={"top_k": xxx}; when calling through the Node.js SDK or HTTP, pass it as a top-level parameter.
The repetition level in consecutive sequences during model generation. Increasing repetition_penalty reduces the repetition in model output, and 1.0 means no penalty. This parameter has a significant impact on model performance, so we recommend keeping the default value.
Controls the content repetition level when the model generates text.
Value range: [-2.0, 2.0]. Positive values reduce repetition, and negative values increase it.
We recommend increasing this value in scenarios that require diversity, fun, or creativity such as creative writing or brainstorming; we recommend decreasing it in scenarios that emphasize consistency and terminology accuracy such as technical documents or formal text.
How it works
If the parameter value is positive, the model applies a penalty to tokens already present in the current text (the penalty is independent of how many times the text appears), reducing the chance of these tokens appearing again, thereby reducing content repetition and increasing word diversity.
We recommend keeping the default value.
seedinteger (optional)
The random number seed, used to ensure that results are reproducible with the same input and parameters. If the same seed is passed with other parameters unchanged, the model will return the same result as much as possible.
Value range: [0,2 31 −1].
We recommend keeping the default value.
stopstring or array (optional)
Specifies stop words. When a string or token_id specified by stop appears in the text generated by the model, generation stops immediately.
You can pass sensitive words to control the model output.
When stop is an array, you cannot mix token_id and strings as elements, for example, you cannot specify ["Hello",104307].
Non-streaming output
from openai import OpenAI
import os
PROMPT_TICKET_EXTRACTION = """
Please extract the invoice number, train number, departure station, arrival station, departure date and time, seat number, seat class, ticket price, ID card number, and passenger name from the train ticket image.
You must accurately extract the key information. Do not omit or fabricate information. Replace any single character that is blurry or obscured by strong light with an English question mark (?).
Return the data in JSON format as follows: {'invoice_number': 'xxx', 'departure_station': 'xxx', 'arrival_station': 'xxx', 'departure_date_and_time':'xxx', 'seat_number': 'xxx','ticket_price':'xxx', 'id_card_number': 'xxx', 'passenger_name': 'xxx'},
"""
try:
client = OpenAI(
# If the environment variable is not configured, replace the following line with your Model Studio API key: api_key="sk-xxx"
# API keys differ by region. Get an API key: https://help.aliyun.com/zh/model-studio/get-api-key
api_key=os.getenv("DASHSCOPE_API_KEY"),
# The following is the base_url for the China (Beijing) region. For the US (Virginia) region, replace base_url with https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/compatible-mode/v1
# For the Singapore region, replace base_url with: https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1
base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
model="qwen3.5-ocr",
messages=[
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {"url":"https://img.alicdn.com/imgextra/i2/O1CN01ktT8451iQutqReELT_!!6000000004408-0-tps-689-487.jpg"},
# Minimum pixel threshold for the input image. Images below this value are enlarged until the total pixels exceed min_pixels
"min_pixels": 32 * 32 * 3,
# Maximum pixel threshold for the input image. Images above this value are reduced until the total pixels fall below max_pixels
"max_pixels": 32 * 32 * 8192
},
# The model supports passing a prompt in the text field below. If not passed, the default prompt is used: Please output only the text content from the image without any additional descriptions or formatting.
{"type": "text",
"text": PROMPT_TICKET_EXTRACTION}
]
}
])
print(completion.choices[0].message.content)
except Exception as e:
print(f"Error message: {e}")
import OpenAI from 'openai';
// Define the prompt for extracting ticket information
const PROMPT_TICKET_EXTRACTION = `
Please extract the invoice number, train number, departure station, arrival station, departure date and time, seat number, seat class, ticket price, ID card number, and passenger name from the train ticket image.
You must accurately extract the key information. Do not omit or fabricate information. Replace any single character that is blurry or obscured by strong light with an English question mark (?).
Return the data in JSON format as follows: {'invoice_number': 'xxx', 'departure_station': 'xxx', 'arrival_station': 'xxx', 'departure_date_and_time':'xxx', 'seat_number': 'xxx','ticket_price':'xxx', 'id_card_number': 'xxx', 'passenger_name': 'xxx'}
`;
// Initialize the OpenAI client
const client = new OpenAI({
// If the environment variable is not configured, replace the following line with your Model Studio API key: apiKey: "sk-xxx",
// API keys differ by region. Get an API key: https://help.aliyun.com/zh/model-studio/get-api-key
apiKey: process.env.DASHSCOPE_API_KEY,
// The following is the base_url for the China (Beijing) region. For the US (Virginia) region, replace base_url with https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/compatible-mode/v1
// For the Singapore region, replace base_url with: https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1
baseURL: "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
});
async function main() {
try {
// Create a chat completion request
const completion = await client.chat.completions.create({
model: "qwen3.5-ocr",
messages: [
{
role: "user",
content: [
// The model supports passing a prompt in the text field. If not passed, the default prompt is used: Please output only the text content from the image without any additional descriptions or formatting.
{
type: "image_url",
image_url: {
url: "https://img.alicdn.com/imgextra/i2/O1CN01ktT8451iQutqReELT_!!6000000004408-0-tps-689-487.jpg",
},
// Minimum pixel threshold for the input image. Images below this value are enlarged until the total pixels exceed min_pixels
min_pixels: 32 * 32 * 3,
// Maximum pixel threshold for the input image. Images above this value are reduced until the total pixels fall below max_pixels
max_pixels: 32 * 32 * 8192
},
{type: "text",
text: PROMPT_TICKET_EXTRACTION}
]
}
]
});
// Output the result
console.log(completion.choices[0].message.content);
} catch (error) {
console.log(`Error message: ${error}`);
}
}
main();
# ======= Important =======
# API keys differ by region. Get an API key: https://help.aliyun.com/zh/model-studio/get-api-key
# The following is the base_url for the China (Beijing) region. For the US (Virginia) region, replace base_url with https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions
# For the Singapore region, replace base_url with: https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions
# === Delete this comment before running ===
curl -X POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen3.5-ocr",
"messages": [
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {"url":"https://img.alicdn.com/imgextra/i2/O1CN01ktT8451iQutqReELT_!!6000000004408-0-tps-689-487.jpg"},
"min_pixels": 3072,
"max_pixels": 8388608
},
{"type": "text", "text": "Please extract the invoice number, train number, departure station, arrival station, departure date and time, seat number, seat class, ticket price, ID card number, and passenger name from the train ticket image. You must accurately extract the key information. Do not omit or fabricate information. Replace any single character that is blurry or obscured by strong light with an English question mark (?). Return the data in JSON format as follows: {'invoice_number': 'xxx', 'departure_station': 'xxx', 'arrival_station': 'xxx', 'departure_date_and_time':'xxx', 'seat_number': 'xxx','ticket_price':'xxx', 'id_card_number': 'xxx', 'passenger_name': 'xxx'"}
]
}
]
}'
Streaming output
import os
from openai import OpenAI
PROMPT_TICKET_EXTRACTION = """
Please extract the invoice number, train number, departure station, arrival station, departure date and time, seat number, seat class, ticket price, ID card number, and passenger name from the train ticket image.
You must accurately extract the key information. Do not omit or fabricate information. Replace any single character that is blurry or obscured by strong light with an English question mark (?).
Return the data in JSON format as follows: {'invoice_number': 'xxx', 'departure_station': 'xxx', 'arrival_station': 'xxx', 'departure_date_and_time':'xxx', 'seat_number': 'xxx','ticket_price':'xxx', 'id_card_number': 'xxx', 'passenger_name': 'xxx'},
"""
client = OpenAI(
# If the environment variable is not configured, replace the following line with your Model Studio API key: api_key="sk-xxx"
# API keys differ by region. Get an API key: https://help.aliyun.com/zh/model-studio/get-api-key
api_key=os.getenv("DASHSCOPE_API_KEY"),
# The following is the base_url for the China (Beijing) region. For the Singapore region, replace base_url with: https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1
base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
model="qwen3.5-ocr",
messages=[
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {"url":"https://img.alicdn.com/imgextra/i2/O1CN01ktT8451iQutqReELT_!!6000000004408-0-tps-689-487.jpg"},
# Minimum pixel threshold for the input image. Images below this value are enlarged until the total pixels exceed min_pixels
"min_pixels": 32 * 32 * 3,
# Maximum pixel threshold for the input image. Images above this value are reduced until the total pixels fall below max_pixels
"max_pixels": 32 * 32 * 8192
},
# The model supports passing a prompt in the text field. If not passed, the default prompt is used: Please output only the text content from the image without any additional descriptions or formatting.
{"type": "text","text": PROMPT_TICKET_EXTRACTION}
]
}
],
stream=True,
stream_options={"include_usage": True}
)
for chunk in completion:
print(chunk.model_dump_json())
import OpenAI from 'openai';
// Define the prompt for extracting ticket information
const PROMPT_TICKET_EXTRACTION = `
Please extract the invoice number, train number, departure station, arrival station, departure date and time, seat number, seat class, ticket price, ID card number, and passenger name from the train ticket image.
You must accurately extract the key information. Do not omit or fabricate information. Replace any single character that is blurry or obscured by strong light with an English question mark (?).
Return the data in JSON format as follows: {'invoice_number': 'xxx','departure_station': 'xxx', 'arrival_station': 'xxx', 'departure_date_and_time':'xxx', 'seat_number': 'xxx','ticket_price':'xxx', 'id_card_number': 'xxx', 'passenger_name': 'xxx'}
`;
const openai = new OpenAI({
// If the environment variable is not configured, replace the following line with your Model Studio API key: apiKey: "sk-xxx",
// The following is the base_url for the China (Beijing) region. For the Singapore region, replace base_url with: https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1
apiKey: process.env.DASHSCOPE_API_KEY,
// The following is the base_url for the China (Beijing) region. For the Singapore region, replace base_url with: https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1
baseURL: 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1',
});
async function main() {
const response = await openai.chat.completions.create({
model: 'qwen3.5-ocr',
messages: [
{
role: 'user',
content: [
// The model supports passing a prompt in the text field. If not passed, the default prompt is used: Please output only the text content from the image without any additional descriptions or formatting.
{ type: 'text', text: PROMPT_TICKET_EXTRACTION},
{
type: 'image_url',
image_url: {
url: 'https://img.alicdn.com/imgextra/i2/O1CN01ktT8451iQutqReELT_!!6000000004408-0-tps-689-487.jpg',
},
// Minimum pixel threshold for the input image. Images below this value are enlarged until the total pixels exceed min_pixels
"min_pixels": 32 * 32 * 3,
// Maximum pixel threshold for the input image. Images above this value are reduced until the total pixels fall below max_pixels
"max_pixels": 32 * 32 * 8192
}
]
}
],
stream: true,
stream_options:{"include_usage": true}
});
let fullContent = ""
console.log("Streaming output content:")
for await (const chunk of response) {
if (chunk.choices[0] && chunk.choices[0].delta.content != null) {
fullContent += chunk.choices[0].delta.content;
console.log(chunk.choices[0].delta.content);
}
}
console.log(`Full output content: ${fullContent}`)
}
main();
# ======= Important =======
# API keys differ by region. Get an API key: https://help.aliyun.com/zh/model-studio/get-api-key
# The following is the base_url for the China (Beijing) region. For the US (Virginia) region, replace base_url with https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions
# For the Singapore region, replace base_url with: https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions
# === Delete this comment before running ===
curl -X POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen3.5-ocr",
"messages": [
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {"url":"https://img.alicdn.com/imgextra/i2/O1CN01ktT8451iQutqReELT_!!6000000004408-0-tps-689-487.jpg"},
"min_pixels": 3072,
"max_pixels": 8388608
},
{"type": "text", "text": "Please extract the invoice number, train number, departure station, arrival station, departure date and time, seat number, seat class, ticket price, ID card number, and passenger name from the train ticket image. You must accurately extract the key information. Do not omit or fabricate information. Replace any single character that is blurry or obscured by strong light with an English question mark (?). Return the data in JSON format as follows: {'invoice_number': 'xxx', 'departure_station': 'xxx', 'arrival_station': 'xxx', 'departure_date_and_time':'xxx', 'seat_number': 'xxx','ticket_price':'xxx', 'id_card_number': 'xxx', 'passenger_name': 'xxx'"}
]
}
],
"stream": true,
"stream_options": {"include_usage": true}
}'
chat response object (non-streaming output)
idstring
The unique identifier of this request.
choicesarray
The array of content generated by the model.
Attributes
finish_reasonstring
The reason the model stopped generating.
There are two cases:
stop when output ends naturally;
length when generation ends because the output is too long.
indexinteger
The index of the current object in the choices array.
messageobject
The message output by the model.
Attributes
contentstring
The result returned by the model.
processed_textstring
The post-processed result of the model's raw output, which automatically removes repeated segments. When the model output contains repeated content, this field provides the cleaned text.
Returned only when called through the DashScope SDK and curl. The OpenAI-compatible SDK does not return this field.
refusalstring
This parameter is currently fixed to null.
rolestring
The role of the message, fixed to assistant.
audioobject
This parameter is currently fixed to null.
function_callobject
This parameter is currently fixed to null.
tool_callsarray
This parameter is currently fixed to null.
createdinteger
The timestamp when this request was created.
modelstring
The model used for this request.
objectstring
Always chat.completion.
service_tierstring
This parameter is currently fixed to null.
system_fingerprintstring
This parameter is currently fixed to null.
usageobject
The token usage information of this request.
Attributes
completion_tokensinteger
The number of tokens generated by the model.
prompt_tokensinteger
The number of input tokens.
total_tokensinteger
The total number of tokens consumed, the sum of prompt_tokens and completion_tokens.
completion_tokens_detailsobject
The fine-grained classification of output tokens.
Attributes
accepted_prediction_tokensinteger
This parameter is currently fixed to null.
audio_tokensinteger
This parameter is currently fixed to null.
reasoning_tokensinteger
This parameter is currently fixed to null.
text_tokensinteger
The number of tokens corresponding to the model's text output.
rejected_prediction_tokensinteger
This parameter is currently fixed to null.
prompt_tokens_detailsobject
The fine-grained classification of input tokens.
Attributes
audio_tokensinteger
This parameter is currently fixed to null.
cached_tokensinteger
This parameter is currently fixed to null.
text_tokensinteger
The number of tokens corresponding to the model's text input.
image_tokensinteger
The number of tokens corresponding to the model's image input.
The model name. For supported models, see Select a model.
messagesarray (required)
The context passed to the model, arranged in conversation order.
When calling through HTTP, put messages in the input object.
Message types
User Messageobject (required)
The user message, used to pass questions, instructions, or context to the model.
Attributes
contentstring or array (required)
The message content. If the input is text only, it is of string type; if the input contains image data, it is of array type.
Attributes
textstring (optional)
The input text.
Default value: Please output only the text content from the image without any additional descriptions or formatting., that is, by default the model extracts all text from the image.
imagestring (optional)
The image URL, Base64 Data URL, or local path. To pass a local file, see Passing local files.
Example value: {"image":"https://xxxx.jpeg","enable_rotate": True}
min_pixelsinteger (optional)
Sets the minimum pixel threshold for the input image, in pixels.
When the input image has fewer pixels than min_pixels, the image is enlarged until the total number of pixels exceeds min_pixels.
Conversion between image tokens and pixels
The number of pixels corresponding to each image token varies by model:
qwen3.5-ocr, qwen-vl-ocr-2025-11-20: each token corresponds to 32*32 pixels.
qwen-vl-ocr and earlier models: each token corresponds to 28*28 pixels.
min_pixels value range
qwen3.5-ocr, qwen-vl-ocr-2025-11-20: the default and minimum values are both 3072 (that is, 3×32×32)
qwen-vl-ocr and earlier models: the default and minimum values are both 3136 (that is, 4×28×28).
Example value: {"image":"https://xxxx.jpeg","min_pixels": 3072}
max_pixelsinteger (optional)
Sets the maximum pixel threshold for the input image, in pixels.
When the input image is within the [min_pixels, max_pixels] range, the model recognizes the original image. When the input image has more pixels than max_pixels, the image is reduced until the total number of pixels falls below max_pixels.
Conversion between image tokens and pixels
The number of pixels corresponding to each image token varies by model:
qwen3.5-ocr, qwen-vl-ocr-2025-11-20: each token corresponds to 32*32 pixels.
qwen-vl-ocr and earlier models: each token corresponds to 28*28 pixels.
max_pixels value range
qwen3.5-ocr, qwen-vl-ocr-2025-11-20
Default value: 8388608 (that is, 8192x32x32)
Maximum value: 30720000 (that is, 30000x32x32)
qwen-vl-ocr and earlier models
Default value: 6422528 (that is, 8192x28x28)
Maximum value: 23520000 (that is, 30000x28x28)
Example value: {"image":"https://xxxx.jpeg","max_pixels": 8388608}
rolestring (required)
The role of the user message, fixed to user.
max_tokensinteger (optional)
Limits the maximum number of tokens the model generates. If the generated content exceeds this value, the response is truncated.
qwen3.5-ocr: the default and maximum values are both 32768.
qwen-vl-ocr-2025-11-20, qwen-vl-ocr-2024-10-28: the default and maximum values are both the model's maximum output length. See Model selection.
qwen-vl-ocr: the default and maximum values are both 4096.
To increase this value (within the 4097~8192 range), contact your business manager to apply, and provide the following information: primary account ID, image type (such as document images, e-commerce images, and contracts), model name, estimated QPS and total daily requests, and the percentage of requests whose model output length exceeds 4096.
In the Java SDK, this is maxTokens. When calling through HTTP, put max_tokens in the parameters object.
ocr_optionsobject (optional)
Parameters required when using the Qwen OCR model to call a built-in task. When calling a built-in task, you do not need to pass a User Message; the model uses the prompt of the corresponding task internally. For more information, see Calling built-in tasks.
Attributes
taskstring (required)
The name of the built-in task. Valid values:
text_recognition: general text recognition
key_information_extraction: key information extraction
document_parsing: document parsing
table_parsing: table parsing
formula_recognition: formula recognition
multi_lan: multi-language recognition
advanced_recognition: high-precision recognition
task_configobject (optional)
When task is set to key_information_extraction, this parameter specifies the specific fields to extract. If task_config is not specified, the model extracts all fields from the image by default.
Attributes
result_schemaobject (optional)
The fields for the model to extract. It must be a JSON object structure with up to three levels of nested JSON objects.
Specify the name of the field to extract in the key of the JSON object. The corresponding value can be empty. We recommend providing a field description or format requirements in the value to improve extraction accuracy.
Example value:
"result_schema": {
"invoice_number": "The unique identification number of the invoice, usually a combination of numbers and letters.",
"issue_date": "The date the invoice was issued. Extract it in YYYY-MM-DD format, for example, 2023-10-26.",
"seller_name": "The full company name of the seller shown on the invoice.",
"total_amount": "The total amount on the invoice, including tax. Extract the numerical value and keep two decimal places, for example, 123.45."
}
In the Java SDK, this is OcrOptions. The minimum DashScope Python SDK version is 2.0.1, and the minimum Java SDK version is 2.18.4.
When calling through HTTP, put ocr_options in the parameters object.
seedinteger (optional)
The random number seed, used to ensure that results are reproducible with the same input and parameters. If the same seed is passed with other parameters unchanged, the model will return the same result as much as possible.
Value range: [0,2 31 −1].
We recommend keeping the default value.
When calling through HTTP, put seed in the parameters object.
temperaturefloat (optional) Default value: 0.01
The sampling temperature, which controls the diversity of the text generated by the model.
A higher temperature produces more diverse text, while a lower temperature produces more deterministic text.
Value range: [0, 2)
Both temperature and top_p control the diversity of generated text. We recommend setting only one of them.
We recommend keeping the default value.
When calling through HTTP, put temperature in the parameters object.
top_pfloat (optional) Default value: 0.001
The probability threshold for nucleus sampling, which controls the diversity of the text generated by the model.
A higher top_p produces more diverse text, while a lower top_p produces more deterministic text.
Value range: (0,1.0]
Both temperature and top_p control the diversity of generated text. We recommend setting only one of them.
We recommend keeping the default value.
In the Java SDK, this is topP. When calling through HTTP, put top_p in the parameters object.
top_kinteger (optional) Default value: 1
The size of the candidate set sampled during generation. For example, when set to 50, only the 50 highest-scoring tokens from a single generation form the random sampling candidate set. A larger value increases randomness, while a smaller value increases determinism. When set to None or greater than 100, the top_k policy is not enabled and only the top_p policy takes effect.
The value must be greater than or equal to 0.
This is not an OpenAI standard parameter. When calling through the Python SDK, put it in the extra_body object, configured as: extra_body={"top_k": xxx}; when calling through the Node.js SDK or HTTP, pass it as a top-level parameter.
The repetition level in consecutive sequences during model generation. Increasing repetition_penalty reduces the repetition in model output, and 1.0 means no penalty. This parameter has a significant impact on model performance, so we recommend keeping the default value.
We recommend keeping the default value.
In the Java SDK, this is repetitionPenalty. When calling through HTTP, put repetition_penalty in the parameters object.
Controls the content repetition level when the model generates text.
Value range: [-2.0, 2.0]. Positive values reduce repetition, and negative values increase it.
We recommend increasing this value in scenarios that require diversity, fun, or creativity such as creative writing or brainstorming; we recommend decreasing it in scenarios that emphasize consistency and terminology accuracy such as technical documents or formal text.
How it works
If the parameter value is positive, the model applies a penalty to tokens already present in the current text (the penalty is independent of how many times the text appears), reducing the chance of these tokens appearing again, thereby reducing content repetition and increasing word diversity.
We recommend keeping the default value.
streamboolean (optional) Default value: false
Whether to return responses in streaming mode. Parameter values:
false: the model returns the result all at once after generating all content.
true: output while generating, that is, a chunk is returned immediately each time part of the content is generated.
This parameter is supported only by the Python SDK. For streaming output through the Java SDK, use the streamCall interface; for streaming output through HTTP, set X-DashScope-SSE to enable in the header.
Whether to enable incremental output in streaming mode. We recommend setting it to true first.
Parameter values:
false: each output is the entire sequence generated so far, and the last output is the complete result.
I
I like
I like apple
I like apple.
true (recommended): incremental output, that is, subsequent output does not contain the content already output. You need to read these chunks one by one in real time to obtain the complete result.
I
like
apple
.
In the Java SDK, this is incrementalOutput. When calling through HTTP, put incremental_output in the parameters object.
stopstring or array (optional)
Specifies stop words. When a string or token_id specified by stop appears in the text generated by the model, generation stops immediately.
You can pass sensitive words to control the model output.
When stop is an array, you cannot mix token_id and strings as elements, for example, you cannot specify ["Hello",104307].
logprobsboolean (optional) Default value: false
Whether to return the log probabilities of output tokens. Valid values:
true
Return
false
Do not return
Supported models: qwen-vl-ocr-2025-11-20 and later models
When calling through HTTP, put logprobs in the parameters object.
top_logprobsinteger (optional) Default value: 0
Specifies the number of the most likely candidate tokens to return at each generation step. Effective only when logprobs is true.
Value range: [0,5]
In the Java SDK, this is topLogprobs. When calling through HTTP, put top_logprobs in the parameters object.
High-precision recognition
The following is a code example for calling the high-precision recognition built-in task. For more information, see Calling built-in tasks.
import os
import dashscope
# The following is the URL for the China (Beijing) region. Replace {WorkspaceId} with your actual workspace ID when calling. The URL varies by region.
dashscope.base_http_api_url = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1"
messages = [{
"role": "user",
"content": [{
"image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/ctdzex/biaozhun.jpg",
# Minimum pixel threshold for the input image. Images below this value are enlarged until the total pixels exceed min_pixels
"min_pixels": 32 * 32 * 3,
# Maximum pixel threshold for the input image. Images above this value are reduced until the total pixels fall below max_pixels
"max_pixels": 32 * 32 * 8192,
# Whether to enable automatic image rotation correction
"enable_rotate": False}]
}]
response = dashscope.MultiModalConversation.call(
# If the environment variable is not configured, replace the following line with your Model Studio API key: api_key="sk-xxx"
# API keys differ by region. Get an API key: https://help.aliyun.com/zh/model-studio/get-api-key
api_key=os.getenv('DASHSCOPE_API_KEY'),
model='qwen3.5-ocr',
messages=messages,
# Set the built-in task to high-precision recognition
ocr_options={"task": "advanced_recognition"}
)
# The text and coordinate results of the high-precision recognition task are obtained from the ocr_result field
print(response["output"]["choices"][0]["message"].content[0]["ocr_result"])
// dashscope SDK version >= 2.21.8
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import java.util.HashMap;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.aigc.multimodalconversation.OcrOptions;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;
public class Main {
// The following is the URL for the China (Beijing) region. Replace {WorkspaceId} with your actual workspace ID when calling. The URL varies by region.
static {Constants.baseHttpApiUrl="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";}
public static void simpleMultiModalConversationCall()
throws ApiException, NoApiKeyException, UploadFileException {
MultiModalConversation conv = new MultiModalConversation();
Map<String, Object> map = new HashMap<>();
map.put("image", "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/ctdzex/biaozhun.jpg");
// Maximum pixel threshold for the input image. Images above this value are reduced until the total pixels fall below max_pixels
map.put("max_pixels", 8388608);
// Minimum pixel threshold for the input image. Images below this value are enlarged until the total pixels exceed min_pixels
map.put("min_pixels", 3072);
// Whether to enable automatic image rotation correction
map.put("enable_rotate", false);
// Configure the built-in OCR task
OcrOptions ocrOptions = OcrOptions.builder()
.task(OcrOptions.Task.ADVANCED_RECOGNITION)
.build();
MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
.content(Arrays.asList(
map
)).build();
MultiModalConversationParam param = MultiModalConversationParam.builder()
// If the environment variable is not configured, replace the following line with your Model Studio API key: .apiKey("sk-xxx")
// API keys differ by region. Get an API key: https://help.aliyun.com/zh/model-studio/get-api-key
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.model("qwen3.5-ocr")
.message(userMessage)
.ocrOptions(ocrOptions)
.build();
MultiModalConversationResult result = conv.call(param);
System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("ocr_result"));
}
public static void main(String[] args) {
try {
simpleMultiModalConversationCall();
} catch (ApiException | NoApiKeyException | UploadFileException e) {
System.out.println(e.getMessage());
}
System.exit(0);
}
}
# ======= Important =======
# API keys differ by region. Get an API key: https://help.aliyun.com/zh/model-studio/get-api-key
# The following is the URL for the China (Beijing) region. Replace {WorkspaceId} with your actual workspace ID when calling. The URL varies by region.
# === Delete this comment before running ===
curl --location 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '
{
"model": "qwen3.5-ocr",
"input": {
"messages": [
{
"role": "user",
"content": [
{
"image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/ctdzex/biaozhun.jpg",
"min_pixels": 3072,
"max_pixels": 8388608,
"enable_rotate": false
}
]
}
]
},
"parameters": {
"ocr_options": {
"task": "advanced_recognition"
}
}
}
'
Key information extraction
The following is a code example for calling the key information extraction built-in task. For more information, see Calling built-in tasks.
# use [pip install -U dashscope] to update sdk
import os
import dashscope
from dashscope import MultiModalConversation
# The following is the URL for the China (Beijing) region. Replace {WorkspaceId} with your actual workspace ID when calling. The URL varies by region.
dashscope.base_http_api_url = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1"
messages = [
{
"role":"user",
"content":[
{
"image":"http://duguang-labelling.oss-cn-shanghai.aliyuncs.com/demo_ocr/receipt_zh_demo.jpg",
"min_pixels": 32 * 32 * 3,
"max_pixels": 32 * 32 *8192,
"enable_rotate": False
}
]
}
]
# Specify the fields to extract
params = {
"ocr_options":{
"task": "key_information_extraction",
"task_config": {
"result_schema": {
"Ride Date": "Corresponds to the ride date and time in the image, in the format YYYY-MM-DD, for example, 2025-03-05",
"Invoice Code": "Extract the invoice code from the image, usually a combination of numbers or letters",
"Invoice Number": "Extract the number from the invoice, usually composed of only digits."
}
}
}
}
response = MultiModalConversation.call(
model='qwen3.5-ocr',
messages=messages,
**params,
# API keys differ by region. Get an API key: https://help.aliyun.com/zh/model-studio/get-api-key
api_key=os.getenv('DASHSCOPE_API_KEY'))
print(response.output.choices[0].message.content[0]["ocr_result"])
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import java.util.HashMap;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.aigc.multimodalconversation.OcrOptions;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.google.gson.JsonObject;
import com.alibaba.dashscope.utils.Constants;
public class Main {
// The following is the URL for the China (Beijing) region. Replace {WorkspaceId} with your actual workspace ID when calling. The URL varies by region.
static {Constants.baseHttpApiUrl="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";}
public static void simpleMultiModalConversationCall()
throws ApiException, NoApiKeyException, UploadFileException {
MultiModalConversation conv = new MultiModalConversation();
Map<String, Object> map = new HashMap<>();
map.put("image", "http://duguang-labelling.oss-cn-shanghai.aliyuncs.com/demo_ocr/receipt_zh_demo.jpg");
// Maximum pixel threshold for the input image. Images above this value are reduced until the total pixels fall below max_pixels
map.put("max_pixels", 8388608);
// Minimum pixel threshold for the input image. Images below this value are enlarged until the total pixels exceed min_pixels
map.put("min_pixels",3072);
// Whether to enable automatic image rotation correction
map.put("enable_rotate", false);
MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
.content(Arrays.asList(
map
)).build();
// Create the main JSON object
JsonObject resultSchema = new JsonObject();
resultSchema.addProperty("Ride Date", "Corresponds to the ride date and time in the image, in the format YYYY-MM-DD, for example, 2025-03-05");
resultSchema.addProperty("Invoice Code", "Extract the invoice code from the image, usually a combination of numbers or letters");
resultSchema.addProperty("Invoice Number", "Extract the number from the invoice, usually composed of only digits.");
// Configure the built-in OCR task
OcrOptions ocrOptions = OcrOptions.builder()
.task(OcrOptions.Task.KEY_INFORMATION_EXTRACTION)
.taskConfig(OcrOptions.TaskConfig.builder()
.resultSchema(resultSchema)
.build())
.build();
MultiModalConversationParam param = MultiModalConversationParam.builder()
// If the environment variable is not configured, replace the following line with your Model Studio API key: .apiKey("sk-xxx")
// API keys differ by region. Get an API key: https://help.aliyun.com/zh/model-studio/get-api-key
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.model("qwen3.5-ocr")
.message(userMessage)
.ocrOptions(ocrOptions)
.build();
MultiModalConversationResult result = conv.call(param);
System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("ocr_result"));
}
public static void main(String[] args) {
try {
simpleMultiModalConversationCall();
} catch (ApiException | NoApiKeyException | UploadFileException e) {
System.out.println(e.getMessage());
}
System.exit(0);
}
}
# ======= Important =======
# API keys differ by region. Get an API key: https://help.aliyun.com/zh/model-studio/get-api-key
# The following is the URL for the China (Beijing) region. Replace {WorkspaceId} with your actual workspace ID when calling. The URL varies by region.
# === Delete this comment before running ===
curl --location 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '
{
"model": "qwen3.5-ocr",
"input": {
"messages": [
{
"role": "user",
"content": [
{
"image": "http://duguang-labelling.oss-cn-shanghai.aliyuncs.com/demo_ocr/receipt_zh_demo.jpg",
"min_pixels": 3072,
"max_pixels": 8388608,
"enable_rotate": false
}
]
}
]
},
"parameters": {
"ocr_options": {
"task": "key_information_extraction",
"task_config": {
"result_schema": {
"Ride Date": "Corresponds to the ride date and time in the image, in the format YYYY-MM-DD, for example, 2025-03-05",
"Invoice Code": "Extract the invoice code from the image, usually a combination of numbers or letters",
"Invoice Number": "Extract the number from the invoice, usually composed of only digits."
}
}
}
}
}
'
Table parsing
The following is a code example for calling the table parsing built-in task. For more information, see Calling built-in tasks.
import os
import dashscope
# The following is the configuration for the China (Beijing) region. Replace {WorkspaceId} with your actual workspace ID when calling. The region value varies by region.
client = dashscope.Client(
# If the environment variable is not configured, replace the following line with your Model Studio API key: api_key="sk-xxx"
# API keys differ by region. Get an API key: https://help.aliyun.com/zh/model-studio/get-api-key
api_key=os.getenv('DASHSCOPE_API_KEY'),
workspace="{WorkspaceId}",
region="cn-beijing",
)
messages = [{
"role": "user",
"content": [{
"image": "http://duguang-llm.oss-cn-hangzhou.aliyuncs.com/llm_data_keeper/data/doc_parsing/tables/photo/eng/17.jpg",
# Minimum pixel threshold for the input image. Images below this value are enlarged until the total pixels exceed min_pixels
"min_pixels": 32 * 32 * 3,
# Maximum pixel threshold for the input image. Images above this value are reduced until the total pixels fall below max_pixels
"max_pixels": 32 * 32 * 8192}]
}]
response = client.multimodal.chat.create(
model='qwen3.5-ocr',
messages=messages,
# Set the built-in task to table parsing
parameters={"ocr_options": {"task": "table_parsing"}}
)
# The table parsing task returns results in HTML format
print(response.output_text)
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import java.util.HashMap;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.aigc.multimodalconversation.OcrOptions;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;
public class Main {
// The following is the URL for the China (Beijing) region. Replace {WorkspaceId} with your actual workspace ID when calling. The URL varies by region.
static {Constants.baseHttpApiUrl="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";}
public static void simpleMultiModalConversationCall()
throws ApiException, NoApiKeyException, UploadFileException {
MultiModalConversation conv = new MultiModalConversation();
Map<String, Object> map = new HashMap<>();
map.put("image", "https://duguang-llm.oss-cn-hangzhou.aliyuncs.com/llm_data_keeper/data/doc_parsing/tables/photo/eng/17.jpg");
// Maximum pixel threshold for the input image. Images above this value are reduced until the total pixels fall below max_pixels
map.put("max_pixels", 8388608);
// Minimum pixel threshold for the input image. Images below this value are enlarged until the total pixels exceed min_pixels
map.put("min_pixels", 3072);
// Whether to enable automatic image rotation correction
map.put("enable_rotate", false);
// Configure the built-in OCR task
OcrOptions ocrOptions = OcrOptions.builder()
.task(OcrOptions.Task.TABLE_PARSING)
.build();
MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
.content(Arrays.asList(
map
)).build();
MultiModalConversationParam param = MultiModalConversationParam.builder()
// If the environment variable is not configured, replace the following line with your Model Studio API key: .apiKey("sk-xxx")
// API keys differ by region. Get an API key: https://help.aliyun.com/zh/model-studio/get-api-key
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.model("qwen3.5-ocr")
.message(userMessage)
.ocrOptions(ocrOptions)
.build();
MultiModalConversationResult result = conv.call(param);
System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text"));
}
public static void main(String[] args) {
try {
simpleMultiModalConversationCall();
} catch (ApiException | NoApiKeyException | UploadFileException e) {
System.out.println(e.getMessage());
}
System.exit(0);
}
}
# ======= Important =======
# API keys differ by region. Get an API key: https://help.aliyun.com/zh/model-studio/get-api-key
# The following is the URL for the China (Beijing) region. Replace {WorkspaceId} with your actual workspace ID when calling. The URL varies by region.
# === Delete this comment before running ===
curl --location 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '
{
"model": "qwen3.5-ocr",
"input": {
"messages": [
{
"role": "user",
"content": [
{
"image": "http://duguang-llm.oss-cn-hangzhou.aliyuncs.com/llm_data_keeper/data/doc_parsing/tables/photo/eng/17.jpg",
"min_pixels": 3072,
"max_pixels": 8388608,
"enable_rotate": false
}
]
}
]
},
"parameters": {
"ocr_options": {
"task": "table_parsing"
}
}
}
'
Document parsing
The following is a code example for calling the document parsing built-in task. For more information, see Calling built-in tasks.
import os
import dashscope
# The following is the configuration for the China (Beijing) region. Replace {WorkspaceId} with your actual workspace ID when calling. The region value varies by region.
client = dashscope.Client(
# If the environment variable is not configured, replace the following line with your Model Studio API key: api_key="sk-xxx"
# API keys differ by region. Get an API key: https://help.aliyun.com/zh/model-studio/get-api-key
api_key=os.getenv('DASHSCOPE_API_KEY'),
workspace="{WorkspaceId}",
region="cn-beijing",
)
messages = [{
"role": "user",
"content": [{
"image": "https://img.alicdn.com/imgextra/i1/O1CN01ukECva1cisjyK6ZDK_!!6000000003635-0-tps-1500-1734.jpg",
# Minimum pixel threshold for the input image. Images below this value are enlarged until the total pixels exceed min_pixels
"min_pixels": 32 * 32 * 3,
# Maximum pixel threshold for the input image. Images above this value are reduced until the total pixels fall below max_pixels
"max_pixels": 32 * 32 * 8192}]
}]
response = client.multimodal.chat.create(
model='qwen3.5-ocr',
messages=messages,
# Set the built-in task to document parsing
parameters={"ocr_options": {"task": "document_parsing"}}
)
# The document parsing task returns results in LaTeX format
print(response.output_text)
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import java.util.HashMap;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.aigc.multimodalconversation.OcrOptions;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;
public class Main {
// The following is the URL for the China (Beijing) region. Replace {WorkspaceId} with your actual workspace ID when calling. The URL varies by region.
static {Constants.baseHttpApiUrl="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";}
public static void simpleMultiModalConversationCall()
throws ApiException, NoApiKeyException, UploadFileException {
MultiModalConversation conv = new MultiModalConversation();
Map<String, Object> map = new HashMap<>();
map.put("image", "https://img.alicdn.com/imgextra/i1/O1CN01ukECva1cisjyK6ZDK_!!6000000003635-0-tps-1500-1734.jpg");
// Maximum pixel threshold for the input image. Images above this value are reduced until the total pixels fall below max_pixels
map.put("max_pixels", 8388608);
// Minimum pixel threshold for the input image. Images below this value are enlarged until the total pixels exceed min_pixels
map.put("min_pixels", 3072);
// Whether to enable automatic image rotation correction
map.put("enable_rotate", false);
// Configure the built-in OCR task
OcrOptions ocrOptions = OcrOptions.builder()
.task(OcrOptions.Task.DOCUMENT_PARSING)
.build();
MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
.content(Arrays.asList(
map
)).build();
MultiModalConversationParam param = MultiModalConversationParam.builder()
// If the environment variable is not configured, replace the following line with your Model Studio API key: .apiKey("sk-xxx")
// API keys differ by region. Get an API key: https://help.aliyun.com/zh/model-studio/get-api-key
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.model("qwen3.5-ocr")
.message(userMessage)
.ocrOptions(ocrOptions)
.build();
MultiModalConversationResult result = conv.call(param);
System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text"));
}
public static void main(String[] args) {
try {
simpleMultiModalConversationCall();
} catch (ApiException | NoApiKeyException | UploadFileException e) {
System.out.println(e.getMessage());
}
System.exit(0);
}
}
# ======= Important =======
# API keys differ by region. Get an API key: https://help.aliyun.com/zh/model-studio/get-api-key
# The following is the URL for the China (Beijing) region. Replace {WorkspaceId} with your actual workspace ID when calling. The URL varies by region.
# === Delete this comment before running ===
curl --location 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation'\
--header "Authorization: Bearer $DASHSCOPE_API_KEY"\
--header 'Content-Type: application/json'\
--data '{
"model": "qwen3.5-ocr",
"input": {
"messages": [
{
"role": "user",
"content": [{
"image": "https://img.alicdn.com/imgextra/i1/O1CN01ukECva1cisjyK6ZDK_!!6000000003635-0-tps-1500-1734.jpg",
"min_pixels": 3072,
"max_pixels": 8388608,
"enable_rotate": false
}
]
}
]
},
"parameters": {
"ocr_options": {
"task": "document_parsing"
}
}
}
'
Formula recognition
The following is a code example for calling the formula recognition built-in task. For more information, see Calling built-in tasks.
import os
import dashscope
# The following is the configuration for the China (Beijing) region. Replace {WorkspaceId} with your actual workspace ID when calling. The region value varies by region.
client = dashscope.Client(
# If the environment variable is not configured, replace the following line with your Model Studio API key: api_key="sk-xxx"
# API keys differ by region. Get an API key: https://help.aliyun.com/zh/model-studio/get-api-key
api_key=os.getenv('DASHSCOPE_API_KEY'),
workspace="{WorkspaceId}",
region="cn-beijing",
)
messages = [{
"role": "user",
"content": [{
"image": "http://duguang-llm.oss-cn-hangzhou.aliyuncs.com/llm_data_keeper/data/formula_handwriting/test/inline_5_4.jpg",
# Minimum pixel threshold for the input image. Images below this value are enlarged until the total pixels exceed min_pixels
"min_pixels": 32 * 32 * 3,
# Maximum pixel threshold for the input image. Images above this value are reduced until the total pixels fall below max_pixels
"max_pixels": 32 * 32 * 8192}]
}]
response = client.multimodal.chat.create(
model='qwen3.5-ocr',
messages=messages,
# Set the built-in task to formula recognition
parameters={"ocr_options": {"task": "formula_recognition"}}
)
# The formula recognition task returns results in LaTeX format
print(response.output_text)
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import java.util.HashMap;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.aigc.multimodalconversation.OcrOptions;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;
public class Main {
// The following is the URL for the China (Beijing) region. Replace {WorkspaceId} with your actual workspace ID when calling. The URL varies by region.
static {Constants.baseHttpApiUrl="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";}
public static void simpleMultiModalConversationCall()
throws ApiException, NoApiKeyException, UploadFileException {
MultiModalConversation conv = new MultiModalConversation();
Map<String, Object> map = new HashMap<>();
map.put("image", "http://duguang-llm.oss-cn-hangzhou.aliyuncs.com/llm_data_keeper/data/formula_handwriting/test/inline_5_4.jpg");
// Maximum pixel threshold for the input image. Images above this value are reduced until the total pixels fall below max_pixels
map.put("max_pixels", 8388608);
// Minimum pixel threshold for the input image. Images below this value are enlarged until the total pixels exceed min_pixels
map.put("min_pixels", 3072);
// Whether to enable automatic image rotation correction
map.put("enable_rotate", false);
// Configure the built-in OCR task
OcrOptions ocrOptions = OcrOptions.builder()
.task(OcrOptions.Task.FORMULA_RECOGNITION)
.build();
MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
.content(Arrays.asList(
map
)).build();
MultiModalConversationParam param = MultiModalConversationParam.builder()
// If the environment variable is not configured, replace the following line with your Model Studio API key: .apiKey("sk-xxx")
// API keys differ by region. Get an API key: https://help.aliyun.com/zh/model-studio/get-api-key
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.model("qwen3.5-ocr")
.message(userMessage)
.ocrOptions(ocrOptions)
.build();
MultiModalConversationResult result = conv.call(param);
System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text"));
}
public static void main(String[] args) {
try {
simpleMultiModalConversationCall();
} catch (ApiException | NoApiKeyException | UploadFileException e) {
System.out.println(e.getMessage());
}
System.exit(0);
}
}
# ======= Important =======
# API keys differ by region. Get an API key: https://help.aliyun.com/zh/model-studio/get-api-key
# The following is the URL for the China (Beijing) region. Replace {WorkspaceId} with your actual workspace ID when calling. The URL varies by region.
# === Delete this comment before running ===
curl --location 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '
{
"model": "qwen3.5-ocr",
"input": {
"messages": [
{
"role": "user",
"content": [
{
"image": "http://duguang-llm.oss-cn-hangzhou.aliyuncs.com/llm_data_keeper/data/formula_handwriting/test/inline_5_4.jpg",
"min_pixels": 3072,
"max_pixels": 8388608,
"enable_rotate": false
}
]
}
]
},
"parameters": {
"ocr_options": {
"task": "formula_recognition"
}
}
}
'
General text recognition
The following is a code example for calling the general text recognition built-in task. For more information, see Calling built-in tasks.
import os
import dashscope
# The following is the configuration for the China (Beijing) region. Replace {WorkspaceId} with your actual workspace ID when calling. The region value varies by region.
client = dashscope.Client(
# If the environment variable is not configured, replace the following line with your Model Studio API key: api_key="sk-xxx"
# API keys differ by region. Get an API key: https://help.aliyun.com/zh/model-studio/get-api-key
api_key=os.getenv('DASHSCOPE_API_KEY'),
workspace="{WorkspaceId}",
region="cn-beijing",
)
messages = [{
"role": "user",
"content": [{
"image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/ctdzex/biaozhun.jpg",
# Minimum pixel threshold for the input image. Images below this value are enlarged until the total pixels exceed min_pixels
"min_pixels": 32 * 32 * 3,
# Maximum pixel threshold for the input image. Images above this value are reduced until the total pixels fall below max_pixels
"max_pixels": 32 * 32 * 8192}]
}]
response = client.multimodal.chat.create(
model='qwen3.5-ocr',
messages=messages,
# Set the built-in task to general text recognition
parameters={"ocr_options": {"task": "text_recognition"}}
)
# The general text recognition task returns results in plain text format
print(response.output_text)
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import java.util.HashMap;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.aigc.multimodalconversation.OcrOptions;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;
public class Main {
// The following is the URL for the China (Beijing) region. Replace {WorkspaceId} with your actual workspace ID when calling. The URL varies by region.
static {Constants.baseHttpApiUrl="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";}
public static void simpleMultiModalConversationCall()
throws ApiException, NoApiKeyException, UploadFileException {
MultiModalConversation conv = new MultiModalConversation();
Map<String, Object> map = new HashMap<>();
map.put("image", "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/ctdzex/biaozhun.jpg");
// Maximum pixel threshold for the input image. Images above this value are reduced until the total pixels fall below max_pixels
map.put("max_pixels", 8388608);
// Minimum pixel threshold for the input image. Images below this value are enlarged until the total pixels exceed min_pixels
map.put("min_pixels", 3072);
// Whether to enable automatic image rotation correction
map.put("enable_rotate", false);
// Configure the built-in task
OcrOptions ocrOptions = OcrOptions.builder()
.task(OcrOptions.Task.TEXT_RECOGNITION)
.build();
MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
.content(Arrays.asList(
map
)).build();
MultiModalConversationParam param = MultiModalConversationParam.builder()
// If the environment variable is not configured, replace the following line with your Model Studio API key: .apiKey("sk-xxx")
// API keys differ by region. Get an API key: https://help.aliyun.com/zh/model-studio/get-api-key
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.model("qwen3.5-ocr")
.message(userMessage)
.ocrOptions(ocrOptions)
.build();
MultiModalConversationResult result = conv.call(param);
System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text"));
}
public static void main(String[] args) {
try {
simpleMultiModalConversationCall();
} catch (ApiException | NoApiKeyException | UploadFileException e) {
System.out.println(e.getMessage());
}
System.exit(0);
}
}
# ======= Important =======
# API keys differ by region. Get an API key: https://help.aliyun.com/zh/model-studio/get-api-key
# The following is the URL for the China (Beijing) region. Replace {WorkspaceId} with your actual workspace ID when calling. The URL varies by region.
# === Delete this comment before running ===
curl --location 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation'\
--header "Authorization: Bearer $DASHSCOPE_API_KEY"\
--header 'Content-Type: application/json'\
--data '{
"model": "qwen3.5-ocr",
"input": {
"messages": [
{
"role": "user",
"content": [{
"image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/ctdzex/biaozhun.jpg",
"min_pixels": 3072,
"max_pixels": 8388608,
"enable_rotate": false
}
]
}
]
},
"parameters": {
"ocr_options": {
"task": "text_recognition"
}
}
}'
Multi-language recognition
The following is a code example for calling the general multi-language recognition built-in task. For more information, see Calling built-in tasks.
import os
import dashscope
# The following is the configuration for the China (Beijing) region. Replace {WorkspaceId} with your actual workspace ID when calling. The region value varies by region.
client = dashscope.Client(
# If the environment variable is not configured, replace the following line with your Model Studio API key: api_key="sk-xxx"
# API keys differ by region. Get an API key: https://help.aliyun.com/zh/model-studio/get-api-key
api_key=os.getenv('DASHSCOPE_API_KEY'),
workspace="{WorkspaceId}",
region="cn-beijing",
)
messages = [{
"role": "user",
"content": [{
"image": "https://img.alicdn.com/imgextra/i2/O1CN01VvUMNP1yq8YvkSDFY_!!6000000006629-2-tps-6000-3000.png",
# Minimum pixel threshold for the input image. Images below this value are enlarged until the total pixels exceed min_pixels
"min_pixels": 32 * 32 * 3,
# Maximum pixel threshold for the input image. Images above this value are reduced until the total pixels fall below max_pixels
"max_pixels": 32 * 32 * 8192}]
}]
response = client.multimodal.chat.create(
model='qwen3.5-ocr',
messages=messages,
# Set the built-in task to multi-language recognition
parameters={"ocr_options": {"task": "multi_lan"}}
)
# The multi-language recognition task returns results in plain text format
print(response.output_text)
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import java.util.HashMap;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.aigc.multimodalconversation.OcrOptions;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;
public class Main {
// The following is the URL for the China (Beijing) region. Replace {WorkspaceId} with your actual workspace ID when calling. The URL varies by region.
static {Constants.baseHttpApiUrl="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";}
public static void simpleMultiModalConversationCall()
throws ApiException, NoApiKeyException, UploadFileException {
MultiModalConversation conv = new MultiModalConversation();
Map<String, Object> map = new HashMap<>();
map.put("image", "https://img.alicdn.com/imgextra/i2/O1CN01VvUMNP1yq8YvkSDFY_!!6000000006629-2-tps-6000-3000.png");
// Maximum pixel threshold for the input image. Images above this value are reduced until the total pixels fall below max_pixels
map.put("max_pixels", 8388608);
// Minimum pixel threshold for the input image. Images below this value are enlarged until the total pixels exceed min_pixels
map.put("min_pixels", 3072);
// Whether to enable automatic image rotation correction
map.put("enable_rotate", false);
// Configure the built-in OCR task
OcrOptions ocrOptions = OcrOptions.builder()
.task(OcrOptions.Task.MULTI_LAN)
.build();
MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
.content(Arrays.asList(
map
)).build();
MultiModalConversationParam param = MultiModalConversationParam.builder()
// If the environment variable is not configured, replace the following line with your Model Studio API key: .apiKey("sk-xxx")
// API keys differ by region. Get an API key: https://help.aliyun.com/zh/model-studio/get-api-key
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.model("qwen3.5-ocr")
.message(userMessage)
.ocrOptions(ocrOptions)
.build();
MultiModalConversationResult result = conv.call(param);
System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text"));
}
public static void main(String[] args) {
try {
simpleMultiModalConversationCall();
} catch (ApiException | NoApiKeyException | UploadFileException e) {
System.out.println(e.getMessage());
}
System.exit(0);
}
}
# ======= Important =======
# API keys differ by region. Get an API key: https://help.aliyun.com/zh/model-studio/get-api-key
# The following is the URL for the China (Beijing) region. Replace {WorkspaceId} with your actual workspace ID when calling. The URL varies by region.
# === Delete this comment before running ===
curl --location 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '
{
"model": "qwen3.5-ocr",
"input": {
"messages": [
{
"role": "user",
"content": [
{
"image": "https://img.alicdn.com/imgextra/i2/O1CN01VvUMNP1yq8YvkSDFY_!!6000000006629-2-tps-6000-3000.png",
"min_pixels": 3072,
"max_pixels": 8388608,
"enable_rotate": false
}
]
}
]
},
"parameters": {
"ocr_options": {
"task": "multi_lan"
}
}
}
'
Streaming output
import os
import dashscope
# The following is the configuration for the China (Beijing) region. Replace {WorkspaceId} with your actual workspace ID when calling. The region value varies by region.
# For the US (Virginia) region, replace region with us-east-1; for the Singapore region, replace region with ap-southeast-1.
client = dashscope.Client(
# If the environment variable is not configured, replace the following line with your Model Studio API key: api_key="sk-xxx"
# API keys differ by region. Get an API key: https://help.aliyun.com/zh/model-studio/get-api-key
api_key=os.getenv("DASHSCOPE_API_KEY"),
workspace="{WorkspaceId}",
region="cn-beijing",
)
PROMPT_TICKET_EXTRACTION = """
Please extract the invoice number, train number, departure station, arrival station, departure date and time, seat number, seat class, ticket price, ID card number, and passenger name from the train ticket image.
You must accurately extract the key information. Do not omit or fabricate information. Replace any single character that is blurry or obscured by strong light with an English question mark (?).
Return the data in JSON format as follows: {'invoice_number': 'xxx', 'departure_station': 'xxx', 'arrival_station': 'xxx', 'departure_date_and_time':'xxx', 'seat_number': 'xxx','ticket_price':'xxx', 'id_card_number': 'xxx', 'passenger_name': 'xxx'},
"""
messages = [
{
"role": "user",
"content": [
{
"image": "https://img.alicdn.com/imgextra/i2/O1CN01ktT8451iQutqReELT_!!6000000004408-0-tps-689-487.jpg",
# Minimum pixel threshold for the input image. Images below this value are enlarged until the total pixels exceed min_pixels
"min_pixels": 32 * 32 * 3,
# Maximum pixel threshold for the input image. Images above this value are reduced until the total pixels fall below max_pixels
"max_pixels": 32 * 32 * 8192,
},
# When no built-in task is set, the model supports passing a prompt in the text field. If not passed, the default prompt is used: Please output only the text content from the image without any additional descriptions or formatting.
{
"type": "text",
"text": PROMPT_TICKET_EXTRACTION,
},
],
}
]
stream = client.multimodal.chat.create(
model="qwen3.5-ocr",
messages=messages,
stream=True,
# Streaming output defaults to incremental mode: each data chunk contains only the newly generated content.
)
full_content = ""
print("Streaming output content:")
for chunk in stream:
delta = chunk.choices[0].delta
if delta.content:
print(delta.content)
full_content += delta.content
print(f"Full content: {full_content}")
import java.util.*;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import io.reactivex.Flowable;
import com.alibaba.dashscope.utils.Constants;
public class Main {
// The following is the base_url for the China (Beijing) region. For the US (Virginia) region, replace base_url with https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/api/v1
// For the Singapore region, replace base_url with: https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1
static {Constants.baseHttpApiUrl="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";}
public static void simpleMultiModalConversationCall()
throws ApiException, NoApiKeyException, UploadFileException {
MultiModalConversation conv = new MultiModalConversation();
Map<String, Object> map = new HashMap<>();
map.put("image", "https://img.alicdn.com/imgextra/i2/O1CN01ktT8451iQutqReELT_!!6000000004408-0-tps-689-487.jpg");
// Maximum pixel threshold for the input image. Images above this value are reduced until the total pixels fall below max_pixels
map.put("max_pixels", 8388608);
// Minimum pixel threshold for the input image. Images below this value are enlarged until the total pixels exceed min_pixels
map.put("min_pixels", 3072);
// Enable automatic image rotation correction
map.put("enable_rotate", false);
MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
.content(Arrays.asList(
map,
// When no built-in task is set, the model supports passing a prompt in the text field. If not passed, the default prompt is used: Please output only the text content from the image without any additional descriptions or formatting.
Collections.singletonMap("text", "Please extract the invoice number, train number, departure station, arrival station, departure date and time, seat number, seat class, ticket price, ID card number, and passenger name from the train ticket image. You must accurately extract the key information. Do not omit or fabricate information. Replace any single character that is blurry or obscured by strong light with an English question mark (?). Return the data in JSON format as follows: {'invoice_number': 'xxx', 'departure_station': 'xxx', 'arrival_station': 'xxx', 'departure_date_and_time':'xxx', 'seat_number': 'xxx','ticket_price':'xxx', 'id_card_number': 'xxx', 'passenger_name': 'xxx'"))).build();
MultiModalConversationParam param = MultiModalConversationParam.builder()
// If the environment variable is not configured, replace the following line with your Model Studio API key: .apiKey("sk-xxx")
// API keys differ by region. Get an API key: https://help.aliyun.com/zh/model-studio/get-api-key
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.model("qwen3.5-ocr")
.message(userMessage)
.incrementalOutput(true)
.build();
Flowable<MultiModalConversationResult> result = conv.streamCall(param);
result.blockingForEach(item -> {
try {
List<Map<String, Object>> contentList = item.getOutput().getChoices().get(0).getMessage().getContent();
if (!contentList.isEmpty()){
System.out.println(contentList.get(0).get("text"));
}//
} catch (Exception e){
System.exit(0);
}
});
}
public static void main(String[] args) {
try {
simpleMultiModalConversationCall();
} catch (ApiException | NoApiKeyException | UploadFileException e) {
System.out.println(e.getMessage());
}
System.exit(0);
}
}
# ======= Important =======
# API keys differ by region. Get an API key: https://help.aliyun.com/zh/model-studio/get-api-key
# The following is the base_url for the China (Beijing) region. For the US (Virginia) region, replace base_url with https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
# For the Singapore region, replace base_url with: https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
# === Delete this comment before running ===
curl --location 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
-H 'X-DashScope-SSE: enable' \
--data '{
"model": "qwen3.5-ocr",
"input":{
"messages":[
{
"role": "user",
"content": [
{
"image": "https://img.alicdn.com/imgextra/i2/O1CN01ktT8451iQutqReELT_!!6000000004408-0-tps-689-487.jpg",
"min_pixels": 3072,
"max_pixels": 8388608
},
{"type": "text", "text": "Please extract the invoice number, train number, departure station, arrival station, departure date and time, seat number, seat class, ticket price, ID card number, and passenger name from the train ticket image. You must accurately extract the key information. Do not omit or fabricate information. Replace any single character that is blurry or obscured by strong light with an English question mark (?). Return the data in JSON format as follows: {'invoice_number': 'xxx', 'departure_station': 'xxx', 'arrival_station': 'xxx', 'departure_date_and_time':'xxx', 'seat_number': 'xxx','ticket_price':'xxx', 'id_card_number': 'xxx', 'passenger_name': 'xxx'"}
]
}
]
},
"parameters": {
"incremental_output": true
}
}'
chat response object (identical format for streaming and non-streaming output)
The following is the raw response returned by the HTTP interface. If the call fails, the Python SDK raises a DashScopeError exception, and you can obtain error information from the exception attributes e.status_code/e.code/e.message/e.request_id; a failed Java SDK call throws an exception whose message contains status_code and message.
request_idstring
The unique identifier of this call.
In the Java SDK, the return parameter is requestId.
outputobject
The call result information.
Attributes
textstring
This parameter is currently fixed to null.
finish_reasonstring
The reason the model stopped generating. There are the following cases:
null while generating;
stop when the model output ends naturally;
length when generation ends because the output is too long;
choicesarray
The output information of the model.
Attributes
finish_reasonstring
There are the following cases:
null while generating;
stop when the model output ends naturally;
length when generation ends because the output is too long;
messageobject
The message object output by the model.
Attributes
rolestring
The role of the output message, fixed to assistant.
contentobject
The content of the output message.
Attributes
ocr_resultobject
The task result information output when the Qwen-OCR series models call the built-in key information extraction or high-precision recognition tasks.
Attributes
kv_resultarray
The output result of the key information extraction task.
words_infoarray
The output result of the high-precision recognition task.
Attributes
rotate_rectarray
Example value: [center_x, center_y, width, height, angle]
The rotated rectangle representation of the text box:
center_x, center_y are the coordinates of the text box center
width is the width of the text box, height is the height
angle is the rotation angle of the text box relative to the horizontal direction, with a value range of [-90, 90]
locationarray
Example value: [x1, y1, x2, y2, x3, y3, x4, y4]
The coordinates of the four vertices of the text box, starting from the top-left corner and arranged clockwise in the order top-left → top-right → bottom-right → bottom-left.
textstring
The content of the text line.
textstring
The content of the output message.
processed_textstring
The post-processed result of the model's raw output, which automatically removes repeated segments. When the model output contains repeated content, this field provides the cleaned text.
logprobsobject
The probability information of the current choices object.
Attributes
contentarray
The token array with log probability information.
Attributes
tokenstring
The current token.
bytesarray
The list of raw UTF-8 bytes of the current token, used to precisely restore the output content, which is helpful for processing emoji and Chinese characters.
logprobfloat
The log probability of the current token. A null return value indicates an extremely low probability.
top_logprobsarray
The several most likely tokens at the current token position and their log probabilities. The number of elements is consistent with the input parameter top_logprobs.
Attributes
tokenstring
The current token.
bytesarray
The list of raw UTF-8 bytes of the current token, used to precisely restore the output content, which is helpful for processing emoji and Chinese characters.
logprobfloat
The log probability of the current token. A null return value indicates an extremely low probability.
usageobject
The token usage information of this request.
Attributes
input_tokensinteger
The number of input tokens.
output_tokensinteger
The number of output tokens.
charactersinteger
This parameter is currently fixed to 0.
input_tokens_detailsobject
The fine-grained classification of input tokens.
Attributes
image_tokensinteger
The number of tokens corresponding to the model's image input.
text_tokensinteger
The number of tokens corresponding to the model's text input.
output_tokens_detailsobject
The fine-grained classification of output tokens.
Attributes
text_tokensinteger
The number of tokens corresponding to the model's text input.
total_tokensinteger
The total number of tokens consumed, the sum of input_tokens and output_tokens.
image_tokensinteger
This field is returned when the input contains image. It is the length of the user's input image content after being converted into tokens.