如需完整的文件索引,請參閱 llms.txt。在文件頁面的網址末尾加上 .md ,即可取得該頁面的 Markdown 版本。
主要導覽
主題

Shell

在託管容器或自己的本機執行環境中執行 Shell 指令。

Shell 工具讓模型能在完整的終端環境中工作。透過 Responses API,你可以在本機或託管環境中執行 Shell 指令。

模型可以使用 Shell 工具,在下列任一環境中執行指令:

Responses API 提供 Shell 工具。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 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-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 環境可產生供下載的檔案。請使用與程式碼解譯器相同的容器與檔案 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_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 伺服器不會持久儲存實際密鑰值,模型可見的上下文中也不會出現這些值。

這樣一來,助理就能呼叫受保護的服務,同時降低憑證外洩的風險。

搭配 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 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-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-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 管理的範圍內。透過網路連線傳送至第三方服務的資料,則受該服務的資料保留政策規範。請確認外部端點符合你的資料駐留、資料保留與法規遵循要求。