For the complete documentation index, see llms.txt. Markdown versions of documentation pages are available by appending .md to the page URL.
主导航

Shell

在托管容器或您自己的本地运行时中运行 Shell 命令。

Shell 工具让模型能够在完整的终端环境中工作。我们支持通过 Responses API 在本地执行或以托管方式执行 Shell 命令。

Shell 工具让模型能够通过以下任一方式运行命令:

Shell 可通过 Responses API 使用,但不支持 Chat Completions API。

运行任意 Shell 命令可能存在危险。请始终在沙盒中执行,尽可能使用允许列表或拒绝列表,并记录工具活动以供审计。

托管式 Shell 快速入门

从运行计算到处理多媒体,对于需要更丰富的确定性处理能力的任务,托管式 Shell 提供了一种原生且简便的选择。

如果您希望 OpenAI 为请求配置和管理容器,请使用 container_auto

使用 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"
  }'

托管运行时详情

  • 运行时目前基于 Debian 12,未来可能会发生变化。
  • 默认工作目录为 /mnt/data
  • /mnt/data 始终存在,是用于存放可供用户下载的产物的受支持路径。
  • 托管式 Shell 不支持交互式 TTY 会话。
  • 托管式 Shell 命令不会通过 sudo 运行。
  • 如果工作流需要,您可以在容器内运行服务。

目前预装的语言包括:

  • Python 3.11
  • Node.js 22.16
  • Java 17.0
  • PHP 8.2
  • Ruby 3.1
  • Go 1.23

跨请求复用容器

如果您的迭代工作流需要长时间运行的环境,请创建一个容器,然后在后续的 Responses API 调用中引用它。

1. 创建容器

创建可复用的容器
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 }
  }'

2. 在 Responses 中引用容器

通过 container_reference 使用 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_reference",
          "container_id": "cntr_08f3d96c87a585390069118b594f7481a088b16cda7d9415fe"
        }
      }
    ],
    "input": "List files in the container and show disk usage."
  }'

附加技能

技能是可复用、带有版本的资源包,您可以将其挂载到托管式 Shell 环境中。挂载操作确定了可用的技能,而模型会在执行 Shell 命令时决定是否调用这些技能。

有关上传和版本管理的详情,请参阅技能指南

创建附加了技能的容器
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" }
    ]
  }'

网络访问

托管容器默认无法访问外部网络。

如需启用此功能:

  1. 管理员必须在控制台中配置您组织的允许列表。
  2. 您必须在请求中为容器环境显式设置 network_policy
使用网络允许列表的 Shell 工具
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."
      }
    ]
  }'

将域名加入允许列表会带来安全风险,例如 提示注入导致的数据外泄。请仅将您信任且 攻击者无法用来接收外泄数据的域名加入允许列表。使用此工具前,请仔细阅读下方的风险 与安全部分。

网络策略优先级

当存在多项控制措施时:

  • 您组织的允许列表定义了 allowed_domains 的完整集合。
  • 请求级别的 network_policy 会进一步限制访问。
  • 如果 allowed_domains 包含您组织允许列表之外的域名,请求将失败。

数据保留与容器生命周期

托管式 Shell 和代码解释器使用的托管容器在处于活动状态时,可能会将临时应用状态写入容器文件系统(由临时块存储支持)。容器到期或被显式删除时,容器数据也会被删除。

有关数据控制的更多详情,请参阅 ZDR 与数据驻留

下载产物

托管式 Shell 可以生成可供下载的文件。请使用与代码解释器相同的 container/files API,获取写入 /mnt/data 下的产物。

其他数据控制选项

如果您希望内容和文件仅在托管环境的生命周期内临时保留,可以在请求中内联文件,并在容器中挂载内联技能。

使用内联文件和内联技能
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."
          }
        ]
      }
    ]
  }'

对于后续请求,请通过 container_reference 传入相同的 container_id。只要容器仍处于活动状态,已挂载的技能和容器中的现有文件就仍然可用。

主动删除容器

工作完成后,您可以主动删除容器,无需等待容器因闲置而过期。

