# Code Interpreter

> Enable the built-in Python Code Interpreter when calling a model. The model writes and runs Python code in a sandbox to solve complex problems such as mathematical calculations and data analytics.

<meta property="og:title" content="Code Interpreter" />

## How to use <span id="529c63eb16f2d" />

Code Interpreter supports three invocation methods. The parameters differ for each method:

<Tabs>
  <Tab title="OpenAI-compatible - Responses API">
    To enable Code Interpreter, add the `code_interpreter` tool to the `tools` parameter.

    > For the best results, enable the `code_interpreter`, `web_search`, and `web_extractor` tools at the same time.

    ```python
    # Import dependencies and create the client...
    response = client.responses.create(
        model="qwen3.8-max",
        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)
    ```
  </Tab>

  <Tab title="OpenAI-compatible - Chat Completions API">
    To enable Code Interpreter, pass `enable_code_interpreter: true` in the API request.

    ```python
    # Import dependencies and create the client...
    completion = client.chat.completions.create(
        # Use a model that supports Code Interpreter
        model="qwen3.8-max",
        messages=[{"role": "user", "content": "What is 123 to the power of 21?"}],
        # Because enable_code_interpreter is not a standard OpenAI parameter, you must pass it through extra_body when using the Python SDK. When using the Node.js SDK, pass it as a top-level parameter.
        extra_body={
            "enable_code_interpreter": True,
            # The Code Interpreter feature only supports calls in thinking mode
            "enable_thinking": True,
        },
        # Only streaming output calls are supported
        stream=True
    )
    ```

    > The OpenAI-compatible protocol does not return code execution details.
  </Tab>

  <Tab title="DashScope">
    To enable Code Interpreter, set `enable_code_interpreter` to `true` in the API request.

    ```python
    # Import dependencies...
    response = dashscope.MultiModalConversation.call(
        # If the environment variable is not configured, replace the next line with: api_key="sk-xxx", using your Model Studio API key.
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        model="qwen3.5-plus",
        messages=[{"role": "user", "content": "What is 123 to the power of 21?"}],
        # Enable Code Interpreter using the enable_code_interpreter parameter
        enable_code_interpreter=True,
        # The Code Interpreter feature only supports thinking mode
        enable_thinking=True,
        result_format="message",
        # Only streaming output calls are supported
        stream=True
    )
    ```

    The executed code is returned in the `tool_info` field.
  </Tab>
</Tabs>

After Code Interpreter is enabled, the model processes requests in these stages:

1. <strong>Thinking</strong>: The model analyzes the user's request and generates ideas and steps to solve the problem.
2. <strong>Code execution</strong>: The model generates and executes Python code.
3. <strong>Result integration</strong>: The model receives the code execution result and plans the next steps.
4. <strong>Response</strong>: The model generates a natural language response.

> Steps 2 and 3 may loop multiple times.

The fields returned by different APIs vary:

- Responses API: Thinking content is returned in an object with `type="reasoning"` in the output. Code execution is returned with `type="code_interpreter_call"`. The response is returned with `type="message"`.
- Chat Completions API / DashScope: Thinking content is returned in the `reasoning_content` field. The response is returned in the `content` field. DashScope also supports returning code content in the `tool_info` field.

## Scope <span id="980e4e9787miv" />

`deepseek-v4.1-flash-1017` supports the built-in `code_interpreter` tool in the Responses API in all six regions and corresponding deployment scopes listed on the [model page](/help/en/model-studio/deepseek-v4-1-flash).

### Recommended models <span id="ci_rec_title" />

<Tabs>
  <Tab title="Responses API">
    Qwen-Max: Qwen3.8-Max series, Qwen3.7-Max series

    Qwen-Plus: Qwen3.7-Plus series, Qwen3.6-Plus series, Qwen3.5-Plus series

    DeepSeek: deepseek-v4-flash-0731, deepseek-v4-pro

    GLM: glm-5.2

    Qwen3.8 open source series
  </Tab>

  <Tab title="Chat Completions API / DashScope">
    - Qwen-Max (thinking mode): Qwen3-Max series
    - Qwen-Plus: Qwen3.5-Plus series
  </Tab>
</Tabs>

### Other models <span id="ci_other_title" />

These models also support Code Interpreter but may not perform as well. Only supported through the Responses API.

- Qwen-Flash: Qwen3.7-Flash series, Qwen3.6-Flash series, Qwen3.5-Flash series
- Qwen3.6 open-source series (except qwen3.6-27b)
- Qwen3.5 open source series

## Getting started <span id="744bf8e1c66p3" />

These examples show how Code Interpreter solves mathematical problems.

