codecamp

OpenAI Shell

Shell工具让模型使用完整终端环境,支持Responses API中的本地执行和托管执行。可以采用OpenAI管理的托管容器,也可以采用自己托管并执行的本地运行时。不支持Chat Completions API。

任意命令执行具有风险。应始终使用沙箱,尽可能使用允许或拒绝列表,并记录工具活动供审计。

托管Shell快速开始

托管Shell适合计算、多媒体处理等需要更丰富、确定性处理的任务。希望OpenAI为请求创建并管理容器时,使用 container_auto。

来源示例1(bash)

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

执行列出/mnt/data详细文件清单并显示Python和Node版本的命令。

## [中文] 配置container_auto,让托管Shell运行请求中的终端任务。
curl -L 'https://api.openai.com/v1/responses' \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "model": "gpt-6-astra",
    "tools": [
      { "type": "shell", "environment": { "type": "container_auto" } }
    ],
    "input": [
      {
        "type": "message",
        "role": "user",
        "content": [
          { "type": "input_text", "text": "Execute: ls -lah /mnt/data && python --version && node --version" }
        ]
      }
    ],
    "tool_choice": "auto"
  }'

来源示例2(javascript)

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

// [中文] 配置container_auto,让托管Shell运行请求中的终端任务。
import OpenAI from "openai";

const client = new OpenAI();

const response = await client.responses.create({
  model: "gpt-6-astra",
  tools: [{ type: "shell", environment: { type: "container_auto" } }],
  input: [
    {
      type: "message",
      role: "user",
      content: [
        {
          type: "input_text",
          text: "Execute: ls -lah /mnt/data && python --version && node --version",
        },
      ],
    },
  ],
  tool_choice: "auto",
});

console.log(response.output_text);

来源示例3(python)

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

## [中文] 配置container_auto,让托管Shell运行请求中的终端任务。
from openai import OpenAI

client = OpenAI()

response = client.responses.create(
    model="gpt-6-astra",
    tools=[{"type": "shell", "environment": {"type": "container_auto"}}],
    input=[
        {
            "type": "message",
            "role": "user",
            "content": [
                {
                    "type": "input_text",
                    "text": "Execute: ls -lah /mnt/data && python --version && node --version",
                }
            ],
        }
    ],
    tool_choice="auto",
)

print(response.output_text)

来源示例4(go)

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

// [中文] 配置container_auto,让托管Shell运行请求中的终端任务。
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.ToolUnionParam{OfShell: &responses.FunctionShellToolParam{
        Environment: responses.FunctionShellToolEnvironmentUnionParam{OfContainerAuto: &responses.ContainerAutoParam{}},
    }}
    response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
        Model: "gpt-6-astra",
        Tools: []responses.ToolUnionParam{tool},
        Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Execute: ls -lah /mnt/data && python --version && node --version")},
    })
    if err != nil {
        panic(err)
    }
    fmt.Println(response.OutputText())
}

来源示例5(java)

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

列出/mnt/data详细文件清单,再显示Python及Node.js版本。

// [中文] 配置container_auto,让托管Shell运行请求中的终端任务。
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.ContainerAuto;
import com.openai.models.responses.FunctionShellTool;
import com.openai.models.responses.ResponseCreateParams;

ResponseCreateParams params =
    ResponseCreateParams.builder()
        .model("gpt-6-astra")
        .input("Run ls -lah /mnt/data, then show the Python and Node.js versions.")
        .addTool(
            FunctionShellTool.builder().environment(ContainerAuto.builder().build()).build())
        .build();

client.responses().create(params).output().stream()
    .flatMap(item -> item.message().stream())
    .flatMap(message -> message.content().stream())
    .flatMap(content -> content.outputText().stream())
    .forEach(text -> System.out.println(text.text()));

来源示例6(ruby)

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

## [中文] 配置container_auto,让托管Shell运行请求中的终端任务。
require "openai"

client = OpenAI::Client.new
response = client.responses.create(
  model: "gpt-6-astra",
  input: "Run ls -lah /mnt/data, then show the Python and Node.js versions.",
  tools: [
    {
      type: :shell,
      environment: { type: :container_auto }
    }
  ]
)

puts(response.output_text)

托管运行时详情

  • 当前基于Debian 12,未来可能变化。
  • 默认工作目录 /mnt/data 始终存在,也是面向用户提供可下载制品的受支持路径。
  • 不支持交互式TTY会话。
  • 命令不使用 sudo 运行。
  • 工作流需要时,可以在容器内运行服务。

当前预装语言:Python 3.11、Node.js 22.16、Java 17.0、PHP 8.2、Ruby 3.1、Go 1.23。

跨请求复用容器

迭代任务需要长期运行环境时,先创建容器,再在后续Responses请求中引用。

1. 创建容器

来源示例7(bash)

## [中文] 创建可复用容器,后续调用需使用返回的ID。
curl -L 'https://api.openai.com/v1/containers' \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "name": "analysis-container",
    "memory_limit": "1g",
    "expires_after": { "anchor": "last_active_at", "minutes": 20 }
  }'

来源示例8(javascript)

// [中文] 创建可复用容器,后续调用需使用返回的ID。
import OpenAI from "openai";

const client = new OpenAI();

const container = await client.containers.create({
  name: "analysis-container",
  memory_limit: "1g",
  expires_after: { anchor: "last_active_at", minutes: 20 },
});

console.log(container.id);

来源示例9(python)

## [中文] 创建可复用容器,后续调用需使用返回的ID。
from openai import OpenAI

client = OpenAI()

container = client.containers.create(
    name="analysis-container",
    memory_limit="1g",
    expires_after={"anchor": "last_active_at", "minutes": 20},
)

print(container.id)

来源示例10(go)

// [中文] 创建可复用容器,后续调用需使用返回的ID。
package main

import (
    "context"
    "fmt"

    "github.com/openai/openai-go/v3"
)

func main() {
    client := openai.NewClient()
    container, err := client.Containers.New(context.Background(), openai.ContainerNewParams{
        Name:        "analysis-container",
        MemoryLimit: openai.ContainerNewParamsMemoryLimit1g,
        ExpiresAfter: openai.ContainerNewParamsExpiresAfter{
            Anchor:  "last_active_at",
            Minutes: 20,
        },
    })
    if err != nil {
        panic(err)
    }
    fmt.Println(container.ID)
}

来源示例11(java)

// [中文] 创建可复用容器,后续调用需使用返回的ID。
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.containers.ContainerCreateParams;

var container =
    client
        .containers()
        .create(
            ContainerCreateParams.builder()
                .name("analysis")
                .expiresAfter(
                    ContainerCreateParams.ExpiresAfter.builder()
                        .anchor(ContainerCreateParams.ExpiresAfter.Anchor.LAST_ACTIVE_AT)
                        .minutes(20)
                        .build())
                .build());

System.out.println(container.id());

来源示例12(ruby)

## [中文] 创建可复用容器,后续调用需使用返回的ID。
require "openai"

client = OpenAI::Client.new
container = client.containers.create(
  name: "analysis", expires_after: {
    anchor: :last_active_at,
    minutes: 20
  }
)
puts(container.id)

2. 在Responses中引用容器

使用 container_reference:

来源示例13(bash)

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

