Interpreter kode Python bawaan memungkinkan model untuk menulis dan menjalankan kode Python di dalam sandbox guna menyelesaikan masalah kompleks seperti perhitungan matematika dan analitik data.
Penggunaan
Sertakan enable_code_interpreter: true dalam permintaan API Anda.
Contoh berikut menunjukkan kode inti untuk pemanggilan API menggunakan SDK Python yang Kompatibel dengan OpenAI dan DashScope:
Kompatibel dengan OpenAI
# Impor dependensi dan buat klien...
completion = client.chat.completions.create(
# Gunakan model yang mendukung interpreter kode
model="qwen3-max-preview",
messages=[{"role": "user", "content": "Berapa 123 pangkat 21?"}],
# Karena enable_code_interpreter bukan parameter standar OpenAI, Anda harus melewatinya melalui extra_body saat menggunakan SDK Python. Saat menggunakan SDK Node.js, lewatkan sebagai parameter tingkat atas.
extra_body={
"enable_code_interpreter": True,
# Fitur interpreter kode hanya mendukung panggilan dalam mode berpikir
"enable_thinking": True,
},
# Fitur interpreter kode hanya mendukung panggilan keluaran streaming
stream=True
)Protokol kompatibel dengan OpenAI tidak mengembalikan kode yang dijalankan oleh interpreter.
DashScope
# 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-preview",
messages=[{"role": "user", "content": "Berapa 123 pangkat 21?"}],
# Aktifkan interpreter kode menggunakan parameter enable_code_interpreter
enable_code_interpreter=True,
# Fitur interpreter kode hanya mendukung mode berpikir
enable_thinking=True,
result_format="message",
# Fitur interpreter kode hanya mendukung panggilan keluaran streaming
stream=True
)Kode yang dijalankan oleh interpreter dikembalikan di bidang tool_info.
Model memproses permintaan dalam beberapa tahap:
Berpikir: Model menganalisis permintaan pengguna dan menghasilkan ide serta langkah-langkah untuk menyelesaikan masalah, dikembalikan di
reasoning_content.Eksekusi kode: Model menghasilkan dan mengeksekusi kode Python, dikembalikan di
tool_info. Protokol kompatibel dengan OpenAI tidak mendukungtool_info.Integrasi hasil: Model menerima hasil eksekusi kode dan merencanakan tanggapan akhir, dikembalikan di
reasoning_content.Tanggapan: Model menghasilkan tanggapan bahasa alami, dikembalikan di
content.
Ketersediaan
Wilayah: Didukung hanya di wilayah China (Beijing). Gunakan Kunci API dari wilayah China (Beijing).
Model: Didukung hanya untuk model qwen3-max-preview dalam mode berpikir.
Memulai
Contoh berikut menunjukkan bagaimana interpreter kode secara efisien menyelesaikan masalah perhitungan matematika.
DashScope
SDK Java tidak didukung.
Python
import os
import dashscope
messages = [
{"role": "user", "content": "Berapa 123 pangkat 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-preview",
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://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-preview",
"input":{
"messages":[
{
"role": "user",
"content": "Berapa 123 pangkat 21?"
}
]
},
"parameters": {
"enable_code_interpreter": true,
"enable_thinking": true,
"result_format": "message"
}
}'Contoh tanggapan
<...Isi teks...> adalah komentar penjelasan 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"}Kompatibel dengan OpenAI
Python
from openai import OpenAI
import os
# Inisialisasi klien OpenAI
client = OpenAI(
# Jika Anda belum mengonfigurasi variabel lingkungan, ganti ini dengan Kunci API Model Studio Alibaba Cloud Anda: api_key="sk-xxx"
api_key=os.getenv("DASHSCOPE_API_KEY"),
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
)
messages = [{"role": "user", "content": "Berapa 123 pangkat 21?"}]
completion = client.chat.completions.create(
model="qwen3-max-preview",
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 # Tanda untuk memeriksa apakah tahap tanggapan telah dimulai
print("\n" + "=" * 20 + "Proses berpikir" + "=" * 20 + "\n")
for chunk in completion:
if not chunk.choices:
print("\nPenggunaan:")
print(chunk.usage)
continue
delta = chunk.choices[0].delta
# Kumpulkan hanya konten berpikir
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
# Ketika konten diterima, mulai tanggapan
if hasattr(delta, "content") and delta.content:
if not is_answering:
print("\n" + "=" * 20 + "Tanggapan lengkap" + "=" * 20 + "\n")
is_answering = True
print(delta.content, end="", flush=True)
answer_content += delta.contentContoh tanggapan
====================Proses berpikir====================
Pengguna meminta 123 pangkat 21. Ini adalah masalah matematika. Saya perlu menghitung 123^21.
Saya bisa menggunakan kalkulator kode untuk menghitung nilai ini. Saya perlu memanggil fungsi code_interpreter dan melewati kode Python untuk menghitung 123**21.
Izinkan saya membuat panggilan fungsi ini.
Pengguna meminta 123 pangkat 21, dan saya menggunakan kode Python untuk menghitung hasilnya. Perhitungan menunjukkan bahwa 123 pangkat 21 sama dengan 77269364466549865653073473388030061522211723. Ini adalah angka yang sangat besar. Saya harus memberikan ini langsung
====================Tanggapan lengkap====================
123 pangkat 21 adalah: 77269364466549865653073473388030061522211723
Penggunaan:
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
// Berikut adalah base_url untuk wilayah Beijing. Jika Anda menggunakan model di wilayah Singapura, ganti base_url dengan: 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: 'Berapa 123 pangkat 21?' }];
const stream = await openai.chat.completions.create({
model: 'qwen3-max-preview',
messages,
stream: true,
enable_thinking: true,
enable_code_interpreter: true
});
console.log('\n' + '='.repeat(20) + 'Proses berpikir' + '='.repeat(20) + '\n');
for await (const chunk of stream) {
if (!chunk.choices?.length) {
console.log('\nPenggunaan:');
console.log(chunk.usage);
continue;
}
const delta = chunk.choices[0].delta;
// Kumpulkan hanya konten berpikir
if (delta.reasoning_content !== undefined && delta.reasoning_content !== null) {
if (!isAnswering) {
process.stdout.write(delta.reasoning_content);
}
reasoningContent += delta.reasoning_content;
}
// Ketika 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 berpikir====================
Pengguna meminta nilai 123 dipangkatkan 21. Ini adalah perhitungan matematis yang dapat saya lakukan menggunakan interpreter kode Python. Saya akan menggunakan operator eksponensial ** untuk menghitung ini.
Izinkan saya menulis kode untuk menghitung 123**21.Hasil perhitungan telah selesai dengan sukses. 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: 77269364466549865653073473388030061522211723curl
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-preview",
"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-max-preview","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-preview","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-preview","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-preview","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-preview","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-preview","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-preview","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-preview","id":"chatcmpl-2f96ef0b-5924-4dfc-b768-4d53ec538b4e"}
data: [DONEPenguraian tanggapan
Contoh SDK Python DashScope berikut menunjukkan cara melakukan dua perhitungan dalam satu permintaan dan mengembalikan kode serta jumlah total panggilan.
Protokol yang kompatibel dengan OpenAI tidak mengembalikan data selama tahap eksekusi kode, sehingga terdapat celah tanggapan antara tahap berpikir dan integrasi hasil. Karena kedua tahap ini mengembalikan konten di reasoning_content, Anda dapat memprosesnya bersama sebagai tahap berpikir. Untuk contoh penguraian tanggapan, lihat kode di bagian Memulai.import os
from dashscope import Generation
messages = [{"role": "user", "content": "Jalankan interpreter kode dua kali: pertama, hitung nilai 123 pangkat 23, dan kedua, bagi hasilnya dengan 5"}]
response = Generation.call(
api_key=os.getenv("DASHSCOPE_API_KEY"),
model="qwen3-max-preview",
messages=messages,
result_format="message",
enable_thinking=True,
enable_code_interpreter=True,
stream=True,
incremental_output=True,
)
# Status flag: lacak apakah info alat telah dicetak, apakah tahap menjawab telah dimulai, dan apakah dalam bagian penalaran
is_answering = False
in_reasoning_section = False
cur_tools = []
# Cetak area terpisah dengan judul
def print_section(title):
print(f"\n{'=' * 20}{title}{'=' * 20}")
# Awalnya cetak judul "Proses berpikir"
print_section("Proses berpikir")
in_reasoning_section = True
# Proses setiap blok data yang dikembalikan oleh model dalam aliran
for chunk in response:
try:
# Ekstrak bidang kunci dari respons: konten, teks penalaran, informasi pemanggilan alat
choice = chunk.output.choices[0]
msg = choice.message
content = msg.get("content", "") # Konten jawaban akhir
reasoning = msg.get("reasoning_content", "") # Teks proses penalaran
tools = chunk.output.get("tool_info", None) # Informasi pemanggilan alat
except (IndexError, AttributeError, KeyError):
# Lewati blok data dengan struktur abnormal
continue
# Jika tidak ada konten yang valid, lewati blok saat ini
if not content and not reasoning and tools is None:
continue
# Keluarkan proses penalaran
if reasoning and not is_answering:
if not in_reasoning_section:
print_section("Proses berpikir")
in_reasoning_section = True
print(reasoning, end="", flush=True)
if tools is not None and tools != cur_tools:
print_section("Informasi alat")
print(tools)
in_reasoning_section = False
cur_tools = tools
# Keluarkan konten jawaban akhir
if content:
if not is_answering:
print_section("Tanggapan lengkap")
is_answering = True
in_reasoning_section = False
print(content, end="", flush=True)
# Cetak jumlah panggilan interpreter kode
print_section("Jumlah eksekusi interpreter kode")
print(chunk.usage.plugins)Contoh tanggapan
====================Proses berpikir====================
Pengguna ingin menjalankan interpreter kode dua kali:
1. Jalankan pertama: Hitung 123 pangkat 23
2. Jalankan kedua: Bagi hasil dari jalankan pertama dengan 5
Saya perlu memanggil interpreter kode terlebih dahulu untuk menghitung 123**23, lalu gunakan hasil ini untuk memanggil interpreter kode lagi untuk dibagi dengan 5.
Izinkan saya melakukan perhitungan pertama.
====================Informasi alat====================
[{'code_interpreter': {'code': '123**23'}, 'type': 'code_interpreter'}]
====================Proses berpikir====================
Perhitungan pertama mendapatkan nilai 123 pangkat 23: 1169008215014432917465348578887506800769541157267
Sekarang untuk jalankan kedua, saya perlu membagi hasil ini dengan 5. Saya perlu menggunakan nilai tepat ini untuk pembagian
====================Informasi alat====================
[{'code_interpreter': {'code': '123**23'}, 'type': 'code_interpreter'}, {'code_interpreter': {'code': ''}, 'type': 'code_interpreter'}]
====================Informasi alat====================
[{'code_interpreter': {'code': '123**23'}, 'type': 'code_interpreter'}, {'code_interpreter': {'code': '1169008215014432917465348578887506800769541157267 / 5'}, 'type': 'code_interpreter'}]
====================Proses berpikir====================
Pengguna meminta untuk menjalankan interpreter kode dua kali:
1. Pertama, hitung 123 pangkat 23, hasilnya adalah: 1169008215014432917465348578887506800769541157267
2. Kedua, bagi hasil ini dengan 5, yang menghasilkan: 2.338016430028866e+47
Sekarang saya perlu melaporkan kedua hasil ini kepada pengguna
====================Tanggapan lengkap====================
Hasil jalankan pertama: 123 pangkat 23 = 1169008215014432917465348578887506800769541157267
Hasil jalankan kedua: Hasil di atas dibagi dengan 5 = 2.338016430028866e+47
====================Jumlah eksekusi interpreter kode====================
{'code_interpreter': {'count': 2}}Catatan
Interpreter kode dan pemanggilan fungsi bersifat saling eksklusif, sehingga tidak dapat diaktifkan secara bersamaan.
Jika diaktifkan bersamaan, akan terjadi kesalahan.
Setelah mengaktifkan interpreter kode, satu permintaan dapat memicu beberapa inferensi model. Bidang
usagemerangkum total konsumsi token untuk semua panggilan.
Penagihan
Tidak ada biaya tambahan untuk interpreter kode, namun akan meningkatkan konsumsi token.