Developer Dashboard

Code Interpreter

Code Interpreter lets a model write and run Python in a sandboxed container, inspect results, and return generated files. OpenAI documents it as a hosted /v1/responses tool with tools: [{"type": "code_interpreter", ...}] and a container configuration.

Adapted from OpenAI's official Code Interpreter tool guide, with AvalAI endpoint, API key, model, and availability notes.

Warning

In AvalAI, hosted Code Interpreter is route-, model-, and account-dependent. Use the hosted shape only after the selected /v1/responses route explicitly supports code_interpreter. Otherwise, run code in your own locked-down backend and expose it through a narrow function tool.

When to Use It

TaskRecommended AvalAI path
Math, data analysis, CSV inspectionHosted Code Interpreter when enabled; otherwise app-managed Python function
User-uploaded filesValidate and store files in your app, then pass approved file IDs or extracted data
Charts or generated artifactsReturn files through the hosted container when enabled, or through your own storage
Image inspection and preprocessingLet the hosted Python tool crop, zoom, rotate, or analyze images only when file inputs and Code Interpreter are enabled; otherwise run image processing in your backend
Iterative computationUseful when the model needs to write code, inspect errors, and retry until a calculation or transformation succeeds
Production automationPrefer a deterministic backend tool with policy checks and audit logs

Avoid Code Interpreter for untrusted arbitrary execution, hidden network access, secrets handling, or workflows where a deterministic library call is enough.

For vision-heavy workflows, keep the image policy explicit: validate file type and size first, strip unnecessary metadata, ask the model to explain any transformation it performs, and store the original plus generated artifacts in your own system if users need an audit trail.

Hosted Responses Shape

Use this only after you have verified hosted Code Interpreter support for the selected AvalAI model and route.

OpenAI notes that the model knows this hosted capability as the python tool. Prompts that say "code interpreter" usually work, but production instructions should explicitly say when to use "the python tool" and when to answer without running code.

If the user request must execute Python, set tool_choice: "required" on supported routes. If Python execution is optional, leave tool choice automatic and instruct the model to use the tool only when it improves accuracy, repeatability, or artifact generation.

python
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["AVALAI_API_KEY"],
    base_url="https://api.avalai.ir/v1",
)

response = client.responses.create(
    model=os.getenv("AVALAI_MODEL", "gpt-5.5"),
    instructions=(
        "You are a careful data analyst. Use Python only when it improves "
        "accuracy, explain assumptions, and return the final answer clearly."
    ),
    input="Solve 3x + 11 = 14 and show the verification.",
    tools=[
        {
            "type": "code_interpreter",
            "container": {"type": "auto", "memory_limit": "4g"},
        }
    ],
)

print(response.output_text)
for item in response.output:
    if item.type == "code_interpreter_call":
        print("Container:", item.container_id)
javascript
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.AVALAI_API_KEY,
  baseURL: "https://api.avalai.ir/v1",
});

const response = await client.responses.create({
  model: process.env.AVALAI_MODEL ?? "gpt-5.5",
  instructions:
    "You are a careful data analyst. Use Python only when it improves accuracy, explain assumptions, and return the final answer clearly.",
  input: "Solve 3x + 11 = 14 and show the verification.",
  tools: [
    {
      type: "code_interpreter",
      container: { type: "auto", memory_limit: "4g" },
    },
  ],
});

console.log(response.output_text);
for (const item of response.output ?? []) {
  if (item.type === "code_interpreter_call") {
    console.log("Container:", item.container_id);
  }
}
bash
curl https://api.avalai.ir/v1/responses \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $AVALAI_API_KEY" \
  -d '{
    "model": "gpt-5.5",
    "instructions": "You are a careful data analyst. Use Python only when it improves accuracy, explain assumptions, and return the final answer clearly.",
    "input": "Solve 3x + 11 = 14 and show the verification.",
    "tools": [
      {
        "type": "code_interpreter",
        "container": { "type": "auto", "memory_limit": "4g" }
      }
    ]
  }'

Containers and Files

OpenAI's hosted tool uses a sandboxed container. In auto mode, the API creates or reuses an active container from prior code_interpreter_call context. In explicit mode, a container is created first and the response references that container ID.

