Skip to main content

Code Interpreter

Habilite el Code Interpreter de Python integrado al llamar a un modelo. El modelo escribe y ejecuta código Python en un entorno aislado para resolver problemas complejos, como cálculos matemáticos y análisis de datos.

Cómo usar

Code Interpreter admite tres métodos de invocación. Los parámetros difieren para cada método:
  • Compatible con OpenAI - Responses API
  • Compatible con OpenAI - Chat Completions API
  • DashScope
Para habilitar Code Interpreter, añada la herramienta code_interpreter al parámetro tools.
Para obtener los mejores resultados, habilite las herramientas code_interpreter, web_search y web_extractor al mismo tiempo.
# 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)
Una vez habilitado Code Interpreter, el modelo procesa las solicitudes en estas etapas:
  1. Pensamiento: El modelo analiza la solicitud del usuario y genera ideas y pasos para resolver el problema.
  2. Ejecución de código: El modelo genera y ejecuta código Python.
  3. Integración de resultados: El modelo recibe el resultado de la ejecución del código y planifica los siguientes pasos.
  4. Respuesta: El modelo genera una respuesta en lenguaje natural.
Los pasos 2 y 3 pueden repetirse varias veces.
Los campos devueltos por las diferentes API varían:
  • Responses API: El contenido de pensamiento se devuelve en un objeto con type="reasoning" en la salida. La ejecución de código se devuelve con type="code_interpreter_call". La respuesta se devuelve con type="message".
  • Chat Completions API / DashScope: El contenido de pensamiento se devuelve en el campo reasoning_content. La respuesta se devuelve en el campo content. DashScope también admite la devolución de contenido de código en el campo tool_info.

Ámbito

deepseek-v4.1-flash-1017 admite la herramienta integrada code_interpreter en la Responses API en las seis regiones y los alcances de implementación correspondientes indicados en la página del modelo. kimi-k3.1-pro (implementado en Alibaba Cloud Model Studio) admite la herramienta integrada code_interpreter en la Responses API en Pekín, Singapur, EE. UU. (Virginia), Alemania (Fráncfort), Japón (Tokio) y China (Hong Kong).

Modelos recomendados

  • API de respuestas
  • Chat Completions API / DashScope
Qwen-Max: qwen4-max-preview (solo Token Plan), serie Qwen3.8-Max, serie Qwen3.7-MaxQwen-Plus: serie Qwen3.7-Plus, serie Qwen3.6-Plus, serie Qwen3.5-PlusDeepSeek: deepseek-v4-flash-0731, deepseek-v4-proGLM: glm-5.2Serie de código abierto Qwen3.8

Otros modelos

Estos modelos también admiten Code Interpreter, pero es posible que no tengan un rendimiento tan óptimo. Solo se admiten a través de la Responses API.
  • Qwen-Flash: serie Qwen3.7-Flash, serie Qwen3.6-Flash, serie Qwen3.5-Flash
  • Serie de código abierto Qwen3.6 (excepto qwen3.6-27b)
  • Serie de código abierto Qwen3.5

Introducción

Estos ejemplos muestran cómo Code Interpreter resuelve problemas matemáticos.
  • Compatible con OpenAI - Responses API
  • Compatible con OpenAI - Chat Completions API
  • DashScope
Para obtener los mejores resultados, habilite las herramientas code_interpreter, web_search y web_extractor al mismo tiempo.
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)
Respuesta de ejemplo
====================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álisis de respuestas

  • Compatible con OpenAI - Responses API
  • DashScope
El siguiente ejemplo del SDK de Python de OpenAI muestra cómo analizar una respuesta en 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_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")

Notas

  • Code Interpreter y Function calling son mutuamente excluyentes.
    Habilitar ambas opciones en la misma solicitud provoca un error.
  • Cuando Code Interpreter está habilitado, una sola solicitud puede desencadenar múltiples inferencias del modelo. El campo usage resume el consumo total de tokens para todas las llamadas en esa solicitud.

Facturación

Code Interpreter es gratuito por tiempo limitado, pero aumenta el consumo de tokens.