Intermediate
useCompletion Hook
The useCompletion hook is designed for single-turn text generation. Use it for summarization, translation, code generation, auto-complete, and any non-conversational AI feature.
Basic Completion
TypeScript - Server Route
// app/api/completion/route.ts import { openai } from '@ai-sdk/openai'; import { streamText } from 'ai'; export async function POST(req: Request) { const { prompt } = await req.json(); const result = streamText({ model: openai('gpt-4o'), prompt, }); return result.toDataStreamResponse(); }
TypeScript - Client Component
'use client'; import { useCompletion } from 'ai/react'; export default function Summarizer() { const { completion, // Generated text (streams in) input, // Current input value handleInputChange, // Input onChange handleSubmit, // Form submit isLoading, // Is generating? stop, // Stop generation } = useCompletion({ api: '/api/completion' }); return ( <div> <form onSubmit={handleSubmit}> <textarea value={input} onChange={handleInputChange} placeholder="Paste text to summarize..." rows={5} /> <button type="submit" disabled={isLoading}> {isLoading ? 'Summarizing...' : 'Summarize'} </button> </form> {completion && <div className="result">{completion}</div>} </div> ); }
useChat vs useCompletion
| Feature | useChat | useCompletion |
|---|---|---|
| State | Array of messages | Single completion string |
| History | Full conversation | No history (single turn) |
| API Format | messages: Message[] | prompt: string |
| Use Case | Chatbots, assistants | Summarize, translate, generate |
Programmatic Completion
TypeScript
const { complete, completion, isLoading } = useCompletion(); // Call programmatically (not from a form) const handleSummarize = async () => { await complete(`Summarize this article:\n\n${articleText}`); }; // With extra body params const handleTranslate = async () => { await complete(text, { body: { language: 'French', tone: 'formal' }, }); };
Pro tip: Use
complete() for programmatic calls (button clicks, effects) and handleSubmit for form submissions. Both stream the result into the completion variable.What's Next?
Let's explore the provider system — how to use OpenAI, Anthropic, Google, and other AI providers with the AI SDK.
Lilly Tech Systems