### Initialize AI Agent with Few-Shot System Prompt (TypeScript)
Source: https://www.aisdkagents.com/docs/prompts/few-shot-prompting
Demonstrates initializing an AI Agent using the `ai` SDK with a system prompt that includes few-shot examples structured as task-pattern pairs. This guides the agent's behavior for specific tasks like code generation or debugging.
```typescript
import { Experimental_Agent as Agent } from "ai"
const codingAgent = new Agent({
model: "openai/gpt-5-nano",
system: `You are a coding assistant. Follow these patterns:
Task: Create a function
Pattern: Write clean, well-documented functions with TypeScript types
Task: Debug code
Pattern: Identify the issue, explain why it happens, provide a fix
Task: Optimize performance
Pattern: Analyze bottlenecks, suggest improvements, show before/after`,
tools: {
// Your tools here
},
})
const result = await codingAgent.generate({
prompt: "Create a function that validates email addresses",
})
```
--------------------------------
### Generate Text with Dynamic Few-Shot Examples (TypeScript)
Source: https://www.aisdkagents.com/docs/prompts/few-shot-prompting
Shows a TypeScript function that dynamically loads few-shot examples from a data source (e.g., database) based on a given task. It then constructs a prompt incorporating these examples to guide the text generation.
```typescript
async function generateWithDynamicExamples(task: string) {
// Load relevant examples from your database
const examples = await loadExamplesForTask(task)
const prompt = `Here are examples of ${task}:
${examples.map((ex) => `Input: ${ex.input}\nOutput: ${ex.output}`).join("\n\n")}
Now process: ${task}`
const result = await generateText({
model: "openai/gpt-5-nano",
prompt,
})
return result.text
}
```
--------------------------------
### Improve AI Example Following with Clear Formatting (TypeScript)
Source: https://www.aisdkagents.com/docs/prompts/few-shot-prompting
Illustrates the difference between poorly formatted and well-formatted few-shot examples in a prompt. The 'Good' example uses clear, structured input-output pairs to help the AI better understand and follow the desired pattern for classification.
```typescript
// Bad: Examples buried in text
const prompt = `Please help me classify emails. Here are some examples: urgent emails are important, not urgent ones aren't. Classify this email...`
// Good: Clear, structured examples
const prompt = `Classify emails as "urgent" or "not urgent":
Email: "Server is down"
Classification: urgent
Email: "Weekly report attached"
Classification: not urgent
Email: "Security breach detected"
Classification: urgent
Classify: "Meeting moved to tomorrow"`
```
--------------------------------
### Install and Create Upstash Redis Database (CLI)
Source: https://www.aisdkagents.com/docs/ai/ai-sdk-blocks
This snippet shows how to install the Upstash CLI and create a new Redis database instance. This is a prerequisite for using Upstash for rate limiting in the project.
```bash
# Install Upstash CLI
npm install -g @upstash/cli
# Create Redis database
upstash redis create my-redis-db
```
--------------------------------
### Install Shadcn using CLI
Source: https://www.aisdkagents.com/view/marketing-bento-1
Install shadcn using the Command Line Interface for seamless integration and AI-powered development. This command adds UI components to your project.
```bash
npx shadcn..@latest add ui/button
```
--------------------------------
### Build Complexity in Few-Shot Examples Gradually (TypeScript)
Source: https://www.aisdkagents.com/docs/prompts/few-shot-prompting
Shows a strategy for handling complex few-shot prompting scenarios by starting with simple examples and progressively adding complexity. This approach helps the AI learn the basic pattern before tackling more intricate requirements, leading to better results.
```typescript
// Start with basic examples
const simplePrompt = `Extract names:
Text: "Hello, I'm John"
Name: John
Text: "My name is Sarah"
Name: Sarah
Text: "I'm Mike"`
// Then add complexity
const complexPrompt = `Extract contact info:
Text: "Hi, I'm John Smith, call me at 555-1234"
Contact: {"name": "John Smith", "phone": "555-1234"}
Text: "Sarah Johnson here, email me at sarah@email.com"
Contact: {"name": "Sarah Johnson", "email": "sarah@email.com"}
Text: "Mike Chen, 555-9876, mike@company.com"`
```
--------------------------------
### ButtonGroupInputGroup Installation (pnpm)
Source: https://www.aisdkagents.com/docs/components/button-group-input-group
Instructions for installing the ButtonGroupInputGroup component using pnpm, a package manager for Node.js.
```bash
pnpm dlx shadcn@latest add button-group-input-group
```
--------------------------------
### Deploy Project to Vercel (CLI)
Source: https://www.aisdkagents.com/docs/ai/ai-sdk-blocks
This snippet demonstrates the command-line steps to install the Vercel CLI and deploy the project to Vercel for production. This assumes the project is already configured with necessary environment variables.
```bash
# Install Vercel CLI
npm install -g vercel
# Deploy
vercel --prod
```
--------------------------------
### Project Dependencies Installation (pnpm)
Source: https://www.aisdkagents.com/docs/ai/ai-sdk-blocks
This command installs the necessary AI SDK packages and Upstash Redis client for rate limiting. It's a common step before integrating AI functionalities and setting up advanced features like rate limiting.
```bash
pnpm add ai @ai-sdk/react @ai-sdk/openai @ai-sdk/google @upstash/ratelimit @upstash/redis
```
--------------------------------
### Consistent Prompt Formatting (JavaScript)
Source: https://www.aisdkagents.com/docs/prompts/few-shot-prompting
Demonstrates good and bad examples of consistent formatting for AI prompts. Good examples show clear, repeatable patterns, while bad examples are inconsistent and harder for the AI to follow.
```javascript
// Good: Consistent structure
const prompt = `Task: [description]
Input: [example input]
Output: [example output]
Task: [description]
Input: [example input]
Output: [example output]
Task: [description]
Input: [new input]
Output:`
// Bad: Inconsistent structure
const prompt = `Do this: example1 -> result1
Now do: example2 -> result2
Please: example3 -> result3`
```
--------------------------------
### Code Generation with Few-Shot Prompting
Source: https://www.aisdkagents.com/docs/prompts/few-shot-prompting
Generates React components based on provided examples of desired code structure and patterns. This demonstrates how few-shot prompting can be used to guide AI in producing code in a specific style or framework.
```javascript
const result = await generateText({
model: "openai/gpt-5-nano",
prompt: `Generate React components with these patterns:
Task: Create a button component
Code:
```tsx
interface ButtonProps {
children: React.ReactNode
variant?: 'primary' | 'secondary'
onClick?: () => void
}
export function Button({ children, variant = 'primary', onClick }: ButtonProps) {
return (
)
}
```
Task: Create a card component
Code:
```tsx
interface CardProps {
title: string
children: React.ReactNode
className?: string
}
export function Card({ title, children, className }: CardProps) {
return (
{title}
{children}
)
}
```
Now create a modal component:`,
})
```
--------------------------------
### Role-Based Prompting (JavaScript)
Source: https://www.aisdkagents.com/docs/prompts/few-shot-prompting
Demonstrates role-based prompting, where a specific role is defined for the AI. This example sets the AI as a coding tutor and shows example interactions.
```javascript
const result = await generateText({
model: "openai/gpt-5-nano",
prompt: `You are a helpful coding tutor. Teach concepts with examples:
Student: "What is a function?"
Tutor: "A function is a reusable block of code. Here's an example:
```javascript
function greet(name) {
return `Hello, ${name}!`
}
console.log(greet('Alice')) // Output: Hello, Alice!
```
Functions take inputs (parameters) and return outputs."
Student: "What is an array?"
Tutor: "An array is a list of items. Here's how to use one:
```javascript
const fruits = ['apple', 'banana', 'orange']
console.log(fruits[0]) // Output: apple
console.log(fruits.length) // Output: 3
```
Arrays store multiple values in order."
Student: "What is a loop?"`,
})
```
--------------------------------
### Context-Action Prompt Pattern (JavaScript)
Source: https://www.aisdkagents.com/docs/prompts/few-shot-prompting
Demonstrates the 'Context → Action' prompt pattern, ideal for decision-making and recommendations. This example provides situations and suggests appropriate actions.
```javascript
const prompt = `Given this situation, what should I do?
Situation: User reports the app crashes when uploading large files
Action: Investigate file size limits and implement proper error handling
Situation: Database queries are running slowly
Action: Add database indexes and optimize query performance
Situation: Users can't find the settings menu
Action: Improve navigation design and add search functionality
Situation: Payment processing fails for international users`
```
--------------------------------
### Input-Output Prompt Pattern (JavaScript)
Source: https://www.aisdkagents.com/docs/prompts/few-shot-prompting
Demonstrates the 'Input → Output' prompt pattern, suitable for transformations and conversions. This example shows temperature conversion from Fahrenheit to Celsius.
```javascript
const prompt = `Convert these temperatures:
Input: 32°F
Output: 0°C
Input: 68°F
Output: 20°C
Input: 100°F
Output: 37.8°C
Convert: 75°F`
```
--------------------------------
### HIL Needs Approval - Full Stack Example (TypeScript)
Source: https://www.aisdkagents.com/patterns/ai-chat-agent-tool-approval
A full-stack demonstration of tool approval with asynchronous generators. This example includes real-time feedback, approval workflows, and interactive management capabilities, showcasing a practical application of the AI SDK.
```typescript
new Agenttool()stepCountIsExperimental_AgentgatewayUIToolInvocation
```
--------------------------------
### AI Elements Chat Demo Explanation
Source: https://www.aisdkagents.com/patterns/ai-elements-chat
This section describes a demo showcasing AI elements like Reasoning, Sources, and Actions. It suggests example prompts to illustrate how the AI demonstrates different capabilities based on user requests.
```markdown
# Basic Chat Interface
FULL STACK
Unlock All Access
Chat interface with streaming responses and message history. Includes typing indicators and message status tracking.
PreviewCode
Download as Nextjs App
Open in New TabRefresh Preview
Default ThemeCopy theme
AI Elements Chat Demo
This demo showcases various AI elements including Reasoning, Sources, and Actions components working together.
Try asking questions that might require reasoning, sources, or actions. The AI will demonstrate different capabilities based on your request.
Example prompts:
* • "What's the weather like today?" (Actions)
* • "Explain quantum computing" (Reasoning)
* • "Tell me about the latest AI research" (Sources)
SearchGPT 4oGPT 4oDeepseek R1
Basic Chat Interface | AI SDK Agents | AI SDK Agents
Files
* app
* page.tsx
* layout.tsx
* api
* chat
* route.ts
* components
* chat-form.tsx
Pro
## Basic Chat Interface
ai-elements-chat
Chat interface with streaming responses and message history. Includes typing indicators and message status tracking.
streamTextconvertToModelMessages
Previous
Unlock All Access
Next
```
--------------------------------
### Question-Answer Prompt Pattern (JavaScript)
Source: https://www.aisdkagents.com/docs/prompts/few-shot-prompting
Illustrates the 'Question → Answer' prompt pattern, useful for Q&A and problem-solving. This example uses questions and answers about React concepts.
```javascript
const prompt = `Answer these questions about React:
Q: What is JSX?
A: JSX is a syntax extension that lets you write HTML-like code in JavaScript
Q: What is a component?
A: A component is a reusable piece of UI that can accept props and return JSX
Q: What is state?
A: State is data that can change over time and affects how a component renders
Q: What is useEffect?`
```
--------------------------------
### Generate Text Response with Few-Shot Examples using OpenAI
Source: https://www.aisdkagents.com/patterns/ai-sdk-prompt-few-shot
Asynchronous function that generates text responses using OpenAI's GPT-4.1-mini model with few-shot prompt examples. The function accepts user input and processes it through a message chain containing system prompts and few-shot examples for context-aware responses. Returns the generated text output from the model.
```TypeScript
import { openai } from "@ai-sdk/openai";
import { generateText } from "ai";
export async function generateResponse(input: string) {
const { text } = await generateText({
model: openai("gpt-4.1-mini"),
system: "",
messages: [
{ role: "user", content: "" },
{ role: "assistant", content: "" },
{ role: "user", content: input }
]
});
return text;
}
```
--------------------------------
### Testing AI Prompt Examples (JavaScript)
Source: https://www.aisdkagents.com/docs/prompts/few-shot-prompting
Shows how to test few-shot examples provided in an AI prompt. It involves calling the text generation function with the prompt and logging the result to verify its correctness.
```javascript
// Test your examples first
const testResult = await generateText({
model: "openai/gpt-5-nano",
prompt: `Your few-shot examples here...`,
})
console.log("Test result:", testResult.text)
// Verify the output matches your expectations
```
--------------------------------
### Install AI SDK dependencies with pnpm
Source: https://www.aisdkagents.com/docs/ai/ai-elements
Install the Vercel AI SDK and OpenAI provider package required for AI Elements functionality. This command adds both the core AI SDK and the OpenAI integration to your project dependencies.
```bash
pnpm add ai @ai-sdk/openai
```
--------------------------------
### Example Project Creation Actions
Source: https://www.aisdkagents.com/view/ai-chat-agent-orchestrater-pattern
Lists potential project creation actions that can be managed by the Orchestrator-Worker system. These represent high-level goals that the agents can break down and execute. Examples include building platforms, apps, integrations, and documentation systems.
```text
Build E-commerce Platform
Create AI-Powered App
Develop API Integration
Design Data Pipeline
Build Microservices
Create Documentation System
```
--------------------------------
### Ensure Consistent Output with Specific Few-Shot Examples (TypeScript)
Source: https://www.aisdkagents.com/docs/prompts/few-shot-prompting
Demonstrates how to use specific, structured few-shot examples to enforce a consistent output format, in this case, JSON. Providing clear input-output pairs helps the model generate responses that adhere to the desired schema.
```typescript
const prompt = `Generate JSON responses in this exact format:
Input: "What's the weather?"
Output: {"type": "weather", "response": "I can help you check the weather"}
Input: "Set a reminder"
Output: {"type": "reminder", "response": "I'll help you set a reminder"}
Input: "Play music"
Output: {"type": "music", "response": "I can help you play music"}
Input: "What time is it?"`
```
--------------------------------
### Writing Style Adaptation with Few-Shot Prompting
Source: https://www.aisdkagents.com/docs/prompts/few-shot-prompting
Adapts sentences from an informal style to a professional, technical style by providing examples of original and rewritten sentences. This showcases few-shot prompting's utility in style transfer and text refinement.
```javascript
const result = await generateText({
model: "openai/gpt-5-nano",
prompt: `Rewrite these sentences in a professional, technical style:
Original: "This thing is really fast and works great"
Technical: "The system demonstrates exceptional performance with optimized processing capabilities"
Original: "The app is easy to use and looks nice"
Technical: "The application features an intuitive user interface with modern design principles"
Original: "It's super reliable and never breaks"
Technical: "The platform maintains high availability with robust error handling mechanisms"
Now rewrite: "This tool is awesome and saves tons of time"`,
})
```
--------------------------------
### Apply Utility Classes for Component Theming
Source: https://www.aisdkagents.com/docs/theming
Example of applying Tailwind utility classes directly for theming instead of CSS variables. Demonstrates responsive dark mode styling using the dark: prefix for conditional styling based on color scheme.
```jsx
```
--------------------------------
### Apply Primary Color Theme Variables
Source: https://www.aisdkagents.com/docs/theming
Example demonstrating the background and foreground color convention. Shows how to apply primary color variables to a component where the background suffix is omitted for the background color, following the established naming convention.
```jsx
Hello
```
--------------------------------
### Generate text response using OpenAI with few-shot examples
Source: https://www.aisdkagents.com/blocks/ai-sdk-prompt-few-shot
Async function that generates AI responses using the OpenAI GPT-4.1-mini model with few-shot prompting. Accepts a user input string and returns generated text. Requires @ai-sdk/openai and ai packages for model integration.
```TypeScript
import { openai } from "@ai-sdk/openai";
import { generateText } from "ai";
export async function generateResponse(input: string) {
const { text } = await generateText({
model: openai("gpt-4.1-mini"),
system: "",
messages: [
{ role: "user", content: "" },
{ role: "assistant", content: "" },
{ role: "user", content: input }
]
});
return text;
}
```
--------------------------------
### Chain of Thought Prompting (JavaScript)
Source: https://www.aisdkagents.com/docs/prompts/few-shot-prompting
Shows how to use the 'Chain of Thought' prompting technique to guide the AI in thinking through problems step by step. This example involves solving math problems.
```javascript
const result = await generateText({
model: "openai/gpt-5-nano",
prompt: `Solve these math problems step by step:
Problem: If a train travels 120 miles in 2 hours, what's its speed?
Solution:
Step 1: Distance = 120 miles
Step 2: Time = 2 hours
Step 3: Speed = Distance ÷ Time = 120 ÷ 2 = 60 mph
Answer: 60 mph
Problem: A rectangle has length 8 and width 5. What's its area?
Solution:
Step 1: Length = 8
Step 2: Width = 5
Step 3: Area = Length × Width = 8 × 5 = 40
Answer: 40 square units
Problem: If 3 apples cost $6, how much do 7 apples cost?`,
})
```
--------------------------------
### Handling Edge Cases in Prompts (JavaScript)
Source: https://www.aisdkagents.com/docs/prompts/few-shot-prompting
Illustrates how to include edge cases in AI prompts to guide the AI in handling unusual situations. This example focuses on extracting topics from sentences, including an ambiguous one.
```javascript
const result = await generateText({
model: "openai/gpt-5-nano",
prompt: `Extract the main topic from these sentences:
Sentence: "The weather is nice today"
Topic: weather
Sentence: "I can't find my keys anywhere"
Topic: lost items
Sentence: "The meeting was postponed until next week"
Topic: meeting
Sentence: "I don't know what to do about this problem"
Topic: uncertainty
Sentence: "Can you help me with this?"
Topic: request for help
Now extract from: "This is confusing and I'm not sure what's happening"`,
})
```
--------------------------------
### Define Sending Welcome Email Step for AI SDK Agents
Source: https://www.aisdkagents.com/view/marketing-feature-code-block-1
Defines a workflow step for sending a welcome email using the Resend email service. This step requires an API key for Resend and handles potential errors during email sending by throwing a FatalError. It takes an email address as input and returns nothing.
```typescript
import { Resend } from 'resend';
import { FatalError } from 'workflow';
export async function sendWelcomeEmail(email) {
"use step"
const resend = new Resend('YOUR_API_KEY');
const resp = await resend.emails.send({
from: 'Acme ',
to: [email],
subject: 'Welcome!',
html: `Thanks for joining Acme.`,
});
if (resp.error) {
throw new FatalError(resp.error.message);
}
};
// Other steps...
```
--------------------------------
### Build a Tasting Menu Planner Agent using AI SDK (JavaScript)
Source: https://www.aisdkagents.com/docs/agents/building-agents
Demonstrates how to construct a 'Tasting Menu Planner' agent using the AI SDK. This agent leverages tools like 'checkPantry', 'flavorPairings', 'composeMenu', and 'renderAsciiPlating' to generate a seasonal menu with an ASCII plating sketch. The agent's loop and stop conditions are managed automatically by the Agent class.
```javascript
import { Experimental_Agent as Agent, stepCountIs, tool } from "ai"
import { z } from "zod"
export const chefAgent = new Agent({
model: "openai/gpt-4o",
system: "You are a head chef creating a light, seasonal tasting menu.",
tools: {
checkPantry: tool({
description: "Return available seasonal ingredients by section",
inputSchema: z.object({
sections: z
.array(z.enum(["veg", "seafood", "dairy", "aromatics", "all"]))
.default(["all"])
}),
execute: async ({ sections }) => ({
veg: ["asparagus", "pea shoots", "lemon"],
seafood: ["scallops", "halibut"],
dairy: ["crème fraîche"],
aromatics: ["mint", "chive"]
})
}),
flavorPairings: tool({
description: "Suggest classic flavor pairings for given ingredients",
inputSchema: z.object({ items: z.array(z.string()) }),
execute: async ({ items }) => ({
suggestions: [
{ base: "scallops", pairs: ["lemon", "pea shoots", "mint"] },
{ base: "asparagus", pairs: ["lemon", "crème fraîche", "chive"] }
]
})
}),
composeMenu: tool({
description: "Compose a 3-course tasting menu from pairings",
inputSchema: z.object({
theme: z.string(),
courses: z.number().min(3).max(5).default(3)
}),
execute: async ({ theme, courses }) => ({
courses: [
{ name: "Scallop crudo", note: "lemon · mint · pea shoots" },
{ name: "Asparagus velouté", note: "crème fraîche · chive" },
{ name: "Halibut en papillote", note: "lemon · herbs" }
].slice(0, courses)
})
}),
renderAsciiPlating: tool({
description: "Render a tiny ASCII plating sketch for a course list",
inputSchema: z.object({ names: z.array(z.string()) }),
execute: async ({ names }) => ({
sketch: `
${names.map((n) => `• ${n} — [○ ● ○]`).join("\n")}`
})
})
},
stopWhen: stepCountIs(20) // loop ends when model emits text or a stop rule fires
})
const result = await chefAgent.generate({
prompt:
"Create a light, seasonal 3-course tasting menu and include a tiny plating sketch."
})
console.log(result.text) // final menu in Markdown
console.log(result.steps) // tool-call trace (observability)
```
--------------------------------
### Text Classification with Few-Shot Prompting
Source: https://www.aisdkagents.com/docs/prompts/few-shot-prompting
Classifies emails as urgent or not urgent by providing the AI model with examples of input-output pairs. This method leverages the model's pattern recognition capabilities to infer rules from provided examples.
```javascript
import { generateText } from "ai"
const result = await generateText({
model: "openai/gpt-5-nano",
prompt: `Classify these emails as "urgent" or "not urgent":
Email: "The server is down and customers can't access the website"
Classification: urgent
Email: "Here's the weekly report from last week"
Classification: not urgent
Email: "Can you review this document when you have time?"
Classification: not urgent
Email: "Security breach detected - immediate action required"
Classification: urgent
Email: "The quarterly budget meeting has been moved to next Tuesday"
Classification: urgent
Now classify this email: "Please send me the project timeline by end of day"`,
})
```
--------------------------------
### Create Chef Agent with Multiple Tools
Source: https://www.aisdkagents.com/docs/agents/building-agents
Define an experimental agent with multiple tool definitions using Zod schemas for validation. Includes checkFridge and suggestDish tools with deterministic outputs. Sets a step limit to prevent infinite loops.
```typescript
import { Experimental_Agent as Agent, stepCountIs, tool } from "ai"
import { z } from "zod"
const chefAgent = new Agent({
model: "openai/gpt-4o",
system:
"You are a helpful chef. Use tools to check ingredients and propose recipes.",
tools: {
checkFridge: tool({
description: "Check available ingredients",
inputSchema: z.object({
section: z.enum(["proteins", "veg", "dairy", "all"]),
}),
execute: async ({ section }) => ({
proteins: ["chicken", "eggs"],
veg: ["peppers", "onions", "tomatoes"],
dairy: ["parmesan", "yogurt"],
}),
}),
suggestDish: tool({
description: "Propose a dish from ingredients",
inputSchema: z.object({ have: z.array(z.string()) }),
execute: async ({ have }) => ({
dish: "chicken peperonata",
reason: "uses chicken + peppers + tomatoes",
}),
}),
},
stopWhen: stepCountIs(10),
})
```
--------------------------------
### Simple Augmented LLM Example in TypeScript
Source: https://www.aisdkagents.com/docs/agents/agent-patterns
Demonstrates creating a simple augmented LLM agent using the AI SDK. This agent is equipped with search and document analysis tools. It takes a prompt, searches for relevant information, analyzes documents, and synthesizes an answer. The `tool` function is used to define the available tools with their descriptions and parameters.
```typescript
import { Experimental_Agent as Agent, tool } from "ai"
import { z } from "zod"
const augmentedAgent = new Agent({
model: "openai/gpt-4o",
system: `You are a helpful assistant with access to search and document tools.
When answering questions:
1. Always search for relevant information first
2. Use document analysis for detailed information
3. Cross-reference multiple sources before drawing conclusions
4. Cite your sources when presenting information`,
tools: {
search: tool({
description: "Search for information on the web",
parameters: z.object({
query: z.string().describe("The search query"),
}),
execute: async ({ query }) => {
// Simulate search API call
return { results: `Search results for: ${query}` }
},
}),
analyzeDocument: tool({
description: "Analyze a document for key information",
parameters: z.object({
documentId: z.string().describe("The document ID to analyze"),
}),
execute: async ({ documentId }) => {
// Simulate document analysis
return { analysis: `Analysis of document ${documentId}` }
},
}),
},
})
// Use the agent
const result = await augmentedAgent.generate({
prompt: "What are the latest trends in AI?",
})
console.log(result.text)
```
--------------------------------
### ButtonGroupInputGroup Usage (React)
Source: https://www.aisdkagents.com/docs/components/button-group-input-group
Example of how to import and use the ButtonGroupInputGroup component in a React application. It shows the basic props for handling messages, file selections, and audio recordings.
```jsx
import { ButtonGroupInputGroup } from "@/components/ui/button-group-input-group"
{
console.log("Sending message:", message)
}}
onFileSelect={(file) => {
console.log("File selected:", file.name)
}}
onAudioRecord={(audioBlob) => {
console.log("Audio recorded:", audioBlob)
}}
/>
```
--------------------------------
### Configure Agent with prepareStep for Model Escalation
Source: https://www.aisdkagents.com/docs/agents/building-agents
Runs custom logic before each iteration to trim message history and optionally escalate to a more capable model as task complexity increases. Returns updated model and/or messages for the current step.
```javascript
const agent = new Agent({
model: "openai/gpt-4o-mini",
tools,
prepareStep: async ({ stepNumber, messages }) => {
const trimmed = messages.slice(-12) // keep it lean
if (stepNumber >= 3) {
return { model: "openai/gpt-4o", messages: trimmed }
}
return { messages: trimmed }
},
})
```
--------------------------------
### Next.js Layout Configuration
Source: https://www.aisdkagents.com/patterns/basics-stream-text
Root layout configuration for the AI SDK Agents application. Provides the basic HTML structure and metadata setup required for the streaming text demo.
```typescript
// app/layout.tsx
import type { Metadata } from 'next';
export const metadata: Metadata = {
title: 'Stream Text - AI SDK Agents',
description: 'Stream text responses from AI prompts in real-time'
};
export default function RootLayout({
children
}: {
children: React.ReactNode;
}) {
return (
{children}
);
}
```
--------------------------------
### Custom AI Agent Hook Example (React)
Source: https://www.aisdkagents.com/docs/ai/ai-sdk-blocks
This React component demonstrates a custom AI agent using the `useChat` hook from the AI SDK. It sets up a basic chat interface with initial messages and provides a structure for further customization.
```typescript
export function MyCustomAgent() {
const { messages, input, handleInputChange, handleSubmit } = useChat({
api: "/api/my-custom-agent",
initialMessages: [
{
id: "1",
role: "assistant",
content: "Hello! I'm your custom AI agent. How can I help?",
},
],
})
return (
{/* Your customized implementation */}
)
}
```
--------------------------------
### Implement Prompt Chaining with AI SDK Agents (TypeScript)
Source: https://www.aisdkagents.com/docs/agents/agent-patterns
This TypeScript code defines an AI Agent that chains multiple prompts together to create content. It uses predefined tools for outlining, drafting, and evaluating content quality. The agent is configured with a system prompt that dictates the creation process and a stopping condition for the number of execution steps. The output includes the generated text and a log of all executed steps.
```typescript
import { Experimental_Agent as Agent, stepCountIs, tool } from "ai"
import { z } from "zod"
const chainingAgent = new Agent({
model: "openai/gpt-4o",
system: `You are a content creation assistant that works in stages.
Process:
1. Create a detailed outline first
2. Write a draft based on the outline
3. Polish and refine the content
Always evaluate quality at each step and retry if needed.`,
tools: {
createOutline: tool({
description: "Create a detailed outline for the given topic",
parameters: z.object({
topic: z.string().describe("The topic to create an outline for"),
}),
execute: async ({ topic }) => {
return { outline: `Detailed outline for: ${topic}` }
},
}),
writeDraft: tool({
description: "Write a draft based on the outline",
parameters: z.object({
outline: z.string().describe("The outline to write from"),
}),
execute: async ({ outline }) => {
return { draft: `Draft based on: ${outline}` }
},
}),
evaluateQuality: tool({
description: "Evaluate the quality of content (1-10 scale)",
parameters: z.object({
content: z.string().describe("The content to evaluate"),
type: z.enum(["outline", "draft", "final"]).describe("Type of content"),
}),
execute: async ({ content, type }) => {
// Simulate quality evaluation
const score = Math.floor(Math.random() * 4) + 7 // 7-10 range
return { score, feedback: `Quality score for ${type}: ${score}/10` }
},
}),
},
stopWhen: stepCountIs(10), // Allow multiple steps for chaining
})
// Use the agent for content creation
const result = await chainingAgent.generate({
prompt: "Create a comprehensive guide about machine learning",
})
console.log(result.text)
console.log(result.steps) // See all the steps taken
```
--------------------------------
### Configure Tailwind Utility Classes in components.json
Source: https://www.aisdkagents.com/docs/theming
Configuration file setup to use Tailwind utility classes for theming by setting tailwind.cssVariables to false. This approach uses predefined Tailwind color utilities instead of custom CSS variables.
```json
{
"style": "default",
"rsc": true,
"tailwind": {
"config": "",
"css": "app/globals.css",
"baseColor": "neutral",
"cssVariables": false
},
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
},
"iconLibrary": "lucide"
}
```
--------------------------------
### Configure Agent with Default Single Generation Step
Source: https://www.aisdkagents.com/docs/agents/building-agents
Demonstrates default agent behavior with implicit stepCountIs(1), allowing one model generation that produces either text output or tool calls. After tool execution, the loop continues to the next step.
```javascript
const agent = new Agent({
model: "openai/gpt-4o",
tools: { checkPantry, composeMenu },
// stopWhen: stepCountIs(1) ← implicit default
})
// This agent:
// - Step 1: Model might call checkPantry → tool executes → continues
// - Step 2: Model generates final answer → stops
// The limit is on GENERATIONS, not tool calls
```
--------------------------------
### Configure Tailwind CSS Variables in components.json
Source: https://www.aisdkagents.com/docs/theming
Configuration file setup to enable CSS variable-based theming by setting tailwind.cssVariables to true. This enables the use of CSS custom properties defined in globals.css for dynamic theming across the application.
```json
{
"style": "default",
"rsc": true,
"tailwind": {
"config": "",
"css": "app/globals.css",
"baseColor": "neutral",
"cssVariables": true
},
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
},
"iconLibrary": "lucide"
}
```
--------------------------------
### React Component Example with State Management
Source: https://www.aisdkagents.com/patterns/chat-gpt
This React component demonstrates state management using the `useState` hook for text input, search preferences, and message statuses. It also includes functions for streaming responses and handling user messages.
```typescript
import React, { useState, useCallback } from 'react';
// Assuming MessageType and other types/icons are defined elsewhere
const Example = () => {
const [text, setText] = useState("");
const [useWebSearch, setUseWebSearch] = useState(false);
const [useMicrophone, setUseMicrophone] = useState(false);
const [status, setStatus] = useState<
"submitted" | "streaming" | "ready" | "error"
>("ready");
const [messages, setMessages] = useState([]);
const [streamingMessageId, setStreamingMessageId] = useState(
null
);
const streamReasoning = async (
messageKey: string,
versionId: string,
reasoningContent: string
) => {
const words = reasoningContent.split(" ");
let currentContent = "";
for (let i = 0; i < words.length; i++) {
currentContent += (i > 0 ? " " : "") + words[i];
setMessages((prev) =>
prev.map((msg) => {
if (msg.key === messageKey) {
return {
...msg,
reasoning: msg.reasoning
? { ...msg.reasoning, content: currentContent }
: undefined,
};
}
return msg;
})
);
await new Promise((resolve) =>
setTimeout(resolve, Math.random() * 30 + 20)
);
}
setMessages((prev) =>
prev.map((msg) => {
if (msg.key === messageKey) {
return {
...msg,
isReasoningComplete: true,
isReasoningStreaming: false,
};
}
return msg;
})
);
};
const streamContent = async (
messageKey: string,
versionId: string,
content: string
) => {
const words = content.split(" ");
let currentContent = "";
for (let i = 0; i < words.length; i++) {
currentContent += (i > 0 ? " " : "") + words[i];
setMessages((prev) =>
prev.map((msg) => {
if (msg.key === messageKey) {
return {
...msg,
versions: msg.versions.map((v) =>
v.id === versionId ? { ...v, content: currentContent } : v
),
};
}
return msg;
})
);
await new Promise((resolve) =>
setTimeout(resolve, Math.random() * 50 + 25)
);
}
setMessages((prev) =>
prev.map((msg) => {
if (msg.key === messageKey) {
return { ...msg, isContentComplete: true };
}
return msg;
})
);
};
const streamResponse = useCallback(
async (
messageKey: string,
versionId: string,
content: string,
reasoning?: { content: string; duration: number }
) => {
setStatus("streaming");
setStreamingMessageId(versionId);
if (reasoning) {
await streamReasoning(messageKey, versionId, reasoning.content);
await new Promise((resolve) => setTimeout(resolve, 500));
}
await streamContent(messageKey, versionId, content);
setStatus("ready");
setStreamingMessageId(null);
},
[]
);
const streamMessage = useCallback(
async (message: MessageType) => {
if (message.from === "user") {
setMessages((prev) => [...prev, message]);
return;
}
// ... rest of the function
},
[]
);
// ... rest of the component
};
export default Example;
```
--------------------------------
### Design Production-Safe Tool with Input Validation
Source: https://www.aisdkagents.com/docs/agents/building-agents
Implements a tool with strict input schema validation, limit enforcement, user context derivation from server (not model text), and curated output summarization. Demonstrates safe tool patterns including idempotency and output curation.
```javascript
const searchDocs = tool({
description: "Search product docs",
inputSchema: z.object({
q: z.string().min(2),
limit: z.number().int().min(1).max(5).default(3),
}),
execute: async ({ q, limit }, ctx) => {
const results = await docs.search(q, { limit, userId: ctx.user.id })
return {
hits: results.map((r) => ({
id: r.id,
title: r.title,
summary: r.snippet,
})),
}
},
})
```