すべてのプロダクト
Search
ドキュメントセンター

Alibaba Cloud Model Studio:コードインタープリター

最終更新日:Nov 08, 2025

組み込みの Python コードインタープリターを使用すると、モデルはサンドボックスで Python コードを記述して実行し、数学的計算やデータ分析などの複雑な問題を解決できます。

使用方法

API リクエストで enable_code_interpreter: true を渡します。

次の例は、OpenAI 互換および DashScope Python SDK を使用した API 呼び出しのコアコードを示しています。

OpenAI 互換

# 依存関係をインポートし、クライアントを作成します...
completion = client.chat.completions.create(
    # コードインタープリターをサポートするモデルを使用します
    model="qwen3-max-preview",
    messages=[{"role": "user", "content": "123 の 21 乗はいくつですか?"}],
    # enable_code_interpreter は標準の OpenAI パラメーターではないため、Python SDK を使用する場合は extra_body を介して渡す必要があります。Node.js SDK を使用する場合は、トップレベルのパラメーターとして渡します。
    extra_body={
        "enable_code_interpreter": True,
        # コードインタープリター機能は、思考モードでの呼び出しのみをサポートします
        "enable_thinking": True,
    },
    # コードインタープリター機能は、ストリーミング出力呼び出しのみをサポートします
    stream=True
)
OpenAI 互換プロトコルは、インタープリターによって実行されたコードを返しません。

DashScope

# 依存関係をインポートします...
response = dashscope.Generation.call(
    # 環境変数を設定していない場合は、次の行を Model Studio API キーに置き換えてください: api_key="sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    model="qwen3-max-preview",
    messages=[{"role": "user", "content": "123 の 21 乗はいくつですか?"}],
    # enable_code_interpreter パラメーターを使用してコードインタープリターを有効にします
    enable_code_interpreter=True,
    # コードインタープリター機能は思考モードのみをサポートします
    enable_thinking=True,
    result_format="message",
    # コードインタープリター機能はストリーミング出力呼び出しのみをサポートします
    stream=True
)

インタープリターが実行するコードは tool_info フィールドで返されます。

モデルはリクエストを段階的に処理します:

  • 思考: モデルはユーザーのリクエストを分析し、問題を解決するためのアイデアとステップを生成します。これは reasoning_content で返されます。

  • コードの実行: モデルは Python コードを生成して実行します。これは tool_info で返されます。OpenAI 互換プロトコルは tool_info をサポートしていません。

  • 結果の統合: モデルはコードの実行結果を受け取り、最終的な応答を計画します。これは reasoning_content で返されます。

  • 応答: モデルは自然言語の応答を生成します。これは content で返されます。

利用可能性

  • リージョン: 中国 (北京) リージョンでのみサポートされています。中国 (北京) リージョンの API キー を使用してください。

  • モデル: 思考モードqwen3-max-preview モデルでのみサポートされています。

はじめに

次の例は、コードインタープリターが数学的計算問題を効率的に解決する方法を示しています。

DashScope

Java SDK はサポートされていません。
Python
import os
import dashscope

messages = [
    {"role": "user", "content": "123 の 21 乗はいくつですか?"},
]

response = dashscope.Generation.call(
    # 環境変数を設定していない場合は、次の行を Model Studio API キーに置き換えてください: 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",
    # ストリーミング出力のみがサポートされています
    stream=True
)

for chunk in response:
    output = chunk["output"]
    print(output)
応答例
{"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": "123 の 21 乗はいくつですか?"
            }
        ]
    },
    "parameters": {
        "enable_code_interpreter": true,
        "enable_thinking": true,
        "result_format": "message"
    }
}'

応答例

<...テキストコンテンツ...> は、処理段階を特定するための説明コメントであり、実際の API 応答の一部ではありません。
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"}

...思考段階...

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"}

...思考が終了し、コードインタープリターが開始します...

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"}

...コードインタープリターの実行後に思考が開始します...

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"}

...思考段階...

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"}

...思考が終了し、応答が開始します...

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"}

OpenAI 互換

Python
from openai import OpenAI
import os