<Tabs>
  <Tab title="OpenAI-compatible - Responses API">
    > For the best results, enable the `code_interpreter`, `web_search`, and `web_extractor` tools at the same time.

    <CodeGroup dropdown>
      ```python expandable
      import os
      from openai import OpenAI

      client = OpenAI(
          # If the environment variable is not configured, replace the next line with: api_key="sk-xxx", using your Model Studio API key.
          api_key=os.getenv("DASHSCOPE_API_KEY"),
          # The following URL is for the Singapore region. Replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
          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
          }
      )
      # Uncomment the following line to view the intermediate process output
      # print(response.output)
      print("="*20+"Response Content"+"="*20)
      print(response.output_text)
      print("="*20+"Token Consumption and Tool Calls"+"="*20)
      print(response.usage)
      ```

      ```javascript expandable
      import OpenAI from "openai";
      import process from 'process';

      const openai = new OpenAI({
          // If the environment variable is not configured, replace the next line with: apiKey: "sk-xxx", using your Model Studio API key.
          apiKey: process.env.DASHSCOPE_API_KEY,
          // The following URL is for the Singapore region. Replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
          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: "Calculate 12 to the power of 3",
              tools: [
                  { type: "code_interpreter" },
                  { type: "web_search" },
                  { type: "web_extractor" }
              ],
              enable_thinking: true
          });

          console.log("====================Response Content====================");
          console.log(response.output_text);

          // Print the number of tool calls
          console.log("====================Token Consumption and Tool Calls====================");
          if (response.usage && response.usage.x_tools) {
              console.log(`Code Interpreter runs: ${response.usage.x_tools.code_interpreter?.count || 0}`);
          }
          // Uncomment the following line to view the intermediate process output
          // console.log(JSON.stringify(response.output[0], null, 2));
      }

      main();
      ```

      ```bash
      # The following URL is for the Singapore region. Replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
      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": "Calculate 12 to the power of 3",
          "tools": [
              {"type": "code_interpreter"},
              {"type": "web_search"},
              {"type": "web_extractor"}
          ],
          "enable_thinking": true
      }'
      ```
    </CodeGroup>

    ###### Example response <span id="36fa335a3df1z" />

    ```plaintext
    ====================Response Content====================
    12 to the power of 3 is **1728**.

    Calculation process:
    12³ = 12 × 12 × 12 = 144 × 12 = 1728
    ====================Token Consumption 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}})
    ```
  </Tab>

  <Tab title="OpenAI-compatible - Chat Completions API">
    <Tabs>
      <Tab title="Python">
        ```python expandable
        from openai import OpenAI
        import os

        # Initialize the OpenAI client
        client = OpenAI(
            # If the environment variable is not configured, replace with your Alibaba Cloud Model Studio API key: api_key="sk-xxx"
            api_key=os.getenv("DASHSCOPE_API_KEY"),
            # The following URL is for the China (Beijing) region. Replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
            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 = ""  # Complete thinking process
        answer_content = ""  # Complete response
        is_answering = False  # Flag to check if the response phase has started
        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

            # Collect only the thinking content
            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

            # When content is received, start the response
            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
        ```

        ##### Example response <span id="1265cefdbcesz" />

        ```plaintext
        ====================Thinking Process====================

        The user is asking for the value of 123 to the power of 21. This is a mathematical calculation problem. I need to calculate 123^21.

        I can use the code calculator to compute this value. I need to call the code_interpreter function and pass 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 calculated the result using Python code. The calculation shows that 123 to the power of 21 equals 77269364466549865653073473388030061522211723. This is a very large number, and I should provide it 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)
        ```
      </Tab>

      <Tab title="Node.js">
        ```javascript expandable
        import OpenAI from "openai";
        import process from 'process';

        // Initialize the OpenAI client
        const openai = new OpenAI({
            apiKey: process.env.DASHSCOPE_API_KEY, // Read from environment variables
            // The following URL is for the China (Beijing) region. Replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
            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: 'What is 123 to the power of 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) + '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;

                    // Collect only the thinking content
                    if (delta.reasoning_content !== undefined && delta.reasoning_content !== null) {
                        if (!isAnswering) {
                            process.stdout.write(delta.reasoning_content);
                        }
                        reasoningContent += delta.reasoning_content;
                    }

                    // When content is received, start the response
                    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();
        ```

        ##### Example response <span id="84d7249094q6c" />

        ```plaintext
        ====================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: 77269364466549865653073473388030061522211723
        ```
      </Tab>

      <Tab title="curl">
        ```bash
        # The following URL is for the China (Beijing) region. Replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
        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": "What is 123 to the power of 21?"
                }
            ],
            "enable_code_interpreter": true,
            "enable_thinking": true,
            "stream": true
        }'
        ```

        #### Example response <span id="225a70ba95hp3" />

        ```json
        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]
        ```
      </Tab>
    </Tabs>
  </Tab>

  <Tab title="DashScope">
    > The Java SDK is not supported.

    <Tabs>
      <Tab title="Python">
        ```python
        import os
        import dashscope

        # China (Beijing) region. Replace {WorkspaceId} with your actual Workspace ID. URLs vary by region.
        dashscope.base_http_api_url = 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1'

        messages = [
            {"role": "user", "content": "What is 123 to the power of 21?"},
        ]

        response = dashscope.MultiModalConversation.call(
            # If the environment variable is not configured, replace the next line with: api_key="sk-xxx", using your Model Studio API key.
            api_key=os.getenv("DASHSCOPE_API_KEY"),
            model="qwen3.5-plus",
            messages=messages,
            enable_code_interpreter=True,
            enable_thinking=True,
            result_format="message",
            # Only streaming output is supported
            stream=True
        )

        for chunk in response:
            output = chunk["output"]
            print(output)
        ```

        ##### Example response <span id="618d668bc886s" />

        ```json expandable
        {"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"}]}
        ```
      </Tab>

      <Tab title="curl">
        ```bash
        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": "What is 123 to the power of 21?"
                    }
                ]
            },
            "parameters": {
                "enable_code_interpreter": true,
                "enable_thinking": true,
                "result_format": "message"
            }
        }'
        ```

        #### Example response <span id="3b98a47700182" />

        > The text `<...text content...>` is an explanatory comment and not part of the actual API response. This comment is used to identify the different processing stages.

        ```json expandable
        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"}

        ...Thinking stage...

        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 ends, starting 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 starts after running 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"}

        ...Thinking stage...

        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 ends, starting response...

        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"}
        ```
      </Tab>
    </Tabs>
  </Tab>