列出容器文件并显示磁盘用量。

## [中文] 以container_reference复用已有容器并提交文件与磁盘任务。
curl -L 'https://api.openai.com/v1/responses' \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "model": "gpt-6-astra",
    "tools": [
      {
        "type": "shell",
        "environment": {
          "type": "container_reference",
          "container_id": "cntr_08f3d96c87a585390069118b594f7481a088b16cda7d9415fe"
        }
      }
    ],
    "input": "List files in the container and show disk usage."
  }'

来源示例14(javascript)

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

// [中文] 以container_reference复用已有容器并提交文件与磁盘任务。
import OpenAI from "openai";

const client = new OpenAI();

const response = await client.responses.create({
  model: "gpt-6-astra",
  tools: [
    {
      type: "shell",
      environment: {
        type: "container_reference",
        container_id: "cntr_08f3d96c87a585390069118b594f7481a088b16cda7d9415fe",
      },
    },
  ],
  input: "List files in the container and show disk usage.",
});

console.log(response.output_text);

来源示例15(python)

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

## [中文] 以container_reference复用已有容器并提交文件与磁盘任务。
response = client.responses.create(
    model="gpt-6-astra",
    tools=[
        {
            "type": "shell",
            "environment": {
                "type": "container_reference",
                "container_id": container.id,
            },
        }
    ],
    input="List files in the container and show disk usage.",
)

print(response.output_text)

来源示例16(go)

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

// [中文] 以container_reference复用已有容器并提交文件与磁盘任务。
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.ToolUnionParam{OfShell: &responses.FunctionShellToolParam{
        Environment: responses.FunctionShellToolEnvironmentUnionParam{OfContainerReference: &responses.ContainerReferenceParam{ContainerID: "cntr_08f3d96c87a585390069118b594f7481a088b16cda7d9415fe"}},
    }}
    response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
        Model: "gpt-6-astra",
        Tools: []responses.ToolUnionParam{tool},
        Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("List files in the container and show disk usage.")},
    })
    if err != nil {
        panic(err)
    }
    fmt.Println(response.OutputText())
}

来源示例17(java)

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

// [中文] 以container_reference复用已有容器并提交文件与磁盘任务。
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.FunctionShellTool;
import com.openai.models.responses.ResponseCreateParams;

String containerId = "cntr_08f3d96c87a585390069118b594f7481a088b16cda7d9415fe";

ResponseCreateParams params =
    ResponseCreateParams.builder()
        .model("gpt-6-astra")
        .input("List files in the container and show disk usage.")
        .addTool(FunctionShellTool.builder().containerReferenceEnvironment(containerId).build())
        .build();

client.responses().create(params).output().stream()
    .flatMap(item -> item.message().stream())
    .flatMap(message -> message.content().stream())
    .flatMap(content -> content.outputText().stream())
    .forEach(text -> System.out.println(text.text()));

来源示例18(ruby)

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

## [中文] 以container_reference复用已有容器并提交文件与磁盘任务。
require "openai"

client = OpenAI::Client.new
response = client.responses.create(
  model: "gpt-6-astra",
  input: "List files in the container and show disk usage.",
  tools: [
    {
      type: :shell,
      environment: {
        type: :container_reference,
        container_id: "cntr_08f3d96c87a585390069118b594f7481a088b16cda7d9415fe"
      }
    }
  ]
)

puts(response.output_text)

挂载技能

技能是可复用、带版本的包,可挂载到托管Shell环境。挂载定义可用技能,模型在执行时决定是否使用。上传和版本管理参见技能。

创建附带技能的容器:

来源示例19(bash)

## [中文] 在容器环境挂载带版本的技能引用。
curl -L 'https://api.openai.com/v1/containers' \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "name": "skill-container",
    "skills": [
      { "type": "skill_reference", "skill_id": "skill_4db6f1a2c9e73508b41f9da06e2c7b5f" },
      { "type": "skill_reference", "skill_id": "openai-spreadsheets", "version": "latest" }
    ]
  }'

来源示例20(javascript)

// [中文] 在容器环境挂载带版本的技能引用。
import OpenAI from "openai";

const client = new OpenAI();

const container = await client.containers.create({
  name: "skill-container",
  skills: [
    {
      type: "skill_reference",
      skill_id: "skill_4db6f1a2c9e73508b41f9da06e2c7b5f",
    },
    {
      type: "skill_reference",
      skill_id: "openai-spreadsheets",
      version: "latest",
    },
  ],
});

console.log(container.id);

来源示例21(python)

## [中文] 在容器环境挂载带版本的技能引用。
## [中文] 将示意ID和URL替换成自己的资源值。
## 把下方示例 ID 和 URL 换成你自己的资源值。
from openai import OpenAI

client = OpenAI()
skill_id = "skill_123"

container = client.containers.create(
    name="skill-container",
    skills=[
        {
            "type": "skill_reference",
            "skill_id": skill_id,
        },
        {
            "type": "skill_reference",
            "skill_id": "openai-spreadsheets",
            "version": "latest",
        },
    ],
)

print(container.id)

来源示例22(go)

// [中文] 在容器环境挂载带版本的技能引用。
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: "skill-container",
        Skills: []openai.ContainerNewParamsSkillUnion{
            {OfSkillReference: &responses.SkillReferenceParam{SkillID: "skill_4db6f1a2c9e73508b41f9da06e2c7b5f"}},
            {OfSkillReference: &responses.SkillReferenceParam{SkillID: "openai-spreadsheets", Version: openai.String("latest")}},
        },
    })
    if err != nil {
        panic(err)
    }
    fmt.Println(container.ID)
}

来源示例23(java)

// [中文] 在容器环境挂载带版本的技能引用。
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.containers.ContainerCreateParams;
import com.openai.models.responses.SkillReference;

String skillId = "skill_4db6f1a2c9e73508b41f9da06e2c7b5f";

var container =
    client
        .containers()
        .create(
            ContainerCreateParams.builder()
                .name("skill-container")
                .addSkill(SkillReference.builder().skillId(skillId).build())
                .addSkill(
                    SkillReference.builder()
                        .skillId("openai-spreadsheets")
                        .version("latest")
                        .build())
                .build());

System.out.println(container.id());

来源示例24(ruby)

## [中文] 在容器环境挂载带版本的技能引用。
require "openai"

client = OpenAI::Client.new
container = client.containers.create(
  name: "skill-container",
  skills: [
    {
      type: :skill_reference,
      skill_id: "skill_4db6f1a2c9e73508b41f9da06e2c7b5f"
    },
    {
      type: :skill_reference,
      skill_id: "openai-spreadsheets",
      version: "latest"
    }
  ]
)

puts(container.id)

网络访问

托管容器默认不能访问外部网络。启用需同时满足:管理员在控制台配置组织允许列表;请求在容器环境中显式设置 network_policy。

来源示例25(bash)

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

在容器安装httpx和beautifulsoup4,获取发行页面,并写入/mnt/data/release_digest.md。

