代码解释器让模型在沙盒环境中编写并运行 Python 代码,解决数据分析、编程和数学等领域的复杂问题。您可以用它来:
- 处理数据类型和格式各异的文件
- 生成包含数据和图表图像的文件
- 反复编写并运行代码来解决问题。例如,如果模型编写的代码运行失败,模型可以继续修改并重新运行代码,直到运行成功
- 使用
gpt-6.2-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.2-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.2-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.2-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.2-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.2-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.2-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 工具”。模型通常能理解提到代码解释器的提示,但最明确的调用方式是在提示中要求模型使用“Python 工具”。
代码解释器需要一个容器对象。容器是完全隔离的沙盒虚拟机,模型可以在其中运行 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.2-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.2-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.2-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.2-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.2-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.2-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 文件,模型会直接在您的容器中生成相应的图像或文件,并在下一条消息的 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"
}
您可以调用获取容器文件内容方法,下载这些生成的文件。
模型输入中的所有文件都会自动上传到容器,无需您单独上传。
使用创建容器文件端点向容器添加新文件。此端点支持 multipart 表单上传,也接受包含 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 |