Overview

This example shows how to integrate OpenAI with Gbox to generate and execute Python code using a simple, direct approach.

Use Cases

  • Learning & Education - Generate and test code examples for learning
  • Rapid Prototyping - Rapid prototyping of algorithmic ideas
  • AI-Assisted Development - AI-assisted development workflows

Implementation Example

Step 1: Create the File

Copy the following code locally and create a new file named index.ts:

import OpenAI from "openai";
import GboxSDK from "gbox-sdk";
import * as dotenv from "dotenv";

dotenv.config();

// Initialize clients
const openaiClient = new OpenAI({
  apiKey: process.env["OPENAI_API_KEY"],
});

const gboxSDK = new GboxSDK({
  apiKey: process.env["GBOX_API_KEY"],
});

// Extract Python code blocks
function extractPythonCode(text: string): string[] {
  const regex = /```python\n([\s\S]*?)\n```/g;
  const codeBlocks: string[] = [];
  let match;

  while ((match = regex.exec(text)) !== null) {
    codeBlocks.push(match[1].trim());
  }

  return codeBlocks;
}

async function main() {
  try {
    // 1. Generate Python code using OpenAI
    const response = await openaiClient.chat.completions.create({
      model: "gpt-4o",
      messages: [
        {
          role: "system",
          content:
            "Generate Python code to solve problems. Always wrap code in ```python blocks.",
        },
        {
          role: "user",
          content: "Calculate the first 10 Fibonacci numbers",
        },
      ],
      max_tokens: 1000,
      temperature: 0.7,
    });

    const aiResponse = response.choices[0].message.content || "";
    console.log("\nOpenAI Response:");
    console.log(aiResponse);

    // 2. Extract and execute Python code
    const codeBlocks = extractPythonCode(aiResponse);

    if (codeBlocks.length === 0) {
      console.log("No executable code found");
      return;
    }

    // 3. Execute code in Gbox
    const box = await gboxSDK.create({ type: "linux" });

    try {
      for (const code of codeBlocks) {
        console.log("\nExecuting code:");
        console.log(code);
        console.log("---");

        const result = await box.runCode(code);
        console.log("Execution result:");
        console.log(result.stdout || result.stderr || "No output");
      }
    } finally {
      await box.terminate();
    }
  } catch (error) {
    console.error("Error:", error);
  }
}

main();

Step 2: Run the Code

Execute the following command to run the example:

npx tsx index.ts

OpenAI Function Calling

Use OpenAI’s Function Calling feature to create an AI assistant that can execute code in Gbox based on user queries