AI Model Wiki

    Skip to main content
    45 min
    Lesson 4 of 5

    Vercel AI SDK & Full-Stack Patterns

    From the course TypeScript for AI Applications

    The Vercel AI SDK

    Core Concepts

    The AI SDK provides a unified interface for AI providers with built-in streaming:

    import { generateText, streamText } from "ai";
    import { openai } from "@ai-sdk/openai";
    
    // Non-streaming
    const { text } = await generateText({
      model: openai("gpt-4o"),
      prompt: "Explain React hooks",
    });
    
    // Streaming
    const result = streamText({
      model: openai("gpt-4o"),
      prompt: "Explain React hooks",
    });
    

    Structured Output with AI SDK

    import { generateObject } from "ai";
    
    const { object } = await generateObject({
      model: openai("gpt-4o"),
      schema: z.object({
        recipe: z.object({
          name: z.string(),
          ingredients: z.array(z.string()),
          steps: z.array(z.string()),
        }),
      }),
      prompt: "Create a recipe for chocolate chip cookies",
    });
    // object is fully typed as { recipe: { name: string; ... } }
    

    Provider Switching

    import { anthropic } from "@ai-sdk/anthropic";
    import { google } from "@ai-sdk/google";
    
    // Same interface, different providers
    const result = await generateText({
      model: anthropic("claude-sonnet-4-20250514"), // or google("gemini-2.5-flash")
      prompt: "Hello",
    });
    

    Full-Stack Pattern

    • Server: AI SDK for provider abstraction and streaming
    • Shared: Zod schemas for input/output validation
    • Client: React hooks for streaming UI
    • Testing: Mock providers for deterministic tests

    Common Pitfall: Importing Provider SDKs Directly in Shared Code

    Importing openai or @anthropic-ai/sdk directly in shared utility functions couples that code to a specific provider. When you want to add a new provider or run tests without real API calls, the coupling makes it hard. Define a provider interface instead:

    // Define the interface
    interface LLMProvider {
      complete(messages: ChatMessage[], options?: ChatOptions): Promise<ChatResponse>;
      stream(messages: ChatMessage[], options?: ChatOptions): AsyncGenerator<StreamEvent>;
    }
    
    // Provider implementations conform to the interface
    class OpenAIProvider implements LLMProvider { ... }
    class AnthropicProvider implements LLMProvider { ... }
    class MockProvider implements LLMProvider { ... }  // For tests
    
    // Inject via dependency injection
    function buildChatService(provider: LLMProvider) {
      return { chat: (msg: string) => provider.complete([{ role: "user", content: msg }]) };
    }
    

    Best Practice: Use Environment-Based Provider Selection

    Switch providers via environment variables without code changes:

    function createProvider(): LLMProvider {
      switch (process.env.LLM_PROVIDER) {
        case "anthropic": return new AnthropicProvider();
        case "mock": return new MockProvider();  // For CI/testing
        default: return new OpenAIProvider();
      }
    }
    

    Named Product Reference: Vercel AI SDK Provider Abstraction

    The Vercel AI SDK already implements this pattern — @ai-sdk/openai, @ai-sdk/anthropic, and @ai-sdk/google all conform to the same interface. Switching providers requires changing one import. For teams that want provider flexibility without writing the abstraction layer themselves, starting with the Vercel AI SDK is the right choice.

    Key Takeaways

    • •Vercel AI SDK provides a unified interface across AI providers
    • •generateObject returns typed objects validated against Zod schemas
    • •Switch providers with one line — same interface everywhere
    • •Full-stack pattern: AI SDK server + Zod shared + React hooks client
    0 of 5 lessons marked complete

    Progress is kept in this browser only.