> ## 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.

# Simple

> Generate code with Anthropic Claude and execute it in GBOX

## Overview

This example shows how to integrate **Anthropic Claude** 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`:

````typescript TypeScript expandable highlight={68} icon="https://cdn.worldvectorlogo.com/logos/typescript.svg" theme={null}
import Anthropic from "@anthropic-ai/sdk";
import GboxSDK from "gbox-sdk";
import * as dotenv from "dotenv";

dotenv.config();

// Initialize clients
const anthropicClient = new Anthropic({
  apiKey: process.env["ANTHROPIC_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 Anthropic Claude
    const response = await anthropicClient.messages.create({
      model: "claude-3-7-sonnet-20250219",
      max_tokens: 1000,
      temperature: 0.7,
      system:
        "Generate Python code to solve problems. Always wrap code in ```python blocks.",
      messages: [
        {
          role: "user",
          content: "Calculate the first 10 Fibonacci numbers",
        },
      ],
    });

    const aiResponse =
      response.content[0].type === "text" ? response.content[0].text : "";
    console.log("\nAnthropic Claude 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();
````

````python Python expandable highlight={61} icon="https://cdn.worldvectorlogo.com/logos/python-5.svg" theme={null}
import os
import re
from anthropic import Anthropic
from gbox_sdk import GboxSDK
from dotenv import load_dotenv

# Load environment variables from .env file
load_dotenv()

# Initialize clients
anthropic_client = Anthropic(api_key=os.getenv("ANTHROPIC_API_KEY"))
gbox_sdk = GboxSDK(api_key=os.getenv("GBOX_API_KEY"))

def extract_python_code(text):
    """Extract Python code blocks from text"""
    pattern = r'```python\n([\s\S]*?)\n```'
    code_blocks = []
    matches = re.finditer(pattern, text)

    for match in matches:
        code_blocks.append(match.group(1).strip())

    return code_blocks

def main():
    try:
        # 1. Generate Python code using Anthropic Claude
        response = anthropic_client.messages.create(
            model="claude-3-7-sonnet-20250219",
            max_tokens=1000,
            temperature=0.7,
            system="Generate Python code to solve problems. Always wrap code in ```python blocks.",
            messages=[
                {
                    "role": "user",
                    "content": "Calculate the first 10 Fibonacci numbers"
                }
            ]
        )

        ai_response = response.content[0].text if response.content[0].type == "text" else ""
        print("\nAnthropic Claude Response:")
        print(ai_response)

        # 2. Extract and execute Python code
        code_blocks = extract_python_code(ai_response)

        if not code_blocks:
            print("No executable code found")
            return

        # 3. Execute code in GBOX
        box = gbox_sdk.create(type="linux")

        try:
            for code in code_blocks:
                print(f"\nExecuting code:")
                print(code)
                print("---")

                result = box.run_code(code)
                print("Execution result:")
                print(result.stdout or result.stderr or "No output")
        finally:
            box.terminate()

    except Exception as error:
        print(f"Error: {error}")

if __name__ == "__main__":
    main()
````

### Step 2: Run the Code

Execute the following command to run the example:

```bash TypeScript icon="https://cdn.worldvectorlogo.com/logos/typescript.svg" theme={null}
npx tsx index.ts
```

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

## Related Examples

> [card] [Anthropic Function Calling](https://docs.gbox.ai/run-code/anthropic/function-calling.md)
>
> Use Anthropic's Function Calling feature to create an AI assistant that can
> execute code in GBOX based on user queries

&#x20;


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.