Skip to main content
Chamada de ferramentas

Code Interpreter

Ative o Code Interpreter Python integrado ao chamar um modelo. O modelo escreve e executa código Python em um sandbox para resolver problemas complexos, como cálculos matemáticos e análise de dados.

Como usar

O Code Interpreter oferece suporte a três métodos de invocação. Os parâmetros variam conforme o método:
  • OpenAI-compatible - Responses API
  • OpenAI-compatible - Chat Completions API
  • DashScope
Para ativar o Code Interpreter, adicione a ferramenta code_interpreter ao parâmetro tools.
Para obter os melhores resultados, ative simultaneamente as ferramentas code_interpreter , web_search e web_extractor .
# 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)
Após a ativação do Code Interpreter, o modelo processa as solicitações nas seguintes etapas:
  1. Raciocínio: O modelo analisa a solicitação do usuário e gera ideias e etapas para resolver o problema.
  2. Execução de código: O modelo gera e executa código Python.
  3. Integração de resultados: O modelo recebe o resultado da execução do código e planeja as próximas etapas.
  4. Resposta: O modelo gera uma resposta em linguagem natural.
As etapas 2 e 3 podem se repetir várias vezes.
Os campos retornados variam conforme a API:
  • Responses API: O conteúdo de raciocínio é retornado em um objeto com type="reasoning" na saída. A execução do código vem com type="code_interpreter_call". A resposta final vem com type="message".
  • Chat Completions API / DashScope: O conteúdo de raciocínio aparece no campo reasoning_content. A resposta final vem no campo content. O DashScope também permite retornar o conteúdo do código no campo tool_info.

Escopo

Modelos recomendados

  • Responses API
  • Chat Completions API / DashScope
Qwen-Max: Séries Qwen3,8-Max, Qwen3,7-MaxQwen-Plus: Séries Qwen3,7-Plus, Qwen3,6-Plus, Qwen3,5-PlusDeepSeek: deepseek-v4-flash, deepseek-v4-flash-0731, deepseek-v4-proGLM: glm-5.2Série open source Qwen3,8

Outros modelos

Estes modelos também oferecem suporte ao Code Interpreter, mas podem apresentar desempenho inferior. O suporte está disponível apenas pela Responses API.
  • Qwen-Flash: Séries Qwen3,7-Flash, Qwen3,6-Flash, Qwen3,5-Flash
  • Série open-source Qwen3,6 (exceto qwen3.6-27b)
  • Série open source Qwen3,5

Primeiros passos

Os exemplos a seguir demonstram como o Code Interpreter resolve problemas matemáticos.
  • OpenAI-compatible - Responses API
  • OpenAI-compatible - Chat Completions API
  • DashScope
Para obter os melhores resultados, ative simultaneamente as ferramentas code_interpreter , web_search e web_extractor .
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)
Exemplo de resposta
====================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}})

Análise de respostas

  • OpenAI-compatible - Responses API
  • DashScope
O exemplo abaixo, usando o SDK Python da OpenAI, demonstra como analisar uma resposta em streaming.
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_summary_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}")
    # Se o modelo não invocar realmente o interpretador de código (por exemplo, perguntas simples respondidas diretamente), a resposta não terá o campo x_tools
    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")

Observações

  • O Code Interpreter e o Function calling são mutuamente exclusivos.
    Ativar ambos na mesma solicitação causa um erro.
  • Com o Code Interpreter ativado, uma única solicitação pode acionar múltiplas inferências do modelo. O campo usage resume o consumo total de tokens de todas as chamadas nessa solicitação.

Faturamento

O Code Interpreter é gratuito por tempo limitado, mas aumenta o consumo de tokens.
Plano de Tokens
Playground de Modelos
Inferência do Modelo
Avaliação
Compressão de Modelos
Estatísticas e Monitoramento
Suporte