Explore topics

Topic

AI SDK Examples

Every example here is a complete implementation — API route, client component, and the SDK call in context — not a snippet. Start with the core functions (generateText, streamText, generateObject), then move into the Agent API: loop control with stopWhen, context trimming with prepareStep, structured agent output, and tool-call repair. Examples track the current AI SDK release, with version notes where behavior changed.

52 patterns7 featured

AI SDK version notes

These examples track the current AI SDK release. Prefer the Agent API (`ToolLoopAgent`, `stopWhen`, `prepareStep`) over one-off versioned landing pages — version URLs rot as soon as the next major ships.

If you are migrating from older AI SDK majors: structured output moved toward `Output.object()` / schema-first helpers, agent loops expose explicit stop conditions (`stopWhen`, `stepCountIs`), and tool-call repair is a first-class recovery path when the model emits malformed arguments. Open the featured Agent API patterns below for the working shape; skim the pattern READMEs for breaking-change callouts.

Featured patterns

A curated starting point for this topic — open a live preview, then adapt the source.

7 curated
Generate Text preview
01

Generate Text

Generate text from prompts using AI. Simple interface with character counting and response rendering.

  • Generate complete text responses with generateText
  • Call an AI Gateway model from a minimal API route
  • Show non-streaming prompt-to-text results in the UI
generateTextconvertToModelMessagesaiprompt
Stream Text preview
02

Stream Text

Stream text responses from AI prompts in real-time. Includes character counting and live response rendering with useCompletion.

  • Stream text tokens to the client in real time
  • Render live completions with useCompletion
  • Demonstrate AI SDK streaming text over an API route
streamTextuseCompletionaiprompt
OpenAI Structured Output preview
03

OpenAI Structured Output

Generate structured output from AI prompts using OpenAI. Create typed data with generateText and Output.object().

  • Generate schema-validated objects with OpenAI via generateObject
  • Return complete structured JSON in one response
  • Demonstrate OpenAI structured output through the AI SDK
generateTextOutput.objectaiprompt
Loop Control: stopWhen preview
04Intermediate

Loop Control: stopWhen

Demonstrate ToolLoopAgent loop control with stopWhen. Covers stepCountIs, hasToolCall, combined conditions, and a custom StopCondition with step timeline visualization.

  • Stop agent loops with stepCountIs
  • Halt when a specific tool is called via hasToolCall
  • Combine multiple stopWhen conditions
ToolLoopAgentstopWhenstepCountIsai
PrepareStep: Trim Message History preview
05Intermediate

PrepareStep: Trim Message History

Demonstrate ToolLoopAgent prepareStep for trimming long message history. Pre-seeded 24-message conversation shows context compression on the first run with per-step trim telemetry.

  • Trim long message histories before each agent step
  • Keep recent tool results while dropping stale turns
  • Observe prepareStep compression with per-step telemetry
ToolLoopAgentprepareStepstepCountIsai
Tool Call Repair preview
06Intermediate

Tool Call Repair

Repair invalid tool calls using experimental_repairToolCall. Fix schema validation errors without requiring additional steps that pollute message history.

  • Repair malformed tool calls before retrying execution
  • Fix schema validation errors with generateObject
  • Avoid polluting message history with extra repair turns
