AI Agents & UI - Building Agentic Applications with AI SDK 6
Comprehensive guide for building AI agents using ToolLoopAgent, workflow patterns, and AI SDK UI components (useChat, generative UIs, tool calling)
What this skill does
# AI Agents & UI Skills
**Status:** AI SDK 6 Beta
**Package Manager:** pnpm
**Key Version:** @ai-sdk/core, @ai-sdk/react (for UI)
**Official Docs:**
- [Agents Overview](https://v6.ai-sdk.dev/docs/agents/overview)
- [Building Agents](https://v6.ai-sdk.dev/docs/agents/building-agents)
- [Workflow Patterns](https://v6.ai-sdk.dev/docs/agents/workflows)
- [AI SDK UI](https://v6.ai-sdk.dev/docs/ai-sdk-ui/overview)
- [Chatbot Guide](https://v6.ai-sdk.dev/docs/ai-sdk-ui/chatbot)
- [Chatbot Tool Usage](https://v6.ai-sdk.dev/docs/ai-sdk-ui/chatbot-tool-usage)
- [Generative User Interfaces](https://v6.ai-sdk.dev/docs/ai-sdk-ui/generative-user-interfaces)
---
## Table of Contents
1. [Installation & Setup](#installation--setup)
2. [Understanding Agents](#understanding-agents)
3. [Building ToolLoopAgent](#building-toolloopagent)
4. [Agent Configuration Options](#agent-configuration-options)
5. [System Instructions & Behavior](#system-instructions--behavior)
6. [Workflow Patterns](#workflow-patterns)
7. [AI SDK UI - useChat Hook](#ai-sdk-ui---usechat-hook)
8. [Building Chatbot Applications](#building-chatbot-applications)
9. [Tool Calling in UI](#tool-calling-in-ui)
10. [Generative User Interfaces](#generative-user-interfaces)
11. [Advanced Patterns](#advanced-patterns)
12. [Best Practices](#best-practices)
---
## Installation & Setup
### Install Dependencies
```bash
# Core packages
pnpm add ai @ai-sdk/core @ai-sdk/anthropic
# For UI (React)
pnpm add @ai-sdk/react
# Optional: specific providers
pnpm add @ai-sdk/openai @ai-sdk/google
```
### TypeScript Configuration
Ensure your `tsconfig.json` has proper settings:
```json
{
"compilerOptions": {
"target": "ES2020",
"lib": ["ES2020", "DOM"],
"moduleResolution": "bundler",
"strict": true
}
}
```
---
## Understanding Agents
### What Are Agents?
Agents are LLMs that use tools in a loop to accomplish tasks. Three core components work together:
1. **LLMs** - Process input, decide next action
2. **Tools** - Extend capabilities (APIs, databases, files)
3. **Loop** - Orchestrates execution through context management and stopping conditions
### ToolLoopAgent Class
The `ToolLoopAgent` class is the recommended approach because it:
- **Reduces boilerplate** - Manages loops and message arrays automatically
- **Improves reusability** - Define once, use throughout application
- **Simplifies maintenance** - Single place to update configuration
- **Provides type safety** - Full TypeScript support for tools and outputs
### vs. Core Functions
For most use cases, use `ToolLoopAgent`. Use core functions (`generateText`, `streamText`) when you need explicit control for complex structured workflows.
---
## Building ToolLoopAgent
### Basic Agent
```typescript
import { ToolLoopAgent, tool } from 'ai';
import { z } from 'zod';
const weatherAgent = new ToolLoopAgent({
model: 'anthropic/claude-sonnet-4.5',
tools: {
weather: tool({
description: 'Get weather in a location (Fahrenheit)',
inputSchema: z.object({
location: z.string().describe('The location'),
}),
execute: async ({ location }) => ({
location,
temperature: 72 + Math.floor(Math.random() * 21) - 10,
}),
}),
convertFahrenheitToCelsius: tool({
description: 'Convert Fahrenheit to Celsius',
inputSchema: z.object({
temperature: z.number(),
}),
execute: async ({ temperature }) => ({
celsius: Math.round((temperature - 32) * (5 / 9)),
}),
}),
},
});
// Use the agent
const result = await weatherAgent.generate({
prompt: 'What is the weather in San Francisco in celsius?',
});
console.log(result.text); // Agent's final answer
console.log(result.steps); // Steps taken by agent
```
### Multi-Tool Execution
The agent automatically:
1. Calls `weather` tool to get temperature in Fahrenheit
2. Calls `convertFahrenheitToCelsius` to convert it
3. Generates final text response with result
---
## Agent Configuration Options
### Model and System Instructions
```typescript
const agent = new ToolLoopAgent({
model: 'anthropic/claude-sonnet-4.5',
instructions: 'You are an expert data analyst. Provide clear insights.',
});
```
### Tools
```typescript
const codeAgent = new ToolLoopAgent({
model: 'anthropic/claude-sonnet-4.5',
tools: {
runCode: tool({
description: 'Execute Python code',
inputSchema: z.object({
code: z.string(),
}),
execute: async ({ code }) => {
// Execute code
return { output: 'Result' };
},
}),
},
});
```
### Loop Control (stopWhen)
By default, agents run for 20 steps (`stopWhen: stepCountIs(20)`). Each step is one generation (text or tool call).
```typescript
import { ToolLoopAgent, stepCountIs } from 'ai';
const agent = new ToolLoopAgent({
model: 'anthropic/claude-sonnet-4.5',
stopWhen: stepCountIs(20), // Allow up to 20 steps
});
// Combine multiple stop conditions
const agent2 = new ToolLoopAgent({
model: 'anthropic/claude-sonnet-4.5',
stopWhen: [
stepCountIs(20),
yourCustomCondition(), // Custom logic
],
});
```
The loop stops when:
- Finish reasoning (non-tool-call) is returned
- Tool without execute function is invoked
- Tool call needs approval
- Stop condition is met
### Tool Choice
Control how agent uses tools:
```typescript
const agent = new ToolLoopAgent({
model: 'anthropic/claude-sonnet-4.5',
tools: { /* ... */ },
toolChoice: 'required', // Force tool use
// or 'none' to disable tools
// or 'auto' (default) to let model decide
});
// Force specific tool
const agent2 = new ToolLoopAgent({
model: 'anthropic/claude-sonnet-4.5',
tools: { weather: weatherTool, attractions: attractionsTool },
toolChoice: {
type: 'tool',
toolName: 'weather', // Force weather tool
},
});
```
### Structured Output
Define structured output schemas:
```typescript
import { ToolLoopAgent, Output, stepCountIs } from 'ai';
const analysisAgent = new ToolLoopAgent({
model: 'anthropic/claude-sonnet-4.5',
output: Output.object({
schema: z.object({
sentiment: z.enum(['positive', 'neutral', 'negative']),
summary: z.string(),
keyPoints: z.array(z.string()),
}),
}),
stopWhen: stepCountIs(10),
});
const { output } = await analysisAgent.generate({
prompt: 'Analyze customer feedback',
});
```
---
## System Instructions & Behavior
### Basic System Instructions
```typescript
const agent = new ToolLoopAgent({
model: 'anthropic/claude-sonnet-4.5',
instructions: 'You are an expert software engineer.',
});
```
### Detailed Behavioral Instructions
```typescript
const codeReviewAgent = new ToolLoopAgent({
model: 'anthropic/claude-sonnet-4.5',
instructions: `You are a senior software engineer conducting code reviews.
Your approach:
- Focus on security vulnerabilities first
- Identify performance bottlenecks
- Suggest improvements for readability and maintainability
- Be constructive and educational in your feedback
- Always explain why something is an issue and how to fix it`,
});
```
### Constrain Agent Behavior
```typescript
const supportAgent = new ToolLoopAgent({
model: 'anthropic/claude-sonnet-4.5',
instructions: `You are a customer support specialist.
Rules:
- Never make promises about refunds without checking policy
- Always be empathetic and professional
- If you don't know something, say so and offer to escalate
- Keep responses concise and actionable
- Never share internal company information`,
tools: {
checkOrderStatus,
lookupPolicy,
createTicket,
},
});
```
### Tool Usage Instructions
```typescript
const researchAgent = new ToolLoopAgent({
model: 'anthropic/claude-sonnet-4.5',
instructions: `You are a research assistant with access to search and document tools.
When researching:
1. Always start with a broad search to understand the topic
2. Use document analysis for detailed information
3. Cross-reference multiple sources before drawiRelated in Design
contribute
IncludedLocal-only OSS contribution command center. Auto-refreshes the user's in-flight PR and issue state on invoke so conversations start with full context — no need to brief Claude on what's in flight. Helps the user find issues to contribute to on GitHub, builds per-repo dossiers of what each upstream expects (CLA, DCO, branch convention, AI policy, draft-first, review bots, issue templates), runs deterministic gates before any external action so AI-assisted contributions don't reach maintainers as slop. State is markdown-only: candidate files at ~/.contribute-system/candidates/, repo dossiers at ~/.contribute-system/research/, append-only event log at ~/.contribute-system/log.jsonl. No database, no cloud calls. Use when the user asks about their PRs / issues / contributions, wants to find new work to take on, claim an issue, build/refresh a repo's dossier, or draft a Design Issue or PR. Trigger with "/contribute", "what's my PR status", "find a contribution", "claim issue X", "draft a Design Issue for Y", "refresh dossier for Z".
architectural-analysis
IncludedUser-triggered deep architectural analysis of a codebase or scoped subtree across eight modes — information architecture, data flow, integration points, UI surfaces, interaction patterns, data model, control flow, and failure modes. This skill should be used when the user asks to "diagram this codebase," "map the architecture," "show the data flow," "give me an ERD," "trace control flow," "find the integration points," "verify the layout pattern," "audit the UX architecture," or any similar request whose primary deliverable is mermaid diagrams plus cited reports under docs/architecture/. Dispatches haiku/sonnet sub-agents in parallel for per-mode exploration, then verifies every citation mechanically before any node lands in a diagram. Not for one-off prose explanations of code (use code-explanation) or for high-level system design from scratch (use system-design).
mcp
IncludedModel Context Protocol (MCP) server development and tool management. Languages: Python, TypeScript. Capabilities: build MCP servers, integrate external APIs, discover/execute MCP tools, manage multi-server configs, design agent-centric tools. Actions: create, build, integrate, discover, execute, configure MCP servers/tools. Keywords: MCP, Model Context Protocol, MCP server, MCP tool, stdio transport, SSE transport, tool discovery, resource provider, prompt template, external API integration, Gemini CLI MCP, Claude MCP, agent tools, tool execution, server config. Use when: building MCP servers, integrating external APIs as MCP tools, discovering available MCP tools, executing MCP capabilities, configuring multi-server setups, designing tools for AI agents.
react-native-skia
IncludedDesign, build, debug, and optimise high-polish animated graphics in React Native or Expo using @shopify/react-native-skia, Reanimated, and Gesture Handler. Use when the user wants canvas-driven UI, shaders, paths, rich text, image filters, sprite fields, Skottie, video frames, snapshots, web CanvasKit setup, or performance tuning for custom motion-heavy elements such as loaders, hero art, cards, charts, progress indicators, particle systems, or gesture-driven surfaces. Also use when the user asks for fluid, glow, glass, blob, parallax, 60fps/120fps, or GPU-friendly animated effects in React Native, even if they do not explicitly say "Skia". Do not use for ordinary form/layout work with standard views.
plaid
IncludedProduct Led AI Development — guides founders from idea to launched product. Six capabilities: Idea (discover a product idea), Validate (pressure-test the idea against fatal flaws, problem reality, competition, and 2-week MVP feasibility), Plan (vision intake + document generation), Design (translate image references into a design.md spec), Launch (go-to-market strategy), and Build (roadmap execution). Use when someone says "PLAID", "plaid idea", "help me find an idea", "product idea", "idea from my business", "idea from my expertise", "plaid validate", "validate my idea", "pressure-test", "is this idea good", "find fatal flaws", "validate the problem", "plan a product", "define my vision", "generate a PRD", "product strategy", "plaid design", "design from image", "translate image to design", "create design.md", "extract design tokens", "plaid launch", "go-to-market", "launch plan", "GTM strategy", "launch playbook", "plaid build", "build the app", "start building", or "execute the roadmap".
nextjs-framer-motion-animations
IncludedAdds production-safe Motion for React or Framer Motion animations to Next.js apps, including reveal, hover and tap micro-interactions, whileInView, stagger, AnimatePresence, layout and layoutId transitions, reorder, scroll-linked UI, and lightweight route-content transitions. Use when the user asks to add, refactor, or debug Motion or Framer Motion in App Router or Pages Router codebases, especially around server/client boundaries, reduced motion, LazyMotion, bundle size, hydration, or route transitions. Avoid for GSAP-style timelines, WebGL or 3D scenes, heavy scroll storytelling, or CSS-only effects unless Motion is explicitly requested.