Code Interpreter ツールを使うと、モデルがサンドボックス環境で Python コードを作成・実行し、データ分析、コーディング、数学などの分野の複雑な問題を解決できます。次のような用途に利用できます。
- 多様なデータや書式を含むファイルの処理
- データやグラフ画像を含むファイルの生成
- コードの作成と実行を繰り返すことによる問題解決。たとえば、モデルが作成したコードの実行に失敗した場合、成功するまでコードの修正と実行を繰り返すことが可能
- 最新のリーズニングモデル(o3 や o4-mini など)の視覚的な理解能力の向上。モデルはこのツールを使って、画像の切り抜き、拡大・縮小、回転などの処理や変換を行えます。
Code Interpreter へのツール呼び出しを含めて Responses API を呼び出す例を示します。
1
2
3
4
5
6
7
8
9
10
11
12curl https://api.openai.com/v1/responses \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-d '{
"model": "gpt-6-astra",
"tools": [{
"type": "code_interpreter",
"container": { "type": "auto", "memory_limit": "4g" }
}],
"instructions": "You are a personal math tutor. When asked a math question, write and run code using the python tool to answer the question.",
"input": "I need to solve the equation 3x + 11 = 14. Can you help me?"
}'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21import OpenAI from "openai";
const client = new OpenAI();
const instructions = `
You are a personal math tutor. When asked a math question,
write and run code using the python tool to answer the question.
`;
const resp = await client.responses.create({
model: "gpt-6-astra",
tools: [
{
type: "code_interpreter",
container: { type: "auto", memory_limit: "4g" },
},
],
instructions,
input: "I need to solve the equation 3x + 11 = 14. Can you help me?",
});
console.log(JSON.stringify(resp.output, null, 2));
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22from openai import OpenAI
client = OpenAI()
instructions = """
You are a personal math tutor. When asked a math question,
write and run code using the python tool to answer the question.
"""
resp = client.responses.create(
model="gpt-6-astra",
tools=[
{
"type": "code_interpreter",
"container": {"type": "auto", "memory_limit": "4g"},
}
],
instructions=instructions,
input="I need to solve the equation 3x + 11 = 14. Can you help me?",
)
print(resp.output)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24package main
import (
"context"
"fmt"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/responses"
)
func main() {
client := openai.NewClient()
tool := responses.ToolParamOfCodeInterpreter(responses.ToolCodeInterpreterContainerCodeInterpreterContainerAutoParam{MemoryLimit: "4g"})
response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
Model: "gpt-6-astra",
Tools: []responses.ToolUnionParam{tool},
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."),
Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("I need to solve the equation 3x + 11 = 14. Can you help me?")},
})
if err != nil {
panic(err)
}
fmt.Println(response.Output)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.Tool;
ResponseCreateParams params =
ResponseCreateParams.builder()
.model("gpt-6-astra")
.input("I need to solve the equation 3x + 11 = 14. Can you help me?")
.instructions(
"You are a personal math tutor. Write and run Python code to answer each math question.")
.addCodeInterpreterTool(
Tool.CodeInterpreter.Container.CodeInterpreterToolAuto.builder()
.memoryLimit(
Tool.CodeInterpreter.Container.CodeInterpreterToolAuto.MemoryLimit._4G)
.build())
.build();
client.responses().create(params).output().forEach(System.out::println);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20require "openai"
client = OpenAI::Client.new
response = client.responses.create(
model: "gpt-6-astra",
instructions: "You are a personal math tutor. Write and run Python code to answer each math question.",
input: "I need to solve the equation 3x + 11 = 14. Can you help me?",
tools: [
{
type: :code_interpreter,
container: {
type: :auto,
memory_limit: "4g"
}
}
]
)
puts(response.output)
このツールは Code Interpreter という名称ですが、モデルは「python tool」として認識しています。通常、プロンプトで Code Interpreter ツールに言及してもモデルは理解しますが、最も明確に呼び出すには、プロンプトで「the python tool」を使うように指定します。
Code Interpreter ツールには、コンテナオブジェクトが必要です。コンテナは、モデルが Python コードを実行できる、完全にサンドボックス化された仮想マシンです。アップロードしたファイルやモデルが生成したファイルを格納できます。
コンテナを作成する方法は 2 つあります。
- 自動モード:上の例のように、新しい Response オブジェクトを作成する際、ツール構成に
"container": { "type": "auto", "memory_limit": "4g", "file_ids": ["file-1", "file-2"] } プロパティを渡します。これにより、新しいコンテナが自動的に作成されるか、モデルのコンテキスト内にある以前の code_interpreter_call 項目で使用されたアクティブなコンテナが再利用されます。memory_limit を省略すると、コンテナにはデフォルトの 1 GB の階層が適用されます。生成または使用された container_id は、この API リクエストの出力に含まれる code_interpreter_call 項目で確認できます。
- 明示的モード:
v1/containers エンドポイントで、必要な memory_limit(たとえば "memory_limit": "4g")を指定して明示的にコンテナを作成します。その id を、Response オブジェクト内のツール構成の container 値に設定します。次に例を示します。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21curl https://api.openai.com/v1/containers \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"name": "My Container",
"memory_limit": "4g"
}'
# Use the returned container id in the next call:
curl https://api.openai.com/v1/responses \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-6-astra",
"tools": [{
"type": "code_interpreter",
"container": "cntr_abc123"
}],
"tool_choice": "required",
"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"
}'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22import OpenAI from "openai";
const client = new OpenAI();
const container = await client.containers.create({
name: "test-container",
memory_limit: "4g",
});
const resp = await client.responses.create({
model: "gpt-6-astra",
tools: [
{
type: "code_interpreter",
container: container.id,
},
],
tool_choice: "required",
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",
});
console.log(resp.output_text);
1
2
3
4
5
6
7
8
9
10
11
12
13
14from openai import OpenAI
client = OpenAI()
container = client.containers.create(name="test-container", memory_limit="4g")
response = client.responses.create(
model="gpt-6-astra",
tools=[{"type": "code_interpreter", "container": container.id}],
tool_choice="required",
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",
)
print(response.output_text)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36package main
import (
"context"
"fmt"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/responses"
)
func main() {
client := openai.NewClient()
container, err := client.Containers.New(context.Background(), openai.ContainerNewParams{
Name: "test-container",
MemoryLimit: openai.ContainerNewParamsMemoryLimit4g,
})
if err != nil {
panic(err)
}
defer func() {
if err := client.Containers.Delete(context.Background(), container.ID); err != nil {
panic(err)
}
}()
response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
Model: "gpt-6-astra",
Tools: []responses.ToolUnionParam{responses.ToolParamOfCodeInterpreter(container.ID)},
ToolChoice: responses.ResponseNewParamsToolChoiceUnion{OfToolChoiceMode: openai.Opt(responses.ToolChoiceOptionsRequired)},
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")},
})
if err != nil {
panic(err)
}
fmt.Println(response.OutputText())
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.containers.ContainerCreateParams;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ToolChoiceOptions;
var container =
client
.containers()
.create(
ContainerCreateParams.builder()
.name("analysis")
.memoryLimit(ContainerCreateParams.MemoryLimit._4G)
.build());
var response =
client
.responses()
.create(
ResponseCreateParams.builder()
.model("gpt-6-astra")
.input("Calculate 4 * 3.82, then take the square root twice.")
.toolChoice(ToolChoiceOptions.REQUIRED)
.addCodeInterpreterTool(container.id())
.build());
response.output().stream()
.flatMap(item -> item.message().stream())
.flatMap(message -> message.content().stream())
.flatMap(content -> content.outputText().stream())
.forEach(text -> System.out.println(text.text()));
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16require "openai"
client = OpenAI::Client.new
container = client.containers.create(name: "analysis", memory_limit: "4g")
response = client.responses.create(
model: "gpt-6-astra",
tools: [
{
type: :code_interpreter,
container: container.id
}
],
tool_choice: :required,
input: "Calculate 4 * 3.82, then take the square root twice."
)
puts(response.output_text)
1g(デフォルト)、4g、16g、64g から選択できます。上位の階層ではセッションで使える RAM が増え、Code Interpreter の組み込みツール料金に基づいて課金されます。選択した memory_limit は、自動作成か containers API 経由の作成かにかかわらず、そのコンテナの存続期間全体に適用されます。
自動モードで作成されたコンテナにも、/v1/containers エンドポイントでアクセスできます。
コンテナは一時的なものとして扱い、このツールの使用に関するすべてのデータをご自身のシステムに保存することを強く推奨します。有効期限の詳細は次のとおりです。
- コンテナは 20 分間使用されないと有効期限が切れます。その後、
v1/responses でそのコンテナを使用しようとすると失敗します。有効期限が切れた時点のコンテナのメタデータのスナップショットは引き続き確認できますが、コンテナに関連するすべてのデータは OpenAI のシステムから破棄され、復元できなくなります。必要になる可能性があるファイルは、コンテナがアクティブな間にダウンロードしてください。
- 有効期限が切れたコンテナをアクティブな状態に戻すことはできません。新しいコンテナを作成し、ファイルを再度アップロードしてください。古いコンテナのメモリ内にあった状態(Python オブジェクトなど)はすべて失われます。
- コンテナの取得や、コンテナ内のファイルの追加・削除など、コンテナに対する操作を行うと、そのコンテナの
last_active_at の時刻が自動的に更新されます。
Code Interpreter の実行中、モデルは自らファイルを作成できます。たとえば、グラフの描画や CSV の作成を依頼すると、コンテナ内にこれらの画像が直接作成されます。作成したファイルは、モデルの次のメッセージの annotations で引用されます。次に例を示します。
123456789101112131415161718192021222324{
"id": "msg_682d514e268c8191a89c38ea318446200f2610a7ec781a4f",
"content": [
{
"annotations": [
{
"file_id": "cfile_682d514b2e00819184b9b07e13557f82",
"index": null,
"type": "container_file_citation",
"container_id": "cntr_682d513bb0c48191b10bd4f8b0b3312200e64562acc2e0af",
"end_index": 0,
"filename": "cfile_682d514b2e00819184b9b07e13557f82.png",
"start_index": 0
}
],
"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!",
"type": "output_text",
"logprobs": []
}
],
"role": "assistant",
"status": "completed",
"type": "message"
}
作成されたファイルは、コンテナファイルの内容を取得するメソッドを呼び出すことでダウンロードできます。
モデルへの入力に含まれるファイルは、すべてコンテナに自動的にアップロードされます。コンテナに明示的にアップロードする必要はありません。
コンテナファイルを作成するエンドポイントで、コンテナに新しいファイルを追加します。このエンドポイントは、マルチパートアップロード、または file_id を含む JSON 本文を受け付けます。
コンテナファイルの一覧を取得するエンドポイントで既存のファイルを確認し、コンテナファイルの内容を取得するエンドポイントでバイトデータをダウンロードできます。
モデルが生成したファイルや画像は、アシスタントのメッセージに付加されるアノテーションとして返されます。container_file_citation アノテーションはコンテナ内で作成されたファイルを参照し、container_id、file_id、filename を含みます。これらのアノテーションを解析してダウンロードリンクを表示したり、ファイルにその他の処理を行ったりできます。
| ファイル形式 | MIME タイプ |
|---|
.c | text/x-c |
.cs | text/x-csharp |
.cpp | text/x-c++ |
.csv | text/csv |
.doc | application/msword |
.docx | application/vnd.openxmlformats-officedocument.wordprocessingml.document |
.html | text/html |
.java | text/x-java |
.json | application/json |
.md | text/markdown |
.pdf | application/pdf |
.php | text/x-php |
.pptx | application/vnd.openxmlformats-officedocument.presentationml.presentation |
.py | text/x-python |
.py | text/x-script.python |
.rb | text/x-ruby |
.tex | text/x-tex |
.txt | text/plain |
.css | text/css |
.js | text/javascript |
.sh | application/x-sh |
.ts | application/typescript |
.csv | application/csv |
.jpeg | image/jpeg |
.jpg | image/jpeg |
.gif | image/gif |
.pkl | application/octet-stream |
.png | image/png |
.tar | application/x-tar |
.xlsx | application/vnd.openxmlformats-officedocument.spreadsheetml.sheet |
.xml | application/xml or "text/xml" |
.zip | application/zip |