Claude
Skills
Sign in
Back

AI Agents & UI - Building Agentic Applications with AI SDK 6

Included with Lifetime
$97 forever

Comprehensive guide for building AI agents using ToolLoopAgent, workflow patterns, and AI SDK UI components (useChat, generative UIs, tool calling)

Design

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 drawi

Related in Design