## [中文] 通过network_policy限制联网目标;请求范围仍须在组织允许列表内。
curl -L 'https://api.openai.com/v1/responses' \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-6-astra",
    "tool_choice": "required",
    "tools": [
      {
        "type": "shell",
        "environment": {
          "type": "container_auto",
          "network_policy": {
            "type": "allowlist",
            "allowed_domains": ["pypi.org", "files.pythonhosted.org", "github.com"]
          }
        }
      }
    ],
    "input": [
      {
        "role": "user",
        "content": "In the container, pip install httpx beautifulsoup4, fetch release pages, and write /mnt/data/release_digest.md."
      }
    ]
  }'

来源示例26(javascript)

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

// [中文] 通过network_policy限制联网目标;请求范围仍须在组织允许列表内。
import OpenAI from "openai";

const client = new OpenAI();

const response = await client.responses.create({
  model: "gpt-6-astra",
  tool_choice: "required",
  tools: [
    {
      type: "shell",
      environment: {
        type: "container_auto",
        network_policy: {
          type: "allowlist",
          allowed_domains: ["pypi.org", "files.pythonhosted.org", "github.com"],
        },
      },
    },
  ],
  input: [
    {
      role: "user",
      content:
        "In the container, pip install httpx beautifulsoup4, fetch release pages, and write /mnt/data/release_digest.md.",
    },
  ],
});

console.log(response.output_text);

来源示例27(python)

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

## [中文] 通过network_policy限制联网目标;请求范围仍须在组织允许列表内。
from openai import OpenAI

client = OpenAI()

response = client.responses.create(
    model="gpt-6-astra",
    tool_choice="required",
    tools=[
        {
            "type": "shell",
            "environment": {
                "type": "container_auto",
                "network_policy": {
                    "type": "allowlist",
                    "allowed_domains": [
                        "pypi.org",
                        "files.pythonhosted.org",
                        "github.com",
                    ],
                },
            },
        }
    ],
    input=[
        {
            "role": "user",
            "content": "In the container, pip install httpx beautifulsoup4, fetch release pages, and write /mnt/data/release_digest.md.",
        }
    ],
)

print(response.output_text)

来源示例28(go)

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

// [中文] 通过network_policy限制联网目标;请求范围仍须在组织允许列表内。
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.ToolUnionParam{OfShell: &responses.FunctionShellToolParam{
        Environment: responses.FunctionShellToolEnvironmentUnionParam{OfContainerAuto: &responses.ContainerAutoParam{
            NetworkPolicy: responses.ContainerAutoNetworkPolicyUnionParam{OfAllowlist: &responses.ContainerNetworkPolicyAllowlistParam{
                AllowedDomains: []string{"pypi.org", "files.pythonhosted.org", "github.com"},
            }},
        }},
    }}
    response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
        Model:      "gpt-6-astra",
        ToolChoice: responses.ResponseNewParamsToolChoiceUnion{OfToolChoiceMode: openai.Opt(responses.ToolChoiceOptionsRequired)},
        Tools:      []responses.ToolUnionParam{tool},
        Input:      responses.ResponseNewParamsInputUnion{OfString: openai.String("In the container, pip install httpx beautifulsoup4, fetch release pages, and write /mnt/data/release_digest.md.")},
    })
    if err != nil {
        panic(err)
    }
    fmt.Println(response.OutputText())
}

来源示例29(java)

// [中文] 通过network_policy限制联网目标;请求范围仍须在组织允许列表内。
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.ContainerAuto;
import com.openai.models.responses.ContainerNetworkPolicyAllowlist;
import com.openai.models.responses.FunctionShellTool;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ToolChoiceOptions;

ResponseCreateParams params =
    ResponseCreateParams.builder()
        .model("gpt-6-astra")
        .input("Fetch release pages and write /mnt/data/release_digest.md.")
        .toolChoice(ToolChoiceOptions.REQUIRED)
        .addTool(
            FunctionShellTool.builder()
                .environment(
                    ContainerAuto.builder()
                        .networkPolicy(
                            ContainerNetworkPolicyAllowlist.builder()
                                .addAllowedDomain("pypi.org")
                                .addAllowedDomain("files.pythonhosted.org")
                                .addAllowedDomain("github.com")
                                .build())
                        .build())
                .build())
        .build();

client.responses().create(params).output().stream()
    .flatMap(item -> item.message().stream())
    .flatMap(message -> message.content().stream())
    .flatMap(content -> content.outputText().stream())
    .forEach(text -> System.out.println(text.text()));

来源示例30(ruby)

## [中文] 通过network_policy限制联网目标;请求范围仍须在组织允许列表内。
require "openai"

client = OpenAI::Client.new
response = client.responses.create(
  model: "gpt-6-astra",
  input: "Fetch release pages and write /mnt/data/release_digest.md.",
  tool_choice: :required,
  tools: [
    {
      type: :shell,
      environment: {
        type: :container_auto,
        network_policy: {
          type: :allowlist,
          allowed_domains: ["pypi.org", "files.pythonhosted.org", "github.com"]
        }
      }
    }
  ]
)

puts(response.output_text)

域名允许列表会引入提示注入导致数据外传等风险。只允许可信且不会被攻击者用来接收外传数据的域名,并核对风险与安全。

网络策略的优先级

组织允许列表定义完整的 allowed_domains 范围,请求级 network_policy 进一步收窄访问。请求若包含组织列表以外的域名会失败。

数据保留与容器生命周期

托管Shell及代码解释器可以在活动容器的临时文件系统中写应用状态,其底层为临时块存储。容器过期或显式删除时,容器数据随之删除。详见ZDR与数据驻留。

下载制品

托管Shell可生成下载文件。通过与代码解释器相同的容器和文件API,取回 /mnt/data 下的制品。

其他数据控制

希望内容和文件只存在于托管生命周期中,可在请求内联文件,并在容器挂载内联技能。

来源示例31(bash)

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

汇总CSV文件并生成Markdown报告。

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

使用csv-insights技能汇总report.csv。

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

技能描述:汇总CSV文件。技能正文:读取CSV并生成包含总计的Markdown报告。name等技能标识保持不变。

## [中文] 内联文件及技能并请求报告,避免另建长期文件或技能资源。
INLINE_ZIP=$(base64 -i ./csv_insights.zip)
REPORT_CSV=$(base64 -i ./report.csv)

CONTAINER_ID=$(
  curl -sL 'https://api.openai.com/v1/containers' \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $OPENAI_API_KEY" \
    -d '{
      "name": "inline-skill-container",
      "skills": [
        {
          "type": "inline",
          "name": "csv-insights",
          "description": "Summarize CSV files and produce a markdown report.",
          "source": {
            "type": "base64",
            "media_type": "application/zip",
            "data": "'"$INLINE_ZIP"'"
          }
        }
      ]
    }' | jq -r '.id'
)

curl -L 'https://api.openai.com/v1/responses' \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "model": "gpt-6-astra",
    "tools": [
      {
        "type": "shell",
        "environment": {
          "type": "container_reference",
          "container_id": "'"$CONTAINER_ID"'"
        }
      }
    ],
    "input": [
      {
        "role": "user",
        "content": [
          {
            "type": "input_file",
            "filename": "report.csv",
            "file_data": "data:text/csv;base64,'"${REPORT_CSV}"'"
          },
          {
            "type": "input_text",
            "text": "Use the csv-insights skill to summarize report.csv."
          }
        ]
      }
    ]
  }'

来源示例32(javascript)

本段复用的中文释义:译释82、译释83、译释108。

