> ## Documentation Index
> Fetch the complete documentation index at: https://docs.gbox.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Function Calling

> Use function call to execute code in GBOX

## 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`:

<CodeGroup>
  ```typescript TypeScript expandable icon="https://cdn.worldvectorlogo.com/logos/typescript.svg" theme={null}
  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();
  ```

  ```python Python expandable icon="https://cdn.worldvectorlogo.com/logos/python-5.svg" theme={null}
  import os
  import sys
  import json
  import openai
  from dotenv import load_dotenv
  from gbox_sdk import GboxSDK
  from typing import Dict, List, Any

  # Load environment variables from .env file
  load_dotenv()

  # ==================== Initialize Clients ====================
  gbox_sdk = GboxSDK(api_key=os.getenv("GBOX_API_KEY"))
  openai_client = openai.OpenAI(api_key=os.getenv("OPENAI_API_KEY"))

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

  # ==================== Utility Functions ====================

  def get_user_question():
      """Get user question from command line arguments or use default"""
      args = sys.argv[1:]

      if args:
          user_question = " ".join(args).strip()
          if user_question:
              print(f"📝 Using user question: \"{user_question}\"")
              return user_question

      print(f"📝 Using default question: \"{DEFAULT_QUESTION}\"")
      return DEFAULT_QUESTION

  def create_initial_messages(question: str) -> List[Dict[str, Any]]:
      """Create initial conversation messages"""
      return [{"role": "user", "content": question}]

  def create_tools() -> List[Dict[str, Any]]:
      """Define available tools"""
      return [
          {
              "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 ====================

  def execute_python_code(code: str) -> Dict[str, Any]:
      """Execute Python code using GBOX"""
      box = gbox_sdk.create(type="linux")

      try:
          print("📝 Executing Python code:")
          print(code)
          print("─" * 50)

          execution = box.run_code(code)
          result = execution.stdout or execution.stderr or "No output"

          print("✅ Execution result:")
          print(result)
          print("─" * 50)

          return {"success": True, "result": result}

      except Exception as error:
          error_message = f"Error: {error}"
          print(f"❌ Execution failed: {error_message}")
          return {"success": False, "result": error_message}

      finally:
          box.terminate()

  def process_tool_calls(tool_calls: List[Dict[str, Any]], messages: List[Dict[str, Any]]):
      """Process tool calls from OpenAI response"""
      for tool_call in tool_calls:
          if tool_call["function"]["name"] == "execute_python":
              try:
                  arguments = json.loads(tool_call["function"]["arguments"])
                  code = arguments["code"]
                  execution_result = execute_python_code(code)

                  # Add tool result to conversation
                  messages.append({
                      "role": "tool",
                      "content": execution_result["result"],
                      "tool_call_id": tool_call["id"]
                  })

              except Exception as parse_error:
                  print(f"❌ Failed to parse tool arguments: {parse_error}")
                  messages.append({
                      "role": "tool",
                      "content": f"Error parsing arguments: {parse_error}",
                      "tool_call_id": tool_call["id"]
                  })

  def generate_chat_completion(messages: List[Dict[str, Any]], tools: List[Dict[str, Any]] = None):
      """Generate OpenAI chat completion"""
      params = {
          "model": "gpt-4o",
          "messages": messages
      }

      if tools:
          params["tools"] = tools

      response = openai_client.chat.completions.create(**params)
      return response.choices[0].message

  # ==================== Main Execution Flow ====================

  def main():
      """Main function - orchestrates the entire execution flow"""
      try:
          print("🚀 Starting OpenAI + GBOX integration")
          print("═" * 50)

          user_question = get_user_question()
          messages = create_initial_messages(user_question)
          tools = create_tools()

          # Get initial response from OpenAI
          print("💬 Getting initial response from OpenAI...")
          initial_response = generate_chat_completion(messages, tools)
          messages.append(initial_response.model_dump())

          # Process any tool calls
          if hasattr(initial_response, 'tool_calls') and initial_response.tool_calls:
              print(f"🔧 Processing {len(initial_response.tool_calls)} tool call(s)...")
              tool_calls_dict = [tc.model_dump() for tc in initial_response.tool_calls]
              process_tool_calls(tool_calls_dict, messages)

              # Generate final response after tool execution
              print("💬 Getting final response from OpenAI...")
              final_response = generate_chat_completion(messages)

              print("🎉 Final response:")
              print("═" * 50)
              print(final_response.content)
          else:
              print("🎉 Response (no tools used):")
              print("═" * 50)
              print(initial_response.content)

      except Exception as error:
          print(f"💥 Application error: {error}")
          sys.exit(1)

  # ==================== Help Information ====================

  if "--help" in sys.argv or "-h" in sys.argv:
      print(f"""
  🤖 OpenAI + GBOX Cloud Integration Tool

  Usage:
    python index.py [question]

  Examples:
    python index.py
    # Uses default question: "{DEFAULT_QUESTION}"

    python index.py "Write a Python function to sort a list"
    # Uses custom question

    python index.py "Calculate prime numbers"
    # Works with any natural language question

  Options:
    --help, -h    Show this help message
      """)
      sys.exit(0)

  # Launch the application
  if __name__ == "__main__":
      main()
  ```
</CodeGroup>

### Step 2: Run the Code

Execute the following commands to run the code:

<CodeGroup>
  ```bash TypeScript icon="https://cdn.worldvectorlogo.com/logos/typescript.svg" theme={null}
  # Use default question
  npx tsx index.ts

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

  ```bash Python icon="https://cdn.worldvectorlogo.com/logos/python-5.svg" theme={null}
  # Use default question
  python index.py

  # Use custom question
  python index.py "your question here"
  ```
</CodeGroup>