# OpenAI クライアントを初期化します
client = OpenAI(
    # 環境変数を設定していない場合は、これを Alibaba Cloud Model Studio API キーに置き換えてください: api_key="sk-xxx"
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
)

messages = [{"role": "user", "content": "123 の 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 = ""  # 完全な思考プロセス
answer_content = ""  # 完全な応答
is_answering = False  # 応答段階が開始したかどうかを確認するフラグ
print("\n" + "=" * 20 + "思考プロセス" + "=" * 20 + "\n")

for chunk in completion:
    if not chunk.choices:
        print("\nUsage:")
        print(chunk.usage)
        continue

    delta = chunk.choices[0].delta

    # 思考コンテンツのみを収集します
    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

    # コンテンツが受信されたら、応答を開始します
    if hasattr(delta, "content") and delta.content:
        if not is_answering:
            print("\n" + "=" * 20 + "完全な応答" + "=" * 20 + "\n")
            is_answering = True
        print(delta.content, end="", flush=True)
        answer_content += delta.content
応答例
====================思考プロセス====================

ユーザーは 123 の 21 乗を要求しています。これは数学の問題です。123^21 を計算する必要があります。

コード電卓を使用してこの値を計算できます。code_interpreter 関数を呼び出し、123**21 を計算するための Python コードを渡す必要があります。

この関数呼び出しを構築します。
ユーザーは 123 の 21 乗を要求し、私は Python コードを使用して結果を計算しました。計算の結果、123 の 21 乗は 77269364466549865653073473388030061522211723 になります。これは非常に大きな数です。これを直接提供する必要があります。
====================完全な応答====================

123 の 21 乗は次のとおりです: 77269364466549865653073473388030061522211723
使用状況:
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';

// OpenAI クライアントを初期化します
const openai = new OpenAI({
    apiKey: process.env.DASHSCOPE_API_KEY, // 環境変数から読み取ります
    // 以下は北京リージョンの base_url です。シンガポールリージョンのモデルを使用する場合は、base_url を 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: '123 の 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) + '思考プロセス' + '='.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;
            
            // 思考コンテンツのみを収集します
            if (delta.reasoning_content !== undefined && delta.reasoning_content !== null) {
                if (!isAnswering) {
                    process.stdout.write(delta.reasoning_content);
                }
                reasoningContent += delta.reasoning_content;
            }

            // コンテンツが受信されたら、応答を開始します
            if (delta.content !== undefined && delta.content) {
                if (!isAnswering) {
                    console.log('\n' + '='.repeat(20) + '完全な応答' + '='.repeat(20) + '\n');
                    isAnswering = true;
                }
                process.stdout.write(delta.content);
                answerContent += delta.content;
            }
        }
    } catch (error) {
        console.error('Error:', error);
    }
}

main();
応答例
====================思考プロセス====================

ユーザーは 123 の 21 乗の値を求めています。これは、Python のコードインタープリターを使用して実行できる数学的な計算です。べき乗演算子 ** を使用してこれを計算します。

123**21 を計算するコードを記述します。計算は正常に完了しました。123 の 21 乗の結果は、77269364466549865653073473388030061522211723 という非常に大きな数です。

この結果をユーザーに明確に提示すべきです。

====================完全な応答====================

123 の 21 乗は次のとおりです: 77269364466549865653073473388030061522211723
curl
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": "123 の 21 乗はいくつですか?"
        }
    ],
    "enable_code_interpreter": true,
    "enable_thinking": true,
    "stream": true
}'

応答例

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: [DONE]

応答の解析

次の DashScope Python SDK の例は、1 つのリクエストで 2 つの計算を実行する方法を示しています。次に、コードと呼び出しの総数を返します。

OpenAI 互換プロトコルは、コード実行段階ではデータを返しません。これにより、思考段階と結果統合段階の間で応答にギャップが生じます。これらの両方の段階は reasoning_content でコンテンツを返すため、これらをまとめて思考段階として処理できます。応答解析の例については、「はじめに」セクションのコードをご参照ください。
import os  
from dashscope import Generation  

