Code Interpreter を使うと、モデルはサンドボックス環境で Python コードを記述・実行し、データ分析、プログラミング、数学などの分野で複雑な問題を解決できます。次のような用途に使えます。
- さまざまな種類のデータや書式を含むファイルの処理
- データやグラフ画像を含むファイルの生成
- コードの記述と実行を繰り返すことによる問題解決。たとえば、モデルが書いたコードの実行に失敗しても、成功するまで修正と実行を繰り返せます。
gpt-6-astra を使った画像の調査。Code Interpreter は Python を使って、画像の切り抜き、拡大、回転のほか、個々のピクセル値の読み取りも行えます。
次の例では、Responses API を使って Code Interpreter を呼び出します。
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 を指定しても通じますが、最も明確に指定するには「python tool」を使うように指示してください。
Code Interpreter にはコンテナオブジェクトが必要です。コンテナは、モデルが Python コードを実行できる、完全に隔離された仮想マシンです。コンテナには、ユーザーがアップロードしたファイルやモデルが生成したファイルを格納できます。
コンテナは自動で作成することも、明示的に作成することもできます。
- 自動モード:上の例のように、新しい Response オブジェクトの作成時に、ツール設定に
"container": { "type": "auto", "memory_limit": "4g", "file_ids": ["file-1", "file-2"] } プロパティを渡します。これにより、新しいコンテナが自動的に作成されるか、モデルのコンテキスト内の以前の code_interpreter_call 項目で使用されたアクティブなコンテナが再利用されます。memory_limit を省略すると、コンテナのメモリはデフォルトの 1 GB になります。この API リクエストの出力に含まれる code_interpreter_call 項目で、作成または再利用されたコンテナの container_id を確認できます。
- 明示モード:コンテナを明示的に作成するには、
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 の組み込みツール料金が適用されます。コンテナを自動で作成した場合も、コンテナ API で作成した場合も、選択した memory_limit はコンテナの存続期間を通じて適用されます。
自動モードで作成したコンテナにも、/v1/containers エンドポイントからアクセスできます。
コンテナは一時的なものとして扱い、このツールの利用に関するデータはすべてご自身のシステムに保存することを強くおすすめします。有効期限については、次の点に注意してください。
- コンテナを 20 分間使用しないと期限切れになります。その後、
v1/responses でそのコンテナを使用するとリクエストは失敗します。期限切れ時点のメタデータのスナップショットは引き続き確認できますが、コンテナに関連するデータはすべて OpenAI のシステムから破棄され、復元できません。後で必要になる可能性のあるファイルは、コンテナがアクティブなうちにダウンロードしてください。
- 期限切れのコンテナをアクティブな状態に戻すことはできません。新しいコンテナを作成し、ファイルを再度アップロードしてください。以前のコンテナのメモリに保持されていた状態(Python オブジェクトなど)は失われます。
- コンテナの取得やコンテナ内のファイルの追加・削除など、コンテナに対する操作を行うたびに、
last_active_at の時刻が自動的に更新されます。
Code Interpreter の実行中、モデルは自分でファイルを作成できます。たとえば、グラフの描画や CSV の作成を依頼すると、モデルはグラフ画像や 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 |