Appearance
How to make Qwen generate a JSON string -
Reference, synced 2026-06-13.
flowchart TD n0["Models"] n1["Overview"] n2["Products"] n3["Solutions"] n4["Pricing"] n5["Resources"] n6["Partners"] n7["Support"] n8["Language"] n0 --> n1 n1 --> n2 n2 --> n3 n3 --> n4 n4 --> n5 n5 --> n6 n6 --> n7 n7 --> n8
Free access Accelerate Delivery with Fixed-Cost Agentic CodingWatch how it works
Models
Empowering AI innovation for both enterprises and developers with Alibaba Cloud’s best-in-class Qwen models, AI-native apps, and AI solutions.
Alibaba Cloud Model Studio \ Enterprise-grade large model service and application development platform.
Try Visual Model \ Supports image understanding, image generation, and video generation.
Models
HappyHorse-1.0-T2V \ Cinematic creative generation, ultimate dynamic details Qwen3-VL-Plus \ Native VL, spatial reasoning, 1M-context video analysis Wan2.7-VideoEdit \ Supports both localized and global editing with prompt
Qwen3.6-Plus \ Native multimodal, 1M context, agentic coding Wan2.7-Image-Pro \ Interactive editing, long-text rendering, precise prompt following Qwen-Plus \ Balanced intelligence, efficient inference, production-ready performance
Qwen-Image-2.0 \ Professional infographics, exquisite photorealism Z-Image-Turbo \ Ultra-fast image generation, high throughput, cost-optimized inference Qwen3-Coder-Next \ Multi-turn tool interactions, future-ready development support
Wan2.7-T2V \ High-fidelity T2V, 15s duration, advanced camera control Wan2.7-I2V \ Cinematic I2V with emotional depth and visceral impact Wan2.7-R2V \ Up to 5 mixed image/video inputs and audio timbre cloning
GenAI Application
Qoder \ Intelligent coding assistant, available for enterprise-dedicated deployment. Qoder CN \ AI-powered coding assistant that boosts developer productivity with intelligent code completion, AI chat, multi-file editing, and task automation.
AI Service
Model Experience \ Experience full-scale, multimodal model capabilities online. Platform for AI \ An AI-native algorithm engineering platform for end-to-end modeling, training, and inference service deployment. Fine-tune Video Generation Model \ Customize Wan’s text-to-video capabilities through model fine-tuning to meet your unique requirements.
AI Use Case
AI Savings Plan Hot \ Save up to 47% on AI costs. Limited-time offer tailored to your usage. AI Video Creation \ Elevate your professional video production with Wan 2.6.
AI Token Plan \ One plan. Multiple models. Big Savings with a Fixed Subscription. AI Image Creation \ All-in-one creative suite for copywriting, image generation, and poster design.
Overview
As a global full-stack AI leader, Alibaba Cloud aims to make computing accessible to everyone and help worldwide customers accelerate innovation.
Why Alibaba Cloud
About Alibaba Cloud \ AI Powered Cloud Technology Our Global Network \ Explore our global presence and deployment regions around the world Our Global Offices \ With offices in 4 continents, we're always close to where it matters.
Asia Accelerator \ Accelerate Success in Asia with Alibaba Cloud Go Global \ Benefits of our Global Alliance Trust Center \ Empowering enterprises with a secure, compliant, and globally trusted cloud infrastructure
Customers and Insights
Olympic Games \ Alibaba Cloud Powers Olympic Games with AI-powered cloud technology Case Studies \ Learn how customers are scaling their businesses on Alibaba Cloud Analyst Reports \ Learn what the top industry analyst firms are saying about Alibaba Cloud
What's New
Events and Webinars \ Quick access to upcoming and on-demand events Product Updates \ Stay informed of the latest innovations Press Room \ Latest news and media releases
Products
Featured ProductsAI & Machine Learning Computing Container Storage Networking & CDN Security Middleware Database Analytics ComputingMedia ServicesEnterprise Services & Cloud CommunicationDomain Names and WebsitesEnd User ComputingServerlessDeveloper ToolsMigration & O&M ManagementApsara Stack
Featured Products
Alibaba Cloud Model Studio \ Supercharge your AI journey effortlessly with industry-leading GenAI models ApsaraDB RDS \ Store and manage your business data, with automated monitoring and backups Certificate Management Service (Original SSL Certificate) \ Create a safe and secure connection between your website and users
Elastic Compute Service (ECS) \ Host websites anywhere and scale enterprise workloads Container Service for Kubernetes (ACK) \ Run and scale containerized applications on managed Kubernetes infrastructure Object Storage Service (OSS) \ Store large amounts of data in the cloud and access it anywhere, anytime
Simple Application Server (SAS) \ All-in-one services for fast deployment Elastic IP Address (EIP) \ Manage your public IPs independently to improve internet network quality Domain Names and Website \ Get the perfect domain name to suit your every need
Related Programs
Solutions
Solutions by Industry Technical Solutions AI WebsitesNetworking Security and ComplianceData and AnalyticsEnterprise Service and ApplicationCloud MigrationCloud NativeHybrid CloudSMB solutions
Financial Services \ Innovate faster with Alibaba Cloud Games \ Grow your game rapidly with high global availability
New Retail \ Alibaba Cloud enables digital retail transformation to fuel growth and realize an omnichannel customer experience throughout the consumer journey. Media and Entertainment \ Ready your content for today's media market with a digitalized media journey
Supply Chain \ Power your supply chain with intelligent, efficient, and reliable solutions Sports \ Digitizing the sports industry with intelligent tech
Sustainability \ Achieve a sustainable future with low-carbon and energy-efficient technologies
Pricing
Flexible options like pay-as-you-go and clear billing rules to meet diverse business needs.
Overview & Tools
Pricing Calculator \ Get an instant pricing estimate based on your usage and needs Free Trial \ Try our 80+ cloud products for free.
Pricing Options \ Get the most out of Alibaba Cloud with flexible pricing
Optimize your cost
Migrate & Save \ Superior Performance At Lower Pricing. Save up to 50%. Promotion Center \ Unlock the latest Alibaba Cloud offers & promos
Resources
Official documentation, extensive tools, training resources, and a community to grow and innovate in the cloud.
Technical Resources
Documentation \ Product guides and FAQs Architecture Center \ Design reliable, secure, and efficient cloud architecture. Intelligent Solution Explorer \ Find the right solution for you, powered by AI
Blog \ Latest cloud insights and developer trends Whitepapers \ Research that explores the how and why behind our technology
Training&Certification
Alibaba Cloud Academy \ Build cloud skills and earn certifications with expert-led training.
Developer Hub
Alibaba Cloud Project Hub \ Explore real-world projects built by developers using our platform. Our Developer MVPs \ Celebrating the developers who lead, build, and inspire our community
Partners
Partner-first strategy offering collaborative product, sales, and service models, plus high-quality partner solutions that complement Alibaba Cloud’s capabilities.
Marketplace
AI Alliance for ISVs \ Partner with us to build and grow AI solutions together ISV Benefits \ Unlock resources, market access, and go-to-market support as an ISV partner
Alibaba Cloud Marketplace \ Explore ready-to-deploy solutions from our partners and ISVs
Find a Partner
Partner Hub \ Find your ideal partner in no time
Become a Partner
Partner Network \ A partner portal for Alibaba Cloud Channel, Technology, MSP partner and other partner programs
Support
Full-lifecycle support and expert services, from cloud advisory and migration to operations.
Support & Professional Services
Professional Services \ Expert-led services to design, migrate, and optimize your cloud journey Support Plans \ Flexible support for every stage — from startup to enterprise
Partner Support Program \ Priority technical support for partners, with dedicated managers and faster issue resolution
Contact us
Connect With Us \
Talk to a sales expert and get a custom quote for your business
Language
- English
- 简体中文
- 繁體中文
- 日本語
- Bahasa Indonesia
Locale
Visit aliyun.com
Documentation
Alibaba Cloud Model Studio
User Guide (Models) User Guide (Application) API Reference (Models) API Reference (Application)
Search for Help Content
Getting Started
The Beginner's Guide
Well-Architected Framework
AI & Machine Learning
Platform For AI
Alibaba Cloud Model Studio
DashVector
Artificial Intelligence Recommendation
OpenSearch
Image Search
Machine Translation
Intelligent Speech Interaction
Optimization Solver
Intelligent Computing LINGJUN
Computing
Elastic Compute Service
Elastic GPU Service
Elastic Container Instance
Dedicated Host
Compute Nest
Simple Application Server
Cloud Box
Auto Scaling
Elastic High Performance Computing
Batch Compute (Deprecated)
Function Compute
Serverless App Engine
ENS
Elastic Desktop Service
App Streaming
WUYING Terminal
Cloud Phone
Edge Network Acceleration
Alibaba Cloud Linux
AgentBay
Container
Container Service for Kubernetes
Container Compute Service
Container Registry
Storage
Object Storage Service
Cloud Parallel File Storage
File Storage NAS
Tablestore
Storage Capacity Unit
Simple Log Service
Cloud Backup
Intelligent Media Management
Drive and Photo Service
Data Transport
Cloud Storage Gateway
Data Online Migration
Hybrid Cloud Storage Array
Storage Services Overview
Backup and Disaster Recovery Center
Networking and CDN
Server Load Balancer
Elastic IP Address
Internet Shared Bandwidth
Data Transfer Plan
Virtual Private Cloud
NAT Gateway
PrivateLink
Alibaba Cloud DNS PrivateZone
Network Intelligence Service
Cloud Data Transfer
IPv6 Gateway
Anycast Elastic IP Address
Cloud Enterprise Network
Global Accelerator
VPN Gateway
Smart Access Gateway
Express Connect
CDN
Edge Security Acceleration
Cloud Network Well-architected Design Guidelines
Security
Anti-DDoS
Web Application Firewall
Cloud Firewall
Security Center
Bastionhost
Secure Access Service Edge
Certificate Management Service
Key Management Service
Data Security Center
Identity as a Service
Fraud Detection
AI Guardrails
Captcha
Blockchain as a Service
ID Verification
Managed Security Service
Middleware
Enterprise Distributed Application Service
Microservices Engine
Alibaba Cloud Service Mesh
SchedulerX
ApsaraMQ for RocketMQ
ApsaraMQ for Kafka
ApsaraMQ for RabbitMQ
ApsaraMQ for MQTT
Simple Message Queue (formerly MNS)
CloudFlow
EventBridge
Application Real-Time Monitoring Service
Managed Service for Prometheus
Managed Service for Grafana
Managed Service for OpenTelemetry
Performance Testing
STAROps
Databases
ApsaraDB Console
PolarDB
ApsaraDB RDS
ApsaraDB for OceanBase (Deprecated)
Tair (Redis® OSS-Compatible)
Lindorm
Time Series Database
ApsaraDB for MongoDB
ApsaraDB for HBase
ApsaraDB for Memcache
ApsaraDB for MyBase
AnalyticDB
ApsaraDB for ClickHouse
ApsaraDB for SelectDB
Data Transmission Service
Database Autonomy Service
Data Management
Database Gateway - Deprecated
ApsaraDB for Cassandra - Deprecated
Analytics Computing
MaxCompute
Hologres
Realtime Compute for Apache Flink
Elasticsearch
Vector Retrieval Service for Milvus
E-MapReduce
Data Lake Formation
DataV
Quick BI
Quick Audience
Quick Tracking
DataWorks
DataHub
Dataphin
Media Services
ApsaraVideo VOD
ApsaraVideo Live
Intelligent Media Services
ApsaraVideo Media Processing
Apsara Video SDK
Enterprise Services & Cloud Communication
Energy Expert
CloudQuotation
Salesforce on Alibaba Cloud
GoChina ICP Filing Assistant
Marketplace
Alibaba Mail
Direct Mail
Short Message Service
Voice Service
Phone Number Verification Service
Cell Phone Number Service
Chat App Message Service
Financial Intelligence Engine
Domain Names and Websites
Domain Names
ICP Filing
Alibaba Cloud DNS
End User Computing
Elastic Desktop Service
App Streaming
WUYING Terminal
Cloud Phone
AgentBay
Internet of Things
IoT Platform
Serverless
Serverless App Engine
CloudFlow
EventBridge
Simple Message Queue (formerly MNS)
Function Compute
Developer Tools
OpenAPI Explorer
Alibaba Cloud SDK
Cloud Shell
Resource Orchestration Service
Alibaba Cloud CLI
BSS OpenAPI
Terraform
Pulumi
Ticket System API
Mobile Platform as a Service
Alibaba Cloud DevOps
API Gateway
Cloud Control API
AI Coding Assistant Lingma
Cloud Skills Portal
Migration & O&M Management
CloudOps Orchestration Service
Cloud Monitor
Intelligent Advisor
Cloud Governance Center
ActionTrail
Cloud Config
Resource Access Management
Resource Management
Cloud Architect Design Tools
Migration Hub
Server Migration Center
Service Catalog
Logic Composer
Quota Center
CloudSSO
HTTPDNS
Solutions
SAP
SuperApp
OpenLake
Membership Service
Expenses and Costs
Account Center
More
Support
Legal
Tech Share Terms and Conditions
After Sales Support
China Gateway Program
Service Level Objectives
Management Console
Security Control
Structured output (JSON mode) makes the model return a valid JSON string that your code can parse directly, without extra text like json that breaks downstream parsing.
Usage
To enable structured output, set response_format in your request with two requirements:
Set the
response_formatparameter to{"type": "json_object"}in the request body.Include the word "JSON" (case-insensitive) in your system message or user message. Without it, the API returns:
'messages' must contain the word 'json' in some form, to use 'response_format' of type 'json_object'.
Supported models
Qwen
Kimi
GLM
- Text generation models
Qwen-Max (non-thinking mode): Qwen3.6-Max series, Qwen3-Max series, Qwen-Max series
Qwen-Plus (non-thinking mode): Qwen3.7-Plus series, Qwen3.6-Plus series, Qwen3.5-Plus series, Qwen-Plus series
Qwen-Flash (non-thinking mode): Qwen3.6-Flash series, Qwen3.5-Flash series, Qwen-Flash series
Qwen-Turbo (non-thinking mode): Qwen-Turbo series
Qwen-Coder: Qwen3-Coder series
Qwen-Long: Qwen-Long series
Qwen3.6 open-source series (non-thinking mode)
Qwen3.5 open-source series (non-thinking mode)
Qwen3 open-source series (non-thinking mode)
Qwen3-Coder open-source series
Qwen2.5 open-source series (excluding math and coder models)
- Multimodal models
Qwen-VL (non-thinking mode): Qwen3-VL-Plus series, Qwen3-VL-Flash series, Qwen-VL-Max series (excluding the latest and snapshot versions), Qwen-VL-Plus series (excluding the latest and snapshot versions)
Qwen-Omni: Qwen3.5-Omni-Plus series, Qwen3.5-Omni-Flash series
Qwen3-VL open-source series (non-thinking mode)
Note
Models in thinking mode do not currently support structured output.
kimi-k2-thinking
Non-thinking mode: glm-5.1, glm-5, glm-4.7, glm-4.6
Getting started
This example extracts structured information from a personal profile.
Obtain an API key and export the API key as an environment variable. If you use the OpenAI SDK or DashScope SDK to make calls, install the SDK.
OpenAI compatible
DashScope
Python
Node.js
curl
python
from openai import OpenAI
import os
client = OpenAI(
# API keys differ by region. If you haven't configured an environment variable, replace the next line with: api_key="sk-xxx"
api_key=os.getenv("DASHSCOPE_API_KEY"),
# If you use Beijing region models, replace base_url with: https://dashscope.aliyuncs.com/compatible-mode/v1
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
model="qwen-flash",
messages=[\
{\
"role": "system",\
"content": "Extract the user's name and age, and return them in JSON format"\
},\
{\
"role": "user",\
"content": "Hi everyone, my name is Alex Brown, I'm 34 years old, my email is alexbrown@example.com, and I enjoy playing basketball and traveling",\
},\
],
response_format={"type": "json_object"}
)
json_string = completion.choices[0].message.content
print(json_string)Response
plaintext
{
"Name": "Alex Brown",
"Age": 34
}nodejs
import OpenAI from "openai";
const openai = new OpenAI({
// If you haven't configured an environment variable, replace the next line with: apiKey: "sk-xxx"
apiKey: process.env.DASHSCOPE_API_KEY,
// For Beijing region models, replace baseURL with: https://dashscope.aliyuncs.com/compatible-mode/v1
baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
});
const completion = await openai.chat.completions.create({
model: "qwen-flash",
messages: [\
{\
role: "system",\
content: "Extract the user's name and age, and return them in JSON format"\
},\
{\
role: "user",\
content: "Hi everyone, my name is Alex Brown, I'm 34 years old, my email is alexbrown@example.com, and I enjoy playing basketball and traveling"\
}\
],
response_format: {
type: "json_object"
}
});
const jsonString = completion.choices[0].message.content;
console.log(jsonString);Response
plaintext
{
"name": "Alex Brown",
"age": 34
}curl
# ======= Important =======
# API keys differ by region. To obtain an API key, visit: https://www.alibabacloud.com/help/en/model-studio/get-api-key
# If you use a model in the Beijing region, replace the URL with: https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
# === 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": "qwen-plus",
"messages": [\
{\
"role": "system",\
"content": "You need to extract the name (string), age (string), and email (string). Output the result as a JSON string. Do not include any other irrelevant content.\nExamples:\nQ: My name is Alice, I am 25 years old, and my email is alice@example.com\nA: {\"name\":\"Alice\",\"age\":\"25 years old\",\"email\":\"alice@example.com\"}\nQ: My name is Bob, I am 30 years old, and my email is bob@example.com\nA: {\"name\":\"Bob\",\"age\":\"30 years old\",\"email\":\"bob@example.com\"}\nQ: My name is Charlie, my email is charlie@example.com, and I am 40 years old\nA: {\"name\":\"Charlie\",\"age\":\"40 years old\",\"email\":\"charlie@example.com\"}"\
},\
{\
"role": "user",\
"content": "Hello everyone, my name is Alex Brown, I am 34 years old, and my email is alexbrown@example.com"\
}\
],
"response_format": {
"type": "json_object"
}
}'Response
json
{
"choices": [\
{\
"message": {\
"role": "assistant",\
"content": "{\"name\":\"Alex Brown\",\"age\":\"34 years old\"}"\
},\
"finish_reason": "stop",\
"index": 0,\
"logprobs": null\
}\
],
"object": "chat.completion",
"usage": {
"prompt_tokens": 207,
"completion_tokens": 20,
"total_tokens": 227,
"prompt_tokens_details": {
"cached_tokens": 0
}
},
"created": 1756455080,
"system_fingerprint": null,
"model": "qwen-plus",
"id": "chatcmpl-624b665b-fb93-99e7-9ebd-bb6d86d314d2"
}Python
Java
curl
python
import os
import dashscope
# For Beijing region models, replace the URL with: https://dashscope.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
messages=[\
{\
"role": "system",\
"content": "Extract the user's name and age, and return them in JSON format"\
},\
{\
"role": "user",\
"content": "Hi everyone, my name is Alex Brown, I'm 34 years old, my email is alexbrown@example.com, and I enjoy playing basketball and traveling",\
},\
]
response = dashscope.Generation.call(
# If you haven't configured an environment variable, replace the next line with: api_key="sk-xxx" (Alibaba Cloud Model Studio API key),
api_key=os.getenv('DASHSCOPE_API_KEY'),
model="qwen-flash",
messages=messages,
result_format='message',
response_format={'type': 'json_object'}
)
json_string = response.output.choices[0].message.content
print(json_string)Response
plaintext
{
"name": "Alex Brown",
"age": 34
}DashScope Java SDK version must be 2.18.4 or higher.
java
// DashScope Java SDK version must be 2.18.4 or higher
import java.util.Arrays;
import java.lang.System;
import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.common.ResponseFormat;
import com.alibaba.dashscope.protocol.Protocol;
public class Main {
public static GenerationResult callWithMessage() throws ApiException, NoApiKeyException, InputRequiredException {
// For Beijing region models, replace the URL with: https://dashscope.aliyuncs.com/api/v1
Generation gen = new Generation(Protocol.HTTP.getValue(), "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1");
Message systemMsg = Message.builder()
.role(Role.SYSTEM.getValue())
.content("Extract the user's name and age, and return them in JSON format")
.build();
Message userMsg = Message.builder()
.role(Role.USER.getValue())
.content("Hi everyone, my name is Alex Brown, I'm 34 years old, my email is alexbrown@example.com, and I enjoy playing basketball and traveling")
.build();
ResponseFormat jsonMode = ResponseFormat.builder().type("json_object").build();
GenerationParam param = GenerationParam.builder()
// If you haven't configured an environment variable, replace the next line with: .apiKey("sk-xxx") (Alibaba Cloud Model Studio API key)
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.model("qwen-flash")
.messages(Arrays.asList(systemMsg, userMsg))
.resultFormat(GenerationParam.ResultFormat.MESSAGE)
.responseFormat(jsonMode)
.build();
return gen.call(param);
}
public static void main(String[] args) {
try {
GenerationResult result = callWithMessage();
System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent());
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
// Log the exception using a logging framework
System.err.println("An error occurred while calling the generation service: " + e.getMessage());
}
}
}Response
plaintext
{
"name": "Alex Brown",
"age": 34
}curl
# ======= Important notes =======
# For Beijing region models, replace the URL with: https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation
# API keys differ by region. Get an API key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
# === Delete this comment before running ===
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen-flash",
"input": {
"messages": [\
{\
"role": "system",\
"content": "Extract the user'\''s name and age, and return them in JSON format"\
},\
{\
"role": "user",\
"content": "Hi everyone, my name is Alex Brown, I'\''m 34 years old, my email is alexbrown@example.com, and I enjoy playing basketball and traveling"\
}\
]
},
"parameters": {
"result_format": "message",
"response_format": {
"type": "json_object"
}
}
}'Response
json
{
"name": "Alex Brown",
"age": 34
}Image and video data processing
Multimodal models also support structured output for images and videos. Use JSON mode to extract structured data from visual content, such as field values from receipts, object locations in images, or events in video.
For image and video file limits, see Image and video understanding .
OpenAI compatible
DashScope
Python
Node.js
curl
python
import os
from openai import OpenAI
client = OpenAI(
# API keys differ by region. Get an API key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
api_key=os.getenv("DASHSCOPE_API_KEY"),
# For Beijing region models, replace base_url with: https://dashscope.aliyuncs.com/compatible-mode/v1
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
)
completion = client.chat.completions.create(
model="qwen3-vl-plus",
messages=[\
{\
"role": "system",\
"content": [{"type": "text", "text": "You are a helpful assistant."}],\
},\
{\
"role": "user",\
"content": [\
{\
"type": "image_url",\
"image_url": {\
"url": "http://duguang-labelling.oss-cn-shanghai.aliyuncs.com/demo_ocr/receipt_zh_demo.jpg"\
},\
},\
{"type": "text", "text": "Extract ticket (array type, including travel_date, trains, seat_num, arrival_site, price) and invoice information (array type, including invoice_code and invoice_number) from the image. Output a JSON containing both ticket and invoice arrays"},\
],\
},\
],
response_format={"type": "json_object"}
)
json_string = completion.choices[0].message.content
print(json_string)Response
plaintext
{
"ticket": [\
{\
"travel_date": "2013-06-29",\
"trains": "stream",\
"seat_num": "371",\
"arrival_site": "Development Zone",\
"price": "8.00"\
}\
],
"invoice": [\
{\
"invoice_code": "221021325353",\
"invoice_number": "10283819"\
}\
]
}nodejs
import OpenAI from "openai";
const openai = new OpenAI({
// API keys differ by region. Get an API key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
// If you haven't configured an environment variable, replace the next line with: apiKey: "sk-xxx" (Model Studio API key)
apiKey: process.env.DASHSCOPE_API_KEY,
// For Beijing region models, replace base_url with https://dashscope.aliyuncs.com/compatible-mode/v1
baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
});
async function main() {
const response = await openai.chat.completions.create({
model: "qwen3-vl-plus",
messages: [{\
role: "system",\
content: [{\
type: "text",\
text: "You are a helpful assistant."\
}]\
},\
{\
role: "user",\
content: [{\
type: "image_url",\
image_url: {\
"url": "http://duguang-labelling.oss-cn-shanghai.aliyuncs.com/demo_ocr/receipt_zh_demo.jpg"\
}\
},\
{\
type: "text",\
text: "Extract ticket (array type, including travel_date, trains, seat_num, arrival_site, price) and invoice information (array type, including invoice_code and invoice_number) from the image. Output a JSON containing both ticket and invoice arrays"\
}\
]\
}\
],
response_format: {type: "json_object"}
});
console.log(response.choices[0].message.content);
}
main()Response
plaintext
{
"ticket": [\
{\
"travel_date": "2013-06-29",\
"trains": "stream",\
"seat_num": "371",\
"arrival_site": "Development Zone",\
"price": "8.00"\
}\
],
"invoice": [\
{\
"invoice_code": "221021325353",\
"invoice_number": "10283819"\
}\
]
}curl
# ======= Important notes =======
# For Beijing region models, replace base_url with: https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
# API keys differ by region. Get an API key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
# === Delete this comment before running ===
curl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"model": "qwen3-vl-plus",
"messages": [\
{"role":"system",\
"content":[\
{"type": "text", "text": "You are a helpful assistant."}]},\
{\
"role": "user",\
"content": [\
{"type": "image_url", "image_url": {"url": "http://duguang-labelling.oss-cn-shanghai.aliyuncs.com/demo_ocr/receipt_zh_demo.jpg"}},\
{"type": "text", "text": "Extract ticket (array type, including travel_date, trains, seat_num, arrival_site, price) and invoice information (array type, including invoice_code and invoice_number) from the image. Output a JSON containing both ticket and invoice arrays"}\
]\
}],
"response_format":{"type": "json_object"}
}'Response
json
{
"ticket": [\
{\
"travel_date": "2013-06-29",\
"trains": "stream",\
"seat_num": "371",\
"arrival_site": "Development Zone",\
"price": "8.00"\
}\
],
"invoice": [\
{\
"invoice_code": "221021325353",\
"invoice_number": "10283819"\
}\
]
}Python
Java
curl
python
import os
import dashscope
# For Beijing region models, replace the URL with: https://dashscope.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
messages = [\
{\
"role": "system",\
"content": [\
{"text": "You are a helpful assistant."}]\
},\
{\
"role": "user",\
"content": [\
{"image": "http://duguang-labelling.oss-cn-shanghai.aliyuncs.com/demo_ocr/receipt_zh_demo.jpg"},\
{"text": "Extract ticket (array type, including travel_date, trains, seat_num, arrival_site, price) and invoice information (array type, including invoice_code and invoice_number) from the image. Output a JSON containing both ticket and invoice arrays"}]\
}]
response = dashscope.MultiModalConversation.call(
# If you haven't configured an environment variable, replace the next line with: api_key ="sk-xxx" (Model Studio API key)
api_key = os.getenv('DASHSCOPE_API_KEY'),
model = 'qwen3-vl-plus',
messages = messages,
response_format={'type': 'json_object'}
)
json_string = response.output.choices[0].message.content[0]["text"]
print(json_string)Response
plaintext
{
"ticket": [\
{\
"travel_date": "2013-06-29",\
"trains": "Liushui",\
"seat_num": "371",\
"arrival_site": "Development Zone",\
"price": "8.00"\
}\
],
"invoice": [\
{\
"invoice_code": "221021325353",\
"invoice_number": "10283819"\
}\
]
}java
// DashScope Java SDK version must be 2.21.4 or higher
import java.util.Arrays;
import java.util.Collections;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.common.ResponseFormat;
import com.alibaba.dashscope.utils.Constants;
public class Main {
// For Beijing region models, replace the URL with: https://dashscope.aliyuncs.com/api/v1
static {
Constants.baseHttpApiUrl="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
}
public static void simpleMultiModalConversationCall()
throws ApiException, NoApiKeyException, UploadFileException {
MultiModalConversation conv = new MultiModalConversation();
MultiModalMessage systemMessage = MultiModalMessage.builder().role(Role.SYSTEM.getValue())
.content(Arrays.asList(
Collections.singletonMap("text", "You are a helpful assistant."))).build();
MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
.content(Arrays.asList(
Collections.singletonMap("image", "http://duguang-labelling.oss-cn-shanghai.aliyuncs.com/demo_ocr/receipt_zh_demo.jpg"),
Collections.singletonMap("text", "Extract ticket (array type, including travel_date, trains, seat_num, arrival_site, price) and invoice information (array type, including invoice_code and invoice_number) from the image. Output a JSON containing both ticket and invoice arrays"))).build();
ResponseFormat jsonMode = ResponseFormat.builder().type("json_object").build();
MultiModalConversationParam param = MultiModalConversationParam.builder()
// If you haven't configured an environment variable, replace the next line with: .apiKey("sk-xxx") (Model Studio API key)
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.model("qwen3-vl-plus")
.messages(Arrays.asList(systemMessage, userMessage))
.responseFormat(jsonMode)
.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());
}
}
}Response
plaintext
{
"ticket": [\
{\
"travel_date": "2013-06-29",\
"trains": "stream",\
"seat_num": "371",\
"arrival_site": "Development Zone",\
"price": "8.00"\
}\
],
"invoice": [\
{\
"invoice_code": "221021325353",\
"invoice_number": "10283819"\
}\
]
}curl
# ======= Important notes =======
# For Beijing region models, replace the URL with: https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
# API keys differ by region. Get an API key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
# === Delete this comment before running ===
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "qwen3-vl-plus",
"input": {
"messages": [\
{\
"role": "system",\
"content": [\
{\
"text": "You are a helpful assistant."\
}\
]\
},\
{\
"role": "user",\
"content": [\
{\
"image": "http://duguang-labelling.oss-cn-shanghai.aliyuncs.com/demo_ocr/receipt_zh_demo.jpg"\
},\
{\
"text": "Extract ticket (array type, including travel_date, trains, seat_num, arrival_site, price) and invoice information (array type, including invoice_code and invoice_number) from the image. Output a JSON containing both ticket and invoice arrays"\
}\
]\
}\
]
},
"parameters": {
"response_format": {
"type": "json_object"
}
}
}'Response
json
{
"output": {
"choices": [\
{\
"message": {\
"content": [\
{\
"text": "{\n \"ticket\": [\n {\n \"travel_date\": \"2013-06-29\",\n \"trains\": \"train number\",\n \"seat_num\": \"371\",\n \"arrival_site\": \"Development Zone\",\n \"price\": \"8.00\"\n }\n ],\n \"invoice\": [\n {\n \"invoice_code\": \"221021325353\",\n \"invoice_number\": \"10283819\"\n }\n ]\n}"\
}\
],\
"role": "assistant"\
},\
"finish_reason": "stop"\
}\
]
},
"usage": {
"total_tokens": 598,
"input_tokens_details": {
"image_tokens": 418,
"text_tokens": 68
},
"output_tokens": 112,
"input_tokens": 486,
"output_tokens_details": {
"text_tokens": 112
},
"image_tokens": 418
},
"request_id": "b129dce1-0d5d-4772-b8b5-bd3a1d5cde63"
}Optimize prompts
Ambiguous prompts like "return user information" lead to unpredictable output structures. For reliable results, describe the expected schema in your prompt: specify field names, types, required vs. optional status, format constraints (such as date format), and include examples.
OpenAI compatible
DashScope
Python
Node.js
python
from openai import OpenAI
import os
import json
import textwrap # Handles indentation for multi-line strings to improve code readability
# Predefined example responses to show the model the expected output format
# Example 1: Complete response with all fields
example1_response = json.dumps(
{
"info": {"name": "Alice", "age": "25 years old", "email": "alice@example.com"},
"hobby": ["singing"]
},
ensure_ascii=False
)
# Example 2: Response with multiple hobbies
example2_response = json.dumps(
{
"info": {"name": "Bob", "age": "30 years old", "email": "bob@example.com"},
"hobby": ["dancing", "swimming"]
},
ensure_ascii=False
)
# Example 3: Response without hobby field (hobby is optional)
example3_response = json.dumps(
{
"info": {"name": "Dave", "age": "28 years old", "email": "dave@example.com"}
},
ensure_ascii=False
)
# Example 4: Another response without hobby field
example4_response = json.dumps(
{
"info": {"name": "Sun Qi", "age": "35 years old", "email": "sunqi@example.com"}
},
ensure_ascii=False
)
# Initialize the OpenAI client
client = OpenAI(
# If you haven't configured an environment variable, replace the next line with: api_key="sk-xxx"
# API keys differ by region. Get an API key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
api_key=os.getenv("DASHSCOPE_API_KEY"),
# This is the Beijing region base_url. If you use Singapore region models, replace base_url with: https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
)
# dedent removes common leading whitespace from each line, allowing the string to be indented nicely in code without including extra spaces at runtime
system_prompt = textwrap.dedent(f"""\
Extract personal information from the user input and output it in the specified JSON Schema format:
[Output format requirements]
The output must strictly follow this JSON structure:
{{
"info": {{
"name": "string type, required field, user's name",
"age": "string type, required field, format 'number years old', e.g., '25 years old'",
"email": "string type, required field, standard email format, e.g., 'user@example.com'"
}},
"hobby": ["string array type, optional field, contains all user hobbies; omit entirely if not mentioned"]
}}
[Field extraction rules]
1. name: Identify the user's name from the text, must extract
2. age: Identify age information, convert to 'number years old' format, must extract
3. email: Identify email address, keep original format, must extract
4. hobby: Identify user hobbies, output as string array; omit hobby field entirely if hobbies are not mentioned
[Reference examples]
Example 1 (with hobby):
Q: My name is Alice, I'm 25 years old, my email is alice@example.com, and my hobby is singing
A: {example1_response}
Example 2 (with multiple hobbies):
Q: My name is Bob, I'm 30 years old, my email is bob@example.com, and I enjoy dancing and swimming
A: {example2_response}
Example 3 (without hobby):
Q: My name is Dave, I'm 28 years old, and my email is dave@example.com
A: {example3_response}
Example 4 (without hobby):
Q: I'm Sun Qi, 35 years old, and my email is sunqi@example.com
A: {example4_response}
Extract information and output JSON strictly according to the above format and rules. Do not include the hobby field if the user doesn't mention hobbies.\
""")
# Call the model API for information extraction
completion = client.chat.completions.create(
model="qwen-plus",
messages=[\
{\
"role": "system",\
"content": system_prompt\
},\
{\
"role": "user",\
"content": "Hi everyone, my name is Alex Brown, I'm 34 years old, my email is alexbrown@example.com, and I enjoy playing basketball and traveling",\
},\
],
response_format={"type": "json_object"}, # Specify JSON format return
)
# Extract and print the model-generated JSON result
json_string = completion.choices[0].message.content
print(json_string)Response
plaintext
{
"info": {
"name": "Alex Brown",
"age": "34 years old",
"email": "alexbrown@example.com"
},
"hobby": ["Basketball", "Traveling"]
}nodejs
import OpenAI from "openai";
// Predefined example responses (to show the model the expected output format)
// Example 1: Complete response with all fields
const example1Response = JSON.stringify({
info: { name: "Alice", age: "25 years old", email: "alice@example.com" },
hobby: ["singing"]
}, null, 2);
// Example 2: Response with multiple hobbies
const example2Response = JSON.stringify({
info: { name: "Bob", age: "30 years old", email: "bob@example.com" },
hobby: ["dancing", "swimming"]
}, null, 2);
// Example 3: Response without hobby field (hobby is optional)
const example3Response = JSON.stringify({
info: { name: "Dave", age: "28 years old", email: "dave@example.com" }
}, null, 2);
// Example 4: Another response without hobby field
const example4Response = JSON.stringify({
info: { name: "Sun Qi", age: "35 years old", email: "sunqi@example.com" }
}, null, 2);
// Initialize OpenAI client configuration
const openai = new OpenAI({
// If you haven't configured an environment variable, replace the next line with: apiKey: "sk-xxx" (Alibaba Cloud Model Studio API key),
// API keys differ by region. Get an API key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
apiKey: process.env.DASHSCOPE_API_KEY,
// This is the Beijing region base_url. If you use Singapore region models, replace base_url with: https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1
baseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1"
});
// Create chat completion request using structured prompts to improve output accuracy
const completion = await openai.chat.completions.create({
model: "qwen-plus",
messages: [\
{\
role: "system",\
content: `Extract personal information from the user input and output it in the specified JSON Schema format:\
\
[Output format requirements]\
The output must strictly follow this JSON structure:\
{\
"info": {\
"name": "string type, required field, user's name",\
"age": "string type, required field, format 'number years old', e.g., '25 years old'",\
"email": "string type, required field, standard email format, e.g., 'user@example.com'"\
},\
"hobby": ["string array type, optional field, contains all user hobbies; omit entirely if not mentioned"]\
}\
\
[Field extraction rules]\
1. name: Identify the user's name from the text, must extract\
2. age: Identify age information, convert to 'number years old' format, must extract\
3. email: Identify email address, keep original format, must extract\
4. hobby: Identify user hobbies, output as string array; omit hobby field entirely if hobbies are not mentioned\
\
[Reference examples]\
Example 1 (with hobby):\
Q: My name is Alice, I'm 25 years old, my email is alice@example.com, and my hobby is singing\
A: ${example1Response}\
\
Example 2 (with multiple hobbies):\
Q: My name is Bob, I'm 30 years old, my email is bob@example.com, and I enjoy dancing and swimming\
A: ${example2Response}\
\
Example 3 (without hobby):\
Q: My name is Dave, I'm 28 years old, and my email is dave@example.com\
A: ${example3Response}\
\
Example 4 (without hobby):\
Q: I'm Sun Qi, 35 years old, and my email is sunqi@example.com\
A: ${example4Response}\
\
Extract information and output JSON strictly according to the above format and rules. Do not include the hobby field if the user doesn't mention hobbies.`\
},\
{\
role: "user",\
content: "Hi everyone, my name is Alex Brown, I'm 34 years old, my email is alexbrown@example.com, and I enjoy playing basketball and traveling"\
}\
],
response_format: {
type: "json_object"
}
});
// Extract and print the model-generated JSON result
const jsonString = completion.choices[0].message.content;
console.log(jsonString);Response
plaintext
{
"info": {
"name": "Alex Brown",
"age": "34 years old",
"email": "alexbrown@example.com"
},
"hobby": [\
"playing basketball",\
"traveling"\
]
}Python
Java
python
import os
import json
import dashscope
# If you use Singapore region models, uncomment the following line
# dashscope.base_http_api_url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"
# Predefined example responses (to show the model the expected output format)
example1_response = json.dumps(
{
"info": {"name": "Alice", "age": "25 years old", "email": "alice@example.com"},
"hobby": ["singing"]
},
ensure_ascii=False
)
example2_response = json.dumps(
{
"info": {"name": "Bob", "age": "30 years old", "email": "bob@example.com"},
"hobby": ["dancing", "swimming"]
},
ensure_ascii=False
)
example3_response = json.dumps(
{
"info": {"name": "Charlie", "age": "40 years old", "email": "charlie@example.com"},
"hobby": ["Rap", "basketball"]
},
ensure_ascii=False
)
messages=[\
{\
"role": "system",\
"content": f"""Extract personal information from the user input and output it in the specified JSON Schema format:\
\
[Output format requirements]\
The output must strictly follow this JSON structure:\
{{\
"info": {{\
"name": "string type, required field, user's name",\
"age": "string type, required field, format 'number years old', e.g., '25 years old'",\
"email": "string type, required field, standard email format, e.g., 'user@example.com'"\
}},\
"hobby": ["string array type, optional field, contains all user hobbies; omit entirely if not mentioned"]\
}}\
\
[Field extraction rules]\
1. name: Identify the user's name from the text, must extract\
2. age: Identify age information, convert to 'number years old' format, must extract\
3. email: Identify email address, keep original format, must extract\
4. hobby: Identify user hobbies, output as string array; omit hobby field entirely if hobbies are not mentioned\
\
[Reference examples]\
Example 1 (with hobby):\
Q: My name is Alice, I'm 25 years old, my email is alice@example.com, and my hobby is singing\
A: {example1_response}\
\
Example 2 (with multiple hobbies):\
Q: My name is Bob, I'm 30 years old, my email is bob@example.com, and I enjoy dancing and swimming\
A: {example2_response}\
\
Example 3 (with multiple hobbies):\
Q: My email is charlie@example.com, I'm 40 years old, my name is Charlie, and I can Rap and play basketball\
A: {example3_response}\
\
Extract information and output JSON strictly according to the above format and rules. Do not include the hobby field if the user doesn't mention hobbies."""\
},\
{\
"role": "user",\
"content": "Hi everyone, my name is Alex Brown, I'm 34 years old, my email is alexbrown@example.com, and I enjoy playing basketball and traveling",\
},\
]
response = dashscope.Generation.call(
# If you haven't configured an environment variable, replace the next line with: api_key="sk-xxx" (Alibaba Cloud Model Studio API key),
api_key=os.getenv('DASHSCOPE_API_KEY'),
model="qwen-plus",
messages=messages,
result_format='message',
response_format={'type': 'json_object'}
)
json_string = response.output.choices[0].message.content
print(json_string)Response
plaintext
{
"info": {
"name": "Alex Brown",
"age": "34 years old",
"email": "alexbrown@example.com"
},
"hobby": [\
"playing basketball",\
"traveling"\
]
}java
import java.util.Arrays;
import java.lang.System;
import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.common.ResponseFormat;
import com.alibaba.dashscope.protocol.Protocol;
public class Main {
public static GenerationResult callWithMessage() throws ApiException, NoApiKeyException, InputRequiredException {
// If you use a model in the Beijing region, you must replace the URL with: https://dashscope.aliyuncs.com/api/v1
Generation gen = new Generation(Protocol.HTTP.getValue(), "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1");
Message systemMsg = Message.builder()
.role(Role.SYSTEM.getValue())
.content("""
Extract personal information from the user input and output it in the specified JSON Schema format:
[Output Format Requirements]
The output must strictly follow the JSON structure below:
{
"info": {
"name": "String type, required field, user's name",
"age": "String type, required field, in the format of 'Number years old', for example, '25 years old'",
"email": "String type, required field, standard email format, for example, 'user@example.com'"
},
"hobby": ["String array type, optional field, contains all of the user's hobbies. If no hobbies are mentioned, do not include this field in the output."]
}
[Field Extraction Rules]
1. name: Identify the user's name from the text. This is a required field.
2. age: Identify the age information and transform it into the 'Number years old' format. This is a required field.
3. email: Identify the email address and keep its original format. This is a required field.
4. hobby: Identify the user's hobbies and output them as a string array. If no hobbies are mentioned, completely omit the hobby field.
[Examples]
Example 1 (with a hobby):
Q: My name is Alice, I am 25 years old, my email is alice@example.com, and my hobby is singing.
A: {"info":{"name":"Alice","age":"25 years old","email":"alice@example.com"},"hobby":["singing"]}
Example 2 (with multiple hobbies):
Q: My name is Bob, I am 30 years old, my email is bob@example.com, and I like dancing and swimming.
A: {"info":{"name":"Bob","age":"30 years old","email":"bob@example.com"},"hobby":["dancing","swimming"]}
Example 3 (without hobbies):
Q: My name is Charlie, my email is charlie@example.com, and I am 40 years old.
A: {"info":{"name":"Charlie","age":"40 years old","email":"charlie@example.com"}}""")
.build();
Message userMsg = Message.builder()
.role(Role.USER.getValue())
.content("Hello everyone, my name is Alex Brown, I am 34 years old, my email is alexbrown@example.com, and I enjoy playing basketball and traveling.")
.build();
ResponseFormat jsonMode = ResponseFormat.builder().type("json_object").build();
GenerationParam param = GenerationParam.builder()
// If you use a model in the Beijing region, you need to use an API key for the Beijing region. Obtain the key from: https://bailian.console.alibabacloud.com/?tab=model#/api-key
// If you have not configured environment variables, replace the following line with your Alibaba Cloud Model Studio API key: .apiKey("sk-xxx")
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.model("qwen-plus")
.messages(Arrays.asList(systemMsg, userMsg))
.resultFormat(GenerationParam.ResultFormat.MESSAGE)
.responseFormat(jsonMode)
.build();
return gen.call(param);
}
public static void main(String[] args) {
try {
GenerationResult result = callWithMessage();
System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent());
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
// Use a logging framework to record the exception.
System.err.println("An error occurred while calling the generation service: " + e.getMessage());
}
}
}Response
plaintext
{
"info": {
"name": "Alex Brown",
"age": "34 years old",
"email": "alexbrown@example.com"
},
"hobby": [\
"Playing basketball",\
"Traveling"\
]
}Going live
- Validate before passing downstream
Always validate the JSON output before passing it to downstream services. Use a library such as jsonschema (Python), Ajv (JavaScript), or Everit (Java) to check for missing fields, type errors, or format issues. If validation fails, retry the request or use a second model to fix the output.
- Do not set max_tokens
Do not set max_tokens when structured output is enabled. This parameter caps the number of output tokens and defaults to the model's maximum. Setting it may truncate the JSON string mid-output, producing invalid JSON that fails to parse.
FAQ
Q: How does Qwen's thinking mode model produce structured output?
Qwen's thinking mode models do not support structured output directly. To get a valid JSON string from a thinking mode model, use a two-step approach: first call the thinking model to get high-quality output, then pass any malformed JSON through a model that supports JSON mode to fix it.
- Get output from the thinking mode model
Call the thinking mode model. The result may not be valid JSON.
Do not set the
response_formatparameter to{"type": "json_object"}when enabling thinking mode, or you will encounter an error.
python
completion = client.chat.completions.create(
model="qwen-plus",
messages=[\
{"role": "system", "content": system_prompt},\
{\
"role": "user",\
"content": "Hi everyone, my name is Alex Brown, I'm 34 years old, my email is alexbrown@example.com, and I enjoy playing basketball and traveling",\
},\
],
# Enable thinking mode; do not set response_format parameter to {"type": "json_object"}, or you will get an error
extra_body={"enable_thinking": True},
# Streaming output is required in thinking mode
stream=True
)
# Extract and print the model-generated JSON result
json_string = ""
for chunk in completion:
if chunk.choices[0].delta.content is not None:
json_string += chunk.choices[0].delta.content- Validate and fix the output
Try to parse the json_string from the previous step:
If the model returned valid JSON, parse and use it directly.
If the model returned invalid JSON, call a model that supports structured output (a fast, low-cost model such as qwen-flash in non-thinking mode works well) to fix the format.
python
import json
from openai import OpenAI
import os
# Initialize the OpenAI client (if the client variable isn't defined in the previous code block, uncomment the lines below)
# client = OpenAI(
# api_key=os.getenv("DASHSCOPE_API_KEY"),
# base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
# )
try:
json_object_from_thinking_model = json.loads(json_string)
print("Generated standard JSON string")
except json.JSONDecodeError:
print("Did not generate standard JSON string; fixing with a model that supports structured output")
completion = client.chat.completions.create(
model="qwen-flash",
messages=[\
{\
"role": "system",\
"content": "You are a JSON format expert. Fix the user's JSON string to standard format",\
},\
{\
"role": "user",\
"content": json_string,\
},\
],
response_format={"type": "json_object"},
)
json_object_from_thinking_model = json.loads(completion.choices[0].message.content)Error codes
If the model call fails and returns an error message, see Error codes for resolution.
Previous:NoneNext: Product introduction
Is this page helpful?
Usage
Supported models
Getting started
Image and video data processing
Optimize prompts
Going live
FAQ
Q: How does Qwen's thinking mode model produce structured output?
Error codes
Contact Us
Sales Support
Live-chat with our sales team or get in touch with a business development professional in your region.
Contact Sales
Technical Support
Open a ticket and get quick help from our technical team.
Open a Ticket >
Connect & Report Abuse
We look forward to your suggestion.
Post a Suggestion > Report Abuse >
\ \ Hi, I'm Alibaba Cloud AI Assistant!\ \ I can help with questions and solutions.
Why Alibaba Cloud
About Alibaba Cloud
Asia Accelerator
Our Global Network
Global Offices
Trust Center
Case Studies
Analyst Reports
Products & Pricings
Pricing Calculator
ECS
SAS
Model Studio
Database
Security
SMS
Solutions
Financial Services
Retail Services
Media Services
Gaming Services
ISV Solutions
Engage
Developer Community
Partner Network
Startups
Marketplace
Join Alibaba Cloud
Resources & Support
Developer Learning Hub
Documentation Center
Training & Certification
Service Notices
Submit a Ticket
Security Report
Qwen Cloud
Careers About Us Privacy Policy Legal Integrity Compliance Reporting Channel Service Notices Links
© 2009-2026 Copyright by Alibaba Cloud All rights reserved
- YouTube
- TikTok
- contact.us@alibabacloud.com
- Call Us Now
- Discord
© 2009-2026 Copyright by Alibaba Cloud All rights reserved
Careers About Us Privacy Policy Legal Integrity Compliance Reporting Channel Service Notices Links