Aktifkan Python Code Interpreter bawaan saat memanggil model. Model menulis dan menjalankan kode Python dalam sandbox untuk menyelesaikan masalah kompleks seperti perhitungan matematika dan analitik data.
Cara menggunakan
Code Interpreter mendukung tiga metode pemanggilan, masing-masing dengan parameter yang berbeda:
OpenAI-compatible - Responses API
Untuk mengaktifkan Code Interpreter, tambahkan tool code_interpreter ke parameter tools.
Untuk hasil terbaik, aktifkan tool
code_interpreter,web_search, danweb_extractorsecara bersamaan.
# Impor dependensi dan buat klien...
response = client.responses.create(
model="qwen3.8-max",
input="Berapa 123 pangkat 21?",
tools=[
{"type": "code_interpreter"},
{"type": "web_search"},
{"type": "web_extractor"},
],
extra_body={
"enable_thinking": True
}
)
print(response.output_text)
OpenAI-compatible - Chat Completions API
Untuk mengaktifkan Code Interpreter, sertakan enable_code_interpreter: true dalam permintaan API.
# Impor dependensi dan buat klien...
completion = client.chat.completions.create(
# Gunakan model yang mendukung Code Interpreter
model="qwen3-max",
messages=[{"role": "user", "content": "Berapa 123 pangkat 21?"}],
# Karena enable_code_interpreter bukan parameter standar OpenAI, Anda harus melewatkan melalui extra_body saat menggunakan Python SDK. Saat menggunakan Node.js SDK, lewatkan sebagai parameter tingkat atas.
extra_body={
"enable_code_interpreter": True,
# Fitur Code Interpreter hanya mendukung pemanggilan dalam mode thinking
"enable_thinking": True,
},
# Hanya pemanggilan keluaran streaming yang didukung
stream=True
)
Protokol kompatibel OpenAI tidak mengembalikan detail eksekusi kode.
DashScope
Untuk mengaktifkan Code Interpreter, atur enable_code_interpreter menjadi true dalam permintaan API.
# Impor dependensi...
response = dashscope.MultiModalConversation.call(
# Jika variabel lingkungan belum dikonfigurasi, ganti baris berikut dengan: api_key="sk-xxx", menggunakan Kunci API Model Studio Anda.
api_key=os.getenv("DASHSCOPE_API_KEY"),
model="qwen3.5-plus",
messages=[{"role": "user", "content": "Berapa 123 pangkat 21?"}],
# Aktifkan Code Interpreter menggunakan parameter enable_code_interpreter
enable_code_interpreter=True,
# Fitur Code Interpreter hanya mendukung mode thinking
enable_thinking=True,
result_format="message",
# Hanya pemanggilan keluaran streaming yang didukung
stream=True
)
Kode yang dieksekusi dikembalikan dalam bidang tool_info.
Setelah Code Interpreter diaktifkan, model memproses permintaan dalam tahapan berikut:
- Thinking: Model menganalisis permintaan pengguna dan menghasilkan ide serta langkah-langkah untuk menyelesaikan masalah.
- Code execution: Model menghasilkan dan mengeksekusi kode Python.
- Result integration: Model menerima hasil eksekusi kode dan merencanakan langkah selanjutnya.
- Response: Model menghasilkan tanggapan dalam bahasa alami.
Langkah 2 dan 3 dapat berulang beberapa kali.
Bidang yang dikembalikan oleh API berbeda-beda:
- Responses API: Konten thinking dikembalikan dalam objek dengan
type="reasoning"pada output. Eksekusi kode dikembalikan dengantype="code_interpreter_call". Tanggapan dikembalikan dengantype="message". - Chat Completions API / DashScope: Konten thinking dikembalikan dalam bidang
reasoning_content. Tanggapan dikembalikan dalam bidangcontent. DashScope juga mendukung pengembalian konten kode dalam bidangtool_info.
Cakupan
Model yang direkomendasikan
Responses API
Qwen-Max: seri Qwen3.8-Max, seri Qwen3.7-Max
Qwen-Plus: seri Qwen3.7-Plus, seri Qwen3.6-Plus, seri Qwen3.5-Plus
DeepSeek: deepseek-v4-flash, deepseek-v4-flash-0731, deepseek-v4-pro
GLM: glm-5.2
seri open source Qwen3.8
Chat Completions API / DashScope
- Qwen-Max (mode thinking): seri Qwen3-Max
- Qwen-Plus: seri Qwen3.5-Plus
Model lainnya
Model-model ini juga mendukung Code Interpreter tetapi mungkin tidak berkinerja sebaik model yang direkomendasikan. Hanya didukung melalui Responses API.
- Qwen-Flash: seri Qwen3.7-Flash, seri Qwen3.6-Flash, seri Qwen3.5-Flash
- seri open-source Qwen3.6 (kecuali qwen3.6-27b)
- seri open source Qwen3.5
Memulai
Contoh berikut menunjukkan cara Code Interpreter menyelesaikan masalah matematika.
OpenAI-compatible - Responses API
Untuk hasil terbaik, aktifkan tool
code_interpreter,web_search, danweb_extractorsecara bersamaan.
import os
from openai import OpenAI
client = OpenAI(
# Jika variabel lingkungan tidak dikonfigurasi, ganti baris berikutnya dengan: api_key="sk-xxx", menggunakan kunci API Model Studio Anda.
api_key=os.getenv("DASHSCOPE_API_KEY"),
# URL berikut adalah untuk Wilayah Singapura. Ganti {WorkspaceId} dengan ID ruang kerja Anda. URL bervariasi menurut wilayah.
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
)
response = client.responses.create(
model="qwen3.8-max",
input="12 to the power of 3",
tools=[
{
"type": "code_interpreter"
},
{
"type": "web_search"
},
{
"type": "web_extractor"
}
],
extra_body = {
"enable_thinking": True
}
)
# Hapus tanda komentar pada baris berikut untuk melihat output proses perantara
# print(response.output)
print("="*20+"Konten Tanggapan"+"="*20)
print(response.output_text)
print("="*20+"Konsumsi Token dan Panggilan Alat"+"="*20)
print(response.usage)
import OpenAI from "openai";
import process from 'process';
const openai = new OpenAI({
// Jika variabel lingkungan belum dikonfigurasi, ganti baris berikut dengan: apiKey: "sk-xxx", menggunakan Kunci API Model Studio Anda.
apiKey: process.env.DASHSCOPE_API_KEY,
// URL berikut untuk wilayah Singapura. Ganti {WorkspaceId} dengan ID ruang kerja aktual Anda. URL berbeda-beda tergantung wilayah.
baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
});
async function main() {
const response = await openai.responses.create({
model: "qwen3.8-max",
input: "Hitung 12 pangkat 3",
tools: [
{ type: "code_interpreter" },
{ type: "web_search" },
{ type: "web_extractor" }
],
enable_thinking: true
});
console.log("====================Konten Tanggapan====================");
console.log(response.output_text);
// Cetak jumlah pemanggilan tool
console.log("====================Konsumsi Token dan Pemanggilan Tool====================");
if (response.usage && response.usage.x_tools) {
console.log(`Jumlah eksekusi Code Interpreter: ${response.usage.x_tools.code_interpreter?.count || 0}`);
}
// Hapus komentar baris berikut untuk melihat output proses antara
// console.log(JSON.stringify(response.output[0], null, 2));
}
main();
# URL berikut untuk wilayah Singapura. Ganti {WorkspaceId} dengan ID ruang kerja aktual Anda. URL berbeda-beda tergantung wilayah.
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/responses \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen3.8-max",
"input": "Hitung 12 pangkat 3",
"tools": [
{"type": "code_interpreter"},
{"type": "web_search"},
{"type": "web_extractor"}
],
"enable_thinking": true
}'
Contoh tanggapan
====================Konten Tanggapan====================
12 pangkat 3 adalah **1728**.
Proses perhitungan:
12³ = 12 × 12 × 12 = 144 × 12 = 1728
====================Konsumsi Token dan Pemanggilan Tool====================
ResponseUsage(input_tokens=1160, input_tokens_details=InputTokensDetails(cached_tokens=0), output_tokens=195, output_tokens_details=OutputTokensDetails(reasoning_tokens=105), total_tokens=1355, x_tools={'code_interpreter': {'count': 1}})
OpenAI-compatible - Chat Completions API
Python
from openai import OpenAI
import os
# Inisialisasi klien OpenAI
client = OpenAI(
# Jika variabel lingkungan tidak dikonfigurasi, ganti dengan kunci API Alibaba Cloud Model Studio Anda: api_key="sk-xxx"
api_key=os.getenv("DASHSCOPE_API_KEY"),
# URL berikut adalah untuk wilayah China (Beijing). Ganti {WorkspaceId} dengan ID ruang kerja Anda yang sebenarnya. URL bervariasi menurut wilayah.
base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)
messages = [{"role": "user", "content": "What is 123 to the power of 21?"}]
completion = client.chat.completions.create(
model="qwen3.5-plus",
messages=messages,
extra_body={"enable_thinking": True, "enable_code_interpreter": True},
stream=True,
stream_options={
"include_usage": True
},
)
reasoning_content = "" # Proses berpikir lengkap
answer_content = "" # Tanggapan lengkap
is_answering = False # Penanda untuk memeriksa apakah fase tanggapan telah dimulai
print("\n" + "=" * 20 + "Thinking Process" + "=" * 20 + "\n")
for chunk in completion:
if not chunk.choices:
print("\nUsage:")
print(chunk.usage)
continue
delta = chunk.choices[0].delta
# Kumpulkan hanya konten pemikiran
if hasattr(delta, "reasoning_content") and delta.reasoning_content is not None:
if not is_answering:
print(delta.reasoning_content, end="", flush=True)
reasoning_content += delta.reasoning_content
# Saat konten diterima, mulai tanggapan
if hasattr(delta, "content") and delta.content:
if not is_answering:
print("\n" + "=" * 20 + "Complete Response" + "=" * 20 + "\n")
is_answering = True
print(delta.content, end="", flush=True)
answer_content += delta.content
Contoh tanggapan
====================Proses Thinking====================
Pengguna menanyakan nilai 123 pangkat 21. Ini adalah masalah perhitungan matematika. Saya perlu menghitung 123^21.
Saya dapat menggunakan kalkulator kode untuk menghitung nilai ini. Saya perlu memanggil fungsi code_interpreter dan memberikan kode Python untuk menghitung 123**21.
Mari saya susun pemanggilan fungsi ini.
Pengguna bertanya tentang 123 pangkat 21, dan saya telah menghitung hasilnya menggunakan kode Python. Perhitungan menunjukkan bahwa 123 pangkat 21 sama dengan 77269364466549865653073473388030061522211723. Ini adalah angka yang sangat besar, dan saya harus memberikannya secara langsung.
====================Tanggapan Lengkap====================
123 pangkat 21 adalah: 77269364466549865653073473388030061522211723
Usage:
CompletionUsage(completion_tokens=245, prompt_tokens=719, total_tokens=964, completion_tokens_details=CompletionTokensDetails(accepted_prediction_tokens=None, audio_tokens=None, reasoning_tokens=153, rejected_prediction_tokens=None), prompt_tokens_details=None)
Node.js
import OpenAI from "openai";
import process from 'process';
// Inisialisasi klien OpenAI
const openai = new OpenAI({
apiKey: process.env.DASHSCOPE_API_KEY, // Baca dari variabel lingkungan
// URL berikut untuk wilayah China (Beijing). Ganti {WorkspaceId} dengan ID ruang kerja aktual Anda. URL berbeda-beda tergantung wilayah.
baseURL: 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1'
});
let reasoningContent = '';
let answerContent = '';
let isAnswering = false;
async function main() {
try {
const messages = [{ role: 'user', content: 'Berapa 123 pangkat 21?' }];
const stream = await openai.chat.completions.create({
model: 'qwen3.5-plus',
messages,
stream: true,
enable_thinking: true,
enable_code_interpreter: true
});
console.log('\n' + '='.repeat(20) + 'Proses Thinking' + '='.repeat(20) + '\n');
for await (const chunk of stream) {
if (!chunk.choices?.length) {
console.log('\nUsage:');
console.log(chunk.usage);
continue;
}
const delta = chunk.choices[0].delta;
// Kumpulkan hanya konten thinking
if (delta.reasoning_content !== undefined && delta.reasoning_content !== null) {
if (!isAnswering) {
process.stdout.write(delta.reasoning_content);
}
reasoningContent += delta.reasoning_content;
}
// Saat konten diterima, mulai tanggapan
if (delta.content !== undefined && delta.content) {
if (!isAnswering) {
console.log('\n' + '='.repeat(20) + 'Tanggapan Lengkap' + '='.repeat(20) + '\n');
isAnswering = true;
}
process.stdout.write(delta.content);
answerContent += delta.content;
}
}
} catch (error) {
console.error('Error:', error);
}
}
main();
Contoh tanggapan
====================Proses Thinking====================
Pengguna menanyakan nilai 123 pangkat 21. Ini adalah perhitungan matematika yang dapat saya lakukan menggunakan interpreter kode Python. Saya akan menggunakan operator eksponensial ** untuk menghitung ini.
Mari saya tulis kode untuk menghitung 123**21.Perhitungan telah berhasil diselesaikan. Hasil dari 123 pangkat 21 adalah angka yang sangat besar: 77269364466549865653073473388030061522211723.
Saya harus menyajikan hasil ini dengan jelas kepada pengguna.
====================Tanggapan Lengkap====================
123 pangkat 21 adalah: 77269364466549865653073473388030061522211723
curl
# URL berikut untuk wilayah China (Beijing). Ganti {WorkspaceId} dengan ID ruang kerja aktual Anda. URL berbeda-beda tergantung wilayah.
curl -X POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen3.5-plus",
"messages": [
{
"role": "user",
"content": "Berapa 123 pangkat 21?"
}
],
"enable_code_interpreter": true,
"enable_thinking": true,
"stream": true
}'
Contoh tanggapan
data: {"choices":[{"delta":{"content":null,"role":"assistant","reasoning_content":""},"index":0,"logprobs":null,"finish_reason":null}],"object":"chat.completion.chunk","usage":null,"created":1761899724,"system_fingerprint":null,"model":"qwen3.8-max","id":"chatcmpl-2f96ef0b-5924-4dfc-b768-4d53ec538b4e"}
data: {"choices":[{"finish_reason":null,"logprobs":null,"delta":{"content":null,"reasoning_content":"The user"},"index":0}],"object":"chat.completion.chunk","usage":null,"created":1761899724,"system_fingerprint":null,"model":"qwen3.8-max","id":"chatcmpl-2f96ef0b-5924-4dfc-b768-4d53ec538b4e"}
data: {"choices":[{"delta":{"content":null,"reasoning_content":" is asking"},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1761899724,"system_fingerprint":null,"model":"qwen3.8-max","id":"chatcmpl-2f96ef0b-5924-4dfc-b768-4d53ec538b4e"}
data: {"choices":[{"delta":{"content":null,"reasoning_content":" for"},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1761899724,"system_fingerprint":null,"model":"qwen3.8-max","id":"chatcmpl-2f96ef0b-5924-4dfc-b768-4d53ec538b4e"}
...
data: {"choices":[{"delta":{"content":"is a very large number, with a total","reasoning_content":null},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1761899724,"system_fingerprint":null,"model":"qwen3.8-max","id":"chatcmpl-2f96ef0b-5924-4dfc-b768-4d53ec538b4e"}
data: {"choices":[{"delta":{"content":"of 43 digits","reasoning_content":null},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1761899724,"system_fingerprint":null,"model":"qwen3.8-max","id":"chatcmpl-2f96ef0b-5924-4dfc-b768-4d53ec538b4e"}
data: {"choices":[{"delta":{"content":".","reasoning_content":null},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1761899724,"system_fingerprint":null,"model":"qwen3.8-max","id":"chatcmpl-2f96ef0b-5924-4dfc-b768-4d53ec538b4e"}
data: {"choices":[{"finish_reason":"stop","delta":{"content":"","reasoning_content":null},"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1761899724,"system_fingerprint":null,"model":"qwen3.8-max","id":"chatcmpl-2f96ef0b-5924-4dfc-b768-4d53ec538b4e"}
data: [DONE]
DashScope
Java SDK tidak didukung.
Python
import os
import dashscope
// Wilayah China (Beijing). Ganti {WorkspaceId} dengan ID Ruang Kerja aktual Anda. URL berbeda-beda tergantung wilayah.
dashscope.base_http_api_url = 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1'
messages = [
{"role": "user", "content": "Berapa 123 pangkat 21?"},
]
response = dashscope.MultiModalConversation.call(
// Jika variabel lingkungan belum dikonfigurasi, ganti baris berikut dengan: api_key="sk-xxx", menggunakan Kunci API Model Studio Anda.
api_key=os.getenv("DASHSCOPE_API_KEY"),
model="qwen3.5-plus",
messages=messages,
enable_code_interpreter=True,
enable_thinking=True,
result_format="message",
// Hanya keluaran streaming yang didukung
stream=True
)
for chunk in response:
output = chunk["output"]
print(output)
Contoh tanggapan
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "", "reasoning_content": "The"}}]}
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "", "reasoning_content": " user is asking"}}]}
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "", "reasoning_content": " me"}}]}
...
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "", "reasoning_content": " I'll write a"}}]}
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "", "reasoning_content": " simple Python program to calculate"}}]}
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "", "reasoning_content": ""}}]}
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "", "reasoning_content": ""}}]}
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "", "reasoning_content": ""}}]}
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "", "reasoning_content": ""}}]}
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "", "reasoning_content": ""}}]}
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "", "reasoning_content": ""}}], "tool_info": [{"code_interpreter": {"code": "123**21"}, "type": "code_interpreter"}]}
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "", "reasoning_content": "The"}}], "tool_info": [{"code_interpreter": {"code": "123**21"}, "type": "code_interpreter"}]}
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "", "reasoning_content": " user"}}], "tool_info": [{"code_interpreter": {"code": "123**21"}, "type": "code_interpreter"}]}
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "", "reasoning_content": " asked"}}], "tool_info": [{"code_interpreter": {"code": "123**21"}, "type": "code_interpreter"}]}
...
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "", "reasoning_content": " I should present this result"}}], "tool_info": [{"code_interpreter": {"code": "123**21"}, "type": "code_interpreter"}]}
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "", "reasoning_content": " to the user in"}}], "tool_info": [{"code_interpreter": {"code": "123**21"}, "type": "code_interpreter"}]}
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "", "reasoning_content": " a clear format."}}], "tool_info": [{"code_interpreter": {"code": "123**21"}, "type": "code_interpreter"}]}
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "123 to the power of ", "reasoning_content": ""}}], "tool_info": [{"code_interpreter": {"code": "123**21"}, "type": "code_interpreter"}]}
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "21 is:\n\n", "reasoning_content": ""}}], "tool_info": [{"code_interpreter": {"code": "123**21"}, "type": "code_interpreter"}]}
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "772693", "reasoning_content": ""}}], "tool_info": [{"code_interpreter": {"code": "123**21"}, "type": "code_interpreter"}]}
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "644665", "reasoning_content": ""}}], "tool_info": [{"code_interpreter": {"code": "123**21"}, "type": "code_interpreter"}]}
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "498656", "reasoning_content": ""}}], "tool_info": [{"code_interpreter": {"code": "123**21"}, "type": "code_interpreter"}]}
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "530734", "reasoning_content": ""}}], "tool_info": [{"code_interpreter": {"code": "123**21"}, "type": "code_interpreter"}]}
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "733880", "reasoning_content": ""}}], "tool_info": [{"code_interpreter": {"code": "123**21"}, "type": "code_interpreter"}]}
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "300615", "reasoning_content": ""}}], "tool_info": [{"code_interpreter": {"code": "123**21"}, "type": "code_interpreter"}]}
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "222117", "reasoning_content": ""}}], "tool_info": [{"code_interpreter": {"code": "123**21"}, "type": "code_interpreter"}]}
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "23", "reasoning_content": ""}}], "tool_info": [{"code_interpreter": {"code": "123**21"}, "type": "code_interpreter"}]}
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "stop", "message": {"role": "assistant", "content": "", "reasoning_content": ""}}], "tool_info": [{"code_interpreter": {"code": "123**21"}, "type": "code_interpreter"}]}
curl
curl -X POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-H "X-DashScope-SSE: enable" \
-d '{
"model": "qwen3.5-plus",
"input":{
"messages":[
{
"role": "user",
"content": "Berapa 123 pangkat 21?"
}
]
},
"parameters": {
"enable_code_interpreter": true,
"enable_thinking": true,
"result_format": "message"
}
}'
Contoh tanggapan
Teks
<...text content...>adalah komentar penjelasan dan bukan bagian dari tanggapan API aktual. Komentar ini digunakan untuk mengidentifikasi tahapan pemrosesan yang berbeda.
id:1
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":"The","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":290,"output_tokens":3,"input_tokens":287,"output_tokens_details":{"reasoning_tokens":1}},"request_id":"a1959ad1-2637-4672-a21f-4d351371d254"}
id:2
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":" user is asking","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":293,"output_tokens":6,"input_tokens":287,"output_tokens_details":{"reasoning_tokens":4}},"request_id":"a1959ad1-2637-4672-a21f-4d351371d254"}
...Tahap thinking...
id:21
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":"","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":388,"output_tokens":101,"input_tokens":287,"output_tokens_details":{"reasoning_tokens":68}},"request_id":"a1959ad1-2637-4672-a21f-4d351371d254"}
...Thinking berakhir, memulai Code Interpreter...
id:22
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":"","role":"assistant"},"finish_reason":"null"}],"tool_info":[{"code_interpreter":{"code":"123**21"},"type":"code_interpreter"}]},"usage":{"total_tokens":388,"output_tokens":101,"input_tokens":287,"output_tokens_details":{"reasoning_tokens":68},"plugins":{"code_interpreter":{"count":1}}},"request_id":"a1959ad1-2637-4672-a21f-4d351371d254"}
...Thinking dimulai setelah menjalankan Code Interpreter...
id:23
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":"The","role":"assistant"},"finish_reason":"null"}],"tool_info":[{"code_interpreter":{"code":"123**21"},"type":"code_interpreter"}]},"usage":{"total_tokens":838,"output_tokens":104,"input_tokens":734,"output_tokens_details":{"reasoning_tokens":69},"plugins":{"code_interpreter":{"count":1}}},"request_id":"a1959ad1-2637-4672-a21f-4d351371d254"}
id:24
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":" user","role":"assistant"},"finish_reason":"null"}],"tool_info":[{"code_interpreter":{"code":"123**21"},"type":"code_interpreter"}]},"usage":{"total_tokens":839,"output_tokens":105,"input_tokens":734,"output_tokens_details":{"reasoning_tokens":70},"plugins":{"code_interpreter":{"count":1}}},"request_id":"a1959ad1-2637-4672-a21f-4d351371d254"}
...Tahap thinking...
id:43
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":" a clear format.","role":"assistant"},"finish_reason":"null"}],"tool_info":[{"code_interpreter":{"code":"123**21"},"type":"code_interpreter"}]},"usage":{"total_tokens":942,"output_tokens":208,"input_tokens":734,"output_tokens_details":{"reasoning_tokens":171},"plugins":{"code_interpreter":{"count":1}}},"request_id":"a1959ad1-2637-4672-a21f-4d351371d254"}
...Thinking berakhir, memulai tanggapan...
id:44
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"123 to the power of","reasoning_content":"","role":"assistant"},"finish_reason":"null"}],"tool_info":[{"code_interpreter":{"code":"123**21"},"type":"code_interpreter"}]},"usage":{"total_tokens":947,"output_tokens":213,"input_tokens":734,"output_tokens_details":{"reasoning_tokens":171},"plugins":{"code_interpreter":{"count":1}}},"request_id":"a1959ad1-2637-4672-a21f-4d351371d254"}
...
id:53
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"23","reasoning_content":"","role":"assistant"},"finish_reason":"null"}],"tool_info":[{"code_interpreter":{"code":"123**21"},"type":"code_interpreter"}]},"usage":{"total_tokens":997,"output_tokens":263,"input_tokens":734,"output_tokens_details":{"reasoning_tokens":171},"plugins":{"code_interpreter":{"count":1}}},"request_id":"a1959ad1-2637-4672-a21f-4d351371d254"}
id:54
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":"","role":"assistant"},"finish_reason":"stop"}],"tool_info":[{"code_interpreter":{"code":"123**21"},"type":"code_interpreter"}]},"usage":{"total_tokens":997,"output_tokens":263,"input_tokens":734,"output_tokens_details":{"reasoning_tokens":171},"plugins":{"code_interpreter":{"count":1}}},"request_id":"a1959ad1-2637-4672-a21f-4d351371d254"}
Mengurai respons
OpenAI-compatible - Responses API
Contoh berikut menggunakan OpenAI Python SDK untuk menunjukkan cara mengurai respons streaming.
import os
from openai import OpenAI
client = OpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"),
# URL berikut digunakan untuk wilayah Singapura. Ganti {WorkspaceId} dengan ID ruang kerja Anda yang sebenarnya. URL bervariasi tergantung wilayah.
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
)
response = client.responses.create(
model="qwen3.8-max",
input="12 to the power of 3",
tools=[
{"type": "code_interpreter"}
],
extra_body={
"enable_thinking": True
},
stream=True
)
def print_section(title):
print(f"\n{'=' * 20}{title}{'=' * 20}")
current_section = None
final_response = None
for event in response:
# Output inkremental dari proses berpikir
if event.type == "response.reasoning_summary_text.delta":
if current_section != "reasoning":
print_section("Thinking Process")
current_section = "reasoning"
print(event.delta, end="", flush=True)
# Pemanggilan Code Interpreter selesai
elif event.type == "response.output_item.done" and hasattr(event.item, "code"):
print_section("Code Execution")
print(f"Code:\n{event.item.code}")
if event.item.outputs:
print(f"Result: {event.item.outputs[0].logs}")
current_section = "code"
# Output inkremental dari respons akhir
elif event.type == "response.output_text.delta":
if current_section != "answer":
print_section("Complete Response")
current_section = "answer"
print(event.delta, end="", flush=True)
# Respons selesai, simpan hasil akhir untuk mendapatkan penggunaan
elif event.type == "response.completed":
final_response = event.response
# Tampilkan konsumsi token dan jumlah pemanggilan tool
if final_response and final_response.usage:
print_section("Token Consumption and Tool Calls")
usage = final_response.usage
print(f"Input Tokens: {usage.input_tokens}")
print(f"Output Tokens: {usage.output_tokens}")
print(f"Thinking Tokens: {usage.output_tokens_details.reasoning_tokens}")
print(f"Code Interpreter calls: {usage.x_tools.get('code_interpreter', {}).get('count', 0)}")
DashScope
Contoh berikut menggunakan DashScope Python SDK untuk melakukan dua perhitungan dalam satu permintaan dan mengurai kode serta jumlah pemanggilan yang dikembalikan.
API OpenAI Chat Completions tidak mengembalikan data selama tahap code execution, sehingga tidak ada respons yang dikirim antara tahap thinking dan result integration. Kedua tahap tersebut mengembalikan konten melalui bidang
reasoning_content, sehingga Anda dapat memprosesnya bersama sebagai tahap thinking. Untuk contoh penguraian respons, lihat kode pada bagian Getting started.
import os
from dashscope import MultiModalConversation
# Wilayah China (Beijing). Ganti {WorkspaceId} dengan ID Workspace Anda yang sebenarnya. URL bervariasi tergantung wilayah.
dashscope.base_http_api_url = 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1'
messages = [{"role": "user", "content": "Run Code Interpreter twice: first, calculate the value of 123 to the power of 23. Second, divide the result by 5."}]
response = MultiModalConversation.call(
api_key=os.getenv("DASHSCOPE_API_KEY"),
model="qwen3.5-plus",
messages=messages,
result_format="message",
enable_thinking=True,
enable_code_interpreter=True,
stream=True,
incremental_output=True,
)
# Bendera status: lacak apakah info tool sudah dicetak, apakah fase menjawab telah dimulai, dan apakah sedang dalam bagian reasoning
is_answering = False
in_reasoning_section = False
cur_tools = []
# Cetak bagian dengan judul
def print_section(title):
print(f"\n{'=' * 20}{title}{'=' * 20}")
# Awalnya cetak judul "Thinking Process"
print_section("Thinking Process")
in_reasoning_section = True
# Proses setiap blok yang dikembalikan oleh model dalam aliran
for chunk in response:
try:
# Ekstrak bidang kunci dari respons: konten, teks reasoning, info pemanggilan tool
choice = chunk.output.choices[0]
msg = choice.message
content = msg.get("content", "") # Konten jawaban akhir
reasoning = msg.get("reasoning_content", "") # Teks proses reasoning
tools = chunk.output.get("tool_info", None) # Informasi pemanggilan tool
except (IndexError, AttributeError, KeyError):
# Lewati blok dengan struktur tidak normal
continue
# Jika tidak ada konten valid, lewati blok saat ini
if not content and not reasoning and tools is None:
continue
# Tampilkan proses reasoning
if reasoning and not is_answering:
if not in_reasoning_section:
print_section("Thinking Process")
in_reasoning_section = True
print(reasoning, end="", flush=True)
if tools is not None and tools != cur_tools:
print_section("Tool Information")
print(tools)
in_reasoning_section = False
cur_tools = tools
# Tampilkan konten jawaban akhir
if content:
if not is_answering:
print_section("Complete Response")
is_answering = True
in_reasoning_section = False
print(content, end="", flush=True)
# Cetak jumlah pemanggilan Code Interpreter
print_section("Code Interpreter Runs")
print(chunk.usage.plugins)
Contoh respons
====================Thinking Process====================
The user wants to run Code Interpreter twice:
1. First run: Calculate the value of 123 to the power of 23.
2. Second run: Divide the result of the first run by 5.
I need to first call Code Interpreter to calculate 123**23, then use this result to call Code Interpreter again to divide by 5.
Let me do the first calculation.
====================Tool Information====================
[{'code_interpreter': {'code': '123**23'}, 'type': 'code_interpreter'}]
====================Thinking Process====================
The first calculation yielded the value of 123 to the power of 23: 1169008215014432917465348578887506800769541157267
Now for the second run, I need to divide this result by 5. I need to use this exact value for the division.
====================Tool Information====================
[{'code_interpreter': {'code': '123**23'}, 'type': 'code_interpreter'}, {'code_interpreter': {'code': ''}, 'type': 'code_interpreter'}]
====================Tool Information====================
[{'code_interpreter': {'code': '123**23'}, 'type': 'code_interpreter'}, {'code_interpreter': {'code': '1169008215014432917465348578887506800769541157267 / 5'}, 'type': 'code_interpreter'}]
====================Thinking Process====================
The user requested to run Code Interpreter twice:
1. First, calculate 123 to the power of 23. The result is: 1169008215014432917465348578887506800769541157267
2. Second, divide this result by 5. The result is: 2.338016430028866e+47
Now I need to report these two results to the user.
====================Complete Response====================
First run result: 123 to the power of 23 = 1169008215014432917465348578887506800769541157267
Second run result: The above result divided by 5 = 2.338016430028866e+47
====================Code Interpreter Runs====================
{'code_interpreter': {'count': 2}}
Catatan
-
Code Interpreter dan Function calling bersifat saling eksklusif.
Mengaktifkan keduanya dalam satu permintaan yang sama akan menyebabkan error.
-
Ketika Code Interpreter diaktifkan, satu permintaan dapat memicu multiple inferensi model. Bidang
usagemerangkum total konsumsi token untuk semua panggilan dalam permintaan tersebut.
Billing
Code Interpreter gratis untuk waktu terbatas tetapi meningkatkan konsumsi token.