For AvalAI docs and production apps:

  • Treat memory_limit, file_ids, container reuse, explicit /v1/containers creation, and generated file annotations as hosted-tool features that require route verification.
  • OpenAI's documented memory tiers are 1g by default, plus 4g, 16g, and 64g; higher tiers cost more and apply for the whole container lifetime. Confirm AvalAI availability and pricing before exposing a user-selectable tier.
  • Treat hosted containers as ephemeral. OpenAI containers expire after 20 minutes of inactivity and discard associated data; download required files while the container is active and store durable artifacts in your own system.
  • Do not assume an expired container can be revived. Create a new container and upload the required files again. Container operations such as retrieving metadata or adding/deleting files can refresh activity while the container is still active.
  • Auto-mode containers may still be visible through /v1/containers on routes that expose the hosted container API. Treat that as a hosted feature, not a portable guarantee across every AvalAI model route.
  • Keep user files outside the model until they pass malware, size, type, and policy checks.
  • Log container IDs, file IDs, generated artifact names, and request IDs for support.
  • Do not pass secrets, database credentials, or private tokens into the code environment.

When hosted file support is enabled, files included in the model input may be uploaded to the container automatically. Files generated by Python, such as charts or CSVs, can appear as container_file_citation annotations that include a container_id, file_id, and filename. Parse those annotations to build download links or to copy artifacts into your own storage before the container expires.

For debugging, routes that support the OpenAI-compatible include parameter can request code_interpreter_call.outputs so your app can inspect Python execution output. Redact stdout, stderr, generated files, and tracebacks before showing them to end users or writing them to durable logs.

OpenAI's supported upload list includes source files, office documents, PDFs, CSV/JSON/XML, archives, and common image types. In AvalAI apps, still keep a product-level allowlist instead of accepting every supported MIME type for every workflow.

Data Retention and Artifacts

OpenAI's hosted /v1/responses flow can retain response application state when storage is enabled, while hosted Code Interpreter containers can write temporary state to the container filesystem until the container expires or is deleted. In AvalAI, treat this as a hosted-tool behavior that may vary by route and account:

  • Set store=false for workflows that do not need server-side state, and document any feature that depends on stored response or container state.
  • Copy generated charts, CSVs, logs, and other artifacts into your own storage while the container is active; do not rely on the hosted container as durable storage.
  • Redact secrets and sensitive data before upload, because Python stdout, stderr, tracebacks, generated files, and annotations can become part of tool outputs or logs.
  • If your fallback Python runner calls third-party services, disclose that those services have their own retention policies.

Fallback: App-Managed Python Tool

When hosted Code Interpreter is unavailable, keep execution in your backend and expose a strict function tool. This is often safer in production because you control packages, network access, timeouts, storage, and approvals.

json
{
  "type": "function",
  "name": "run_python_analysis",
  "description": "Run a small approved Python analysis over prevalidated inputs.",
  "parameters": {
    "type": "object",
    "properties": {
      "task": {
        "type": "string",
        "description": "Short description of the analysis to run."
      },
      "code": {
        "type": "string",
        "description": "Python code that uses only approved libraries and input files."
      },
      "allowed_file_ids": {
        "type": "array",
        "items": {
          "type": "string"
        }
      }
    },
    "required": [
      "task",
      "code",
      "allowed_file_ids"
    ],
    "additionalProperties": false
  },
  "strict": true
}

Implementation checklist:

  1. Validate the generated code against an allowlist before execution.
  2. Run in a container with no default network access, short CPU/memory limits, and a clean filesystem.
  3. Mount only approved input files and write outputs to a temporary directory.
  4. Return structured results plus signed artifact URLs instead of raw filesystem paths.
  5. Require human approval for expensive jobs, external writes, or sensitive datasets.

When you expose this fallback through /v1/responses, handle it like any other function tool: read the function_call item, execute the job in your backend, then send a matching function_call_output with the original call_id. Keep stdout, stderr, artifact URLs, and validation errors compact so the model can summarize them without ingesting full logs or raw files.

Security Checklist

  • Use allowlisted packages and block shell escapes, subprocesses, and arbitrary network calls unless explicitly approved.
  • Redact secrets from prompts, files, stdout, stderr, and generated artifacts.
  • Scan uploaded and generated files before storing or serving them.
  • Cap execution time, memory, output size, and artifact count.
  • Store audit logs with user ID, request ID, model, tool arguments, policy decision, and artifact metadata.
  • Treat generated charts, CSVs, and files as untrusted until validated.