Feb 09, 2026
8 min read

Run the GitHub Copilot CLI in Koyeb Sandboxes for Secure Code Generation of a Gradio App

The GitHub Copilot CLI lets you interact with Copilot directly from the command line. When combined with Koyeb Sandboxes, you can build applications that leverage Copilot's code generation and reasoning capabilities in an isolated, ephemeral environment.

In this tutorial, you'll create a Python application that uses the Koyeb Python SDK to:

  • Launch an ephemeral sandbox environment
  • Clone the example-gradio repository inside the sandbox
  • Use the Copilot CLI to enhance the Gradio application with a new interactive component (a draggable list)
  • Launch Gradio and expose its port via a TCP proxy URL
  • Access the application through a public preview URL

This approach demonstrates how sandboxes enable rapid prototyping of AI-assisted applications without managing local infrastructure.

Requirements

To successfully run the GitHub Copilot SDK in Koyeb Sandboxes, you need:

Steps

To create the code generation application, you will complete the following steps:

  1. Install the Koyeb SDK and Set Up Your Environment
  2. Create the Sandbox Controller Script
  3. Run Your Sandbox Application
  4. Access Your Application
  5. Keep Sandbox Running
  6. Inspect Sandbox Files (Optional)

Use Cases for Sandboxed Copilot

Running Copilot within sandboxed environments offers several advantages:

Isolated Development: Each sandbox is ephemeral and runs in complete isolation. This eliminates environment conflicts and ensures every execution starts from a clean slate.

CI/CD Integration: Automatically generate code, run tests, and validate changes in your deployment pipeline without affecting your local machine.

Multi-tenant SaaS: Offer Copilot-assisted features to users safely. Each user session gets its own isolated sandbox that's destroyed after use.

Compute Offloading: Let Koyeb's infrastructure handle code generation and compilation while you focus on other tasks.

Security: Code generation happens in ephemeral containers that are automatically destroyed. No persistent traces remain on shared systems.

Reproducibility: Generate identical outputs across runs without environmental drift or version conflicts.

Complete the following steps to set up your environment and implement the app functionality. Alternatively, the complete code is available to download on GitHub.

Install the Koyeb SDK and Set Up Your Environment

First, initialize a new Python project using uv:

uv init copilot-in-sandbox

Open your directory in the IDE of your choice.

Set up a new virtual environment and install required dependencies:

uv add koyeb-sdk

Next, create your Koyeb API token and GitHub personal access token. Set them as environment variables:

export KOYEB_API_TOKEN="your_koyeb_api_token_here"
export GITHUB_TOKEN="your_github_token_here"

Create the Sandbox Controller Script

In your copilot-in-sandbox project, open main.py and replace its contents with the following code. This script will orchestrate the entire workflow using the Koyeb Sandbox SDK:

# main.py
import os
import re
import sys
import textwrap
import time
from koyeb import Sandbox

def main():
    """Main function to run Copilot inside a Koyeb Sandbox."""
    GITHUB_TOKEN = os.getenv("GITHUB_TOKEN")
    if not GITHUB_TOKEN:
        print("Error: GITHUB_TOKEN environment variable is not set")
        sys.exit(1)

    # Initialize sandbox
    print("=== Launching Koyeb Sandbox ===\n")
    sandbox = Sandbox.create(
        name="copilot-gradio-sandbox",
        wait_ready=True,
        idle_timeout=0,  # Keep sandbox alive indefinitely
        env={
            "GITHUB_TOKEN": GITHUB_TOKEN,
            }
    )
    print(f"✓ Sandbox created: {sandbox.name}\n")
    
    # Get filesystem and process interfaces
    fs = sandbox.filesystem
    
    try:
        # Step 1: Install dependencies
        print("Step 1: Installing dependencies...")
        result = sandbox.exec("apt-get update && apt-get install -y git curl python3-pip python3-venv", on_stdout=lambda line: print(f"[Sandbox] {line}"), on_stderr=lambda line: print(f"[Sandbox ERROR] {line}"))
        print("✓ Dependencies installed\n")
        
        # Step 2: Install Copilot CLI
        print("Step 2: Setting up Copilot CLI...")
        result = sandbox.exec("curl -fsSL https://gh.io/copilot-install | bash", on_stdout=lambda line: print(f"[Sandbox] {line}"), on_stderr=lambda line: print(f"[Sandbox ERROR] {line}"))
        if result.exit_code != 0:
            print(f"Error during Copilot CLI installation: {result.stderr}")
            return
        print("✓ Copilot CLI installed\n")
        
        # Step 3: Clone the example-gradio repository
        print("Step 3: Cloning example-gradio repository...")
        result = sandbox.exec("cd /tmp && git clone https://github.com/koyeb/example-gradio.git", on_stdout=lambda line: print(f"[Sandbox] {line}"), on_stderr=lambda line: print(f"[Sandbox ERROR] {line}"))
        if result.exit_code != 0:
            print(f"Error during repository cloning: {result.stderr}")
            return
        print("✓ Repository cloned\n")
        
        # Step 4: Install Python dependencies
        print("Step 4: Installing Python dependencies...")
        result = sandbox.exec("cd /tmp/example-gradio && pip install -r requirements.txt", on_stdout=lambda line: print(f"[Sandbox] {line}"), on_stderr=lambda line: print(f"[Sandbox ERROR] {line}"), timeout=300)
        if result.exit_code != 0:
            print(f"Error during Python dependencies installation: {result.stderr}")
            return
        print("✓ Gradio installed\n")
        
        # Step 5: Read the current app.py
        print("Step 5: Reading original application...")
        result = sandbox.exec("cat /tmp/example-gradio/app.py", on_stdout=lambda line: print(f"[Sandbox] {line}"), on_stderr=lambda line: print(f"[Sandbox ERROR] {line}"))
        original_code = result.stdout
        print("✓ Original app loaded\n")
        
        # Step 6: Use Copilot to enhance the app
        print("Step 6: Using Copilot to add a draggable list component...")
        prompt = f'''
I have this Gradio application:

{original_code}

Please enhance it by adding a new interactive component: a draggable list of programming languages (Python, JavaScript, Go).

The enhancement should:
- Add a new gr.Dropdown component with multiselect=True
- Display the three languages: Python, JavaScript, Go
- Show the current selected/reordered languages below
- Keep all existing functionality
- In demo.launch(), use: server_name="0.0.0.0", server_port=7860

Provide only the updated app.py code.
'''
        
        # Create a prompt file in the sandbox
        fs.write_file("/tmp/copilot_prompt.txt", prompt)
        
        # Use gh copilot to suggest code (or use the API if available)
        result = sandbox.exec("copilot -sp /tmp/copilot_prompt.txt")
        if result.exit_code != 0:
            print(f"Error during Copilot suggestion: {result.stderr}")
            return
        print("✓ Copilot suggestion generated\n")
        
        # Step 7: Create enhanced app.py
        # Extract Python code block from Copilot response
        copilot_response = result.stdout
        code_match = re.search(r'```python\s*(.*?)\n?```', copilot_response, re.DOTALL)
        if code_match:
            enhanced_code = textwrap.dedent(code_match.group(1))
        else:
            # Fallback to original code if no code block found
            print("Warning: Could not extract code block from Copilot response, using original code")
            enhanced_code = original_code
        
        print("Step 7: Writing enhanced application...")
        fs.write_file("/tmp/example-gradio/app_enhanced.py", enhanced_code)
        print("✓ Enhanced app created\n")
        
        # Step 8: Start Gradio
        print("Step 8: Starting Gradio application...")
        port = sandbox.expose_port(7860)
        process_id = sandbox.launch_process(
            "cd /tmp/example-gradio && python3 app_enhanced.py",
            cwd="/tmp",
            env={"GRADIO_SERVER_PORT": "7860"}
        )
        domain = port.exposed_at
        print(f"✓ Gradio started (process ID: {process_id})\n")
        
        # Wait for Gradio to start
        time.sleep(3)
        
        print("✓ Gradio is running on port 7860\n")
        print("📍 Your sandbox is now active with Gradio running.\n")
        print(f"Access your application through your sandbox's public URL: {domain}\n")
        
        # Keep sandbox alive
        print("Sandbox is running. Press Ctrl+C to terminate.\n")
        try:
            while True:
                time.sleep(1)
        except KeyboardInterrupt:
            print("\n\nTerminating sandbox...")
        
    finally:
        # Clean up
        print("Cleaning up resources...")
        sandbox.delete()
        print("✓ Sandbox deleted")