删除容器
curl -L -X DELETE 'https://api.openai.com/v1/containers/container_id' \
  -H "Authorization: Bearer $OPENAI_API_KEY"

域名密钥

当您的 allowed_domains 列表中的某个域名需要包含私密凭据的授权标头(例如 Authorization: Bearer <token>)时,请使用 domain_secrets

每个密钥条目包含:

  • 目标域名
  • 密钥的友好名称
  • 密钥值

在运行时:

  • 模型和运行时看到的是占位符名称(例如 $API_KEY),而不是原始凭据。
  • 认证转换边车组件仅在访问获准的目标时使用原始密钥值。
  • 原始密钥值不会持久存储在 API 服务器上,也不会出现在模型可见的上下文中。

这样,助手就能调用受保护的服务,同时降低泄露风险。

使用 domain_secrets 的 Shell 工具
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"
              }
            ]
          }
        }
      }
    ]
  }'

多轮工作流

要在同一托管环境中继续工作,请复用容器并传入 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."
  }'

Responses 中的 Shell 输出

托管式 Shell 和本地 Shell 使用相同的输出项类型。Shell 运行以成对的输出项表示:

  • shell_call:模型请求执行的命令。
  • shell_call_output:命令输出和退出结果。
shell_call 输出项示例
{
  "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 发回模型,从而在自己的本地运行时中运行 Shell 命令。

如果您需要完全控制执行环境、文件系统访问或现有的内部工具,请使用此模式。

本地 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" } }]
  }'

收到 shell_call 输出项时:

  • 在您的运行时中执行所请求的命令。
  • 捕获 stdoutstderr 和执行结果。
  • 在下一次请求中以 shell_call_output 的形式返回结果。
本地 Shell 执行器示例
@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)
shell_call_output 载荷示例
{
  "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 执行器传给 Shell 工具辅助函数。

在 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}`);
});

您可以在 SDK 代码仓库中找到可运行的示例。

Shell 工具示例:TypeScript

Agents SDK 中 Shell 工具的 TypeScript 示例。

Shell 工具示例:Python

Agents SDK 中 Shell 工具的 Python 示例。

处理常见错误

  • 如果命令执行超过您设置的超时时限,请返回超时结果,并附上已捕获的部分输出。
  • 如果 shell_call 中包含 max_output_length,请在 shell_call_output 中也包含该值。
  • 请勿依赖交互式命令;Shell 工具应以非交互方式执行。
  • 请保留以非零退出码结束时的输出,以便模型推理后续恢复步骤。

风险与安全

在 Containers API 中启用网络访问可提供强大的功能,同时也会带来显著的安全和数据治理风险。默认情况下,网络访问处于禁用状态。启用后,出站访问仍应严格限于任务所需的可信域名。

启用网络访问的容器可以与第三方服务和软件包注册表交互。这会带来数据泄露、提示注入导致的工具误用,以及意外超出预期边界的访问等风险。如果策略过于宽泛、长期不更新或执行不一致,这些风险会进一步增加。

了解从网络获取的内容所带来的提示注入风险

通过网络获取的任何外部内容都可能包含意图操纵模型行为的隐藏指令。请将不可信的网络内容视为可能具有对抗性,并对可能修改数据或系统的操作格外谨慎。

仅连接到可信目标

仅允许访问您信任且积极维护的域名。请谨慎对待代理访问其他服务的中间服务和聚合服务,并在将其加入允许的域名列表之前,审查其数据处理和保留做法。

在请求执行前后设置审查环节

请审查 Responses API 响应中提供的 Shell 工具命令及其执行输出。记录每个会话请求访问的主机和实际出站访问的目标。定期审查日志,确认访问模式符合预期,发现偏离预期的情况,并识别可疑行为。

核实数据驻留和保留要求

OpenAI 数据控制适用于 OpenAI 范围内的数据。但是,通过网络连接传输到第三方服务的数据受其数据保留政策约束。请确保外部端点满足您的数据驻留、保留和合规要求。