Aktifkan interpreter kode Python bawaan saat memanggil model untuk memungkinkan model menulis dan menjalankan kode Python dalam lingkungan sandbox, sehingga mampu menyelesaikan masalah kompleks seperti perhitungan matematis dan analisis data.
Penggunaan
Interpreter kode mendukung tiga metode pemanggilan, masing-masing dengan parameter pengaktifan yang berbeda:
OpenAI compatible - Responses API
Aktifkan interpreter kode melalui parameter tools dengan menambahkan tool code_interpreter.
Untuk hasil optimal, kami merekomendasikan mengaktifkan toolcode_interpreter,web_search, danweb_extractorsecara bersamaan.
# Impor dependensi dan buat client...
response = client.responses.create(
model="qwen3-max-2026-01-23",
input="What is 123 to the power of 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
Kirimkan enable_code_interpreter: true dalam permintaan API Anda untuk mengaktifkan interpreter kode.
# Impor dependensi dan buat client...
completion = client.chat.completions.create(
# Gunakan model yang mendukung code interpreter
model="qwen3-max-2026-01-23",
messages=[{"role": "user", "content": "What is 123 to the power of 21?"}],
# Karena enable_code_interpreter bukan parameter standar OpenAI, kirimkan melalui extra_body saat menggunakan Python SDK (kirimkan sebagai parameter tingkat atas saat menggunakan Node.js SDK)
extra_body={
"enable_code_interpreter": True,
# Code interpreter memerlukan thinking mode
"enable_thinking": True,
},
# Hanya untuk streaming output
stream=True
)Protokol kompatibel OpenAI tidak mengembalikan kode yang dieksekusi oleh interpreter.
DashScope
Atur enable_code_interpreter ke true dalam permintaan API Anda untuk mengaktifkan interpreter kode.
# Impor dependensi...
response = dashscope.Generation.call(
# Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan kunci API Model Studio Anda: api_key="sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
model="qwen3-max-2026-01-23",
messages=[{"role": "user", "content": "What is 123 to the power of 21?"}],
# Aktifkan code interpreter
enable_code_interpreter=True,
# Code interpreter memerlukan thinking mode
enable_thinking=True,
result_format="message",
# Hanya untuk streaming output
stream=True
)Kode yang dieksekusi oleh interpreter dikembalikan dalam bidang tool_info.
Setelah diaktifkan, model memproses permintaan dalam beberapa tahap:
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 dan merencanakan langkah selanjutnya.
Response: Model menghasilkan respons dalam bahasa alami.
Tahap 2 dan 3 dapat dieksekusi beberapa kali dalam satu loop.
API yang berbeda mengembalikan bidang yang berbeda:
Responses API: Konten thinking dikembalikan dalam objek output dengan type="reasoning", eksekusi kode dalam type="code_interpreter_call", dan respons dalam type="message".
Chat Completions API / DashScope: Konten thinking dikembalikan dalam bidang reasoning_content, dan respons dalam bidang content. DashScope juga mendukung bidang tool_info untuk konten kode.
Ketersediaan
Internasional
qwen3-max dan qwen3-max-2026-01-23 dalam thinking mode
China
qwen3-max, qwen3-max-2026-01-23, dan qwen3-max-preview dalam thinking mode
Responses API saat ini tidak didukung.
Memulai
Contoh berikut menunjukkan bagaimana interpreter kode secara efisien menyelesaikan masalah perhitungan matematis.
OpenAI compatible - Responses API
Hanya didukung untuk qwen3-coder-next dan qwen3-max-2026-01-23 dalam thinking mode.
Untuk hasil optimal, kami merekomendasikan mengaktifkan toolcode_interpreter,web_search, danweb_extractorsecara bersamaan.
import os
from openai import OpenAI
client = OpenAI(
# Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan kunci API Model Studio Anda: api_key="sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
base_url="https://dashscope-intl.aliyuncs.com/api/v2/apps/protocols/compatible-mode/v1"
)
response = client.responses.create(
model="qwen3-max-2026-01-23",
input="What is 12 to the power of 3?",
tools=[
{
"type": "code_interpreter"
},
{
"type": "web_search"
},
{
"type": "web_extractor"
}
],
extra_body = {
"enable_thinking": True
}
)
# Hapus komentar pada baris berikut untuk melihat output antara
# print(response.output)
print("="*20+"Response"+"="*20)
print(response.output_text)
print("="*20+"Token usage and tool calls"+"="*20)
print(response.usage)import OpenAI from "openai";
import process from 'process';
const openai = new OpenAI({
// Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan kunci API Model Studio Anda: apiKey: "sk-xxx",
apiKey: process.env.DASHSCOPE_API_KEY,
baseURL: "https://dashscope-intl.aliyuncs.com/api/v2/apps/protocols/compatible-mode/v1"
});
async function main() {
const response = await openai.responses.create({
model: "qwen3-max-2026-01-23",
input: "What is 12 to the power of 3?",
tools: [
{ type: "code_interpreter" },
{ type: "web_search" },
{ type: "web_extractor" }
],
enable_thinking: true
});
console.log("====================Response====================");
console.log(response.output_text);
// Cetak jumlah pemanggilan tool
console.log("====================Token usage and tool calls====================");
if (response.usage && response.usage.x_tools) {
console.log(`Code interpreter runs: ${response.usage.x_tools.code_interpreter?.count || 0}`);
}
// Hapus komentar pada baris berikut untuk melihat output antara
// console.log(JSON.stringify(response.output[0], null, 2));
}
main();curl -X POST https://dashscope-intl.aliyuncs.com/api/v2/apps/protocols/compatible-mode/v1/responses \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen3-max-2026-01-23",
"input": "What is 12 to the power of 3?",
"tools": [
{"type": "code_interpreter"},
{"type": "web_search"},
{"type": "web_extractor"}
],
"enable_thinking": true
}'Contoh respons
====================Response====================
12 to the power of 3 equals **1728**.
Calculation:
12³ = 12 × 12 × 12 = 144 × 12 = 1728
====================Token usage and tool calls====================
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 client OpenAI
client = OpenAI(
# Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan kunci API Model Studio Anda: api_key="sk-xxx"
api_key=os.getenv("DASHSCOPE_API_KEY"),
# Untuk wilayah internasional, gunakan "https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
)
messages = [{"role": "user", "content": "What is 123 to the power of 21?"}]
completion = client.chat.completions.create(
model="qwen3-max-2026-01-23",
messages=messages,
extra_body={"enable_thinking": True, "enable_code_interpreter": True},
stream=True,
stream_options={
"include_usage": True
},
)
reasoning_content = "" # Proses thinking lengkap
answer_content = "" # Respons lengkap
is_answering = False # Penanda untuk memeriksa apakah tahap respons 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 thinking
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 respons
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.contentContoh tanggapan
====================Thinking process====================
The user is asking for 123 to the power of 21. This is a mathematical calculation problem. I need to calculate 123^21.
I can use the code interpreter to calculate this value. I need to call the code_interpreter function and pass in the Python code to calculate 123**21.
Let me construct this function call.
The user asked for 123 to the power of 21, and I used Python code to calculate the result. The result shows that 123 to the power of 21 equals 77269364466549865653073473388030061522211723. This is a very large number. I should provide this directly
====================Complete response====================
123 to the power of 21 is: 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 client OpenAI
const openai = new OpenAI({
apiKey: process.env.DASHSCOPE_API_KEY, // Baca dari variabel lingkungan
// Untuk wilayah internasional, gunakan https://dashscope-intl.aliyuncs.com/compatible-mode/v1
baseURL: 'https://dashscope.aliyuncs.com/compatible-mode/v1'
});
let reasoningContent = '';
let answerContent = '';
let isAnswering = false;
async function main() {
try {
const messages = [{ role: 'user', content: 'What is 123 to the power of 21?' }];
const stream = await openai.chat.completions.create({
model: 'qwen3-max-2026-01-23',
messages,
stream: true,
enable_thinking: true,
enable_code_interpreter: true
});
console.log('\n' + '='.repeat(20) + 'Thinking process' + '='.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 respons
if (delta.content !== undefined && delta.content) {
if (!isAnswering) {
console.log('\n' + '='.repeat(20) + 'Complete response' + '='.repeat(20) + '\n');
isAnswering = true;
}
process.stdout.write(delta.content);
answerContent += delta.content;
}
}
} catch (error) {
console.error('Error:', error);
}
}
main();Contoh tanggapan
====================Thinking process====================
The user is asking for the value of 123 raised to the power of 21. This is a mathematical calculation that I can perform using Python's code interpreter. I'll use the exponentiation operator ** to calculate this.
Let me write the code to compute 123**21.The calculation has been completed successfully. The result of 123 raised to the power of 21 is a very large number: 77269364466549865653073473388030061522211723.
I should present this result clearly to the user.
====================Complete response====================
123 to the power of 21 is: 77269364466549865653073473388030061522211723curl
# Untuk wilayah internasional, gunakan https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions
curl -X POST https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen3-max-2026-01-23",
"messages": [
{
"role": "user",
"content": "What is 123 to the power of 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-max-2026-01-23","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-max-2026-01-23","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-max-2026-01-23","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-max-2026-01-23","id":"chatcmpl-2f96ef0b-5924-4dfc-b768-4d53ec538b4e"}
...
data: {"choices":[{"delta":{"content":"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-max-2026-01-23","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-max-2026-01-23","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-max-2026-01-23","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-max-2026-01-23","id":"chatcmpl-2f96ef0b-5924-4dfc-b768-4d53ec538b4e"}
data: [DONE]DashScope
SDK Java tidak didukung.
Python
import os
import dashscope
# Untuk wilayah internasional, hapus komentar pada baris berikut
# dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
messages = [
{"role": "user", "content": "What is 123 to the power of 21?"},
]
response = dashscope.Generation.call(
# Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan kunci API Model Studio Anda: api_key="sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
model="qwen3-max-2026-01-23",
messages=messages,
enable_code_interpreter=True,
enable_thinking=True,
result_format="message",
# Hanya untuk streaming output
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://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-H "X-DashScope-SSE: enable" \
-d '{
"model": "qwen3-max-2026-01-23",
"input":{
"messages":[
{
"role": "user",
"content": "What is 123 to the power of 21?"
}
]
},
"parameters": {
"enable_code_interpreter": true,
"enable_thinking": true,
"result_format": "message"
}
}'Contoh tanggapan
<...text content...> adalah komentar penjelas yang mengidentifikasi tahap pemrosesan dan bukan bagian dari respons API sebenarnya.
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 berpikir...
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"}
...Berpikir berakhir, interpreter kode dimulai...
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"}
...Berpikir dimulai setelah interpreter kode berjalan...
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 berpikir...
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"}
...Berpikir berakhir, tanggapan dimulai...
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"}Penguraian tanggapan
Contoh DashScope Python SDK berikut menunjukkan cara melakukan dua perhitungan dalam satu permintaan dan mengembalikan kode beserta jumlah total pemanggilan.
OpenAI Chat Completions API tidak mengembalikan data selama tahap code execution, sehingga terjadi jeda respons antara tahap thinking dan result integration. Karena kedua tahap tersebut mengembalikan konten melalui reasoning_content, keduanya dapat diproses bersama sebagai tahap thinking. Untuk contoh penguraian respons, lihat kode di Memulai.import os
from dashscope import Generation
# Untuk wilayah internasional, hapus komentar pada baris berikut
# dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
messages = [{"role": "user", "content": "Run the code interpreter twice: first calculate 123 to the power of 23, then divide that result by 5"}]
response = Generation.call(
api_key=os.getenv("DASHSCOPE_API_KEY"),
model="qwen3-max-2026-01-23",
messages=messages,
result_format="message",
enable_thinking=True,
enable_code_interpreter=True,
stream=True,
incremental_output=True,
)
# Penanda status: lacak apakah informasi tool telah dicetak, apakah sedang dalam tahap menjawab, dan apakah 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 chunk data yang dikembalikan oleh model dalam bentuk stream
for chunk in response:
try:
# Ekstrak bidang utama dari respons: konten, teks reasoning, informasi 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 chunk dengan struktur abnormal
continue
# Jika tidak ada konten valid, lewati chunk saat ini
if not content and not reasoning and tools is None:
continue
# Keluarkan 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
# Keluarkan 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 run count")
print(chunk.usage.plugins)Contoh tanggapan
====================Thinking process====================
The user wants to run the code interpreter twice:
1. First run: Calculate 123 to the power of 23
2. Second run: Divide the result by 5
I need to first call the code interpreter to calculate 123**23, then use that result to call the 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 returned the value of 123 to the power of 23: 1169008215014432917465348578887506800769541157267
Now for the second run, I need to divide this result by 5. I'll 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 running the code interpreter twice:
1. First, calculate 123 to the power of 23, result: 1169008215014432917465348578887506800769541157267
2. Second, divide this result by 5, which gives: 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 run count====================
{'code_interpreter': {'count': 2}}Catatan
Interpreter kode dan Function calling saling eksklusif dan tidak dapat diaktifkan secara bersamaan.
Mengaktifkan keduanya akan menghasilkan error.
Setelah mengaktifkan interpreter kode, satu permintaan memicu beberapa inferensi model. Bidang
usagemenggabungkan konsumsi token dari semua pemanggilan.
Penagihan
Mengaktifkan tool interpreter kode sementara gratis, tetapi meningkatkan konsumsi token.