SPB Git

Repository Public

tools-code-interpreter.md 18.6 KB 459 lines markdown

1# Code Interpreter23> For the complete documentation index, see [llms.txt](/llms.txt). Markdown versions of documentation pages are available by appending `.md` to the page URL.45The Code Interpreter tool allows models to write and run Python code in a sandboxed environment to solve complex problems in domains like data analysis, coding, and math. Use it for:67- Processing files with diverse data and formatting8- Generating files with data and images of graphs9- Writing and running code iteratively to solve problems—for example, a model that writes code that fails to run can keep rewriting and running that code until it succeeds10- Boosting visual intelligence in our latest reasoning models (like [o3](https://developers.openai.com/api/docs/models/o3) and [o4-mini](https://developers.openai.com/api/docs/models/o4-mini)). The model can use this tool to crop, zoom, rotate, and otherwise process and transform images.1112Here's an example of calling the [Responses API](https://developers.openai.com/api/reference/resources/responses) with a tool call to Code Interpreter:1314Use the Responses API with Code Interpreter1516```bash17curl https://api.openai.com/v1/responses \18  -H "Content-Type: application/json" \19  -H "Authorization: Bearer $OPENAI_API_KEY" \20  -d '{21    "model": "gpt-6-astra",22    "tools": [{23      "type": "code_interpreter",24      "container": { "type": "auto", "memory_limit": "4g" }25    }],26    "instructions": "You are a personal math tutor. When asked a math question, write and run code using the python tool to answer the question.",27    "input": "I need to solve the equation 3x + 11 = 14. Can you help me?"28  }'29```3031```javascript32import OpenAI from "openai";33const client = new OpenAI();3435const instructions = `36You are a personal math tutor. When asked a math question,37write and run code using the python tool to answer the question.38`;3940const resp = await client.responses.create({41  model: "gpt-6-astra",42  tools: [43    {44      type: "code_interpreter",45      container: { type: "auto", memory_limit: "4g" },46    },47  ],48  instructions,49  input: "I need to solve the equation 3x + 11 = 14. Can you help me?",50});5152console.log(JSON.stringify(resp.output, null, 2));53```5455```python56from openai import OpenAI5758client = OpenAI()5960instructions = """61You are a personal math tutor. When asked a math question,62write and run code using the python tool to answer the question.63"""6465resp = client.responses.create(66    model="gpt-6-astra",67    tools=[68        {69            "type": "code_interpreter",70            "container": {"type": "auto", "memory_limit": "4g"},71        }72    ],73    instructions=instructions,74    input="I need to solve the equation 3x + 11 = 14. Can you help me?",75)7677print(resp.output)78```7980```go81package main8283import (84	"context"85	"fmt"8687	"github.com/openai/openai-go/v3"88	"github.com/openai/openai-go/v3/responses"89)9091func main() {92	client := openai.NewClient()93	tool := responses.ToolParamOfCodeInterpreter(responses.ToolCodeInterpreterContainerCodeInterpreterContainerAutoParam{MemoryLimit: "4g"})94	response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{95		Model:        "gpt-6-astra",96		Tools:        []responses.ToolUnionParam{tool},97		Instructions: openai.String("You are a personal math tutor. When asked a math question, write and run code using the python tool to answer the question."),98		Input:        responses.ResponseNewParamsInputUnion{OfString: openai.String("I need to solve the equation 3x + 11 = 14. Can you help me?")},99	})100	if err != nil {101		panic(err)102	}103	fmt.Println(response.Output)104}105```106107```java108import com.openai.client.OpenAIClient;109import com.openai.client.okhttp.OpenAIOkHttpClient;110import com.openai.models.responses.ResponseCreateParams;111import com.openai.models.responses.Tool;112113ResponseCreateParams params =114    ResponseCreateParams.builder()115        .model("gpt-6-astra")116        .input("I need to solve the equation 3x + 11 = 14. Can you help me?")117        .instructions(118            "You are a personal math tutor. Write and run Python code to answer each math question.")119        .addCodeInterpreterTool(120            Tool.CodeInterpreter.Container.CodeInterpreterToolAuto.builder()121                .memoryLimit(122                    Tool.CodeInterpreter.Container.CodeInterpreterToolAuto.MemoryLimit._4G)123                .build())124        .build();125126client.responses().create(params).output().forEach(System.out::println);127```128129```ruby130require "openai"131132client = OpenAI::Client.new133134response = client.responses.create(135  model: "gpt-6-astra",136  instructions: "You are a personal math tutor. Write and run Python code to answer each math question.",137  input: "I need to solve the equation 3x + 11 = 14. Can you help me?",138  tools: [139    {140      type: :code_interpreter,141      container: {142        type: :auto,143        memory_limit: "4g"144      }145    }146  ]147)148149puts(response.output)150```151152153While we call this tool Code Interpreter, the model knows it as the "python154  tool". Models usually understand prompts that refer to the code interpreter155  tool, however, the most explicit way to invoke this tool is to ask for "the156  python tool" in your prompts.157158## Containers159160The Code Interpreter tool requires a [container object](https://developers.openai.com/api/reference/resources/containers). A container is a fully sandboxed virtual machine that the model can run Python code in. This container can contain files that you upload, or that it generates.161162There are two ways to create containers:1631641. Auto mode: as seen in the example above, you can do this by passing the `"container": { "type": "auto", "memory_limit": "4g", "file_ids": ["file-1", "file-2"] }` property in the tool configuration while creating a new Response object. This automatically creates a new container, or reuses an active container that was used by a previous `code_interpreter_call` item in the model's context. Leaving out `memory_limit` keeps the default 1 GB tier for the container. Look for the `code_interpreter_call` item in the output of this API request to find the `container_id` that was generated or used.1652. Explicit mode: here, you explicitly [create a container](https://developers.openai.com/api/reference/resources/containers/methods/create) using the `v1/containers` endpoint, including the `memory_limit` you need (for example `"memory_limit": "4g"`), and assign its `id` as the `container` value in the tool configuration in the Response object. For example:166167Use explicit container creation168169```bash170curl https://api.openai.com/v1/containers \171  -H "Authorization: Bearer $OPENAI_API_KEY" \172  -H "Content-Type: application/json" \173  -d '{174        "name": "My Container",175        "memory_limit": "4g"176      }'177178# Use the returned container id in the next call:179curl https://api.openai.com/v1/responses \180  -H "Authorization: Bearer $OPENAI_API_KEY" \181  -H "Content-Type: application/json" \182  -d '{183    "model": "gpt-6-astra",184    "tools": [{185      "type": "code_interpreter",186      "container": "cntr_abc123"187    }],188    "tool_choice": "required",189    "input": "use the python tool to calculate what is 4 * 3.82. and then find its square root and then find the square root of that result"190  }'191```192193```javascript194import OpenAI from "openai";195const client = new OpenAI();196197const container = await client.containers.create({198  name: "test-container",199  memory_limit: "4g",200});201202const resp = await client.responses.create({203  model: "gpt-6-astra",204  tools: [205    {206      type: "code_interpreter",207      container: container.id,208    },209  ],210  tool_choice: "required",211  input:212    "use the python tool to calculate what is 4 * 3.82. and then find its square root and then find the square root of that result",213});214215console.log(resp.output_text);216```217218```python219from openai import OpenAI220221client = OpenAI()222223container = client.containers.create(name="test-container", memory_limit="4g")224225response = client.responses.create(226    model="gpt-6-astra",227    tools=[{"type": "code_interpreter", "container": container.id}],228    tool_choice="required",229    input="use the python tool to calculate what is 4 * 3.82. and then find its square root and then find the square root of that result",230)231232print(response.output_text)233```234235```go236package main237238import (239	"context"240	"fmt"241242	"github.com/openai/openai-go/v3"243	"github.com/openai/openai-go/v3/responses"244)245246func main() {247	client := openai.NewClient()248	container, err := client.Containers.New(context.Background(), openai.ContainerNewParams{249		Name:        "test-container",250		MemoryLimit: openai.ContainerNewParamsMemoryLimit4g,251	})252	if err != nil {253		panic(err)254	}255	defer func() {256		if err := client.Containers.Delete(context.Background(), container.ID); err != nil {257			panic(err)258		}259	}()260261	response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{262		Model:      "gpt-6-astra",263		Tools:      []responses.ToolUnionParam{responses.ToolParamOfCodeInterpreter(container.ID)},264		ToolChoice: responses.ResponseNewParamsToolChoiceUnion{OfToolChoiceMode: openai.Opt(responses.ToolChoiceOptionsRequired)},265		Input:      responses.ResponseNewParamsInputUnion{OfString: openai.String("use the python tool to calculate what is 4 * 3.82. and then find its square root and then find the square root of that result")},266	})267	if err != nil {268		panic(err)269	}270	fmt.Println(response.OutputText())271}272```273274```java275import com.openai.client.OpenAIClient;276import com.openai.client.okhttp.OpenAIOkHttpClient;277import com.openai.models.containers.ContainerCreateParams;278import com.openai.models.responses.ResponseCreateParams;279import com.openai.models.responses.ToolChoiceOptions;280281var container =282    client283        .containers()284        .create(285            ContainerCreateParams.builder()286                .name("analysis")287                .memoryLimit(ContainerCreateParams.MemoryLimit._4G)288                .build());289290var response =291    client292        .responses()293        .create(294            ResponseCreateParams.builder()295                .model("gpt-6-astra")296                .input("Calculate 4 * 3.82, then take the square root twice.")297                .toolChoice(ToolChoiceOptions.REQUIRED)298                .addCodeInterpreterTool(container.id())299                .build());300301response.output().stream()302    .flatMap(item -> item.message().stream())303    .flatMap(message -> message.content().stream())304    .flatMap(content -> content.outputText().stream())305    .forEach(text -> System.out.println(text.text()));306```307308```ruby309require "openai"310311client = OpenAI::Client.new312container = client.containers.create(name: "analysis", memory_limit: "4g")313response = client.responses.create(314  model: "gpt-6-astra",315  tools: [316    {317      type: :code_interpreter,318      container: container.id319    }320  ],321  tool_choice: :required,322  input: "Calculate 4 * 3.82, then take the square root twice."323)324puts(response.output_text)325```326327328You can choose from `1g` (default), `4g`, `16g`, or `64g`. Higher tiers offer more RAM for the session and are billed at the [built-in tools rates](https://developers.openai.com/api/docs/pricing#built-in-tools) for Code Interpreter. The selected `memory_limit` applies for the entire life of that container, whether it was created automatically or via the containers API.329330Note that containers created with the auto mode are also accessible using the [`/v1/containers`](https://developers.openai.com/api/reference/resources/containers) endpoint.331332### Expiration333334We highly recommend you treat containers as ephemeral and store all data related to the use of this tool on your own systems. Expiration details:335336- A container expires if it is not used for 20 minutes. When this happens, using the container in `v1/responses` will fail. You'll still be able to see a snapshot of the container's metadata at its expiry, but all data associated with the container will be discarded from our systems and not recoverable. You should download any files you may need from the container while it is active.337- You can't move a container from an expired state to an active one. Instead, create a new container and upload files again. Note that any state in the old container's memory (like python objects) will be lost.338- Any container operation, like retrieving the container, or adding or deleting files from the container, will automatically refresh the container's `last_active_at` time.339340## Work with files341342When running Code Interpreter, the model can create its own files. For example, if you ask it to construct a plot, or create a CSV, it creates these images directly on your container. When it does so, it cites these files in the `annotations` of its next message. Here's an example:343344```json345{346  "id": "msg_682d514e268c8191a89c38ea318446200f2610a7ec781a4f",347  "content": [348    {349      "annotations": [350        {351          "file_id": "cfile_682d514b2e00819184b9b07e13557f82",352          "index": null,353          "type": "container_file_citation",354          "container_id": "cntr_682d513bb0c48191b10bd4f8b0b3312200e64562acc2e0af",355          "end_index": 0,356          "filename": "cfile_682d514b2e00819184b9b07e13557f82.png",357          "start_index": 0358        }359      ],360      "text": "Here is the histogram of the RGB channels for the uploaded image. Each curve represents the distribution of pixel intensities for the red, green, and blue channels. Peaks toward the high end of the intensity scale (right-hand side) suggest a lot of brightness and strong warm tones, matching the orange and light background in the image. If you want a different style of histogram (e.g., overall intensity, or quantized color groups), let me know!",361      "type": "output_text",362      "logprobs": []363    }364  ],365  "role": "assistant",366  "status": "completed",367  "type": "message"368}369```370371You can download these constructed files by calling the [get container file content](https://developers.openai.com/api/reference/resources/containers/subresources/files/subresources/content/methods/retrieve) method.372373Any [files in the model input](https://developers.openai.com/api/docs/guides/file-inputs) get automatically uploaded to the container. You do not have to explicitly upload it to the container.374375### Uploading and downloading files376377Add new files to your container using [Create container file](https://developers.openai.com/api/reference/resources/containers/subresources/files/methods/create). This endpoint accepts either a multipart upload or a JSON body with a `file_id`.378List existing container files with [List container files](https://developers.openai.com/api/reference/resources/containers/subresources/files/methods/list) and download bytes from [Retrieve container file content](https://developers.openai.com/api/reference/resources/containers/subresources/files/subresources/content/methods/retrieve).379380### Dealing with citations381382Files and images generated by the model are returned as annotations on the assistant's message. `container_file_citation` annotations point to files created in the container. They include the `container_id`, `file_id`, and `filename`. You can parse these annotations to surface download links or otherwise process the files.383384### Supported files385386| File format | MIME type                                                                   |387| ----------- | --------------------------------------------------------------------------- |388| `.c`        | `text/x-c`                                                                  |389| `.cs`       | `text/x-csharp`                                                             |390| `.cpp`      | `text/x-c++`                                                                |391| `.csv`      | `text/csv`                                                                  |392| `.doc`      | `application/msword`                                                        |393| `.docx`     | `application/vnd.openxmlformats-officedocument.wordprocessingml.document`   |394| `.html`     | `text/html`                                                                 |395| `.java`     | `text/x-java`                                                               |396| `.json`     | `application/json`                                                          |397| `.md`       | `text/markdown`                                                             |398| `.pdf`      | `application/pdf`                                                           |399| `.php`      | `text/x-php`                                                                |400| `.pptx`     | `application/vnd.openxmlformats-officedocument.presentationml.presentation` |401| `.py`       | `text/x-python`                                                             |402| `.py`       | `text/x-script.python`                                                      |403| `.rb`       | `text/x-ruby`                                                               |404| `.tex`      | `text/x-tex`                                                                |405| `.txt`      | `text/plain`                                                                |406| `.css`      | `text/css`                                                                  |407| `.js`       | `text/javascript`                                                           |408| `.sh`       | `application/x-sh`                                                          |409| `.ts`       | `application/typescript`                                                    |410| `.csv`      | `application/csv`                                                           |411| `.jpeg`     | `image/jpeg`                                                                |412| `.jpg`      | `image/jpeg`                                                                |413| `.gif`      | `image/gif`                                                                 |414| `.pkl`      | `application/octet-stream`                                                  |415| `.png`      | `image/png`                                                                 |416| `.tar`      | `application/x-tar`                                                         |417| `.xlsx`     | `application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`         |418| `.xml`      | `application/xml or "text/xml"`                                             |419| `.zip`      | `application/zip`                                                           |420421## Usage notes422423<table>424<tbody>425426<tr>427  <th>API Availability</th>428  <th>Rate limits</th>429  <th>Notes</th>430</tr>431432<tr>433  <td>434    435436      [Responses](https://developers.openai.com/api/reference/resources/responses)437    438439    440441      [Chat Completions](https://developers.openai.com/api/reference/resources/chat)442    443444    445446      [Assistants](https://developers.openai.com/api/reference/resources/beta/subresources/assistants)447    448449  </td>450  <td style={{ maxWidth: "150px" }}>100 RPM per org</td>451  <td style={{ maxWidth: "150px" }}>452    [Pricing](https://developers.openai.com/api/docs/pricing#built-in-tools) 453454    [ZDR and data residency](https://developers.openai.com/api/docs/guides/your-data)455  </td>456</tr>457458</tbody>459</table>
Files main
Menu

Theme