// [中文] 内联文件及技能并请求报告,避免另建长期文件或技能资源。
import fs from "fs";
import OpenAI from "openai";

const client = new OpenAI();

const inlineZip = fs
  .readFileSync("fixtures/csv_insights.zip")
  .toString("base64");
const reportCsv = fs.readFileSync("fixtures/report.csv").toString("base64");

const container = await client.containers.create({
  name: "inline-skill-container",
  skills: [
    {
      type: "inline",
      name: "csv-insights",
      description: "Summarize CSV files and produce a markdown report.",
      source: {
        type: "base64",
        media_type: "application/zip",
        data: inlineZip,
      },
    },
  ],
});

const response = await client.responses.create({
  model: "gpt-6-astra",
  tools: [
    {
      type: "shell",
      environment: {
        type: "container_reference",
        container_id: container.id,
      },
    },
  ],
  input: [
    {
      role: "user",
      content: [
        {
          type: "input_file",
          filename: "report.csv",
          file_data: `data:text/csv;base64,${reportCsv}`,
        },
        {
          type: "input_text",
          text: "Use the csv-insights skill to summarize report.csv.",
        },
      ],
    },
  ],
});

console.log(response.output_text);

来源示例33(python)

本段复用的中文释义:译释82、译释83、译释108。

## [中文] 内联文件及技能并请求报告,避免另建长期文件或技能资源。
import base64
from openai import OpenAI

client = OpenAI()

with open("csv_insights.zip", "rb") as f:
    inline_zip = base64.b64encode(f.read()).decode("utf-8")

with open("report.csv", "rb") as f:
    base64_string = base64.b64encode(f.read()).decode("utf-8")

container = client.containers.create(
    name="inline-skill-container",
    skills=[
        {
            "type": "inline",
            "name": "csv-insights",
            "description": "Summarize CSV files and produce a markdown report.",
            "source": {
                "type": "base64",
                "media_type": "application/zip",
                "data": inline_zip,
            },
        }
    ],
)

response = client.responses.create(
    model="gpt-6-astra",
    tools=[
        {
            "type": "shell",
            "environment": {
                "type": "container_reference",
                "container_id": container.id,
            },
        }
    ],
    input=[
        {
            "role": "user",
            "content": [
                {
                    "type": "input_file",
                    "filename": "report.csv",
                    "file_data": f"data:text/csv;base64,{base64_string}",
                },
                {
                    "type": "input_text",
                    "text": "Use the csv-insights skill to summarize report.csv.",
                },
            ],
        }
    ],
)

print(response.output_text)

来源示例34(go)

本段复用的中文释义:译释83、译释108。

// [中文] 内联文件及技能并请求报告,避免另建长期文件或技能资源。
var bundle bytes.Buffer
archive := zip.NewWriter(&bundle)
file, err := archive.Create("csv-insights/SKILL.md")
if err != nil {
    log.Fatal(err)
}
if _, err := file.Write([]byte("---\nname: csv-insights\ndescription: Summarize CSV files.\n---\nRead the CSV and produce a Markdown report of totals.\n")); err != nil {
    log.Fatal(err)
}
if err := archive.Close(); err != nil {
    log.Fatal(err)
}
client := openai.NewClient()
inlineZip := base64.StdEncoding.EncodeToString(bundle.Bytes())
reportCSV := base64.StdEncoding.EncodeToString([]byte("product,revenue\nA,120\nB,80\n"))
container, err := client.Containers.New(context.Background(), openai.ContainerNewParams{
    Name: "inline-skill-container",
    Skills: []openai.ContainerNewParamsSkillUnion{
        {
            OfInline: &responses.InlineSkillParam{
                Name:        "csv-insights",
                Description: "Summarize CSV files.",
                Source: responses.InlineSkillSourceParam{
                    Data: inlineZip,
                },
            },
        },
    },
})
if err != nil {
    log.Fatal(err)
}
response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
    Model: "gpt-6-astra",
    Tools: []responses.ToolUnionParam{
        {
            OfShell: &responses.FunctionShellToolParam{
                Environment: responses.FunctionShellToolEnvironmentUnionParam{
                    OfContainerReference: &responses.ContainerReferenceParam{
                        ContainerID: container.ID,
                    },
                },
            },
        },
    },
    Input: responses.ResponseNewParamsInputUnion{
        OfInputItemList: []responses.ResponseInputItemUnionParam{
            {
                OfMessage: &responses.EasyInputMessageParam{
                    Role: responses.EasyInputMessageRoleUser,
                    Content: responses.EasyInputMessageContentUnionParam{
                        OfInputItemContentList: []responses.ResponseInputContentUnionParam{
                            {
                                OfInputFile: &responses.ResponseInputFileParam{
                                    Filename: openai.String("report.csv"),
                                    FileData: openai.String("data:text/csv;base64," + reportCSV),
                                },
                            },
                            {
                                OfInputText: &responses.ResponseInputTextParam{
                                    Text: "Use the csv-insights skill to summarize report.csv.",
                                },
                            },
                        },
                    },
                },
            },
        },
    },
})
if err != nil {
    log.Fatal(err)
}
if response.Status != responses.ResponseStatusCompleted {
    log.Fatalf("Response ended with status %s", response.Status)
}
fmt.Println(response.OutputText())

来源示例35(java)

本段复用的中文释义:译释82、译释83、译释108。

// [中文] 内联文件及技能并请求报告,避免另建长期文件或技能资源。
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.containers.ContainerCreateParams;
import com.openai.models.responses.*;
import java.util.*;

var bundle = new java.io.ByteArrayOutputStream();
try (var zip = new java.util.zip.ZipOutputStream(bundle)) {
  zip.putNextEntry(new java.util.zip.ZipEntry("csv-insights/SKILL.md"));
  zip.write(
      "---\nname: csv-insights\ndescription: Summarize CSV files.\n---\nRead the CSV and produce a Markdown report of totals.\n"
          .getBytes(java.nio.charset.StandardCharsets.UTF_8));
  zip.closeEntry();
}
var client = OpenAIOkHttpClient.fromEnv();

var inlineZip = Base64.getEncoder().encodeToString(bundle.toByteArray());
var reportCsv =
    Base64.getEncoder()
        .encodeToString(
            "product,revenue\nA,120\nB,80\n".getBytes(java.nio.charset.StandardCharsets.UTF_8));
var container =
    client
        .containers()
        .create(
            ContainerCreateParams.builder()
                .name("inline-skill-container")
                .addSkill(
                    InlineSkill.builder()
                        .name("csv-insights")
                        .description("Summarize CSV files and produce a markdown report.")
                        .source(InlineSkillSource.builder().data(inlineZip).build())
                        .build())
                .build());
var response =
    client
        .responses()
        .create(
            ResponseCreateParams.builder()
                .model("gpt-6-astra")
                .addTool(
                    FunctionShellTool.builder()
                        .containerReferenceEnvironment(container.id())
                        .build())
                .inputOfResponse(
                    List.of(
                        ResponseInputItem.ofMessage(
                            ResponseInputItem.Message.builder()
                                .role(ResponseInputItem.Message.Role.USER)
                                .addContent(
                                    ResponseInputFile.builder()
                                        .filename("report.csv")
                                        .fileData("data:text/csv;base64," + reportCsv)
                                        .build())
                                .addInputTextContent(
                                    "Use the csv-insights skill to summarize report.csv.")
                                .build())))
                .build());
