Overview

This example demonstrates how to use OpenAI’s Function Calling with GBOX to create an AI assistant that can execute Python code based on user queries.

How It Works

  1. User Input - User asks a natural language question
  2. AI Analysis - OpenAI determines if code execution is needed
  3. Code Generation - AI generates Python code using the execute_python function
  4. Code Execution - GBOX executes the code and returns results
  5. Result Integration - AI incorporates results into the final response

Use Cases

  • Data Analysis & Visualization - Process and display data
  • Mathematical Problem Solving - Solve complex computational problems
  • Interactive Code Generation - Real-time code generation and execution

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 gboxSDK = new GboxSDK({
  apiKey: process.env["GBOX_API_KEY"],
});

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

// ==================== Type Definitions ====================
interface ToolExecutionResult {
  success: boolean;
  result: string;
}

// ==================== Configuration Constants ====================
const DEFAULT_QUESTION =
  "Please calculate the first 20 terms of the Fibonacci sequence and create a simple chart to visualize the growth trend";

// ==================== Utility Functions ====================

/**
 * Get user question from command line arguments or use default
 */
function getUserQuestion(): string {
  const args = process.argv.slice(2);

  if (args.length > 0) {
    const userQuestion = args.join(" ").trim();
    if (userQuestion) {
      console.info(`📝 Using user question: "${userQuestion}"`);
      return userQuestion;
    }
  }

  console.info(`📝 Using default question: "${DEFAULT_QUESTION}"`);
  return DEFAULT_QUESTION;
}

/**
 * Create initial conversation messages
 */
const createInitialMessages = (
  question: string
): OpenAI.Chat.Completions.ChatCompletionMessageParam[] => [
  {
    role: "user",
    content: question,
  },
];

/**
 * Define available tools
 */
const createTools = (): OpenAI.Chat.Completions.ChatCompletionTool[] => [
  {
    type: "function",
    function: {
      name: "execute_python",
      description:
        "Execute Python code in a Linux environment and return results from stdout/stderr streams",
      parameters: {
        type: "object",
        properties: {
          code: {
            type: "string",
            description:
              "The Python code to execute. Results will be captured from standard output and standard error streams.",
          },
        },
        required: ["code"],
      },
    },
  },
];

// ==================== Core Execution Functions ====================

/**
 * Execute Python code using GBOX
 */
async function executePythonCode(code: string): Promise<ToolExecutionResult> {
  const box = await gboxSDK.create({ type: "linux" });

  try {
    console.info("📝 Executing Python code:");
    console.log(code);
    console.info("─".repeat(50));

    const execution = await box.runCode(code);
    const result = execution.stdout || execution.stderr || "No output";

    console.info("✅ Execution result:");
    console.log(result);
    console.info("─".repeat(50));

    return {
      success: true,
      result,
    };
  } catch (error) {
    const errorMessage = `Error: ${error}`;
    console.error("❌ Execution failed:", errorMessage);

    return {
      success: false,
      result: errorMessage,
    };
  } finally {
    await box.terminate();
  }
}

/**
 * Process tool calls from OpenAI response
 */
async function processToolCalls(
  toolCalls: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[],
  messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[]
): Promise<void> {
  for (const toolCall of toolCalls) {
    if (toolCall.function.name === "execute_python") {
      try {
        const { code } = JSON.parse(toolCall.function.arguments);
        const executionResult = await executePythonCode(code);

        // Add tool result to conversation
        messages.push({
          role: "tool",
          content: executionResult.result,
          tool_call_id: toolCall.id,
        });
      } catch (parseError) {
        console.error("❌ Failed to parse tool arguments:", parseError);

        messages.push({
          role: "tool",
          content: `Error parsing arguments: ${parseError}`,
          tool_call_id: toolCall.id,
        });
      }
    }
  }
}

/**
 * Generate OpenAI chat completion
 */
async function generateChatCompletion(
  messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[],
  tools?: OpenAI.Chat.Completions.ChatCompletionTool[]
): Promise<OpenAI.Chat.Completions.ChatCompletionMessage> {
  const response = await openaiClient.chat.completions.create({
    model: "gpt-4o",
    messages,
    ...(tools && { tools }),
  });

  return response.choices[0].message;
}

// ==================== Main Execution Flow ====================

/**
 * Main function - orchestrates the entire execution flow
 */
async function main(): Promise<void> {
  try {
    console.info("🚀 Starting OpenAI + GBOX integration");
    console.info("═".repeat(50));

    const userQuestion = getUserQuestion();
    const messages = createInitialMessages(userQuestion);
    const tools = createTools();

    // Get initial response from OpenAI
    console.info("💬 Getting initial response from OpenAI...");
    const initialResponse = await generateChatCompletion(messages, tools);
    messages.push(initialResponse);

    // Process any tool calls
    if (initialResponse.tool_calls && initialResponse.tool_calls.length > 0) {
      console.info(
        `🔧 Processing ${initialResponse.tool_calls.length} tool call(s)...`
      );
      await processToolCalls(initialResponse.tool_calls, messages);

      // Generate final response after tool execution
      console.info("💬 Getting final response from OpenAI...");
      const finalResponse = await generateChatCompletion(messages);

      console.info("🎉 Final response:");
      console.info("═".repeat(50));
      console.log(finalResponse.content);
    } else {
      console.info("🎉 Response (no tools used):");
      console.info("═".repeat(50));
      console.log(initialResponse.content);
    }
  } catch (error) {
    console.error("💥 Application error:", error);
    process.exit(1);
  }
}

// ==================== Help Information ====================

/**
 * Display usage instructions
 */
if (process.argv.includes("--help") || process.argv.includes("-h")) {
  console.log(`
🤖 OpenAI + GBOX Cloud Integration Tool

Usage:
  npx tsx index.ts [question]

Examples:
  npx tsx index.ts
  # Uses default question: "${DEFAULT_QUESTION}"

  npx tsx index.ts "Write a Python function to sort a list"
  # Uses custom question

  npx tsx index.ts "Calculate prime numbers"
  # Works with any natural language question

Options:
  --help, -h    Show this help message
    `);
  process.exit(0);
}

// Launch the application
main();

Step 2: Run the Code

Execute the following commands to run the code:
# Use default question
npx tsx index.ts

# Use custom question
npx tsx index.ts "your question here"