Skip to content

Integrations

OpenAI tool calling

No framework: a chat completions loop that runs each tool call in the sandbox and sends the output back.

Install

Terminal
npm i sandboxplease openai

Code

Copy it as openai-tool-loop.ts. The model is the only part you would change.

openai-tool-loop.ts
// Plain OpenAI tool calling, no framework: the model asks for commands, the loop runs them in a sandbox.
// Run: SANDBOXPLEASE_API_KEY=... OPENAI_API_KEY=... npx tsx openai-tool-loop.ts
import OpenAI from "openai";
import type { ChatCompletionMessageParam, ChatCompletionTool } from "openai/resources/chat/completions";
import { SandboxPlease } from "sandboxplease";

const tools: ChatCompletionTool[] = [
  {
    type: "function",
    function: {
      name: "run_command",
      description:
        "Run a shell command in a Linux sandbox with Python 3 and Node. Returns exit code, stdout and stderr.",
      parameters: {
        type: "object",
        properties: { command: { type: "string", description: "Shell command, e.g. python3 -c 'print(1+1)'" } },
        required: ["command"],
      },
    },
  },
];

export async function solve(openai: OpenAI, prompt: string, model = "gpt-5-mini") {
  const sp = new SandboxPlease();
  await using sandbox = await sp.sandboxes.create({ timeout: 600 });
  const messages: ChatCompletionMessageParam[] = [{ role: "user", content: prompt }];
  for (let step = 0; step < 10; step++) {
    const { choices } = await openai.chat.completions.create({ model, messages, tools });
    const reply = choices[0]!.message;
    messages.push(reply);
    if (!reply.tool_calls?.length) return reply.content;
    for (const call of reply.tool_calls) {
      if (call.type !== "function") continue;
      const { command } = JSON.parse(call.function.arguments) as { command: string };
      const { exitCode, stdout, stderr } = await sandbox.exec(command);
      messages.push({ role: "tool", tool_call_id: call.id, content: JSON.stringify({ exitCode, stdout, stderr }) });
    }
  }
  throw new Error("No answer after 10 steps");
}

if (import.meta.url === `file://${process.argv[1]}`) {
  console.log(await solve(new OpenAI(), "Compute 6*7 with Python in the sandbox."));
}

Run it

Terminal
export SANDBOXPLEASE_API_KEY=sp-v1-…
export OPENAI_API_KEY=…
npx tsx openai-tool-loop.ts

The agent runs Python in the sandbox and answers 42. Each sandbox shows up in Logs with its provider and cost.