if (response.status().filter(ResponseStatus.COMPLETED::equals).isEmpty())
  throw new IllegalStateException(
      "Response ended with status " + response.status().orElse(null));
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()));

来源示例36(ruby)

本段复用的中文释义:译释82、译释83、译释108。

## [中文] 内联文件及技能并请求报告,避免另建长期文件或技能资源。
require "base64"
require "openai"

client = OpenAI::Client.new
inline_zip = Base64.strict_encode64(File.binread("csv_insights.zip"))
base64_string = Base64.strict_encode64(File.binread("report.csv"))
container = client.containers.create(
  name: "inline-skill-container",
  skills: [
    {
      type: :inline,
      name: "csv-insights",
      description: "Summarize CSV files and produce a markdown report.",
      source: {
        type: :base64,
        media_type: "application/zip",
        data: inline_zip
      }
    }
  ]
)
response = client.responses.create(
  model: "gpt-6-astra",
  tools: [
    {
      type: :shell,
      environment: {
        type: :container_reference,
        container_id: container.id
      }
    }
  ],
  input: [
    {
      role: :user,
      content: [
        {
          type: :input_file,
          filename: "report.csv",
          file_data: "data:text/csv;base64,#{base64_string}"
        },
        {
          type: :input_text,
          text: "Use the csv-insights skill to summarize report.csv."
        }
      ]
    }
  ]
)
puts(response.output_text)

后续请求通过 container_reference 传入同一个 container_id。容器活动期间,挂载技能及已有文件继续可用。

主动删除容器

工作完成可主动删除,无需等到闲置过期。

来源示例37(bash)

## [中文] 显式删除已完成工作的容器;示例资源ID需替换。
curl -L -X DELETE 'https://api.openai.com/v1/containers/container_id' \
  -H "Authorization: Bearer $OPENAI_API_KEY"

来源示例38(javascript)

// [中文] 显式删除已完成工作的容器;示例资源ID需替换。
import OpenAI from "openai";

const client = new OpenAI();

const deleted = await client.containers.delete("container_id");

console.log(deleted);

来源示例39(python)

## [中文] 显式删除已完成工作的容器;示例资源ID需替换。
## [中文] 将示意ID和URL替换成自己的资源值。
## 把下方示例 ID 和 URL 换成你自己的资源值。
from openai import OpenAI

client = OpenAI()
container_id = "cntr_123"

deleted = client.containers.delete(container_id)

print(deleted)

来源示例40(go)

// [中文] 显式删除已完成工作的容器;示例资源ID需替换。
package main

import (
    "context"
    "fmt"

    "github.com/openai/openai-go/v3"
)

func main() {
    client := openai.NewClient()
    if err := client.Containers.Delete(context.Background(), "container_id"); err != nil {
        panic(err)
    }
    fmt.Println("Container deleted")
}

来源示例41(java)

// [中文] 显式删除已完成工作的容器;示例资源ID需替换。
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;

String containerId = "container_id";

client.containers().delete(containerId);

System.out.println("Container deleted.");

来源示例42(ruby)

## [中文] 显式删除已完成工作的容器;示例资源ID需替换。
require "openai"

client = OpenAI::Client.new
client.containers.delete("container_id")
puts("Deleted container_id")

域名密钥

allowed_domains 中的域名需要私有鉴权头,例如 Authorization: Bearer <token> 时,使用 domain_secrets。每项包含目标域名、便于识别的密钥名称和密钥值。

运行时模型和环境看到的是 $API_KEY 等占位名称;鉴权转换辅助进程仅向批准目标应用真实密钥。真实值不会持久保留在API服务器,也不会进入模型可见上下文,以减少访问受保护服务时的泄露风险。

来源示例43(bash)

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

用curl访问https://httpbin.org/headers,传入Authorization: Bearer $API_KEY请求头,再在最终文本中说明看到的结果。

## [中文] 使用domain_secrets把占位密钥映射到批准目标,真实密钥不直接放入模型输入。
curl -L 'https://api.openai.com/v1/responses' \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-6-astra",
    "input": [
      {
        "role": "user",
        "content": "Use curl to call https://httpbin.org/headers with header Authorization: Bearer $API_KEY. Tell me what you see in the final text response."
      }
    ],
    "tool_choice": "required",
    "tools": [
      {
        "type": "shell",
        "environment": {
          "type": "container_auto",
          "network_policy": {
            "type": "allowlist",
            "allowed_domains": ["httpbin.org"],
            "domain_secrets": [
              {
                "domain": "httpbin.org",
                "name": "API_KEY",
                "value": "debug-secret-123"
              }
            ]
          }
        }
      }
    ]
  }'

来源示例44(javascript)

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

// [中文] 使用domain_secrets把占位密钥映射到批准目标,真实密钥不直接放入模型输入。
import OpenAI from "openai";

const client = new OpenAI();

const response = await client.responses.create({
  model: "gpt-6-astra",
  input: [
    {
      role: "user",
      content:
        "Use curl to call https://httpbin.org/headers with header Authorization: Bearer $API_KEY. Tell me what you see in the final text response.",
    },
  ],
  tool_choice: "required",
  tools: [
    {
      type: "shell",
      environment: {
        type: "container_auto",
        network_policy: {
          type: "allowlist",
          allowed_domains: ["httpbin.org"],
          domain_secrets: [
            {
              domain: "httpbin.org",
              name: "API_KEY",
              value: "debug-secret-123",
            },
          ],
        },
      },
    },
  ],
});

console.log(response.output_text);

来源示例45(python)

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

## [中文] 使用domain_secrets把占位密钥映射到批准目标,真实密钥不直接放入模型输入。
from openai import OpenAI

client = OpenAI()

response = client.responses.create(
    model="gpt-6-astra",
    input=[
        {
            "role": "user",
            "content": "Use curl to call https://httpbin.org/headers with header Authorization: Bearer $API_KEY. Tell me what you see in the final text response.",
        }
    ],
    tool_choice="required",
    tools=[
        {
            "type": "shell",
            "environment": {
                "type": "container_auto",
                "network_policy": {
                    "type": "allowlist",
                    "allowed_domains": ["httpbin.org"],
                    "domain_secrets": [
                        {
                            "domain": "httpbin.org",
                            "name": "API_KEY",
                            "value": "debug-secret-123",
                        }
                    ],
                },
            },
        }
    ],
)

print(response.output_text)

来源示例46(go)

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

