|
| 1 | +--- |
| 2 | +name: develop-ai-functions-example |
| 3 | +description: Develop examples for AI SDK functions. Use when creating, running, or modifying examples under examples/ai-functions/src to validate provider support, demonstrate features, or create test fixtures. |
| 4 | +--- |
| 5 | + |
| 6 | +## AI Functions Examples |
| 7 | + |
| 8 | +The `examples/ai-functions/` directory contains scripts for validating, testing, and iterating on AI SDK functions across providers. |
| 9 | + |
| 10 | +## Example Categories |
| 11 | + |
| 12 | +Examples are organized by AI SDK function in `examples/ai-functions/src/`: |
| 13 | + |
| 14 | +| Directory | Purpose | |
| 15 | +| ------------------ | ---------------------------------------------------- | |
| 16 | +| `generate-text/` | Non-streaming text generation with `generateText()` | |
| 17 | +| `stream-text/` | Streaming text generation with `streamText()` | |
| 18 | +| `generate-object/` | Structured output generation with `generateObject()` | |
| 19 | +| `stream-object/` | Streaming structured output with `streamObject()` | |
| 20 | +| `agent/` | `ToolLoopAgent` examples for agentic workflows | |
| 21 | +| `embed/` | Single embedding generation with `embed()` | |
| 22 | +| `embed-many/` | Batch embedding generation with `embedMany()` | |
| 23 | +| `generate-image/` | Image generation with `generateImage()` | |
| 24 | +| `generate-speech/` | Text-to-speech with `generateSpeech()` | |
| 25 | +| `transcribe/` | Audio transcription with `transcribe()` | |
| 26 | +| `rerank/` | Document reranking with `rerank()` | |
| 27 | +| `middleware/` | Custom middleware implementations | |
| 28 | +| `registry/` | Provider registry setup and usage | |
| 29 | +| `telemetry/` | OpenTelemetry integration | |
| 30 | +| `complex/` | Multi-component examples (agents, routers) | |
| 31 | +| `lib/` | Shared utilities (not examples) | |
| 32 | +| `tools/` | Reusable tool definitions | |
| 33 | + |
| 34 | +## File Naming Convention |
| 35 | + |
| 36 | +Examples follow the pattern: `{provider}-{feature}.ts` |
| 37 | + |
| 38 | +| Pattern | Example | Description | |
| 39 | +| ---------------------------------------- | ------------------------------------------ | -------------------------- | |
| 40 | +| `{provider}.ts` | `openai.ts` | Basic provider usage | |
| 41 | +| `{provider}-{feature}.ts` | `openai-tool-call.ts` | Specific feature | |
| 42 | +| `{provider}-{sub-provider}.ts` | `amazon-bedrock-anthropic.ts` | Provider with sub-provider | |
| 43 | +| `{provider}-{sub-provider}-{feature}.ts` | `google-vertex-anthropic-cache-control.ts` | Sub-provider with feature | |
| 44 | + |
| 45 | +## Example Structure |
| 46 | + |
| 47 | +All examples use the `run()` wrapper from `lib/run.ts` which: |
| 48 | + |
| 49 | +- Loads environment variables from `.env` |
| 50 | +- Provides error handling with detailed API error logging |
| 51 | + |
| 52 | +### Basic Template |
| 53 | + |
| 54 | +```typescript |
| 55 | +import { providerName } from '@ai-sdk/provider-name'; |
| 56 | +import { generateText } from 'ai'; |
| 57 | +import { run } from '../lib/run'; |
| 58 | + |
| 59 | +run(async () => { |
| 60 | + const result = await generateText({ |
| 61 | + model: providerName('model-id'), |
| 62 | + prompt: 'Your prompt here.', |
| 63 | + }); |
| 64 | + |
| 65 | + console.log(result.text); |
| 66 | + console.log('Token usage:', result.usage); |
| 67 | + console.log('Finish reason:', result.finishReason); |
| 68 | +}); |
| 69 | +``` |
| 70 | + |
| 71 | +### Streaming Template |
| 72 | + |
| 73 | +```typescript |
| 74 | +import { providerName } from '@ai-sdk/provider-name'; |
| 75 | +import { streamText } from 'ai'; |
| 76 | +import { printFullStream } from '../lib/print-full-stream'; |
| 77 | +import { run } from '../lib/run'; |
| 78 | + |
| 79 | +run(async () => { |
| 80 | + const result = streamText({ |
| 81 | + model: providerName('model-id'), |
| 82 | + prompt: 'Your prompt here.', |
| 83 | + }); |
| 84 | + |
| 85 | + await printFullStream({ result }); |
| 86 | +}); |
| 87 | +``` |
| 88 | + |
| 89 | +### Tool Calling Template |
| 90 | + |
| 91 | +```typescript |
| 92 | +import { providerName } from '@ai-sdk/provider-name'; |
| 93 | +import { generateText, tool } from 'ai'; |
| 94 | +import { z } from 'zod'; |
| 95 | +import { run } from '../lib/run'; |
| 96 | + |
| 97 | +run(async () => { |
| 98 | + const result = await generateText({ |
| 99 | + model: providerName('model-id'), |
| 100 | + tools: { |
| 101 | + myTool: tool({ |
| 102 | + description: 'Tool description', |
| 103 | + inputSchema: z.object({ |
| 104 | + param: z.string().describe('Parameter description'), |
| 105 | + }), |
| 106 | + execute: async ({ param }) => { |
| 107 | + return { result: `Processed: ${param}` }; |
| 108 | + }, |
| 109 | + }), |
| 110 | + }, |
| 111 | + prompt: 'Use the tool to...', |
| 112 | + }); |
| 113 | + |
| 114 | + console.log(JSON.stringify(result, null, 2)); |
| 115 | +}); |
| 116 | +``` |
| 117 | + |
| 118 | +### Structured Output Template |
| 119 | + |
| 120 | +```typescript |
| 121 | +import { providerName } from '@ai-sdk/provider-name'; |
| 122 | +import { generateObject } from 'ai'; |
| 123 | +import { z } from 'zod'; |
| 124 | +import { run } from '../lib/run'; |
| 125 | + |
| 126 | +run(async () => { |
| 127 | + const result = await generateObject({ |
| 128 | + model: providerName('model-id'), |
| 129 | + schema: z.object({ |
| 130 | + name: z.string(), |
| 131 | + items: z.array(z.string()), |
| 132 | + }), |
| 133 | + prompt: 'Generate a...', |
| 134 | + }); |
| 135 | + |
| 136 | + console.log(JSON.stringify(result.object, null, 2)); |
| 137 | + console.log('Token usage:', result.usage); |
| 138 | +}); |
| 139 | +``` |
| 140 | + |
| 141 | +## Running Examples |
| 142 | + |
| 143 | +From the `examples/ai-functions` directory: |
| 144 | + |
| 145 | +```bash |
| 146 | +pnpm tsx src/generate-text/openai.ts |
| 147 | +pnpm tsx src/stream-text/openai-tool-call.ts |
| 148 | +pnpm tsx src/agent/openai-generate.ts |
| 149 | +``` |
| 150 | + |
| 151 | +## When to Write Examples |
| 152 | + |
| 153 | +Write examples when: |
| 154 | + |
| 155 | +1. **Adding a new provider**: Create basic examples for each supported API (`generateText`, `streamText`, `generateObject`, etc.) |
| 156 | + |
| 157 | +2. **Implementing a new feature**: Demonstrate the feature with at least one provider example |
| 158 | + |
| 159 | +3. **Reproducing a bug**: Create an example that shows the issue for debugging |
| 160 | + |
| 161 | +4. **Adding provider-specific options**: Show how to use `providerOptions` for provider-specific settings |
| 162 | + |
| 163 | +5. **Creating test fixtures**: Use examples to generate API response fixtures (see `capture-api-response-test-fixture` skill) |
| 164 | + |
| 165 | +## Utility Helpers |
| 166 | + |
| 167 | +The `lib/` directory contains shared utilities: |
| 168 | + |
| 169 | +| File | Purpose | |
| 170 | +| ---------------------- | -------------------------------------------------------- | |
| 171 | +| `run.ts` | Error-handling wrapper with `.env` loading | |
| 172 | +| `print.ts` | Clean object printing (removes undefined values) | |
| 173 | +| `print-full-stream.ts` | Colored streaming output for tool calls, reasoning, text | |
| 174 | +| `save-raw-chunks.ts` | Save streaming chunks for test fixtures | |
| 175 | +| `present-image.ts` | Display images in terminal | |
| 176 | +| `save-audio.ts` | Save audio files to disk | |
| 177 | + |
| 178 | +### Using print utilities |
| 179 | + |
| 180 | +```typescript |
| 181 | +import { print } from '../lib/print'; |
| 182 | + |
| 183 | +// Pretty print objects without undefined values |
| 184 | +print('Result:', result); |
| 185 | +print('Usage:', result.usage, { depth: 2 }); |
| 186 | +``` |
| 187 | + |
| 188 | +### Using printFullStream |
| 189 | + |
| 190 | +```typescript |
| 191 | +import { printFullStream } from '../lib/print-full-stream'; |
| 192 | + |
| 193 | +const result = streamText({ ... }); |
| 194 | +await printFullStream({ result }); // Colored output for text, tool calls, reasoning |
| 195 | +``` |
| 196 | + |
| 197 | +## Reusable Tools |
| 198 | + |
| 199 | +The `tools/` directory contains reusable tool definitions: |
| 200 | + |
| 201 | +```typescript |
| 202 | +import { weatherTool } from '../tools/weather-tool'; |
| 203 | + |
| 204 | +const result = await generateText({ |
| 205 | + model: openai('gpt-4o'), |
| 206 | + tools: { weather: weatherTool }, |
| 207 | + prompt: 'What is the weather in San Francisco?', |
| 208 | +}); |
| 209 | +``` |
| 210 | + |
| 211 | +## Best Practices |
| 212 | + |
| 213 | +1. **Keep examples focused**: Each example should demonstrate one feature or use case |
| 214 | + |
| 215 | +2. **Use descriptive prompts**: Make it clear what the example is testing |
| 216 | + |
| 217 | +3. **Handle errors gracefully**: The `run()` wrapper handles this automatically |
| 218 | + |
| 219 | +4. **Use realistic model IDs**: Use actual model IDs that work with the provider |
| 220 | + |
| 221 | +5. **Add comments for complex logic**: Explain non-obvious code patterns |
| 222 | + |
| 223 | +6. **Reuse tools when appropriate**: Use `weatherTool` or create new reusable tools in `tools/` |
0 commit comments