如需查看完整的文档索引,请参阅 llms.txt。在文档页面的 URL 末尾加上 .md 即可查看该页面的 Markdown 版本。
主导航
主题

Shell

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

Shell 工具让模型能够在完整的终端环境中工作。通过 Responses API,您可以在本地或托管环境中执行 Shell 命令。

模型可以使用 Shell 工具在以下任一环境中执行命令:

您可以通过 Responses API 使用 Shell 工具。Chat Completions API 不支持此工具。

执行任意 Shell 命令可能有危险。请始终在沙盒中执行命令,并尽可能明确指定允许或禁止执行哪些命令。请记录工具活动以供审计。

托管式 Shell 快速入门

对于需要更丰富的处理能力且要求结果确定的任务,例如执行计算或处理多媒体,托管式 Shell 提供了一种简便的原生执行方式。

如果您希望 OpenAI 为请求创建并管理容器,请使用 container_auto。

在 Shell 工具中使用 container_auto
curl -L '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": "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 API 中引用容器

通过 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.2-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.2-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 可以生成可供下载的文件。您可以使用与代码解释器相同的容器和文件 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.2-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_id,并使用 container_reference 引用该容器。只要容器仍在运行,已挂载的技能和容器中的现有文件就仍然可用。

主动删除容器

工作完成后,您可以显式删除容器,无需等待容器因闲置而到期。

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

域名密钥

请使用 domain_secrets 为 allowed_domains 列表中需要私密授权请求头的域名配置密钥。此类请求头的一个例子是 Authorization: Bearer <token>。

每个密钥条目包含:

  • 目标域名
  • 便于识别的密钥名称
  • 密钥值

运行时:

  • 模型和运行环境看到的是占位符名称(例如 $API_KEY),不会看到原始凭据。
  • 负责转换授权信息的边车组件仅在请求发往获准的目标时使用原始密钥值。
  • API 服务器不会持久保存原始密钥值,模型可见的上下文中也不会出现这些值。

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

在 Shell 工具中使用 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.2-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.2-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 API 中的 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 命令。为此,请执行 shell_call 请求的操作,再将 shell_call_output 发回给模型。

如果您需要控制文件系统或访问内部工具,请使用此模式。将工具类型设为 shell,环境类型设为 local。如果您正从已停用的 local_shell 工具迁移,请更新请求,并在执行循环中处理 shell_call 和 shell_call_output。

本地 Shell 请求
curl -L 'https://api.openai.com/v1/responses' \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "model": "gpt-6.2-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 输出项后:

  • 执行前逐条检查命令。使用允许列表,并要求破坏性命令或访问敏感数据的命令必须经过审批才能执行。
  • 在沙盒中运行获准执行的命令,并明确限制文件系统和网络访问范围、内存用量及执行时间。即使模型建议了超时时间,也要强制执行您自己设定的时限。
  • 记录命令及其执行结果,以供审计。
  • 捕获 stdout、stderr 和执行结果。
  • 在下一次请求中以 shell_call_output 的形式返回结果。
本地 Shell 执行器示例
from contextlib import suppress
from dataclasses import dataclass
import os
import signal
import subprocess


@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 = self.default_timeout if timeout is None else timeout
        p = subprocess.Popen(
            cmd,
            shell=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True,
            start_new_session=True,
        )
        try:
            out, err = p.communicate(timeout=t)
            return CmdResult(out, err, p.returncode, False)
        except subprocess.TimeoutExpired:
            # Stop the shell and its children before draining their output pipes.
            with suppress(ProcessLookupError):
                os.killpg(p.pid, signal.SIGKILL)
            out, err = p.communicate()
            return CmdResult(out, err, p.returncode, True)

这些示例需要在 Linux 或 macOS 上运行。命令达到执行时限时,示例代码会终止该命令所在的整个进程组。

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"
      }
    }
  ]
}

如果命令执行失败或超时,请返回相应的执行结果,以便模型决定是否重试。请参阅旧版工具停用公告。

在 Agents SDK 中使用本地 Shell

如果您使用 Agents SDK,可以将自己实现的 Shell 执行器传给 Shell 工具的辅助函数。

在 Agents SDK 中使用本地 Shell
import {
  Agent,
  run,
  withTrace,
  shellTool,
  type ShellAction,
  type ShellResult,
} from "@openai/agents";

class LocalShell {
  async run(action: ShellAction): Promise<ShellResult> {
    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.2-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 示例。

处理常见错误

  • 如果命令的执行时间超过您设置的时限,请返回超时结果,并附上超时前已捕获的输出。
  • 如果 max_output_length 出现在 shell_call 中,请在 shell_call_output 中也包含该值。
  • 请勿依赖交互式命令。Shell 工具应以非交互方式执行命令。
  • 如果命令以非零状态码退出,请保留其输出,以便模型判断如何恢复。

风险与安全

在 Containers API 中启用网络访问可以扩展容器的能力,但也会带来显著的安全和数据治理风险。网络访问默认关闭。启用后,应将出站访问严格限制在任务所需的可信域名范围内。

启用网络访问的容器可以与第三方服务和软件包注册表交互。这可能导致数据泄露、攻击者通过提示词注入诱使模型误用工具,或容器意外访问预期范围之外的资源。如果策略范围过宽、长期固定不变或执行不一致,这些风险会进一步增加。

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

通过网络获取的任何外部内容都可能包含旨在操纵模型行为的隐藏指令。请将不可信的网络内容视为可能带有恶意的输入,对可能修改数据或系统的操作尤其要谨慎。

仅连接可信的目标

仅允许访问您信任且主动维护的域名。对于为其他服务代理请求的中间服务和聚合服务,请谨慎评估。在将其域名加入允许列表之前,请审查其数据处理和保留方式。

在请求执行前后进行审查

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

核实数据驻留和保留要求

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