// [中文] 使用domain_secrets把占位密钥映射到批准目标,真实密钥不直接放入模型输入。
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.ToolUnionParam{OfShell: &responses.FunctionShellToolParam{
        Environment: responses.FunctionShellToolEnvironmentUnionParam{OfContainerAuto: &responses.ContainerAutoParam{
            NetworkPolicy: responses.ContainerAutoNetworkPolicyUnionParam{OfAllowlist: &responses.ContainerNetworkPolicyAllowlistParam{
                AllowedDomains: []string{"httpbin.org"},
                DomainSecrets: []responses.ContainerNetworkPolicyDomainSecretParam{{
                    Domain: "httpbin.org",
                    Name:   "API_KEY",
                    Value:  "debug-secret-123",
                }},
            }},
        }},
    }}
    response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
        Model:      "gpt-6-astra",
        ToolChoice: responses.ResponseNewParamsToolChoiceUnion{OfToolChoiceMode: openai.Opt(responses.ToolChoiceOptionsRequired)},
        Tools:      []responses.ToolUnionParam{tool},
        Input:      responses.ResponseNewParamsInputUnion{OfString: openai.String("Use curl to call https://httpbin.org/headers with header Authorization: Bearer $API_KEY. Tell me what you see in the final text response.")},
    })
    if err != nil {
        panic(err)
    }
    fmt.Println(response.OutputText())
}

来源示例47(java)

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

用curl访问https://httpbin.org/status/204,并传入后续代码所指定的Authorization请求头;这个版本访问的是204状态端点,不能描述为读取/headers响应正文。

// [中文] 使用domain_secrets把占位密钥映射到批准目标,真实密钥不直接放入模型输入。
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.ContainerAuto;
import com.openai.models.responses.ContainerNetworkPolicyAllowlist;
import com.openai.models.responses.ContainerNetworkPolicyDomainSecret;
import com.openai.models.responses.FunctionShellTool;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ToolChoiceOptions;

ResponseCreateParams params =
    ResponseCreateParams.builder()
        .model("gpt-6-astra")
        .input(
            "Use curl to call https://httpbin.org/status/204 with an "
                + "Authorization: Bearer $API_KEY header. Print only the HTTP status code; "
                + "never print request headers or secret values.")
        .toolChoice(ToolChoiceOptions.REQUIRED)
        .addTool(
            FunctionShellTool.builder()
                .environment(
                    ContainerAuto.builder()
                        .networkPolicy(
                            ContainerNetworkPolicyAllowlist.builder()
                                .addAllowedDomain("httpbin.org")
                                .addDomainSecret(
                                    ContainerNetworkPolicyDomainSecret.builder()
                                        .domain("httpbin.org")
                                        .name("API_KEY")
                                        .value(System.getenv("OPENAI_EXAMPLE_DOMAIN_SECRET"))
                                        .build())
                                .build())
                        .build())
                .build())
        .build();

client.responses().create(params).output().stream()
    .flatMap(item -> item.message().stream())
    .flatMap(message -> message.content().stream())
    .flatMap(content -> content.outputText().stream())
    .forEach(text -> System.out.println(text.text()));

来源示例48(ruby)

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

用curl访问https://httpbin.org/headers,并传入后续代码所指定的Authorization请求头。

## [中文] 使用domain_secrets把占位密钥映射到批准目标,真实密钥不直接放入模型输入。
require "openai"

client = OpenAI::Client.new
response = client.responses.create(
  model: "gpt-6-astra",
  input: "Use curl to call https://httpbin.org/headers with an " \
    '"Authorization: Bearer $API_KEY" header.',
  tool_choice: :required,
  tools: [
    {
      type: :shell,
      environment: {
        type: :container_auto,
        network_policy: {
          type: :allowlist,
          allowed_domains: ["httpbin.org"],
          domain_secrets: [
            {
              domain: "httpbin.org",
              name: "API_KEY",
              value: "debug-secret-123"
            }
          ]
        }
      }
    }
  ]
)

puts(response.output_text)

多轮工作流

要在同一个托管环境继续工作,复用容器并传入 previous_response_id。

来源示例49(bash)

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

读取/mnt/data/top5.csv并报告排名第一的候选项。

## [中文] 复用容器及previous_response_id继续多轮Shell工作。
curl -L 'https://api.openai.com/v1/responses' \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "model": "gpt-6-astra",
    "previous_response_id": "resp_2a8e5c9174d63b0f18a4c572de9f64a1b3c76d508e12f9ab47",
    "tools": [
      {
        "type": "shell",
        "environment": {
          "type": "container_reference",
          "container_id": "cntr_f19c2b51e4a06793d82d54a7be0fc9154d3361ab28ce7f6041"
        }
      }
    ],
    "input": "Read /mnt/data/top5.csv and report the top candidate."
  }'

来源示例50(javascript)

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

// [中文] 复用容器及previous_response_id继续多轮Shell工作。
import OpenAI from "openai";

const client = new OpenAI();

const response = await client.responses.create({
  model: "gpt-6-astra",
  previous_response_id:
    "resp_2a8e5c9174d63b0f18a4c572de9f64a1b3c76d508e12f9ab47",
  tools: [
    {
      type: "shell",
      environment: {
        type: "container_reference",
        container_id: "cntr_f19c2b51e4a06793d82d54a7be0fc9154d3361ab28ce7f6041",
      },
    },
  ],
  input: "Read /mnt/data/top5.csv and report the top candidate.",
});

console.log(response.output_text);

来源示例51(python)

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

## [中文] 复用容器及previous_response_id继续多轮Shell工作。
from openai import OpenAI

client = OpenAI()

response = client.responses.create(
    model="gpt-6-astra",
    previous_response_id="resp_2a8e5c9174d63b0f18a4c572de9f64a1b3c76d508e12f9ab47",
    tools=[
        {
            "type": "shell",
            "environment": {
                "type": "container_reference",
                "container_id": "cntr_f19c2b51e4a06793d82d54a7be0fc9154d3361ab28ce7f6041",
            },
        }
    ],
    input="Read /mnt/data/top5.csv and report the top candidate.",
)

print(response.output_text)

来源示例52(go)

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

// [中文] 复用容器及previous_response_id继续多轮Shell工作。
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.ToolUnionParam{OfShell: &responses.FunctionShellToolParam{
        Environment: responses.FunctionShellToolEnvironmentUnionParam{OfContainerReference: &responses.ContainerReferenceParam{ContainerID: "cntr_f19c2b51e4a06793d82d54a7be0fc9154d3361ab28ce7f6041"}},
    }}
    response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
        Model:              "gpt-6-astra",
        PreviousResponseID: openai.String("resp_2a8e5c9174d63b0f18a4c572de9f64a1b3c76d508e12f9ab47"),
        Tools:              []responses.ToolUnionParam{tool},
        Input:              responses.ResponseNewParamsInputUnion{OfString: openai.String("Read /mnt/data/top5.csv and report the top candidate.")},
    })
    if err != nil {
        panic(err)
    }
    fmt.Println(response.OutputText())
}

来源示例53(java)

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

// [中文] 复用容器及previous_response_id继续多轮Shell工作。
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.FunctionShellTool;
import com.openai.models.responses.ResponseCreateParams;

String responseId = "resp_2a8e5c9174d63b0f18a4c572de9f64a1b3c76d508e12f9ab47";

String containerId = "cntr_f19c2b51e4a06793d82d54a7be0fc9154d3361ab28ce7f6041";

ResponseCreateParams params =
    ResponseCreateParams.builder()
        .model("gpt-6-astra")
        .input("Read /mnt/data/top5.csv and report the top candidate.")
        .previousResponseId(responseId)
        .addTool(FunctionShellTool.builder().containerReferenceEnvironment(containerId).build())
        .build();

