Output terstruktur (mode JSON) memungkinkan model mengembalikan string JSON yang valid sehingga kode Anda dapat menguraikannya secara langsung, tanpa teks tambahan seperti json yang mengganggu penguraian di tahap berikutnya.
Penggunaan
Untuk mengaktifkan output terstruktur, atur parameter response_format dalam permintaan Anda dengan dua persyaratan berikut:
-
Atur parameter
response_formatmenjadi{"type": "json_object"}dalam badan permintaan. -
Sertakan kata "JSON" (tidak peka huruf besar/kecil) dalam pesan sistem atau pesan pengguna Anda. Tanpa kata tersebut, API akan mengembalikan:
'messages' must contain the word 'json' in some form, to use 'response_format' of type 'json_object'.
Model yang didukung
Qwen
-
Model generasi teks
-
Qwen-Max (mode non-thinking): seri Qwen3.6-Max, seri Qwen3-Max, seri Qwen-Max
-
Qwen-Plus (mode non-thinking): seri Qwen3.7-Plus, seri Qwen3.6-Plus, seri Qwen3.5-Plus, seri Qwen-Plus
-
Qwen-Flash (mode non-thinking): seri Qwen3.6-Flash, seri Qwen3.5-Flash, seri Qwen-Flash
-
Qwen-Turbo (mode non-thinking): seri Qwen-Turbo
-
Qwen-Coder: seri Qwen3-Coder
-
Qwen-Long: seri Qwen-Long
-
seri open-source Qwen3.6 (mode non-thinking)
-
seri open-source Qwen3.5 (mode non-thinking)
-
seri open-source Qwen3 (mode non-thinking)
-
seri open-source Qwen3-Coder
-
seri open-source Qwen2.5 (tidak termasuk model math dan coder)
-
-
Model multimodal
-
Qwen-VL (mode non-thinking): seri Qwen3-VL-Plus, seri Qwen3-VL-Flash, seri Qwen-VL-Max (tidak termasuk versi terbaru dan snapshot), seri Qwen-VL-Plus (tidak termasuk versi terbaru dan snapshot)
-
Qwen-Omni: seri Qwen3.5-Omni-Plus, seri Qwen3.5-Omni-Flash
-
seri open-source Qwen3-VL (mode non-thinking)
-
Model dalam mode thinking saat ini tidak mendukung output terstruktur.
Kimi
kimi-k2-thinking
GLM
-
glm-5.1
-
Mode non-thinking: glm-5, glm-4.7, glm-4.6
DeepSeek
deepseek-v4-pro、deepseek-v4-flash
Mulai
Contoh ini mengekstraksi informasi terstruktur dari profil pribadi.
Dapatkan kunci API dan ekspor kunci API sebagai variabel lingkungan. Jika Anda menggunakan OpenAI SDK atau DashScope SDK untuk melakukan panggilan, instal SDK.
Kompatibel dengan OpenAI
Python
from openai import OpenAI
import os
client = OpenAI(
# Kunci API berbeda berdasarkan wilayah. Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan: api_key="sk-xxx"
api_key=os.getenv("DASHSCOPE_API_KEY"),
# Jika Anda menggunakan model wilayah Beijing, ganti base_url dengan: 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)Tanggapan
{
"Name": "Alex Brown",
"Age": 34
}
Node.js
import OpenAI from "openai";
const openai = new OpenAI({
// Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan: apiKey: "sk-xxx"
apiKey: process.env.DASHSCOPE_API_KEY,
// Untuk model wilayah Beijing, ganti baseURL dengan: 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);Tanggapan
{
"name": "Alex Brown",
"age": 34
}
curl
# ======= Penting =======
# Kunci API berbeda berdasarkan wilayah. Untuk mendapatkan kunci API, kunjungi: https://www.alibabacloud.com/help/en/model-studio/get-api-key
# Jika Anda menggunakan model di wilayah Beijing, ganti URL dengan: https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
# === Hapus komentar ini sebelum eksekusi ===
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"
}
}'Tanggapan
{
"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"
}
DashScope
Python
import os
import dashscope
# Untuk model wilayah Beijing, ganti URL dengan: 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(
# Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan: api_key="sk-xxx" (Kunci API Alibaba Cloud Model Studio),
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)Tanggapan
{
"name": "Alex Brown",
"age": 34
}
Java
Versi DashScope Java SDK harus 2.18.4 atau lebih tinggi.
// Versi DashScope Java SDK harus 2.18.4 atau lebih tinggi
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 {
// Untuk model wilayah Beijing, ganti URL dengan: 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()
// Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan: .apiKey("sk-xxx") (Kunci API Alibaba Cloud Model Studio)
.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) {
// Catat pengecualian menggunakan framework logging
System.err.println("Terjadi kesalahan saat memanggil layanan generasi: " + e.getMessage());
}
}
}
Tanggapan
{
"name": "Alex Brown",
"age": 34
}
curl
# ======= Catatan penting =======
# Untuk model wilayah Beijing, ganti URL dengan: https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation
# Kunci API berbeda berdasarkan wilayah. Dapatkan kunci API: https://www.alibabacloud.com/help/en/model-studio/get-api-key
# === Hapus komentar ini sebelum menjalankan ===
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"
}
}
}'Tanggapan
{
"name": "Alex Brown",
"age": 34
}
Pemrosesan data gambar dan video
Model multimodal juga mendukung output terstruktur untuk gambar dan video. Gunakan mode JSON untuk mengekstraksi data terstruktur dari konten visual, seperti nilai bidang dari tanda terima, lokasi objek dalam gambar, atau event dalam video.
Untuk batasan ukuran file gambar dan video, lihat Pemahaman gambar dan video.
Kompatibel dengan OpenAI
Python
import os
from openai import OpenAI
client = OpenAI(
# Kunci API berbeda berdasarkan wilayah. Dapatkan kunci API: https://www.alibabacloud.com/help/en/model-studio/get-api-key
api_key=os.getenv("DASHSCOPE_API_KEY"),
# Untuk model wilayah Beijing, ganti base_url dengan: 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)
Tanggapan
{
"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"
}
]
}
Node.js
import OpenAI from "openai";
const openai = new OpenAI({
// Kunci API berbeda berdasarkan wilayah. Dapatkan kunci API: https://www.alibabacloud.com/help/en/model-studio/get-api-key
// Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan: apiKey: "sk-xxx" (Kunci API Model Studio)
apiKey: process.env.DASHSCOPE_API_KEY,
// Untuk model wilayah Beijing, ganti base_url dengan 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()
Tanggapan
{
"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
# ======= Catatan penting =======
# Untuk model wilayah Beijing, ganti base_url dengan: https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
# Kunci API berbeda berdasarkan wilayah. Dapatkan kunci API: https://www.alibabacloud.com/help/en/model-studio/get-api-key
# === Hapus komentar ini sebelum menjalankan ===
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"}
}'
Tanggapan
{
"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"
}
]
}
DashScope
Python
import os
import dashscope
# Untuk model wilayah Beijing, ganti URL dengan: 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(
# Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan: api_key ="sk-xxx" (Kunci API Model Studio)
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)
Tanggapan
{
"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
// Versi DashScope Java SDK harus 2.21.4 atau lebih tinggi
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 {
// Untuk model wilayah Beijing, ganti URL dengan: 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()
// Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan: .apiKey("sk-xxx") (Kunci API Model Studio)
.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());
}
}
}
Tanggapan
{
"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
# ======= Catatan penting =======
# Untuk model wilayah Beijing, ganti URL dengan: https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
# Kunci API berbeda berdasarkan wilayah. Dapatkan kunci API: https://www.alibabacloud.com/help/en/model-studio/get-api-key
# === Hapus komentar ini sebelum menjalankan ===
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"
}
}
}'
Tanggapan
{
"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"
}
Optimalkan prompt
Prompt yang ambigu seperti "return user information" menghasilkan struktur output yang tidak dapat diprediksi. Untuk hasil yang andal, jelaskan skema yang diharapkan dalam prompt Anda: tentukan nama bidang, tipe data, status wajib vs opsional, batasan format (seperti format tanggal), dan sertakan contoh.
Kompatibel dengan OpenAI
Python
from openai import OpenAI
import os
import json
import textwrap # Menangani indentasi untuk string multi-baris untuk meningkatkan keterbacaan kode
# Contoh tanggapan yang telah ditentukan sebelumnya untuk menunjukkan format output yang diharapkan kepada model
# Contoh 1: Tanggapan lengkap dengan semua bidang
example1_response = json.dumps(
{
"info": {"name": "Alice", "age": "25 years old", "email": "alice@example.com"},
"hobby": ["singing"]
},
ensure_ascii=False
)
# Contoh 2: Tanggapan dengan beberapa hobi
example2_response = json.dumps(
{
"info": {"name": "Bob", "age": "30 years old", "email": "bob@example.com"},
"hobby": ["dancing", "swimming"]
},
ensure_ascii=False
)
# Contoh 3: Tanggapan tanpa bidang hobi (hobi bersifat opsional)
example3_response = json.dumps(
{
"info": {"name": "Dave", "age": "28 years old", "email": "dave@example.com"}
},
ensure_ascii=False
)
# Contoh 4: Contoh tanggapan lain tanpa bidang hobi
example4_response = json.dumps(
{
"info": {"name": "Sun Qi", "age": "35 years old", "email": "sunqi@example.com"}
},
ensure_ascii=False
)
# Inisialisasi klien OpenAI
client = OpenAI(
# Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikutnya dengan: api_key="sk-xxx"
# Kunci API berbeda menurut Wilayah. Dapatkan Kunci API: https://www.alibabacloud.com/help/en/model-studio/get-api-key
api_key=os.getenv("DASHSCOPE_API_KEY"),
# Ini adalah base_url Wilayah Beijing. Jika Anda menggunakan model Wilayah Singapura, ganti base_url dengan: https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
)
# dedent menghapus spasi putih di awal yang sama dari setiap baris, memungkinkan string untuk diindentasi dengan baik dalam kode tanpa menyertakan spasi tambahan pada waktu proses
system_prompt = textwrap.dedent(f"""\
Ekstrak informasi pribadi dari input pengguna dan output dalam format Skema JSON yang ditentukan:
[Persyaratan format output]
Output harus benar-benar mengikuti struktur JSON ini:
{{
"info": {{
"name": "tipe string, bidang wajib, nama pengguna",
"age": "tipe string, bidang wajib, format 'angka tahun', mis., '25 tahun'",
"email": "tipe string, bidang wajib, format email standar, mis., 'user@example.com'"
}},
"hobby": ["tipe array string, bidang opsional, berisi semua hobi pengguna; hilangkan seluruhnya jika tidak disebutkan"]
}}
[Aturan ekstraksi bidang]
1. name: Identifikasi nama pengguna dari teks, harus diekstrak
2. age: Identifikasi informasi usia, konversi ke format 'angka tahun', harus diekstrak
3. email: Identifikasi alamat email, pertahankan format asli, harus diekstrak
4. hobby: Identifikasi hobi pengguna, output sebagai array string; hilangkan bidang hobi seluruhnya jika hobi tidak disebutkan
[Contoh referensi]
Contoh 1 (dengan hobi):
T: Nama saya Alice, saya berumur 25 tahun, email saya alice@example.com, dan hobi saya menyanyi
J: {example1_response}
Contoh 2 (dengan beberapa hobi):
T: Nama saya Bob, saya berumur 30 tahun, email saya bob@example.com, dan saya suka menari dan berenang
J: {example2_response}
Contoh 3 (tanpa hobi):
T: Nama saya Dave, saya berumur 28 tahun, dan email saya dave@example.com
J: {example3_response}
Contoh 4 (tanpa hobi):
T: Saya Sun Qi, 35 tahun, dan email saya sunqi@example.com
J: {example4_response}
Ekstrak informasi dan output JSON secara ketat sesuai dengan format dan aturan di atas. Jangan sertakan bidang hobi jika pengguna tidak menyebutkan hobi.\
""")
# Panggil API model untuk ekstraksi informasi
completion = client.chat.completions.create(
model="qwen-plus",
messages=[
{
"role": "system",
"content": system_prompt
},
{
"role": "user",
"content": "Halo semuanya, nama saya Alex Brown, saya berumur 34 tahun, email saya alexbrown@example.com, dan saya suka bermain bola basket dan bepergian",
},
],
response_format={"type": "json_object"}, # Tentukan pengembalian format JSON
)
# Ekstrak dan cetak hasil JSON yang dihasilkan model
json_string = completion.choices[0].message.content
print(json_string)Tanggapan
{
"info": {
"name": "Alex Brown",
"age": "34 years old",
"email": "alexbrown@example.com"
},
"hobby": ["Basketball", "Traveling"]
}
Node.js
import OpenAI from "openai";
// Contoh tanggapan yang telah ditentukan sebelumnya (untuk menunjukkan format output yang diharapkan kepada model)
// Contoh 1: Tanggapan lengkap dengan semua bidang
const example1Response = JSON.stringify({
info: { name: "Alice", age: "25 years old", email: "alice@example.com" },
hobby: ["singing"]
}, null, 2);
// Contoh 2: Tanggapan dengan beberapa hobi
const example2Response = JSON.stringify({
info: { name: "Bob", age: "30 years old", email: "bob@example.com" },
hobby: ["dancing", "swimming"]
}, null, 2);
// Contoh 3: Tanggapan tanpa bidang hobby (hobby bersifat opsional)
const example3Response = JSON.stringify({
info: { name: "Dave", age: "28 years old", email: "dave@example.com" }
}, null, 2);
// Contoh 4: Tanggapan lain tanpa bidang hobby
const example4Response = JSON.stringify({
info: { name: "Sun Qi", age: "35 years old", email: "sunqi@example.com" }
}, null, 2);
// Inisialisasi konfigurasi klien OpenAI
const openai = new OpenAI({
// Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan: apiKey: "sk-xxx" (Kunci API Alibaba Cloud Model Studio),
// Kunci API berbeda berdasarkan wilayah. Dapatkan kunci API: https://www.alibabacloud.com/help/en/model-studio/get-api-key
apiKey: process.env.DASHSCOPE_API_KEY,
// Ini adalah base_url wilayah Beijing. Jika Anda menggunakan model wilayah Singapura, ganti base_url dengan: https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1
baseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1"
});
// Buat permintaan penyelesaian chat menggunakan prompt terstruktur untuk meningkatkan akurasi output
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"
}
});
// Ekstrak dan cetak hasil JSON yang dihasilkan model
const jsonString = completion.choices[0].message.content;
console.log(jsonString);Tanggapan
{
"info": {
"name": "Alex Brown",
"age": "34 years old",
"email": "alexbrown@example.com"
},
"hobby": [
"playing basketball",
"traveling"
]
}
DashScope
Python
import os
import json
import dashscope
# Jika Anda menggunakan model wilayah Singapura, hapus komentar baris berikut
# dashscope.base_http_api_url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"
# Contoh tanggapan yang telah ditentukan sebelumnya (untuk menunjukkan format output yang diharapkan kepada model)
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(
# Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan: api_key="sk-xxx" (Kunci API Alibaba Cloud Model Studio),
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)Tanggapan
{
"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 {
// Jika Anda menggunakan model di wilayah Beijing, Anda harus mengganti URL dengan: 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()
// Jika Anda menggunakan model di wilayah Beijing, Anda perlu menggunakan kunci API untuk wilayah Beijing. Dapatkan kunci dari: https://bailian.console.alibabacloud.com/?tab=model#/api-key
// Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan Kunci API Alibaba Cloud Model Studio Anda: .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) {
// Gunakan framework logging untuk mencatat pengecualian.
System.err.println("Terjadi kesalahan saat memanggil layanan generasi: " + e.getMessage());
}
}
}
Tanggapan
{
"info": {
"name": "Alex Brown",
"age": "34 years old",
"email": "alexbrown@example.com"
},
"hobby": [
"Playing basketball",
"Traveling"
]
}
Produksi
-
Validasi sebelum meneruskan ke downstream
Selalu validasi output JSON sebelum meneruskannya ke layanan downstream. Gunakan library seperti jsonschema (Python), Ajv (JavaScript), atau Everit (Java) untuk memeriksa bidang yang hilang, kesalahan tipe, atau masalah format. Jika validasi gagal, ulangi permintaan atau gunakan model kedua untuk memperbaiki output.
-
Jangan atur max_tokens
Jangan atur parameter
max_tokenssaat output terstruktur diaktifkan. Parameter ini membatasi jumlah token output dan secara default menggunakan maksimum model. Mengaturnya dapat memotong string JSON di tengah output, menghasilkan JSON yang tidak valid dan gagal diurai.
FAQ
T: Bagaimana model thinking mode Qwen menghasilkan output terstruktur?
Model thinking mode Qwen tidak mendukung output terstruktur secara langsung. Untuk mendapatkan string JSON yang valid dari model thinking mode, gunakan pendekatan dua langkah: pertama panggil model thinking untuk mendapatkan output berkualitas tinggi, lalu teruskan JSON yang tidak valid melalui model yang mendukung mode JSON untuk memperbaikinya.
-
Dapatkan output dari model thinking mode
Panggil model thinking mode. Hasilnya mungkin bukan JSON yang valid.
Jangan atur parameter
response_formatmenjadi{"type": "json_object"}saat mengaktifkan mode thinking, atau Anda akan mengalami kesalahan.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", }, ], # Aktifkan mode thinking; jangan atur parameter response_format menjadi {"type": "json_object"}, atau Anda akan mendapatkan kesalahan extra_body={"enable_thinking": True}, # Output streaming diperlukan dalam mode thinking stream=True ) # Ekstrak dan cetak hasil JSON yang dihasilkan model json_string = "" for chunk in completion: if chunk.choices[0].delta.content is not None: json_string += chunk.choices[0].delta.content -
Validasi dan perbaiki output
Coba uraikan
json_stringdari langkah sebelumnya:-
Jika model mengembalikan JSON yang valid, uraikan dan gunakan langsung.
-
Jika model mengembalikan JSON yang tidak valid, panggil model yang mendukung output terstruktur (model cepat dan berbiaya rendah seperti qwen-flash dalam mode non-thinking bekerja dengan baik) untuk memperbaiki formatnya.
import json from openai import OpenAI import os # Inisialisasi klien OpenAI (jika variabel client tidak didefinisikan di blok kode sebelumnya, hapus komentar baris di bawah ini) # 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("Menghasilkan string JSON standar") except json.JSONDecodeError: print("Tidak menghasilkan string JSON standar; memperbaiki dengan model yang mendukung output terstruktur") 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) -
Kode kesalahan
Jika pemanggilan model gagal dan mengembalikan pesan kesalahan, lihat Kode kesalahan untuk resolusi.