Skills for Claude Code CLI such as full stack dev Cloudflare, React, Tailwind v4, and AI integrations.
Python aianthropicautomationclaude-codeclaude-skillscloudflaredevtoolsproductivityreactskillstailwindvite
refactor(ai-sdk-ui): Knowledge-gap audit - Add AI SDK 6 beta, useAssistant hook, trim basics
Jez2c5d5912c928
diff --git a/skills/ai-sdk-ui/SKILL.md b/skills/ai-sdk-ui/SKILL.mdindex 17178290..24495740 100644--- a/skills/ai-sdk-ui/SKILL.md+++ b/skills/ai-sdk-ui/SKILL.md@@ -1,30 +1,37 @@---name: ai-sdk-uidescription: |- Build React chat interfaces and AI-powered UIs with Vercel AI SDK v5. Provides useChat, useCompletion,- and useObject hooks for streaming responses, managing conversation state, and handling file attachments.+ Build React chat interfaces with Vercel AI SDK v5/v6. Covers v6 beta (agent integration, tool approval,+ auto-submit), v4→v5 migration (breaking changes), useChat/useCompletion/useObject/useAssistant hooks,+ and 12 UI error solutions (stream parsing, stale body values, React update depth).- Use when: implementing chat interfaces, streaming AI completions, managing message state in Next.js apps,- or troubleshooting "useChat failed to parse stream" or "useChat no response" errors.+ Use when: implementing AI SDK v5/v6 chat UIs, migrating v4→v5, troubleshooting "useChat failed to parse+ stream", "useChat no response", or "stale body values" errors, or integrating OpenAI assistants.license: MITmetadata:- version: 1.0.1- last_verified: 2025-11-19- ai_sdk_version: 5.0.95+- breaking_changes: false+ version: 1.1.0+ last_verified: 2025-11-22+ ai_sdk_version: 5.0.99 stable / 6.0.0-beta.108+ breaking_changes: true (v4→v5 migration guide included)production_tested: truekeywords:- ai sdk ui+ - ai sdk v6 beta+ - ai sdk 6- vercel ai sdk ui- useChat hook- useCompletion hook- useObject hook+ - useAssistant hook- react ai chat- ai chat interface- streaming ai ui- nextjs ai chat- react streaming- ai sdk react+ - agent integration+ - tool approval workflow+ - human in the loop ui- chat message state- ai file attachments- message persistence@@ -32,198 +39,135 @@ metadata:- streaming failed ui- parse stream error- useChat no response+ - stale body values+ - react maximum update depth- react ai hooks- nextjs app router ai- nextjs pages router ai- ai chat component- streaming response react- react ai completion+ - openai assistant ui---# AI SDK UI - Frontend React Hooks-Frontend React hooks for AI-powered user interfaces with Vercel AI SDK v5.+Frontend React hooks for AI-powered user interfaces with Vercel AI SDK v5/v6.-**Version**: AI SDK v5.0.95+ (Stable)+**Version**: AI SDK v5.0.99 (Stable) / v6.0.0-beta.108 (Beta)**Framework**: React 18+, Next.js 14+-**Last Updated**: 2025-11-19+**Last Updated**: 2025-11-22----## Quick Start (5 Minutes)+## AI SDK 6 Beta (November 2025)-### Installation+**Status:** Beta (stable release planned end of 2025)+**Latest:** [email protected] (Nov 22, 2025)+**Migration:** Minimal breaking changes from v5 → v6-```bash-npm install ai @ai-sdk/openai+### New UI Features in v6 Beta++**1. Agent Integration**+Type-safe messaging with agents using `InferAgentUIMessage<typeof agent>`:++```tsx+import { useChat } from '@ai-sdk/react';+import type { InferAgentUIMessage } from 'ai';+import { myAgent } from './agent';++export default function AgentChat() {+ const { messages, sendMessage } = useChat<InferAgentUIMessage<typeof myAgent>>({+ api: '/api/chat',+ });+ // messages are now type-checked against agent schema+}```-### Basic Chat Component (v5)+**2. Tool Approval Workflows (Human-in-the-Loop)**+Request user confirmation before executing tools:```tsx-// app/chat/page.tsx-'use client';-import { useChat } from 'ai/react';-import { useState, FormEvent } from 'react';+import { useChat } from '@ai-sdk/react';+import { useState } from 'react';-export default function Chat() {- const { messages, sendMessage, isLoading } = useChat({+export default function ChatWithApproval() {+ const { messages, sendMessage, addToolApprovalResponse } = useChat({api: '/api/chat',});- const [input, setInput] = useState('');- const handleSubmit = (e: FormEvent) => {- e.preventDefault();- sendMessage({ content: input });- setInput('');+ const handleApprove = (toolCallId: string) => {+ addToolApprovalResponse({+ toolCallId,+ approved: true, // or false to deny+ });};return (<div>- <div>- {messages.map(m => (- <div key={m.id}>- <strong>{m.role}:</strong> {m.content}- </div>- ))}- </div>- <form onSubmit={handleSubmit}>- <input- value={input}- onChange={(e) => setInput(e.target.value)}- placeholder="Type a message..."- disabled={isLoading}- />- </form>+ {messages.map(message => (+ <div key={message.id}>+ {message.toolInvocations?.map(tool => (+ tool.state === 'awaiting-approval' && (+ <div key={tool.toolCallId}>+ <p>Approve tool call: {tool.toolName}?</p>+ <button onClick={() => handleApprove(tool.toolCallId)}>+ Approve+ </button>+ <button onClick={() => addToolApprovalResponse({+ toolCallId: tool.toolCallId,+ approved: false+ })}>+ Deny+ </button>+ </div>+ )+ ))}+ </div>+ ))}</div>);}```-### API Route (Next.js App Router)--```typescript-// app/api/chat/route.ts-import { streamText } from 'ai';-import { openai } from '@ai-sdk/openai';+**3. Auto-Submit Capability**+Automatically continue conversation after handling approvals:-export async function POST(req: Request) {- const { messages } = await req.json();+```tsx+import { useChat, lastAssistantMessageIsCompleteWithApprovalResponses } from '@ai-sdk/react';- const result = streamText({- model: openai('gpt-4-turbo'),- messages,+export default function AutoSubmitChat() {+ const { messages, sendMessage } = useChat({+ api: '/api/chat',+ sendAutomaticallyWhen: lastAssistantMessageIsCompleteWithApprovalResponses,+ // Automatically resubmit after all approval responses provided});-- return result.toDataStreamResponse();}```-**Result**: A functional chat interface with streaming AI responses in ~10 lines of frontend code.-------## useChat Hook - Complete Reference--### Basic Usage (v5 Pattern)+**4. Structured Output in Chat**+Generate structured data alongside tool calling (previously only available in `useObject`):```tsx-'use client';-import { useChat } from 'ai/react';-import { useState, FormEvent } from 'react';+import { useChat } from '@ai-sdk/react';+import { z } from 'zod';++const schema = z.object({+ summary: z.string(),+ sentiment: z.enum(['positive', 'neutral', 'negative']),+});-export default function ChatComponent() {- const { messages, sendMessage, isLoading, error } = useChat({+export default function StructuredChat() {+ const { messages, sendMessage } = useChat({api: '/api/chat',+ // Server can now stream structured output with chat messages});- const [input, setInput] = useState('');-- const handleSubmit = (e: FormEvent) => {- e.preventDefault();- if (!input.trim()) return;-- sendMessage({ content: input });- setInput('');- };-- return (- <div className="flex flex-col h-screen">- {/* Messages */}- <div className="flex-1 overflow-y-auto p-4">- {messages.map(message => (- <div- key={message.id}- className={message.role === 'user' ? 'text-right' : 'text-left'}- >- <div className="inline-block p-2 rounded bg-gray-100">- {message.content}- </div>- </div>- ))}- {isLoading && <div className="text-gray-500">AI is thinking...</div>}- </div>-- {/* Input */}- <form onSubmit={handleSubmit} className="p-4 border-t">- <input- value={input}- onChange={(e) => setInput(e.target.value)}- placeholder="Type a message..."- disabled={isLoading}- className="w-full p-2 border rounded"- />- </form>-- {/* Error */}- {error && <div className="text-red-500 p-4">{error.message}</div>}- </div>- );}```-### Full API Reference--```typescript-const {- // Messages- messages, // Message[] - Chat history- setMessages, // (messages: Message[]) => void - Update messages-- // Actions- sendMessage, // (message: { content: string }) => void - Send message (v5)- reload, // () => void - Reload last response- stop, // () => void - Stop current generation-- // State- isLoading, // boolean - Is AI responding?- error, // Error | undefined - Error if any-- // Data- data, // any[] - Custom data from stream- metadata, // object - Response metadata-} = useChat({- // Required- api: '/api/chat', // API endpoint-- // Optional- id: 'chat-1', // Chat ID for persistence- initialMessages: [], // Initial messages (controlled mode)-- // Callbacks- onFinish: (message, options) => {}, // Called when response completes- onError: (error) => {}, // Called on error-- // Configuration- headers: {}, // Custom headers- body: {}, // Additional body data- credentials: 'same-origin', // Fetch credentials-- // Streaming- streamProtocol: 'data', // 'data' | 'text' (default: 'data')-});-```+----### v4 → v5 Breaking Changes+## useChat Hook - v4 → v5 Breaking Changes**CRITICAL: useChat no longer manages input state in v5!**@@ -259,572 +203,62 @@ const [input, setInput] = useState('');See `references/use-chat-migration.md` for complete migration guide.-### Tool Calling in UI--When your API uses tools, useChat automatically handles tool invocations in the message stream:+----```tsx-'use client';-import { useChat } from 'ai/react';+## useAssistant Hook-export default function ChatWithTools() {- const { messages } = useChat({ api: '/api/chat' });+Interact with OpenAI-compatible assistant APIs with automatic UI state management.- return (- <div>- {messages.map(message => (- <div key={message.id}>- {/* Text content */}- {message.content && <p>{message.content}</p>}-- {/* Tool invocations */}- {message.toolInvocations?.map((tool, idx) => (- <div key={idx} className="bg-blue-50 p-2 rounded my-2">- <div className="font-bold">Tool: {tool.toolName}</div>- <div className="text-sm">- <strong>Args:</strong> {JSON.stringify(tool.args, null, 2)}- </div>- {tool.result && (- <div className="text-sm">- <strong>Result:</strong> {JSON.stringify(tool.result, null, 2)}- </div>- )}- </div>- ))}- </div>- ))}- </div>- );-}+**Import:**+```tsx+import { useAssistant } from '@ai-sdk/react';```-### File Attachments--Upload files (images, PDFs, etc.) alongside messages:-+**Basic Usage:**```tsx'use client';-import { useChat } from 'ai/react';+import { useAssistant } from '@ai-sdk/react';import { useState, FormEvent } from 'react';-export default function ChatWithAttachments() {- const { messages, sendMessage, isLoading } = useChat({ api: '/api/chat' });+export default function AssistantChat() {+ const { messages, sendMessage, isLoading, error } = useAssistant({+ api: '/api/assistant',+ });const [input, setInput] = useState('');- const [files, setFiles] = useState<FileList | null>(null);const handleSubmit = (e: FormEvent) => {e.preventDefault();-- sendMessage({- content: input,- experimental_attachments: files- ? Array.from(files).map(file => ({- name: file.name,- contentType: file.type,- url: URL.createObjectURL(file),- }))- : undefined,- });-+ sendMessage({ content: input });setInput('');- setFiles(null);};return (<div>- {/* Messages */}{messages.map(m => (<div key={m.id}>- {m.content}- {m.experimental_attachments?.map((att, idx) => (- <div key={idx}>- <img src={att.url} alt={att.name} />- </div>- ))}+ <strong>{m.role}:</strong> {m.content}</div>))}-- {/* Input */}- <form onSubmit={handleSubmit}>- <input- type="file"- multiple- onChange={(e) => setFiles(e.target.files)}- accept="image/*"- />- <input- value={input}- onChange={(e) => setInput(e.target.value)}- />- <button type="submit" disabled={isLoading}>Send</button>- </form>- </div>- );-}-```--### Message Persistence--Save and load chat history to localStorage:--```tsx-'use client';-import { useChat } from 'ai/react';-import { useEffect } from 'react';--export default function PersistentChat() {- const chatId = 'my-chat-1';-- const { messages, setMessages, sendMessage } = useChat({- api: '/api/chat',- id: chatId,- initialMessages: loadMessages(chatId),- });-- // Save messages whenever they change- useEffect(() => {- saveMessages(chatId, messages);- }, [messages, chatId]);-- return (- <div>- {messages.map(m => (- <div key={m.id}>{m.role}: {m.content}</div>- ))}- {/* Input form... */}- </div>- );-}--// Helper functions-function loadMessages(chatId: string) {- const stored = localStorage.getItem(`chat-${chatId}`);- return stored ? JSON.parse(stored) : [];-}--function saveMessages(chatId: string, messages: any[]) {- localStorage.setItem(`chat-${chatId}`, JSON.stringify(messages));-}-```-------## useCompletion Hook - Complete Reference--### Basic Usage--```tsx-'use client';-import { useCompletion } from 'ai/react';-import { useState, FormEvent } from 'react';--export default function Completion() {- const { completion, complete, isLoading, error } = useCompletion({- api: '/api/completion',- });- const [input, setInput] = useState('');-- const handleSubmit = (e: FormEvent) => {- e.preventDefault();- complete(input);- setInput('');- };-- return (- <div><form onSubmit={handleSubmit}>- <textarea- value={input}- onChange={(e) => setInput(e.target.value)}- placeholder="Enter a prompt..."- rows={4}- className="w-full p-2 border rounded"- />- <button type="submit" disabled={isLoading}>- {isLoading ? 'Generating...' : 'Generate'}- </button>- </form>-- {completion && (- <div className="mt-4 p-4 bg-gray-50 rounded">- <h3>Result:</h3>- <p>{completion}</p>- </div>- )}-- {error && <div className="text-red-500">{error.message}</div>}- </div>- );-}-```--### Full API Reference--```typescript-const {- completion, // string - Current completion text- complete, // (prompt: string) => void - Trigger completion- setCompletion, // (completion: string) => void - Update completion- isLoading, // boolean - Is generating?- error, // Error | undefined - Error if any- stop, // () => void - Stop generation-} = useCompletion({- api: '/api/completion',- id: 'completion-1',-- // Callbacks- onFinish: (prompt, completion) => {},- onError: (error) => {},-- // Configuration- headers: {},- body: {},-});-```--### API Route for useCompletion--```typescript-// app/api/completion/route.ts-import { streamText } from 'ai';-import { openai } from '@ai-sdk/openai';--export async function POST(req: Request) {- const { prompt } = await req.json();-- const result = streamText({- model: openai('gpt-3.5-turbo'),- prompt,- maxOutputTokens: 500,- });-- return result.toDataStreamResponse();-}-```-------## useObject Hook - Complete Reference--### Basic Usage--Stream structured data (e.g., forms, JSON objects) with live updates:--```tsx-'use client';-import { useObject } from 'ai/react';-import { z } from 'zod';--const recipeSchema = z.object({- recipe: z.object({- name: z.string(),- ingredients: z.array(z.string()),- instructions: z.array(z.string()),- }),-});--export default function RecipeGenerator() {- const { object, submit, isLoading, error } = useObject({- api: '/api/recipe',- schema: recipeSchema,- });-- return (- <div>- <button onClick={() => submit('pasta carbonara')} disabled={isLoading}>- Generate Recipe- </button>-- {isLoading && <div>Generating recipe...</div>}-- {object?.recipe && (- <div className="mt-4">- <h2 className="text-2xl font-bold">{object.recipe.name}</h2>-- <h3 className="text-xl mt-4">Ingredients:</h3>- <ul>- {object.recipe.ingredients?.map((ingredient, idx) => (- <li key={idx}>{ingredient}</li>- ))}- </ul>-- <h3 className="text-xl mt-4">Instructions:</h3>- <ol>- {object.recipe.instructions?.map((step, idx) => (- <li key={idx}>{step}</li>- ))}- </ol>- </div>- )}-- {error && <div className="text-red-500">{error.message}</div>}- </div>- );-}-```--### Full API Reference--```typescript-const {- object, // Partial<T> - Partial object (updates as stream progresses)- submit, // (input: string) => void - Trigger generation- isLoading, // boolean - Is generating?- error, // Error | undefined - Error if any- stop, // () => void - Stop generation-} = useObject({- api: '/api/object',- schema: zodSchema, // Zod schema-- // Callbacks- onFinish: (object) => {},- onError: (error) => {},-});-```--### API Route for useObject--```typescript-// app/api/recipe/route.ts-import { streamObject } from 'ai';-import { openai } from '@ai-sdk/openai';-import { z } from 'zod';--export async function POST(req: Request) {- const { prompt } = await req.json();-- const result = streamObject({- model: openai('gpt-4'),- schema: z.object({- recipe: z.object({- name: z.string(),- ingredients: z.array(z.string()),- instructions: z.array(z.string()),- }),- }),- prompt: `Generate a recipe for ${prompt}`,- });-- return result.toTextStreamResponse();-}-```-------## Next.js Integration--### App Router Complete Example--**Directory Structure:**-```-app/-├── api/-│ └── chat/-│ └── route.ts # Chat API endpoint-├── chat/-│ └── page.tsx # Chat page-└── layout.tsx-```--**Chat Page:**-```tsx-// app/chat/page.tsx-'use client';-import { useChat } from 'ai/react';-import { useState, FormEvent, useRef, useEffect } from 'react';--export default function ChatPage() {- const { messages, sendMessage, isLoading, error } = useChat({- api: '/api/chat',- });- const [input, setInput] = useState('');- const messagesEndRef = useRef<HTMLDivElement>(null);-- // Auto-scroll to bottom- useEffect(() => {- messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });- }, [messages]);-- const handleSubmit = (e: FormEvent) => {- e.preventDefault();- if (!input.trim()) return;-- sendMessage({ content: input });- setInput('');- };-- return (- <div className="flex flex-col h-screen max-w-2xl mx-auto">- {/* Messages */}- <div className="flex-1 overflow-y-auto p-4 space-y-4">- {messages.map(message => (- <div- key={message.id}- className={`flex ${- message.role === 'user' ? 'justify-end' : 'justify-start'- }`}- >- <div- className={`max-w-[70%] p-3 rounded-lg ${- message.role === 'user'- ? 'bg-blue-500 text-white'- : 'bg-gray-200 text-gray-900'- }`}- >- {message.content}- </div>- </div>- ))}- {isLoading && (- <div className="flex justify-start">- <div className="bg-gray-200 p-3 rounded-lg">- <div className="flex space-x-2">- <div className="w-2 h-2 bg-gray-500 rounded-full animate-bounce"></div>- <div className="w-2 h-2 bg-gray-500 rounded-full animate-bounce delay-100"></div>- <div className="w-2 h-2 bg-gray-500 rounded-full animate-bounce delay-200"></div>- </div>- </div>- </div>- )}- <div ref={messagesEndRef} />- </div>-- {/* Error */}- {error && (- <div className="p-4 bg-red-50 border-t border-red-200 text-red-700">- Error: {error.message}- </div>- )}-- {/* Input */}- <form onSubmit={handleSubmit} className="p-4 border-t">- <div className="flex space-x-2">- <input- value={input}- onChange={(e) => setInput(e.target.value)}- placeholder="Type a message..."- disabled={isLoading}- className="flex-1 p-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"- />- <button- type="submit"- disabled={isLoading || !input.trim()}- className="px-4 py-2 bg-blue-500 text-white rounded-lg disabled:bg-gray-300 disabled:cursor-not-allowed"- >- Send- </button>- </div>- </form>- </div>- );-}-```--**API Route:**-```typescript-// app/api/chat/route.ts-import { streamText } from 'ai';-import { openai } from '@ai-sdk/openai';--export async function POST(req: Request) {- const { messages } = await req.json();-- const result = streamText({- model: openai('gpt-4-turbo'),- messages,- system: 'You are a helpful AI assistant.',- maxOutputTokens: 1000,- });-- return result.toDataStreamResponse();-}-```--### Pages Router Complete Example--**Directory Structure:**-```-pages/-├── api/-│ └── chat.ts # Chat API endpoint-└── chat.tsx # Chat page-```--**Chat Page:**-```tsx-// pages/chat.tsx-import { useChat } from 'ai/react';-import { useState, FormEvent } from 'react';--export default function ChatPage() {- const { messages, sendMessage, isLoading } = useChat({- api: '/api/chat',- });- const [input, setInput] = useState('');-- const handleSubmit = (e: FormEvent) => {- e.preventDefault();- sendMessage({ content: input });- setInput('');- };-- return (- <div className="container mx-auto p-4">- <h1 className="text-2xl font-bold mb-4">AI Chat</h1>-- <div className="border rounded p-4 h-96 overflow-y-auto mb-4">- {messages.map(m => (- <div key={m.id} className="mb-4">- <strong>{m.role === 'user' ? 'You' : 'AI'}:</strong> {m.content}- </div>- ))}- </div>-- <form onSubmit={handleSubmit} className="flex space-x-2"><inputvalue={input}onChange={(e) => setInput(e.target.value)}- placeholder="Type a message..."disabled={isLoading}- className="flex-1 p-2 border rounded"/>- <button- type="submit"- disabled={isLoading}- className="px-4 py-2 bg-blue-500 text-white rounded"- >- Send- </button></form>+ {error && <div>{error.message}</div>}</div>);}```-**API Route:**-```typescript-// pages/api/chat.ts-import type { NextApiRequest, NextApiResponse } from 'next';-import { streamText } from 'ai';-import { openai } from '@ai-sdk/openai';--export default async function handler(- req: NextApiRequest,- res: NextApiResponse-) {- const { messages } = req.body;-- const result = streamText({- model: openai('gpt-4-turbo'),- messages,- });-- // Pages Router uses pipeDataStreamToResponse- return result.pipeDataStreamToResponse(res);-}-```+**Use Cases:**+- Building OpenAI Assistant-powered UIs+- Managing assistant threads and runs+- Streaming assistant responses with UI state management+- File search and code interpreter integrations-**Key Difference**: App Router uses `toDataStreamResponse()`, Pages Router uses `pipeDataStreamToResponse()`.+See official docs for complete API reference: https://ai-sdk.dev/docs/reference/ai-sdk-ui/use-assistant---@@ -983,11 +417,12 @@ See `references/streaming-patterns.md` for comprehensive best practices.## Package Versions-**Required:**+**Stable (v5):**```json{"dependencies": {- "ai": "^5.0.95",+ "ai": "^5.0.99",+ "@ai-sdk/react": "^1.0.0","@ai-sdk/openai": "^2.0.68","react": "^18.2.0","zod": "^3.23.8"@@ -995,22 +430,23 @@ See `references/streaming-patterns.md` for comprehensive best practices.}```-**Next.js:**+**Beta (v6):**```json{"dependencies": {- "next": "^14.0.0",- "react": "^18.2.0",- "react-dom": "^18.2.0"+ "ai": "6.0.0-beta.108",+ "@ai-sdk/react": "beta",+ "@ai-sdk/openai": "beta"}}```**Version Notes:**-- AI SDK v5.0.95+ (stable, latest as of November 2025)+- AI SDK v5.0.99 (stable, Nov 2025)+- AI SDK v6.0.0-beta.108 (beta, Nov 22, 2025) - minimal breaking changes- React 18+ (React 19 supported)- Next.js 14+ recommended (13.4+ works)-- Zod 3.23.8+ for schema validation (templates use 3.x for compatibility)+- Zod 3.23.8+ for schema validation---@@ -1071,4 +507,4 @@ See `references/` for:---**Production Tested**: WordPress Auditor (https://wordpress-auditor.webfonts.workers.dev)-**Last Updated**: 2025-11-19+**Last Updated**: 2025-11-22