client.responses().create(params).output().stream()
    .flatMap(item -> item.message().stream())
    .flatMap(message -> message.content().stream())
    .flatMap(content -> content.outputText().stream())
    .forEach(text -> System.out.println(text.text()));

来源示例54(ruby)

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

## [中文] 复用容器及previous_response_id继续多轮Shell工作。
require "openai"

client = OpenAI::Client.new
response = client.responses.create(
  model: "gpt-6-astra",
  input: "Read /mnt/data/top5.csv and report the top candidate.",
  previous_response_id: "resp_2a8e5c9174d63b0f18a4c572de9f64a1b3c76d508e12f9ab47",
  tools: [
    {
      type: :shell,
      environment: {
        type: :container_reference,
        container_id: "cntr_f19c2b51e4a06793d82d54a7be0fc9154d3361ab28ce7f6041"
      }
    }
  ]
)

puts(response.output_text)

Responses中的Shell输出

托管和本地Shell使用相同输出类型:shell_call 表示模型请求的命令;shell_call_output 表示命令输出和退出结果。

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

{
  "type": "shell_call",
  "call_id": "call_9d14ac6f2b73485e91c0f4da6e1b27c8",
  "action": {
    "commands": ["ls -l"],
    "timeout_ms": 120000,
    "max_output_length": 4096
  },
  "status": "in_progress"
}

本地Shell模式

也可在自己的运行时执行 shell_call,将 shell_call_output 返回模型。需要完全控制执行环境、文件系统或内部工具时采用此方式。

来源示例56(bash)

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

本地Bash运行环境位于Mac。

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

在~/Documents中查找最大的PDF文件。

## [中文] 声明本地Shell环境;实际命令仍须自己的执行器处理。
curl -L 'https://api.openai.com/v1/responses' \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "model": "gpt-6-astra",
    "instructions": "The local bash shell environment is on Mac.",
    "input": "find me the largest pdf file in ~/Documents",
    "tools": [{ "type": "shell", "environment": { "type": "local" } }]
  }'

来源示例57(javascript)

本段复用的中文释义:译释86、译释87。

// [中文] 声明本地Shell环境;实际命令仍须自己的执行器处理。
import OpenAI from "openai";

const client = new OpenAI();

const response = await client.responses.create({
  model: "gpt-6-astra",
  instructions: "The local bash shell environment is on Mac.",
  input: "find me the largest pdf file in ~/Documents",
  tools: [{ type: "shell", environment: { type: "local" } }],
});

console.log(response);

来源示例58(python)

本段复用的中文释义:译释86、译释87。

## [中文] 声明本地Shell环境;实际命令仍须自己的执行器处理。
from openai import OpenAI

client = OpenAI()

response = client.responses.create(
    model="gpt-6-astra",
    instructions="The local bash shell environment is on Mac.",
    input="find me the largest pdf file in ~/Documents",
    tools=[{"type": "shell", "environment": {"type": "local"}}],
)

print(response)

来源示例59(go)

本段复用的中文释义:译释86、译释87。

// [中文] 声明本地Shell环境;实际命令仍须自己的执行器处理。
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.ToolUnionParam{OfShell: &responses.FunctionShellToolParam{
        Environment: responses.FunctionShellToolEnvironmentUnionParam{OfLocal: &responses.LocalEnvironmentParam{}},
    }}
    response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
        Model:        "gpt-6-astra",
        Instructions: openai.String("The local bash shell environment is on Mac."),
        Input:        responses.ResponseNewParamsInputUnion{OfString: openai.String("find me the largest pdf file in ~/Documents")},
        Tools:        []responses.ToolUnionParam{tool},
    })
    if err != nil {
        panic(err)
    }
    fmt.Println(response.Output)
}

来源示例60(java)

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

查找~/Documents中最大的PDF文件。

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

本地Shell环境为macOS。

// [中文] 声明本地Shell环境;实际命令仍须自己的执行器处理。
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.JsonValue;
import com.openai.models.responses.ResponseCreateParams;
import java.util.List;
import java.util.Map;

ResponseCreateParams params =
    ResponseCreateParams.builder()
        .model("gpt-6-astra")
        .input("Find the largest PDF in ~/Documents.")
        .instructions("The local shell environment is macOS.")
        .putAdditionalBodyProperty(
            "tools",
            JsonValue.from(
                List.of(Map.of("type", "shell", "environment", Map.of("type", "local")))))
        .build();

client.responses().create(params).output().stream()
    .flatMap(item -> item.shellCall().stream())
    .flatMap(call -> call.action().commands().stream())
    .forEach(System.out::println);

来源示例61(ruby)

本段复用的中文释义:译释134、译释135。

## [中文] 声明本地Shell环境;实际命令仍须自己的执行器处理。
require "openai"

client = OpenAI::Client.new
response = client.responses.create(
  model: "gpt-6-astra",
  instructions: "The local shell environment is macOS.",
  input: "Find the largest PDF in ~/Documents.",
  tools: [
    {
      type: :shell,
      environment: { type: :local }
    }
  ]
)

puts(response.output)

收到调用后,在应用运行时执行命令,捕获 stdout、stderr 和执行结果,再在下一次请求返回输出。

本地执行器示例:

来源示例62(javascript)

// [中文] 在应用侧执行shell_call,捕获标准输出、错误和执行状态,生成对应结果。
import { exec as execCallback } from "node:child_process";
import { promisify } from "node:util";

const exec = promisify(execCallback);

class ShellExecutor {
  constructor(defaultTimeoutMs = 60_000) {
    this.defaultTimeoutMs = defaultTimeoutMs;
  }

  async run(cmd, timeoutMs) {
    const timeout = timeoutMs ?? this.defaultTimeoutMs;

    try {
      const { stdout, stderr } = await exec(cmd, { timeout });
      return { stdout, stderr, exitCode: 0, timedOut: false };
    } catch (error) {
      const timedOut = Boolean(error?.killed) && error?.signal === "SIGTERM";
      const exitCode = timedOut ? null : (error?.code ?? null);
      return {
        stdout: error?.stdout ?? "",
        stderr: error?.stderr ?? String(error),
        exitCode,
        timedOut,
      };
    }
  }
}

来源示例63(python)

## [中文] 在应用侧执行shell_call,捕获标准输出、错误和执行状态,生成对应结果。
@dataclass
class CmdResult:
    stdout: str
    stderr: str
    exit_code: int | None
    timed_out: bool


class ShellExecutor:
    def __init__(self, default_timeout: float = 60):
        self.default_timeout = default_timeout

    def run(self, cmd: str, timeout: float | None = None) -> CmdResult:
        t = timeout or self.default_timeout
        p = subprocess.Popen(
            cmd,
            shell=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True,
        )
        try:
            out, err = p.communicate(timeout=t)
            return CmdResult(out, err, p.returncode, False)
        except subprocess.TimeoutExpired:
            p.kill()
            out, err = p.communicate()
            return CmdResult(out, err, p.returncode, True)

来源示例64(go)

// [中文] 在应用侧执行shell_call,捕获标准输出、错误和执行状态,生成对应结果。
package main

import (
    "bytes"
    "context"
    "fmt"
    "os/exec"
    "time"
)

type shellResult struct {
    Stdout   string
    Stderr   string
    ExitCode int
    TimedOut bool
}

type shellExecutor struct {
    DefaultTimeout time.Duration
}

