| | |

Vercel 15 ▲ AI SDK, AI Gateway & Sandbox — Routing across 400+ AI models with failover and running isolated code in Sandbox VMs

⏱️ Estimated read: 8 min | |

Modern AI applications require more than just a basic API wrapper; they demand robust infrastructure to handle model fragmentation, provider reliability, and secure code execution. The Vercel AI ecosystem provides a three-tiered architecture to solve these challenges: the AI SDK for unified integration, the AI Gateway for traffic orchestration, and the Sandbox for secure, isolated code execution. This stack moves the heavy lifting of managing AI infrastructure from the application layer to the platform, allowing developers to focus on prompt engineering and user experience rather than managing API keys, rate limits, or dangerous remote code execution.

The AI SDK standardizes the interface for interacting with hundreds of models, while the AI Gateway acts as a global traffic controller, providing caching, failover, and observability. Perhaps most crucially, the Sandbox provides a hardened, micro-VM execution environment that mitigates the risks associated with running model-generated code. This tutorial explores the lifecycle of an AI request, from intelligent model routing and caching to the safe execution of dynamic Python or JavaScript code generated by LLMs.

Key point: Vercel’s AI ecosystem decouples your application from specific providers through the AI SDK, optimizes availability and costs via the AI Gateway, and enables secure AI-generated code execution through the Sandbox micro-VM environment.


Why exists

The model fragmentation problem.

Developers currently face dozens of different APIs for various providers (OpenAI, Anthropic, Google, Mistral). The AI SDK provides a single, unified interface (generateText, streamText) so you can swap models without rewriting your entire integration layer.

The provider reliability challenge.

AI APIs are prone to outages and rate limits. If a primary provider (e.g., OpenAI) goes down, your application shouldn’t crash. The AI Gateway provides automated failover, routing requests to secondary models when the primary one fails.

The code execution risk.

LLMs often generate code as part of their response. Executing this code directly on your server is a massive security vulnerability (remote code execution). The Sandbox provides an isolated micro-VM to run this code safely, preventing the AI from accessing your file system or network.

The cost and latency overhead.

Hitting an LLM for repetitive queries is expensive and slow. The AI Gateway caches common responses globally, reducing latency and cost while providing deeper observability into token usage and prompt performance.

The context and state complexity.

Managing conversation history, tool calling (function calling), and streaming responses manually is error-prone. The AI SDK simplifies these complex stateful interactions into intuitive stream-based paradigms, handling the JSON schema parsing and multi-turn conversation memory for you.


a. The AI SDK: Unified Streaming and Tool Calling

The AI SDK is the interface layer. It normalizes responses from different providers, allowing you to use streaming and structured data extraction regardless of whether you are targeting GPT-4o, Claude 3.5, or Gemini. The core primitive is streamText, which handles the response buffering, tool-call orchestration, and finish-reason tracking in a single, predictable flow.

import { streamText } from 'ai';
import { openai } from '@ai-sdk/openai';

// Standardized call across providers
const result = await streamText({
  model: openai('gpt-4o'),
  prompt: 'Explain the Vercel Sandbox in one sentence.',
});

// Streams back to the client directly
for await (const textPart of result.textStream) {
  process.stdout.write(textPart);
}

This abstraction allows “Model Agnosticism.” You can define a configuration file that maps your environment to a specific model provider, and your application code remains identical. If you need to switch from a high-performance model to a cheaper, faster one for a specific use case, you only change the model import.

b. AI Gateway: Routing, Caching, and Failover

The AI Gateway acts as a transparent proxy for your AI calls. By routing requests through the Gateway URL rather than the direct provider URL, you unlock global caching, rate limiting, and failover rules. If your primary provider returns a 5xx error, the Gateway automatically retries or fails over to a pre-configured secondary model, ensuring high availability.

// The Gateway intercepts and routes
const gatewayUrl = 'https://gateway.ai.vercel.com';

const response = await fetch(`${gatewayUrl}/openai/chat/completions`, {
  headers: {
    'Authorization': `Bearer ${process.env.AI_GATEWAY_TOKEN}`,
    'x-ai-gateway-provider': 'openai' // Routing metadata
  },
  body: JSON.stringify({ ... })
});

This layer also provides “Observability.” You can see the exact token usage, latency distribution, and cost per request within the Vercel dashboard, providing insights that are usually siloed inside each provider’s individual dashboard.

c. The Sandbox: Isolated Execution

The Sandbox runs code in a hardened micro-VM, completely isolated from your main application and the underlying host. When the LLM generates a script (e.g., a Python data analysis script), you pass the code to the Sandbox. It executes the code, returns the stdout, stderr, and the final state, then destroys the environment.

import { Sandbox } from '@e2b/sdk'; // Example implementation pattern

const sandbox = await Sandbox.create({ template: 'python-data-science' });
const execution = await sandbox.runCode(`print(f"Result: {1 + 1}")`);

console.log(execution.text); // Output: Result: 2

Because the Sandbox is a micro-VM, it cannot access your environment variables, database, or internal network. This allows you to build “Code Interpreter” style features (like LLM-powered data visualization or mathematical processing) without exposing your production infrastructure to the risks of arbitrary code execution.


Complete Example Session

// ============================================
// PART 1: UNIFIED MODEL CALL
// ============================================
import { streamText } from 'ai';
import { openai } from '@ai-sdk/openai';

const result = await streamText({
  model: openai('gpt-4o'),
  prompt: 'Analyze this data.',
});