messages = [{"role": "user", "content": "コードインタープリターを 2 回実行します: 最初に 123 の 23 乗の値を計算し、次にその結果を 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,
)  

# ステータスフラグ: ツール情報が出力されたか、応答段階が開始されたか、推論セクションにいるかを追跡します
is_answering = False  
in_reasoning_section = False  
cur_tools = []

# タイトル付きの区切られた領域を出力します
def print_section(title):  
    print(f"\n{'=' * 20}{title}{'=' * 20}")  

# 最初に「思考プロセス」のタイトルを出力します
print_section("Thinking process")  
in_reasoning_section = True  

# ストリームでモデルから返された各データブロックを処理します
for chunk in response:  
    try:  
        # 応答から主要なフィールドを抽出します: content、reasoning text、tool call information
        choice = chunk.output.choices[0]  
        msg = choice.message  
        content = msg.get("content", "")            # 最終的な回答内容
        reasoning = msg.get("reasoning_content", "") # 推論プロセステキスト
        tools = chunk.output.get("tool_info", None)  # ツール呼び出し情報
    except (IndexError, AttributeError, KeyError):
        # 異常な構造のデータブロックをスキップします
        continue  
    # 有効なコンテンツがない場合は、現在のブロックをスキップします
    if not content and not reasoning and tools is None:  
        continue  
    # 推論プロセスを出力します
    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
    # 最終的な回答内容を出力します
    if content:  
        if not is_answering:  
            print_section("Complete response")  
            is_answering = True  
            in_reasoning_section = False  
        print(content, end="", flush=True)  
# コードインタープリターの呼び出し回数を出力します
print_section("Code interpreter run count")  
print(chunk.usage.plugins)

応答例

====================思考プロセス====================
ユーザーはコードインタープリターを 2 回実行したいと考えています:
1. 最初の実行: 123 の 23 乗を計算
2. 2 回目の実行: 最初の実行結果を 5 で除算

まず、コードインタープリターを呼び出して 123**23 を計算し、次にこの結果を使用してコードインタープリターを再度呼び出して 5 で除算する必要があります。

最初の計算を実行します。

====================ツール情報====================
[{'code_interpreter': {'code': '123**23'}, 'type': 'code_interpreter'}]

====================思考プロセス====================
最初の計算で 123 の 23 乗の値を取得しました: 1169008215014432917465348578887506800769541157267

次に 2 回目の実行では、この結果を 5 で除算する必要があります。除算にはこの正確な値を使用する必要があります
====================ツール情報====================
[{'code_interpreter': {'code': '123**23'}, 'type': 'code_interpreter'}, {'code_interpreter': {'code': ''}, 'type': 'code_interpreter'}]

====================ツール情報====================
[{'code_interpreter': {'code': '123**23'}, 'type': 'code_interpreter'}, {'code_interpreter': {'code': '1169008215014432917465348578887506800769541157267 / 5'}, 'type': 'code_interpreter'}]

====================思考プロセス====================
ユーザーはコードインタープリターを 2 回実行するようにリクエストしました:
1. まず、123 の 23 乗を計算します。結果は次のとおりです: 1169008215014432917465348578887506800769541157267
2. 次に、この結果を 5 で除算します。これにより、2.338016430028866e+47 が得られます

ここで、これら 2 つをユーザーに報告する必要があります
====================完全な応答====================
最初の実行結果: 123 の 23 乗 = 1169008215014432917465348578887506800769541157267

2 回目の実行結果: 上記の結果を 5 で除算 = 2.338016430028866e+47
====================コードインタープリターの実行回数====================
{'code_interpreter': {'count': 2}}

注意事項

  • コードインタープリターと 関数呼び出し は相互排他的です。同時に有効にすることはできません。

    そうしないと、エラーが発生します。
  • コードインタープリターを有効にすると、1 つのリクエストで複数のモデル推論がトリガーされます。usage フィールドには、すべての呼び出しのトークン消費量が要約されます。

課金

コードインタープリターに追加料金はかかりませんが、トークンの消費量が増加します。