/** * AI SDK UI - Chat with Tool Calling * * Demonstrates: * - Displaying tool calls in UI * - Rendering tool arguments and results * - Handling multi-step tool invocations * - Visual distinction between messages and tool calls * * Requires: * - API route with tools configured (see ai-sdk-core skill) * - Backend using `tool()` helper * * Usage: * 1. Set up API route with tools * 2. Copy this component * 3. Customize tool rendering as needed */ 'use client'; import { useChat } from 'ai/react'; import { useState, FormEvent } from 'react'; export default function ChatWithTools() { const { messages, sendMessage, isLoading, error } = useChat({ api: '/api/chat', }); const [input, setInput] = useState(''); const handleSubmit = (e: FormEvent) => { e.preventDefault(); if (!input.trim()) return; sendMessage({ content: input }); setInput(''); }; return (
{/* Header */}

AI Chat with Tools

Ask about weather, calculations, or search queries

{/* Messages */}
{messages.map((message) => (
{/* Text content */} {message.content && (
{message.content}
)} {/* Tool invocations */} {message.toolInvocations && message.toolInvocations.length > 0 && (
{message.toolInvocations.map((tool, idx) => (
{/* Tool name */}
Tool: {tool.toolName}
{/* Tool state */} {tool.state === 'call' && (
Calling with:
                            {JSON.stringify(tool.args, null, 2)}
                          
)} {tool.state === 'result' && (
Arguments:
                            {JSON.stringify(tool.args, null, 2)}
                          
Result:
                            {JSON.stringify(tool.result, null, 2)}
                          
)} {tool.state === 'partial-call' && (
Preparing arguments...
)}
))}
)}
))} {isLoading && (
)}
{/* Error */} {error && (
Error: {error.message}
)} {/* Input */}
setInput(e.target.value)} placeholder="Try: 'What's the weather in San Francisco?'" disabled={isLoading} className="flex-1 p-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" />
); }