程式碼解譯器讓模型在沙盒環境中編寫並執行 Python 程式碼,解決資料分析、程式設計和數學等領域的複雜問題。你可以用它來:
- 處理資料內容和格式各異的檔案
- 產生包含資料和圖表影像的檔案
- 反覆編寫並執行程式碼來解決問題。例如,如果模型寫的程式碼執行失敗,模型可以持續修改並重新執行,直到成功為止。
- 使用
gpt-6-astra 檢視影像。程式碼解譯器可以使用 Python 裁切、縮放或旋轉影像,也可以讀取個別像素的值。
以下範例示範如何透過 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)
我們稱這項工具為「程式碼解譯器」,模型則以「python tool」這個名稱識別它。模型通常能理解提示詞中提到的「程式碼解譯器」。要明確指定這項工具,最直接的方式是在提示詞中要求使用「the python tool」。
程式碼解譯器需要容器物件。容器是完全隔離的沙盒虛擬機器,模型可以在其中執行 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")。接著,在 Response 物件的工具設定中,將該容器的 id 設為 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。較高的級別會為工作階段提供更多記憶體,費用依程式碼解譯器的內建工具費率計算。無論容器是自動建立還是透過容器 API 建立,所選的 memory_limit 都會在容器的整個生命週期內生效。
透過自動模式建立的容器也可以使用 /v1/containers 端點存取。
我們強烈建議將容器視為暫時性環境,並將使用這項工具時涉及的所有資料儲存在自己的系統中。容器到期規則如下:
- 容器連續 20 分鐘未使用就會到期。此後,任何在
v1/responses 中使用該容器的請求都會失敗。你仍可查看容器到期時的中繼資料快照,但我們的系統會捨棄與容器相關的所有資料,且無法復原。請在容器仍有效時下載可能需要的檔案。
- 已到期的容器無法重新啟用。請建立新容器並重新上傳檔案。舊容器記憶體中的所有狀態(例如 Python 物件)都會遺失。
- 對容器執行任何操作,例如取得容器資訊,或在容器中新增或刪除檔案,都會自動更新容器的
last_active_at 時間。
使用程式碼解譯器時,模型可以自行建立檔案。例如,如果你要求模型繪製圖表或建立 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 |