func (e shellExecutor) run(command string, timeout time.Duration) shellResult {
    if timeout == 0 {
        timeout = e.DefaultTimeout
    }
    ctx, cancel := context.WithTimeout(context.Background(), timeout)
    defer cancel()
    cmd := exec.CommandContext(ctx, "sh", "-c", command)
    var stdout, stderr bytes.Buffer
    cmd.Stdout = &stdout
    cmd.Stderr = &stderr
    err := cmd.Run()
    result := shellResult{Stdout: stdout.String(), Stderr: stderr.String()}
    if ctx.Err() == context.DeadlineExceeded {
        result.TimedOut = true
        result.ExitCode = -1
        return result
    }
    if err != nil {
        if exitError, ok := err.(*exec.ExitError); ok {
            result.ExitCode = exitError.ExitCode()
            return result
        }
        if result.Stderr == "" {
            result.Stderr = err.Error()
        }
        result.ExitCode = -1
    }
    return result
}

func main() {
    executor := shellExecutor{DefaultTimeout: time.Minute}
    fmt.Println(executor.run("printf shell-executor-ready", 0))
}

来源示例65(ruby)

## [中文] 在应用侧执行shell_call,捕获标准输出、错误和执行状态,生成对应结果。
require "open3"

class ShellExecutor
  Result = Data.define(:stdout, :stderr, :exit_code, :timed_out)

  def initialize(default_timeout: 60)
    @default_timeout = default_timeout
  end

  def run(command, timeout: @default_timeout)
    Open3.popen3("sh", "-c", command, pgroup: true) do |stdin, stdout, stderr, wait_thread|
      stdin.close
      stdout_reader = Thread.new { stdout.read }
      stderr_reader = Thread.new { stderr.read }
      finished = wait_thread.join(timeout)
      terminate_process_group(wait_thread) unless finished

      Result.new(
        stdout: stdout_reader.value,
        stderr: stderr_reader.value,
        exit_code: wait_thread.value.exitstatus || -1,
        timed_out: finished.nil?
      )
    end
  end

  private

  def terminate_process_group(wait_thread)
    Process.kill("TERM", -wait_thread.pid)
    wait_thread.join(1)
    Process.kill("KILL", -wait_thread.pid)
  rescue Errno::ESRCH
    nil
  ensure
    wait_thread.join
  end
end

puts(ShellExecutor.new.run("printf shell-executor-ready"))

输出载荷示例:

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

{
  "type": "shell_call_output",
  "call_id": "call_3ef1b8c79a4d6520f9e3ab7d41c68f25",
  "max_output_length": 4096,
  "output": [
    {
      "stdout": "...",
      "stderr": "...",
      "outcome": {
        "type": "exit",
        "exit_code": 0
      }
    },
    {
      "stdout": "...",
      "stderr": "...",
      "outcome": {
        "type": "timeout"
      }
    }
  ]
}

旧工具迁移背景参见本地Shell历史指南。

在Agents SDK中使用本地Shell

可以向Agents SDK的Shell辅助工具提供自己的执行器实现。

来源示例67(javascript)

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

可执行Shell命令查看仓库;回答简洁,必要时包含命令输出。

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

Shell尚不可用,必须先实现执行器。

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

显示Node.js版本。

// [中文] 向Agents SDK注册自有Shell执行器;未实现的占位代码不能当作可用执行服务。
import { Agent, run, withTrace, shellTool } from "@openai/agents";

class LocalShell {
  async run(action) {
    return {
      output: [
        {
          stdout: "Shell is not available. Needs to be implemented first.",
          stderr: "",
          outcome: {
            type: "exit",
            exitCode: 1,
          },
        },
      ],
      maxOutputLength: action.maxOutputLength,
    };
  }
}

const shell = new LocalShell();

const agent = new Agent({
  name: "Shell Assistant",
  model: "gpt-6-astra",
  instructions:
    "You can execute shell commands to inspect the repository. Keep responses concise and include command output when helpful.",
  tools: [
    shellTool({
      shell,
      needsApproval: true,
      onApproval: async (_ctx, _approvalItem) => {
        return { approve: true };
      },
    }),
  ],
});

await withTrace("shell-tool-example", async () => {
  const result = await run(agent, "Show the Node.js version.");
  console.log(`\nFinal response:\n${result.finalOutput}`);
});

来源示例68(python)

本段复用的中文释义:译释88、译释89、译释136。

## [中文] 向Agents SDK注册自有Shell执行器;未实现的占位代码不能当作可用执行服务。
from agents import (
    Agent,
    Runner,
    ShellCallOutcome,
    ShellCommandOutput,
    ShellCommandRequest,
    ShellResult,
    ShellTool,
)


class LocalShell:
    async def __call__(self, request: ShellCommandRequest) -> ShellResult:
        action = request.data.action
        return ShellResult(
            output=[
                ShellCommandOutput(
                    command="(not executed)",
                    stdout="Shell is not available. Needs to be implemented first.",
                    stderr="",
                    outcome=ShellCallOutcome(type="exit", exit_code=1),
                )
            ],
            max_output_length=action.max_output_length,
        )


shell_tool = ShellTool(
    executor=LocalShell(),
    needs_approval=True,
    on_approval=lambda _ctx, _approval_item: {"approve": True},
)

agent = Agent(
    name="Shell Assistant",
    model="gpt-6-astra",
    instructions="You can execute shell commands to inspect the repository. Keep responses concise and include command output when helpful.",
    tools=[shell_tool],
)


async def main():
    result = await Runner.run(agent, input="Show the Node.js version.")
    print(f"\nFinal response:\n{result.final_output}")


if __name__ == "__main__":
    import asyncio

    asyncio.run(main())

可运行实现参见SDK仓库的TypeScript示例和Python示例。

处理常见错误

  • 命令超出执行时限时,返回超时结果和已捕获的部分输出。
  • shell_call 含 max_output_length 时,应在 shell_call_output 中带回。
  • 不依赖交互式命令,工具执行应为非交互模式。
  • 保留非零退出的输出,让模型判断恢复步骤。

风险与安全

容器联网能力会带来安全与数据治理风险。默认关闭;启用后也应严格限于任务需要的可信域名。第三方服务和包仓库可能引发数据泄漏、提示注入导致工具滥用、访问越界;宽泛、静态或执行不一致的策略会增加风险。

理解网络内容的提示注入风险

外部内容可能藏有影响模型行为的指令。把不可信网络内容当作潜在对抗性输入,对可修改系统或数据的操作特别审慎。

仅连接可信目标

仅允许信任并持续维护的域名。对代理到其他服务的中间商与聚合器保持谨慎,加入允许列表前审核其数据处理和保留方式。

执行请求前后设置检查

审查Responses返回的Shell命令及执行输出。记录每个会话请求的主机和实际出站目标,定期检查访问是否符合预期,发现偏离或可疑行为。

验证数据驻留与保留要求

OpenAI数据控制适用于OpenAI边界内。通过网络传给第三方的数据受对方保留政策约束,应确认外部端点满足自己的驻留、保留和合规要求。

OpenAI 程序化工具调用
OpenAI 技能
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

其他能力与进阶指南

Embeddings 接口参考

审计日志接口参考

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }