assistants/tools/code-interpreter.md +0 −615 deleted
File Deleted View Diff
1# Assistants Code Interpreter
2
3> For the complete documentation index, see [llms.txt](/llms.txt). Markdown versions of documentation pages are available by appending `.md` to the page URL.
4
5After achieving feature parity in the Responses API, we've deprecated the Assistants API. It will shut down on August 26, 2026. Follow the [migration guide](https://developers.openai.com/platform/assistants/migration) to update your integration. [Learn more](https://platform.openai.com/docs/guides/migrate-to-responses).
6
7## Overview
8
9Code Interpreter allows Assistants to write and run Python code in a sandboxed execution environment. This tool can process files with diverse data and formatting, and generate files with data and images of graphs. Code Interpreter allows your Assistant to run code iteratively to solve challenging code and math problems. When your Assistant writes code that fails to run, it can iterate on this code by attempting to run different code until the code execution succeeds.
10
11See a quickstart of how to get started with Code Interpreter [here](https://developers.openai.com/api/docs/assistants/migration#step-1-create-an-assistant?context=with-streaming).
12
13## How it works
14
15Code Interpreter is charged at $0.03 per session. If your Assistant calls Code Interpreter simultaneously in two different threads (e.g., one thread per end-user), two Code Interpreter sessions are created. Each session is active by default for one hour, which means that you only pay for one session per if users interact with Code Interpreter in the same thread for up to one hour.
16
17### Enabling Code Interpreter
18
19Pass `code_interpreter` in the `tools` parameter of the Assistant object to enable Code Interpreter:
20
21```javascript
22const assistant = await openai.beta.assistants.create({
23 instructions:
24 "You are a personal math tutor. When asked a math question, write and run code to answer the question.",
25 model: "gpt-4o",
26 tools: [{ type: "code_interpreter" }],
27});
28```
29
30```python
31assistant = client.beta.assistants.create(
32 instructions="You are a personal math tutor. When asked a math question, write and run code to answer the question.",
33 model="gpt-4o",
34 tools=[{"type": "code_interpreter"}],
35)
36```
37
38```go
39assistant, err := client.Beta.Assistants.New(context.Background(), openai.BetaAssistantNewParams{
40 Instructions: openai.String("You are a personal math tutor. When asked a math question, write and run code to answer the question."),
41 Model: shared.ChatModelGPT4o,
42 Tools: []openai.AssistantToolUnionParam{{OfCodeInterpreter: &openai.CodeInterpreterToolParam{}}},
43})
44if err != nil {
45 panic(err)
46}
47```
48
49```java
50import com.openai.client.OpenAIClient;
51import com.openai.client.okhttp.OpenAIOkHttpClient;
52import com.openai.models.beta.assistants.AssistantCreateParams;
53import com.openai.models.beta.assistants.CodeInterpreterTool;
54
55var assistant =
56 client
57 .beta()
58 .assistants()
59 .create(
60 AssistantCreateParams.builder()
61 .model("gpt-4o")
62 .instructions(
63 "You are a personal math tutor. When asked a math question, write and run"
64 + " code to answer the question.")
65 .addTool(CodeInterpreterTool.builder().build())
66 .build());
67
68System.out.println(assistant.id());
69```
70
71```ruby
72require "openai"
73
74client = OpenAI::Client.new
75assistant = client.beta.assistants.create(
76 model: "gpt-4o",
77 tools: [{type: :code_interpreter}]
78)
79puts(assistant.id)
80```
81
82```bash
83curl https://api.openai.com/v1/assistants \
84 -u :$OPENAI_API_KEY \
85 -H 'Content-Type: application/json' \
86 -H 'OpenAI-Beta: assistants=v2' \
87 -d '{
88 "instructions": "You are a personal math tutor. When asked a math question, write and run code to answer the question.",
89 "tools": [
90 { "type": "code_interpreter" }
91 ],
92 "model": "gpt-4o"
93 }'
94```
95
96
97The model then decides when to invoke Code Interpreter in a Run based on the nature of the user request. This behavior can be promoted by prompting in the Assistant's `instructions` (e.g., “write code to solve this problem”).
98
99### Passing files to Code Interpreter
100
101Files that are passed at the Assistant level are accessible by all Runs with this Assistant:
102
103```javascript
104// Upload a file with an "assistants" purpose
105const file = await openai.files.create({
106 file: fs.createReadStream("mydata.csv"),
107 purpose: "assistants",
108});
109
110// Create an assistant using the file ID
111const assistant = await openai.beta.assistants.create({
112 instructions:
113 "You are a personal math tutor. When asked a math question, write and run code to answer the question.",
114 model: "gpt-4o",
115 tools: [{ type: "code_interpreter" }],
116 tool_resources: {
117 code_interpreter: {
118 file_ids: [file.id],
119 },
120 },
121});
122```
123
124```python
125# Upload a file with an "assistants" purpose
126file = client.files.create(file=open("mydata.csv", "rb"), purpose="assistants")
127
128# Create an assistant using the file ID
129assistant = client.beta.assistants.create(
130 instructions="You are a personal math tutor. When asked a math question, write and run code to answer the question.",
131 model="gpt-4o",
132 tools=[{"type": "code_interpreter"}],
133 tool_resources={"code_interpreter": {"file_ids": [file.id]}},
134)
135```
136
137```go
138input, err := os.Open("mydata.csv")
139if err != nil {
140 panic(err)
141}
142defer input.Close()
143file, err := client.Files.New(context.Background(), openai.FileNewParams{
144 File: input,
145 Purpose: openai.FilePurposeAssistants,
146})
147if err != nil {
148 panic(err)
149}
150assistant, err := client.Beta.Assistants.New(context.Background(), openai.BetaAssistantNewParams{
151 Instructions: openai.String("You are a personal math tutor. When asked a math question, write and run code to answer the question."),
152 Model: shared.ChatModelGPT4o,
153 Tools: []openai.AssistantToolUnionParam{{OfCodeInterpreter: &openai.CodeInterpreterToolParam{}}},
154 ToolResources: openai.BetaAssistantNewParamsToolResources{
155 CodeInterpreter: openai.BetaAssistantNewParamsToolResourcesCodeInterpreter{FileIDs: []string{file.ID}},
156 },
157})
158if err != nil {
159 panic(err)
160}
161```
162
163```java
164import com.openai.client.OpenAIClient;
165import com.openai.client.okhttp.OpenAIOkHttpClient;
166import com.openai.models.beta.assistants.AssistantCreateParams;
167import com.openai.models.beta.assistants.CodeInterpreterTool;
168import com.openai.models.files.FileCreateParams;
169import com.openai.models.files.FilePurpose;
170import java.nio.file.Path;
171
172var file =
173 client
174 .files()
175 .create(
176 FileCreateParams.builder()
177 .file(Path.of(System.getenv("OPENAI_EXAMPLE_FILE_PATH")))
178 .purpose(FilePurpose.ASSISTANTS)
179 .build());
180var assistant =
181 client
182 .beta()
183 .assistants()
184 .create(
185 AssistantCreateParams.builder()
186 .model("gpt-4o")
187 .instructions("When asked a math question, write and run code to answer it.")
188 .addTool(CodeInterpreterTool.builder().build())
189 .toolResources(
190 AssistantCreateParams.ToolResources.builder()
191 .codeInterpreter(
192 AssistantCreateParams.ToolResources.CodeInterpreter.builder()
193 .addFileId(file.id())
194 .build())
195 .build())
196 .build());
197System.out.println(assistant.id());
198```
199
200```ruby
201require "openai"
202require "pathname"
203
204client = OpenAI::Client.new
205file = client.files.create(
206 file: Pathname("revenue-forecast.csv"),
207 purpose: :assistants
208)
209assistant = client.beta.assistants.create(
210 model: "gpt-4o",
211 instructions: "When asked a math question, write and run code to answer it.",
212 tools: [{type: :code_interpreter}],
213 tool_resources: {
214 code_interpreter: {file_ids: [file.id]}
215 }
216)
217puts(assistant.id)
218```
219
220```bash
221# Upload a file with an "assistants" purpose
222curl https://api.openai.com/v1/files \
223 -H "Authorization: Bearer $OPENAI_API_KEY" \
224 -F purpose="assistants" \
225 -F file="@/path/to/mydata.csv"
226
227# Create an assistant using the file ID
228curl https://api.openai.com/v1/assistants \
229 -u :$OPENAI_API_KEY \
230 -H 'Content-Type: application/json' \
231 -H 'OpenAI-Beta: assistants=v2' \
232 -d '{
233 "instructions": "You are a personal math tutor. When asked a math question, write and run code to answer the question.",
234 "tools": [{"type": "code_interpreter"}],
235 "model": "gpt-4o",
236 "tool_resources": {
237 "code_interpreter": {
238 "file_ids": ["file-BK7bzQj3FfZFXr7DbL6xJwfo"]
239 }
240 }
241 }'
242```
243
244
245Files can also be passed at the Thread level. These files are only accessible in the specific Thread. Upload the File using the [File upload](https://developers.openai.com/api/reference/resources/files/methods/create) endpoint and then pass the File ID as part of the Message creation request:
246
247```javascript
248const thread = await openai.beta.threads.create({
249 messages: [
250 {
251 role: "user",
252 content: "I need to solve the equation `3x + 11 = 14`. Can you help me?",
253 attachments: [
254 {
255 file_id: file.id,
256 tools: [{ type: "code_interpreter" }],
257 },
258 ],
259 },
260 ],
261});
262```
263
264```python
265thread = client.beta.threads.create(
266 messages=[
267 {
268 "role": "user",
269 "content": "I need to solve the equation `3x + 11 = 14`. Can you help me?",
270 "attachments": [
271 {"file_id": file.id, "tools": [{"type": "code_interpreter"}]}
272 ],
273 }
274 ]
275)
276```
277
278```go
279thread, err := client.Beta.Threads.New(context.Background(), openai.BetaThreadNewParams{
280 Messages: []openai.BetaThreadNewParamsMessage{{
281 Role: "user",
282 Content: openai.BetaThreadNewParamsMessageContentUnion{OfString: openai.String("I need to solve the equation `3x + 11 = 14`. Can you help me?")},
283 Attachments: []openai.BetaThreadNewParamsMessageAttachment{{
284 FileID: openai.String("file-ACq8OjcLQm2eIG0BvRM4z5qX"),
285 Tools: []openai.BetaThreadNewParamsMessageAttachmentToolUnion{{OfCodeInterpreter: &openai.CodeInterpreterToolParam{}}},
286 }},
287 }},
288})
289if err != nil {
290 panic(err)
291}
292```
293
294```java
295import com.openai.client.OpenAIClient;
296import com.openai.client.okhttp.OpenAIOkHttpClient;
297import com.openai.models.beta.assistants.CodeInterpreterTool;
298import com.openai.models.beta.threads.ThreadCreateParams;
299
300String fileId = "file-ACq8OjcLQm2eIG0BvRM4z5qX";
301
302var thread =
303 client
304 .beta()
305 .threads()
306 .create(
307 ThreadCreateParams.builder()
308 .addMessage(
309 ThreadCreateParams.Message.builder()
310 .role(ThreadCreateParams.Message.Role.USER)
311 .content(
312 "I need to solve the equation `3x + 11 = 14`. Can you help me?")
313 .addAttachment(
314 ThreadCreateParams.Message.Attachment.builder()
315 .fileId(fileId)
316 .addTool(CodeInterpreterTool.builder().build())
317 .build())
318 .build())
319 .build());
320
321System.out.println(thread.id());
322```
323
324```ruby
325require "openai"
326
327client = OpenAI::Client.new
328thread = client.beta.threads.create(
329 messages: [{
330 role: :user,
331 content: "I need to solve the equation `3x + 11 = 14`. Can you help me?",
332 attachments: [{
333 file_id: "file-ACq8OjcLQm2eIG0BvRM4z5qX",
334 tools: [{type: :code_interpreter}]
335 }]
336 }]
337)
338puts(thread.id)
339```
340
341```bash
342curl https://api.openai.com/v1/threads/thread_abc123/messages \
343 -u :$OPENAI_API_KEY \
344 -H 'Content-Type: application/json' \
345 -H 'OpenAI-Beta: assistants=v2' \
346 -d '{
347 "role": "user",
348 "content": "I need to solve the equation `3x + 11 = 14`. Can you help me?",
349 "attachments": [
350 {
351 "file_id": "file-ACq8OjcLQm2eIG0BvRM4z5qX",
352 "tools": [{"type": "code_interpreter"}]
353 }
354 ]
355 }'
356```
357
358
359Files have a maximum size of 512 MB. Code Interpreter supports a variety of file formats including `.csv`, `.pdf`, `.json` and many more. More details on the file extensions (and their corresponding MIME-types) supported can be found in the [Supported files](#supported-files) section below.
360
361### Reading images and files generated by Code Interpreter
362
363Code Interpreter in the API also outputs files, such as generating image diagrams, CSVs, and PDFs. There are two types of files that are generated:
364
3651. Images
3662. Data files (e.g. a `csv` file with data generated by the Assistant)
367
368When Code Interpreter generates an image, you can look up and download this file in the `file_id` field of the Assistant Message response:
369
370```json
371{
372 "id": "msg_abc123",
373 "object": "thread.message",
374 "created_at": 1698964262,
375 "thread_id": "thread_abc123",
376 "role": "assistant",
377 "content": [
378 {
379 "type": "image_file",
380 "image_file": {
381 "file_id": "file-abc123"
382 }
383 }
384 ]
385 # ...
386}
387```
388
389The file content can then be downloaded by passing the file ID to the Files API:
390
391```javascript
392import fs from "fs";
393import OpenAI from "openai";
394
395const openai = new OpenAI();
396
397async function main() {
398 const response = await openai.files.content("file-abc123");
399
400 // Extract the binary data from the Response object
401 const image_data = await response.arrayBuffer();
402
403 // Convert the binary data to a Buffer
404 const image_data_buffer = Buffer.from(image_data);
405
406 // Save the image to a specific location
407 fs.writeFileSync("./my-image.png", image_data_buffer);
408}
409
410main();
411```
412
413```python
414import os
415
416from openai import OpenAI
417
418file_id = os.environ["OPENAI_FILE_ID"]
419client = OpenAI()
420
421image_data = client.files.content(file_id)
422image_data_bytes = image_data.read()
423
424with open("./my-image.png", "wb") as file:
425 file.write(image_data_bytes)
426```
427
428```go
429response, err := client.Files.Content(context.Background(), "file-abc123")
430if err != nil {
431 panic(err)
432}
433defer response.Body.Close()
434output, err := os.Create("./my-image.png")
435if err != nil {
436 panic(err)
437}
438if _, err := io.Copy(output, response.Body); err != nil {
439 output.Close()
440 panic(err)
441}
442if err := output.Close(); err != nil {
443 panic(err)
444}
445```
446
447```java
448import com.openai.client.OpenAIClient;
449import com.openai.client.okhttp.OpenAIOkHttpClient;
450import com.openai.core.http.HttpResponse;
451import java.io.IOException;
452import java.nio.file.Files;
453import java.nio.file.Path;
454import java.nio.file.StandardCopyOption;
455
456String fileId = "file-abc123";
457
458try (HttpResponse content = client.files().content(fileId)) {
459 Files.copy(content.body(), Path.of("my-image.png"), StandardCopyOption.REPLACE_EXISTING);
460}
461```
462
463```ruby
464require "openai"
465
466client = OpenAI::Client.new
467image = client.files.content("file-abc123")
468File.binwrite("my-image.png", image.read)
469```
470
471```bash
472curl https://api.openai.com/v1/files/file-abc123/content \
473 -H "Authorization: Bearer $OPENAI_API_KEY" \
474 --output image.png
475```
476
477
478When Code Interpreter references a file path (e.g., ”Download this csv file”), file paths are listed as annotations. You can convert these annotations into links to download the file:
479
480```json
481{
482 "id": "msg_abc123",
483 "object": "thread.message",
484 "created_at": 1699073585,
485 "thread_id": "thread_abc123",
486 "role": "assistant",
487 "content": [
488 {
489 "type": "text",
490 "text": {
491 "value": "The rows of the CSV file have been shuffled and saved to a new CSV file. You can download the shuffled CSV file from the following link:\\n\\n[Download Shuffled CSV File](sandbox:/mnt/data/shuffled_file.csv)",
492 "annotations": [
493 {
494 "type": "file_path",
495 "text": "sandbox:/mnt/data/shuffled_file.csv",
496 "start_index": 167,
497 "end_index": 202,
498 "file_path": {
499 "file_id": "file-abc123"
500 }
501 }
502 ...
503```
504
505### Input and output logs of Code Interpreter
506
507By listing the steps of a Run that called Code Interpreter, you can inspect the code `input` and `outputs` logs of Code Interpreter:
508
509```javascript
510const runSteps = await openai.beta.threads.runs.steps.list(run.id, {
511 thread_id: thread.id,
512});
513```
514
515```python
516import os
517
518thread_id = os.environ["OPENAI_THREAD_ID"]
519run_id = os.environ["OPENAI_RUN_ID"]
520
521run_steps = client.beta.threads.runs.steps.list(
522 thread_id=thread_id,
523 run_id=run_id,
524)
525```
526
527```go
528runSteps, err := client.Beta.Threads.Runs.Steps.List(context.Background(), "thread_abc123", "run_abc123", openai.BetaThreadRunStepListParams{})
529if err != nil {
530 panic(err)
531}
532fmt.Println(runSteps.Data)
533```
534
535```ruby
536require "openai"
537
538client = OpenAI::Client.new
539steps = client.beta.threads.runs.steps.list(
540 "run_abc123",
541 thread_id: "thread_abc123"
542)
543puts(steps.data)
544```
545
546```bash
547curl https://api.openai.com/v1/threads/thread_abc123/runs/RUN_ID/steps \
548 -H "Authorization: Bearer $OPENAI_API_KEY" \
549 -H "OpenAI-Beta: assistants=v2" \
550```
551
552
553```bash
554{
555 "object": "list",
556 "data": [
557 {
558 "id": "step_abc123",
559 "object": "thread.run.step",
560 "type": "tool_calls",
561 "run_id": "run_abc123",
562 "thread_id": "thread_abc123",
563 "status": "completed",
564 "step_details": {
565 "type": "tool_calls",
566 "tool_calls": [
567 {
568 "type": "code",
569 "code": {
570 "input": "# Calculating 2 + 2\\nresult = 2 + 2\\nresult",
571 "outputs": [
572 {
573 "type": "logs",
574 "logs": "4"
575 }
576 ...
577 }
578```
579
580## Supported files
581
582| File format | MIME type |
583| ----------- | --------------------------------------------------------------------------- |
584| `.c` | `text/x-c` |
585| `.cs` | `text/x-csharp` |
586| `.cpp` | `text/x-c++` |
587| `.csv` | `text/csv` |
588| `.doc` | `application/msword` |
589| `.docx` | `application/vnd.openxmlformats-officedocument.wordprocessingml.document` |
590| `.html` | `text/html` |
591| `.java` | `text/x-java` |
592| `.json` | `application/json` |
593| `.md` | `text/markdown` |
594| `.pdf` | `application/pdf` |
595| `.php` | `text/x-php` |
596| `.pptx` | `application/vnd.openxmlformats-officedocument.presentationml.presentation` |
597| `.py` | `text/x-python` |
598| `.py` | `text/x-script.python` |
599| `.rb` | `text/x-ruby` |
600| `.tex` | `text/x-tex` |
601| `.txt` | `text/plain` |
602| `.css` | `text/css` |
603| `.js` | `text/javascript` |
604| `.sh` | `application/x-sh` |
605| `.ts` | `application/typescript` |
606| `.csv` | `application/csv` |
607| `.jpeg` | `image/jpeg` |
608| `.jpg` | `image/jpeg` |
609| `.gif` | `image/gif` |
610| `.pkl` | `application/octet-stream` |
611| `.png` | `image/png` |
612| `.tar` | `application/x-tar` |
613| `.xlsx` | `application/vnd.openxmlformats-officedocument.spreadsheetml.sheet` |
614| `.xml` | `application/xml or "text/xml"` |
615| `.zip` | `application/zip` |