Skip to main content
Qwen-OCR

Qwen-OCR text extraction models

Extract text from images with Qwen-OCR through the OpenAI-compatible API.

POST
/compatible-mode/v1/chat/completions
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 API key: api_key="sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # Singapore (ap-southeast-1). For another region, replace ap-southeast-1 in the URL.
    # API keys are region-specific. See https://docs.qwencloud.com/developer-guides/getting-started/regions
    base_url="https://ap-southeast-1.maas.qwencloudapi.com/compatible-mode/v1",
  )
  completion = client.chat.completions.create(
    model="qwen-vl-ocr-2025-11-20",
    messages=[
      {
        "role": "user",
        "content": [
          {
            "type": "image_url",
            "image_url": {"url":"https://img.alicdn.com/imgextra/i2/O1CN01ktT8451iQutqReELT_!!6000000004408-0-tps-689-487.jpg"},
            # The minimum pixel threshold for the input image. If the image has fewer pixels than this value, it is enlarged until its total pixel count exceeds min_pixels.
            "min_pixels": 32 * 32 * 3,
            # The maximum pixel threshold for the input image. If the image has more pixels than this value, it is reduced until its total pixel count is below max_pixels.
            "max_pixels": 32 * 32 * 8192
          },
          # The model supports passing a prompt in the following text field. If no prompt is 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}")
{
  "id": "<string>",
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "logprobs": {},
      "message": {
        "content": "<string>",
        "refusal": "<string>",
        "role": "assistant",
        "audio": {},
        "function_call": {},
        "tool_calls": [],
        "annotations": null
      }
    }
  ],
  "created": 0,
  "model": "<string>",
  "object": "chat.completion",
  "service_tier": "<string>",
  "system_fingerprint": "<string>",
  "usage": {
    "completion_tokens": 0,
    "prompt_tokens": 0,
    "total_tokens": 0,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 0,
      "text_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0,
      "image_tokens": 0,
      "text_tokens": 0
    }
  }
}

Authorizations

string
header
required

API key authentication. Get an API key from the QwenCloud console.

Body

application/json
string
required

The name of the model. See Qwen-OCR for a list of supported models.

qwen-vl-ocr-2025-11-20
object[]
required

A sequence of messages that provides context to the model in conversational order.

boolean
defaultfalse

Specifies whether to return the response in streaming mode. false: returns the complete response at once. true: returns data blocks as the model generates them.

object

Configuration settings for streaming output. Applies only when stream is true.

integer

The maximum number of tokens to generate in the output. If the generated content exceeds this value, the response is truncated.

  • For qwen3.5-ocr, qwen-vl-ocr-2025-11-20, and qwen-vl-ocr-2024-10-28, the default and maximum values are the same as the model's maximum output length.
boolean
defaultfalse

Specifies whether to return the log probabilities of the output tokens.

integer
default0

Specifies the number of most likely tokens to return at each generation step. Value range: [0, 5]. Takes effect only when logprobs is true.

number
default0.01

The sampling temperature controls the diversity of the generated text. Higher = more diverse, lower = more deterministic. Value range: [0, 2). Only set one of temperature or top_p.

number
default0.001

Probability threshold for nucleus sampling. Higher = more diverse, lower = more deterministic. Value range: (0, 1.0]. Only set one of temperature or top_p.

integer
default1

Size of the candidate set for sampling. A larger value increases randomness. If None or greater than 100, only top_p takes effect. Must be >= 0. Non-standard OpenAI parameter — in Python SDK use extra_body={"top_k": xxx}.

number
default1

Penalty for repeated sequences. Higher values reduce repetition. 1.0 means no penalty.

number
default0

Controls content repetition. Range: [-2.0, 2.0]. Positive reduces repetition, negative increases it.

integer

A random number seed for reproducible results. Value range: [0, 2^31−1].

string

Stop words. When a specified string or token_id appears, generation stops immediately. Can be a string or array. If stop is an array, you cannot mix token_ids and strings as elements.

Response

200-application/json
string

The unique identifier for this request.

object[]
integer

UNIX timestamp when this request was created.

string

The model used for this request.

enum<string>

Always chat.completion.

chat.completion
string | null

Always null.

string | null

Always null.

object

Token usage information.