if __name__ == "__main__":
    main()

Run Your Sandbox Application

Execute the script:

uv run main.py

The script takes these steps:

  1. Creates an ephemeral sandbox using the default Ubuntu image, keeping the sandbox awake indefinitely, and passing your GitHub token.
  2. Installs dependencies and Copilot CLI.
  3. Clones the example-gradio repository.
  4. Installs the project dependencies.
  5. Uses GitHub Copilot to enhance the application by adding a dropdown menu.
  6. Writes the enhanced code to a file in the sandbox.
  7. Exposes port 7860 with a public TCP proxy URL so the app can be viewed externally.
  8. Launches Gradio on port 7860.
  9. Prints the preview URL to access your application.

Access Your Application

When the script completes, the Gradio application is running on port 7860, which is automatically exposed by Koyeb at the root path.

Your sandbox's public URL is printed in the terminal logs when running the application. Access it to interact with your enhanced Gradio application. You'll see the new draggable language list component alongside any existing features from the original example-gradio app.

Example URL:

https://your-sandbox-name.koyeb.app

There is no manual port exposure needed, Koyeb handles it automatically for port 7860.

Keep Sandbox Running

The script keeps the sandbox alive by waiting for a keyboard interrupt. Your Gradio application will continue running and remain accessible through your sandbox's public URL.

To stop the script and clean up the sandbox, press Ctrl+C in your terminal.

Koyeb Sandboxes also give you the option to automatically delete based on user-defined periods configured after creation or after a period of inactivity when the sandbox is scaled to zero. For more information, view the documentaiton on auto-deletion

Inspect Sandbox Files (Optional)

While the sandbox is running, you can inspect files using the filesystem interface:

# Read a file from the sandbox
content = fs.read_file("/tmp/example-gradio/app_enhanced.py")
print(content)

# List directory contents
files = fs.list_dir("/tmp/example-gradio")
print(files)

You can also access the sandbox in the Koyeb control panel. Select the Console tab for your sandbox and run the following command:

Read a file from the sandbox:

cat /tmp/example-gradio/app_enhanced.py

List directory contents:

ls -la /tmp/example-gradio

This shows the updated Gradio app code and Gradio project, respectively, so you can view the changes.

Conclusion

In this tutorial, you successfully:

  • Created a Python script using the Koyeb Sandbox SDK
  • Launched an ephemeral sandbox environment
  • Cloned a GitHub repository inside the sandbox
  • Used GitHub Copilot to enhance a Gradio application
  • Exposed the application via a public TCP proxy URL
  • Accessed the running application from your browser

This pattern enables rapid prototyping of AI-assisted applications while leveraging Koyeb's infrastructure for compute and networking.

Next Steps


Deploy AI apps to production in minutes

Get started
Koyeb is a developer-friendly serverless platform to deploy apps globally. No-ops, servers, or infrastructure management.
All systems operational
© Koyeb