AI Functions Examples
The examples/ai-functions/ directory contains scripts for validating, testing, and iterating on AI SDK functions across providers.
Example Categories
Examples are organized by AI SDK function in examples/ai-functions/src/:
| Directory | Purpose |
|---|---|
generate-text/ | Non-streaming text generation with generateText() |
stream-text/ | Streaming text generation with streamText() |
generate-object/ | Structured output generation with generateObject() |
stream-object/ | Streaming structured output with streamObject() |
agent/ | ToolLoopAgent examples for agentic workflows |
embed/ | Single embedding generation with embed() |
embed-many/ | Batch embedding generation with embedMany() |
generate-image/ | Image generation with generateImage() |
generate-speech/ | Text-to-speech with generateSpeech() |
transcribe/ | Audio transcription with transcribe() |
rerank/ | Document reranking with rerank() |
middleware/ | Custom middleware implementations |
registry/ | Provider registry setup and usage |
telemetry/ | OpenTelemetry integration |
complex/ | Multi-component examples (agents, routers) |
lib/ | Shared utilities (not examples) |
tools/ | Reusable tool definitions |
File Naming Convention
Examples follow the pattern: {provider}-{feature}.ts
| Pattern | Example | Description |
|---|---|---|
{provider}.ts | openai.ts | Basic provider usage |
{provider}-{feature}.ts | openai-tool-call.ts | Specific feature |
{provider}-{sub-provider}.ts | amazon-bedrock-anthropic.ts | Provider with sub-provider |
{provider}-{sub-provider}-{feature}.ts | google-vertex-anthropic-cache-control.ts | Sub-provider with feature |
Example Structure
All examples use the run() wrapper from lib/run.ts which:
- Loads environment variables from
.env - Provides error handling with detailed API error logging
Basic Template
typescript1import { providerName } from "@ai-sdk/provider-name"; 2import { generateText } from "ai"; 3 4import { run } from "../lib/run"; 5 6run(async () => { 7 const result = await generateText({ 8 model: providerName("model-id"), 9 prompt: "Your prompt here.", 10 }); 11 12 console.warn(result.text); 13 console.warn("Token usage:", result.usage); 14 console.warn("Finish reason:", result.finishReason); 15});
Streaming Template
typescript1import { providerName } from "@ai-sdk/provider-name"; 2import { streamText } from "ai"; 3 4import { printFullStream } from "../lib/print-full-stream"; 5import { run } from "../lib/run"; 6 7run(async () => { 8 const result = streamText({ 9 model: providerName("model-id"), 10 prompt: "Your prompt here.", 11 }); 12 13 await printFullStream({ result }); 14});
Tool Calling Template
typescript1import { providerName } from "@ai-sdk/provider-name"; 2import { generateText, tool } from "ai"; 3import { z } from "zod"; 4 5import { run } from "../lib/run"; 6 7run(async () => { 8 const result = await generateText({ 9 model: providerName("model-id"), 10 tools: { 11 myTool: tool({ 12 description: "Tool description", 13 inputSchema: z.object({ 14 param: z.string().describe("Parameter description"), 15 }), 16 execute: async ({ param }) => { 17 return { result: `Processed: ${param}` }; 18 }, 19 }), 20 }, 21 prompt: "Use the tool to...", 22 }); 23 24 console.warn(JSON.stringify(result, null, 2)); 25});
Structured Output Template
typescript1import { providerName } from "@ai-sdk/provider-name"; 2import { generateObject } from "ai"; 3import { z } from "zod"; 4 5import { run } from "../lib/run"; 6 7run(async () => { 8 const result = await generateObject({ 9 model: providerName("model-id"), 10 schema: z.object({ 11 name: z.string(), 12 items: z.array(z.string()), 13 }), 14 prompt: "Generate a...", 15 }); 16 17 console.warn(JSON.stringify(result.object, null, 2)); 18 console.warn("Token usage:", result.usage); 19});
Running Examples
From the examples/ai-functions directory:
bash1pnpm tsx src/generate-text/openai.ts 2pnpm tsx src/stream-text/openai-tool-call.ts 3pnpm tsx src/agent/openai-generate.ts
When to Write Examples
Write examples when:
-
Adding a new provider: Create basic examples for each supported API (
generateText,streamText,generateObject, etc.) -
Implementing a new feature: Demonstrate the feature with at least one provider example
-
Reproducing a bug: Create an example that shows the issue for debugging
-
Adding provider-specific options: Show how to use
providerOptionsfor provider-specific settings -
Creating test fixtures: Use examples to generate API response fixtures (see
capture-api-response-test-fixtureskill)
Utility Helpers
The lib/ directory contains shared utilities:
| File | Purpose |
|---|---|
run.ts | Error-handling wrapper with .env loading |
print.ts | Clean object printing (removes undefined values) |
print-full-stream.ts | Colored streaming output for tool calls, reasoning, text |
save-raw-chunks.ts | Save streaming chunks for test fixtures |
present-image.ts | Display images in terminal |
save-audio.ts | Save audio files to disk |
Using print utilities
typescript1import { print } from "../lib/print"; 2 3// Pretty print objects without undefined values 4print("Result:", result); 5print("Usage:", result.usage, { depth: 2 });
Using printFullStream
typescript1// import { printFullStream } from '../lib/print-full-stream'; 2 3// const result = streamText({ ... }); 4// await printFullStream({ result }); // Colored output for text, tool calls, reasoning
Reusable Tools
The tools/ directory contains reusable tool definitions:
typescript1import { weatherTool } from "../tools/weather-tool"; 2 3const result = await generateText({ 4 model: openai("gpt-4o"), 5 tools: { weather: weatherTool }, 6 prompt: "What is the weather in San Francisco?", 7});
Best Practices
-
Keep examples focused: Each example should demonstrate one feature or use case
-
Use descriptive prompts: Make it clear what the example is testing
-
Handle errors gracefully: The
run()wrapper handles this automatically -
Use realistic model IDs: Use actual model IDs that work with the provider
-
Add comments for complex logic: Explain non-obvious code patterns
-
Reuse tools when appropriate: Use
weatherToolor create new reusable tools intools/