// ============================================
// PART 2: GATEWAY CONFIGURATION
// ============================================
// AI Gateway is configured via Vercel Dashboard
// Failover: OpenAI -> Anthropic
// Cache: Enabled

// ============================================
// PART 3: SANDBOX EXECUTION
// ============================================
import { Sandbox } from '@e2b/sdk';
const sandbox = await Sandbox.create({ template: 'python' });
const { stdout } = await sandbox.runCode('print("Hello from Sandbox")');

// ============================================
// PART 4: INTEGRATION
// ============================================
// The LLM generates the code, the app runs it.
const code = await generateCodeFromLLM();
const output = await sandbox.runCode(code);

This session showcases the pipeline: the SDK handles the conversation, the Gateway ensures the request reaches the model reliably, and the Sandbox executes any code the model generates.


Quick Reference

The Three Pillars

ComponentResponsibilityBenefit
AI SDKNormalizationModel Agnosticism
AI GatewayRouting/FailoverReliability/Cost
SandboxSecure ExecutionCode Safety

AI Gateway Capabilities

FeatureDescription
FailoverSwitch to secondary model on 5xx
CachingServe repeat prompts from Edge
Rate LimitingPrevent abuse/overspending
LoggingToken tracking/Cost analysis

Best Practices

✅ Do This:

// Always stream responses
const result = await streamText({...});                       // ✅

// Set explicit tool definitions
const result = await streamText({ tools: {...} });             // ✅

// Use Sandbox templates
const sandbox = await Sandbox.create({ template: 'js' });      // ✅

// Monitor costs in Gateway
// (Check AI Gateway dashboard)                                 // ✅

❌ Don’t Do This:

// Execute model-generated code in production
eval(modelGeneratedCode);                                      // ❌

// Use raw fetch for AI APIs
// (Misses Gateway features like failover)                      // ❌

// Send sensitive data to Sandbox
// (Unless explicitly intended)                                // ❌

// Forget to limit Sandbox execution time
// (Infinite loops)                                            // ❌

Common Pitfalls

PitfallWhy It HappensFix
Insecure Executioneval() usageUse Sandbox micro-VMs
Provider Lock-inDirect API usageUse AI SDK abstractions
Latency SpikesCache missesWarm up caches/Gateway
Code InjectionMalicious LLM outputsUse strict Sandbox resource limits

Real-World Examples

1. Switching Models

const model = useAlternative ? anthropic('claude-3') : openai('gpt-4o');

2. Gateway Failover

// Configured in Vercel Dashboard

3. Secure Code Runner

const { stdout } = await sandbox.runCode(llmGeneratedCode);

4. Streaming Response

return result.toDataStreamResponse();

5. Tool Calling

tools: { getWeather: { execute: async () => ... } }

6. Global Cache

// Enabled via Gateway settings

7. Token Usage Tracking

const { usage } = await result.usage;

8. Sandbox Timeout

await sandbox.runCode(code, { timeout: 5000 });

9. System Prompt

system: 'You are a data analysis assistant.'

10. Multi-Provider Fallback

// Gateway handles this automatically

Visual

The AI Stack Architecture

┌────────────────────────────────────────────────────────┐
│  USER CLIENT                                           │
│       │                                                │
│  AI SDK (App Code)                                     │
│       │                                                │
│  AI GATEWAY (Failover, Cache, Observability)           │
│       │                                                │
│  AI PROVIDER (OpenAI/Anthropic/Gemini)                 │
│       │                                                │
│  SANDBOX (Micro-VM Code Execution)                     │
└────────────────────────────────────────────────────────┘

Sandbox Isolation

┌────────────────────────────────────────────────────────┐
│  MAIN PROCESS (Node.js)                                │
│  ┌──────────────────────────────────────────────────┐  │
│  │ SANDBOX (Micro-VM)                               │  │
│  │ ┌──────────────┐ ┌──────────────┐                │  │
│  │ │ User Code    │ │ Runtime      │                │  │
│  │ └──────────────┘ └──────────────┘                │  │
│  └──────────────────────────────────────────────────┘  │
│  [No filesystem/Network access to Main Process]        │
└────────────────────────────────────────────────────────┘

Failover Flow

┌────────────────────────────────────────────────────────┐
│  REQUEST ──► AI GATEWAY ──► PROVIDER A (Fail)          │
│                                  │                     │
│                             RETRY TO PROVIDER B        │
│                                  │                     │
│                             SUCCESS                    │
└────────────────────────────────────────────────────────┘

Summary

ItemValue
SDKUnified Interface
GatewayFailover/Caching
SandboxSecure Execution
Primary GoalReliability & Safety

Key takeaways:

  • Unify with AI SDK. Decouple your code from providers using the standard streamText and generateText abstractions.
  • Reliability via Gateway. Route your requests through the AI Gateway to gain automated failover, global caching, and observability without extra code.
  • Safety via Sandbox. Never execute LLM-generated code in the main application process; always pass it to a hardened, micro-VM-based Sandbox.
  • Observe everything. Use the Gateway dashboards to monitor token usage and costs, which are invisible when calling APIs directly.
  • Design for failure. Assume AI models will fail; use the Gateway’s routing rules to ensure your users aren’t impacted by provider outages.

Remember: The Vercel AI ecosystem provides the infrastructure required to scale AI applications safely and reliably. By utilizing the SDK for abstraction, the Gateway for operational resilience, and the Sandbox for secure computation, you transform AI from a fragile experimental feature into a robust production-grade system.

Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!