</Tabs>

## Parsing responses <span id="95fd5ba526qza" />

<Tabs>
  <Tab title="OpenAI-compatible - Responses API">
    The following OpenAI Python SDK example shows how to parse a streaming response.

    ```python expandable
    import os
    from openai import OpenAI

    client = OpenAI(
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        # The following URL is for the Singapore region. Replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
        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:
        # Incremental output of the thinking process
        if event.type == "response.reasoning_text.delta":
            if current_section != "reasoning":
                print_section("Thinking Process")
                current_section = "reasoning"
            print(event.delta, end="", flush=True)

        # Code Interpreter call completed
        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"

        # Incremental output of the final response
        elif event.type == "response.output_text.delta":
            if current_section != "answer":
                print_section("Complete Response")
                current_section = "answer"
            print(event.delta, end="", flush=True)

        # Response completed, save the final result to get usage
        elif event.type == "response.completed":
            final_response = event.response

    # Output token consumption and number of tool calls
    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}")
        # If the model does not actually invoke the code interpreter (e.g., simple questions answered directly), the response has no x_tools field
        if hasattr(usage, 'x_tools'):
            print(f"Code Interpreter calls: {usage.x_tools.get('code_interpreter', {}).get('count', 0)}")
        else:
            print("Code Interpreter calls: 0")
    ```
  </Tab>

  <Tab title="DashScope">
    The following DashScope Python SDK example performs two calculations in a single request and parses the returned code and call count.

    > The OpenAI Chat Completions API does not return data during the <strong>code execution</strong> stage, so no response is sent between the <strong>thinking</strong> and <strong>result integration</strong> stages. Both stages return content through the `reasoning_content` field, so you can process them together as the <strong>thinking</strong> stage. For a response parsing example, see the code in the [Getting started](/help/en/model-studio/qwen-code-interpreter) section.

    ```python expandable
    import os
    from dashscope import MultiModalConversation
    # China (Beijing) region. Replace {WorkspaceId} with your actual Workspace ID. URLs vary by region.
    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,
    )

    # Status flags: track if tool info is printed, if the answering phase has started, and if in the reasoning section
    is_answering = False
    in_reasoning_section = False
    cur_tools = []

    # Print a section with a title
    def print_section(title):
        print(f"\n{'=' * 20}{title}{'=' * 20}")

    # Initially print the "Thinking Process" title
    print_section("Thinking Process")
    in_reasoning_section = True

    # Process each block returned by the model in a stream
    for chunk in response:
        try:
            # Extract key fields from the response: content, reasoning text, tool call info
            choice = chunk.output.choices[0]
            msg = choice.message
            content = msg.get("content", "")            # Final answer content
            reasoning = msg.get("reasoning_content", "") # Reasoning process text
            tools = chunk.output.get("tool_info", None)  # Tool call information
        except (IndexError, AttributeError, KeyError):
            # Skip blocks with abnormal structure
            continue
        # If there is no valid content, skip the current block
        if not content and not reasoning and tools is None:
            continue
        # Output the reasoning process
        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
        # Output the final answer content
        if content:
            if not is_answering:
                print_section("Complete Response")
                is_answering = True
                in_reasoning_section = False
            print(content, end="", flush=True)
    # Print the number of Code Interpreter calls
    print_section("Code Interpreter Runs")
    print(chunk.usage.plugins)
    ```

    ### Example response <span id="fce98d8460mhn" />

    ```plaintext expandable
    ====================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}}
    ```
  </Tab>
</Tabs>

## Notes <span id="8c21a1ed873gp" />

- Code Interpreter and [Function calling](/help/en/model-studio/qwen-function-calling) are mutually exclusive.

  > Enabling both in the same request causes an error.
- When Code Interpreter is enabled, a single request may trigger multiple model inferences. The `usage` field summarizes the total token consumption for all calls in that request.

## Billing <span id="13a18236ef2en" />

Code Interpreter is <strong>free for a limited time</strong> but increases token consumption.