streamTextconvertToModelMessagestool(ai
Structured Agent Output: Output.array preview
07Intermediate

Structured Agent Output: Output.array

Demonstrate structured agent outputs using ToolLoopAgent with Output.array. Returns structured array output with element schema for predictable, type-safe responses.

  • Return structured arrays from ToolLoopAgent with Output.array
  • Validate each array element against a Zod object schema
  • Combine list-shaped outputs with tool-calling agents
ToolLoopAgentOutput.arrayagent.generateai

More patterns

Additional patterns that fit this topic.

45 more
01
HIL Tool Approval BasicChat assistant with human approval workflows for safe tool execution.
02
HIL Agentic Context BuilderBuild brand context through AI-guided questioning and web research. Gathers insights to create detailed brand profiles.
03
Prompt UI ImproverTransform short, vague UI requests into production-grade design briefs with strong visual, interaction, and implementation detail.
04
AI SDK Gemini Flash TextGenerate text and analyze market research using Google's Gemini 2.5 Flash. Includes interactive charts and data visualization.
05
AI SDK Nano Banana ImageGenerate images using Nano Banana 2.5 Flash with prompt optimization. Includes style adaptation and customizable parameters.
06
AI SDK Nano Banana Image EditGenerate and edit images using Nano Banana 2.5 Flash. Create new images from text or edit existing ones with natural language. Includes version history and image comparison.
07
AI SDK Nano Banana Image MergeGenerate, edit, and merge images using Nano Banana 2.5 Flash. Create new images from text, edit existing ones with natural language, or merge two images together. Includes version history and image comparison.
08
HIL Needs ApprovalDemonstrate tool approval with async generators. Includes real-time feedback, approval workflows, and interactive management.
09
Tool Input Lifecycle HooksExplore tool input lifecycle hooks: onInputStart, onInputDelta, and onInputAvailable. See how to track tool input generation in real-time during streaming.
10
Preliminary Tool ResultsReturn preliminary tool results using async iterables. Stream status updates during tool execution before the final result is available.
11
Tool API ContextPass arbitrary context from generateText/streamText to tool execution via experimental_context. Access context in tool execute functions for dynamic behavior.
12
Dynamic ToolCreate dynamic tools with runtime-generated schemas using dynamicTool. Demonstrates unit conversion tools where schema adapts based on conversion type (temperature, length, weight, currency) and supports dynamic model selection.
13
Structured Agent Output: Output.choiceDemonstrate structured agent outputs using ToolLoopAgent with Output.choice. Constrain agent outputs to predefined choices for predictable, type-safe responses.
14
Call Options: prepareCallDynamically configure one ToolLoopAgent per request with callOptionsSchema and prepareCall. A customer-support agent rewrites instructions, gates tools, tunes reasoning effort, and injects RAG context based on account tier and urgency.
15
Tool Context: experimental_contextInject request-scoped context (user identity, database handles, session) into ToolLoopAgent tools via experimental_context, so the model never supplies sensitive identity in tool inputs.
16
Chat-Base CloneA comprehensive Chatbase clone demo with widget interface, model selection, web search integration, and human-in-the-loop tool approval workflows.
17
AI Form GeneratorGenerate Zod schemas from natural language descriptions using AI. Automatically creates form schemas that render interactive forms with real-time validation.
18
Branding AgentExtract brand design systems from any website using Firecrawl, then use AI tools to export tokens, generate color palettes, check accessibility, and analyze brand personality.
19
Brand Product Placement Generator (Nano Banana)Paste a website URL to extract brand signals with Firecrawl, generate a structured product photography brief, auto-create four Nano Banana placement images, and click any result into a local edit flow.
20
Brand Mood Board GeneratorPaste a website URL to extract brand signals with Firecrawl, generate a structured mood-scene brief for abstract and environmental imagery, auto-create four brand-world images, and click any result into a local edit flow.
21
Brand Guidelines Image GeneratorPaste a website URL to extract brand signals with Firecrawl, generate a structured brand-standards brief, render manual-style spreads (color, typography, grid, photography, and more), and refine any image with edit instructions.
22
Competitor Research AgentEnter a competitor URL to get comprehensive competitive intelligence. Uses Firecrawl Map + Parallel Scrape for fast extraction (~3-5s). Analyzes positioning, pricing, features, tech stack, and generates sales battle cards.
23
Data Analysis AgentUpload CSV or JSON data and get AI-powered analysis with interactive visualizations. Detect patterns, correlations, outliers, and generate insights with confidence scores. Export comprehensive reports.
24
Accessibility Audit AgentAudit any website for WCAG 2.1 accessibility compliance using Firecrawl, then use AI tools to analyze issues by severity, check color contrast, validate heading structure, generate alt text, and create prioritized remediation plans with visual tool outputs.
25
SEO AuditAudit any website for on-page SEO issues using Firecrawl. Scrapes a URL, then renders a full-screen report analyzing meta tags, content structure, links, keywords, and schema markup with exportable reports.
26
Marketing agent with skills + readFileChat UI wired to a ToolLoopAgent that loads filesystem skills and exposes readFile on the skill sandbox—demo includes ad-creative, copywriting, and paid-ads skill packs for campaign workflows.
27
Reddit Product Validation AgentValidate startup ideas with a two-phase workflow: discover relevant subreddits, then analyze pain points, existing solutions, willingness to pay, demand trends, and early adopters. Get a go/no-go scorecard with actionable insights.
28
AI Wizard Brand StrategyA full-screen AI levee interface where each stage is an adaptive interview with lock-based progression and dynamic tool-driven prompts.
29
Firecrawl Brand PDFGenerate structured brand brief PDFs from any website URL using Firecrawl branding extraction and JSON Render PDF streaming.
30
Firecrawl Landing Page Teardown PDFGenerate a conversion-focused landing page teardown PDF using one landing URL plus 2-5 competitor URLs.
31
Generate Speech (OpenAI)Convert text to speech using OpenAI's API. Includes multiple voices, speed control, and real-time playback for voiceovers and accessibility.
32
Transcribe Audio (OpenAI)Transcribe audio files using OpenAI's API. Includes real-time transcription and language detection.
33
Streaming Structured OutputStream structured output from AI prompts in real-time using streamText with Output.object(). Generate typed data with useObject and live rendering.
34
Claude Structured OutputGenerate structured output from AI prompts using Anthropic Claude. Create typed data with generateText and Output.object().
35
Gemini Structured OutputGenerate structured output from AI prompts using Google Gemini. Create typed data with generateText and Output.object().
36
Generate Image (OpenAI)Generate images from text prompts using OpenAI's DALL-E 3. Create high-quality images with AI.
37
Generate Image (Fal.ai)Generate images from text prompts using Fal.ai's Flux model. Fast and high-quality image generation.
38
Generate Image (Google Gemini)Generate images from text prompts using Google Gemini's image model.
39
Generate Speech (ElevenLabs)Convert text to speech using ElevenLabs API. Includes multiple voices and high-quality audio generation.
40
Transcribe Audio (ElevenLabs)Transcribe audio files using ElevenLabs API. Includes real-time transcription and language detection.
41
Search - Exa AI (robust)Search the web using Exa's semantic API and real-time crawling. Includes URL search, content extraction, Wikipedia, Reddit, and news search tools.
42
Search - Firecrawl (robust)Search the web using Firecrawl's API and real-time crawling. Includes URL search, content extraction, Wikipedia, Reddit, and news search tools.
43
Scrape - Cheerio (lightweight)Scrape websites using Cheerio's fast HTML parser. Includes URL scraping, website crawling, and content extraction without external API costs.
44
Scrape - Jina AI (advanced)Scrape websites using Jina AI's reader service with JavaScript rendering. Includes URL scraping, website crawling, and content extraction with AI-powered parsing.
45
Scrape - Markdown.new (free)Scrape websites using Cloudflare's markdown.new service. Extract clean markdown content from any URL. No API key required.

Related topics

Continue with adjacent topics that share the same building blocks.

Browse by category

Jump into the catalog filtered by category.

You’ve reached the end of AI SDK Examples.