OpenAI 代码解释器

2026-11-05 17:58 更新

代码解释器让模型在沙箱中编写并执行Python,处理数据分析、编程和数学等复杂问题。它可处理多种数据和格式的文件,生成数据文件和图表,反复编写、运行和修正代码,也可增强推理模型的视觉处理能力,例如裁剪、缩放、旋转和变换图像。

以下示例通过Responses API启用代码解释器。

来源示例1(bash)

程序中的自然语言译释36:

你是私人数学辅导老师。用户提出数学问题时,使用python工具编写并运行代码回答。

程序中的自然语言译释37:

我需要解方程3x + 11 = 14,能帮我吗?

## [中文] 配置自动代码解释器容器,把数学任务交给模型;工具使用Python在托管容器执行。
curl 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?"
  }'

来源示例2(javascript)

本段复用的中文释义:译释36、译释37。

// [中文] 配置自动代码解释器容器,把数学任务交给模型;工具使用Python在托管容器执行。
import 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));

来源示例3(python)

本段复用的中文释义:译释36、译释37。

## [中文] 配置自动代码解释器容器,把数学任务交给模型;工具使用Python在托管容器执行。
from 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)

来源示例4(go)

本段复用的中文释义:译释36、译释37。

// [中文] 配置自动代码解释器容器,把数学任务交给模型;工具使用Python在托管容器执行。
package 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)
}

来源示例5(java)

程序中的自然语言译释127:

你是私人数学辅导老师,为每个数学问题编写并运行Python代码作答。

本段复用的中文释义:译释37。

// [中文] 配置自动代码解释器容器,把数学任务交给模型;工具使用Python在托管容器执行。
import 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);

来源示例6(ruby)

本段复用的中文释义:译释37、译释127。

## [中文] 配置自动代码解释器容器,把数学任务交给模型;工具使用Python在托管容器执行。
require "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”。模型通常能理解“代码解释器”,但提示词中直接要求使用“python工具”最明确。

容器

工具需要容器对象。容器是模型可执行Python的完整沙箱虚拟机,存放你上传的文件及模型生成的文件。

创建方式有两种:

  1. 自动模式:在创建响应时配置 "container": {"type": "auto", "memory_limit": "4g", "file_ids": ["file-1", "file-2"]}。服务会创建容器,或复用模型上下文中先前 code_interpreter_call 使用的活动容器。省略 memory_limit 时使用默认1GB档位。从输出的 code_interpreter_call 项读取生成或使用的 container_id。
  2. 显式模式:先通过 /v1/containers 创建容器,指定所需 memory_limit,再把返回的 id 作为工具配置中的 container。

来源示例7(bash)

程序中的自然语言译释38:

使用python工具计算4 × 3.82,再对结果开平方,再对所得结果开平方。

## [中文] 先显式创建容器,再将返回的容器ID用于后续代码解释器请求。
curl https://api.openai.com/v1/containers \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
        "name": "My Container",
        "memory_limit": "4g"
      }'

## [中文] 下一次调用使用返回的容器ID。
## 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"
  }'

来源示例8(javascript)

本段复用的中文释义:译释38。

// [中文] 先显式创建容器,再将返回的容器ID用于后续代码解释器请求。
import 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);

来源示例9(python)

本段复用的中文释义:译释38。

## [中文] 先显式创建容器,再将返回的容器ID用于后续代码解释器请求。
from 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)

来源示例10(go)

本段复用的中文释义:译释38。

// [中文] 先显式创建容器,再将返回的容器ID用于后续代码解释器请求。
package 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())
}

来源示例11(java)

程序中的自然语言译释128:

计算4乘3.82,再连续开平方两次。

// [中文] 先显式创建容器,再将返回的容器ID用于后续代码解释器请求。
import 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()));

来源示例12(ruby)

本段复用的中文释义:译释128。

## [中文] 先显式创建容器,再将返回的容器ID用于后续代码解释器请求。
require "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。更高档位提供更多内存,按内置工具费率计费。无论自动还是显式创建,所选内存限制均适用于容器的整个生命周期。自动创建的容器也可通过 /v1/containers 访问。

过期

应将容器视为临时环境,在自己的系统保存需要长期保留的数据。

  • 容器20分钟不使用就会过期。之后再在 /v1/responses 使用会失败。仍可查看过期时的元数据快照,但容器相关数据会被丢弃,无法恢复。需要的文件应在活动期间下载。
  • 过期容器不能恢复为活动状态。应创建新容器并重新上传文件;旧容器的内存状态,如Python对象,也会丢失。
  • 检索容器、增删文件等容器操作都会刷新 last_active_at。

处理文件

模型运行代码时可以在容器中创建文件,例如绘图或CSV。随后消息的 annotations 会引用这些文件。

来源示例13(json):以下保留协议载荷、配置、返回示意或语法定义;省略号及片段不代表完整可运行程序。

{
  "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

使用说明

来源表列出Responses、Chat Completions、Assistants入口,组织级限制为100 RPM,并链接到价格及ZDR与数据驻留。具体请求形式应分别按目标接口核对。

以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号