DesarrolloIntermedio35 min
Vercel AI SDK Completo
useChat · useCompletion · Edge Functions · streaming nativo
VercelAI SDKEdge
✓ Guía gratuita · Acceso completo
Mapa rápido · salta al paso que te interese
01
Setup del Vercel AI SDK
Terminal
npm install ai @ai-sdk/anthropicapp/api/chat/route.ts
import { anthropic } from '@ai-sdk/anthropic'
import { streamText } from 'ai'
export const runtime = 'edge' // Opcional: Edge runtime
export async function POST(req: Request) {
const { messages } = await req.json()
const result = streamText({
model: anthropic('claude-sonnet-4-20250514'),
messages,
system: 'Eres un asistente útil y conciso.',
})
return result.toDataStreamResponse()
}02
useChat: chat completo en 20 líneas
app/chat/page.tsx
'use client'
import { useChat } from 'ai/react'
export default function ChatPage() {
const { messages, input, handleInputChange, handleSubmit, isLoading } = useChat()
return (
<div className="flex flex-col h-screen max-w-2xl mx-auto p-4">
<div className="flex-1 overflow-y-auto space-y-4">
{messages.map((m) => (
<div key={m.id} className={`p-3 rounded ${m.role === 'user' ? 'bg-blue-100' : 'bg-gray-100'}`}>
<strong>{m.role === 'user' ? 'Tú' : 'AI'}:</strong> {m.content}
</div>
))}
</div>
<form onSubmit={handleSubmit} className="flex gap-2 pt-4">
<input
value={input}
onChange={handleInputChange}
placeholder="Escribe un mensaje..."
className="flex-1 p-2 border rounded"
disabled={isLoading}
/>
<button type="submit" disabled={isLoading} className="px-4 py-2 bg-black text-white rounded">
{isLoading ? '...' : 'Enviar'}
</button>
</form>
</div>
)
}Tip Pro
useChat maneja automáticamente el historial, streaming, y estados de carga. No necesitas useState ni useEffect.
03
Tools: acciones desde el chat
app/api/chat/route.ts (con tools)
import { anthropic } from '@ai-sdk/anthropic'
import { streamText, tool } from 'ai'
import { z } from 'zod'
export async function POST(req: Request) {
const { messages } = await req.json()
const result = streamText({
model: anthropic('claude-sonnet-4-20250514'),
messages,
tools: {
getWeather: tool({
description: 'Obtener el clima actual de una ciudad',
parameters: z.object({
city: z.string().describe('Nombre de la ciudad'),
}),
execute: async ({ city }) => {
// Llamada real a API de clima
const res = await fetch(`https://wttr.in/${city}?format=j1`)
const data = await res.json()
return {
city,
temp: data.current_condition[0].temp_C,
condition: data.current_condition[0].weatherDesc[0].value,
}
},
}),
},
})
return result.toDataStreamResponse()
}¿Quieres el sistema completo?
500+ páginas, 25 capítulos, código de producción, acceso a todas las guías del Arsenal.
Curso Completo · €29PayPal · Acceso inmediato