Context
A button that shows how much of the model's context window is used, with a breakdown on hover or focus.
Installation
pnpm dlx shadcn@latest add @silkware/ai-contextTo copy the pattern by hand, install the components it composes, then copy the pattern into components/ai-elements/context.tsx:
pnpm dlx shadcn@latest add @silkware/button @silkware/hover-card @silkware/progress"use client"
import { Button } from "@/components/ui/button"import { HoverCard, HoverCardTrigger } from "@/components/ui/hover-card"import { Progress } from "@/components/ui/progress"
const usage = { input: 8420, output: 1260, reasoning: 980, limit: 128000,}
const used = usage.input + usage.output + usage.reasoningconst percent = Math.round((used / usage.limit) * 100)
function formatTokens(value: number) { if (value < 1000) { return String(value) }
return `${(value / 1000).toFixed(1).replace(/\.0$/, "")}k`}
const rows = [ { label: "Input", value: usage.input }, { label: "Output", value: usage.output }, { label: "Reasoning", value: usage.reasoning },]
export function ContextDemo() { return ( <div className="flex justify-center py-12"> <HoverCardTrigger delay={10} closeDelay={100}> <Button variant="outline" size="sm"> {percent}% context </Button> <HoverCard className="flex w-64 flex-col gap-3"> <div className="flex items-center justify-between gap-3 text-sm"> <span className="font-medium">Context</span> <span className="text-muted-foreground"> {formatTokens(used)} / {formatTokens(usage.limit)} </span> </div> <Progress value={percent} aria-label="Context used" /> <div className="flex flex-col gap-1 text-sm"> {rows.map((row) => ( <div key={row.label} className="flex justify-between gap-3"> <span className="text-muted-foreground">{row.label}</span> <span>{formatTokens(row.value)}</span> </div> ))} </div> </HoverCard> </HoverCardTrigger> </div> )}Usage
import { Button } from "@/components/ui/button"import { HoverCard, HoverCardTrigger } from "@/components/ui/hover-card"import { Progress } from "@/components/ui/progress"const used = usage.input + usage.output + usage.reasoningconst percent = Math.round((used / usage.limit) * 100)
<HoverCardTrigger delay={10} closeDelay={100}> <Button variant="outline" size="sm"> {percent}% context </Button> <HoverCard className="flex w-64 flex-col gap-3"> <Progress value={percent} aria-label="Context used" /> {/* the rows: input, output, reasoning */} </HoverCard></HoverCardTrigger>The button shows one number. The card opens on hover, on keyboard focus and on long press, and shows the used and total tokens, a Progress bar and a row for each kind of token. The numbers are in the usage object at the top of the file, and formatTokens shortens them (8420 becomes 8.4k). The pattern shows them; it does not count tokens, so you give it real usage.
Examples
Near the limit
When the window is almost full, say what to do. The number alone does not tell the person that the agent will start to lose earlier details.
AI SDK
The AI SDK reports token use on the server, not in useChat. streamText gives usage with inputTokens and outputTokens (the output details include reasoning tokens). Send it to the client as message metadata, then read it from the last agent message.
return result.toUIMessageStreamResponse({ messageMetadata: ({ part }) => { if (part.type === "finish") { return { totalUsage: part.totalUsage } } },})const last = messages.findLast((message) => message.role === "assistant")const usage = last?.metadata?.totalUsageType the metadata on your UIMessage, and check the field names against the version of ai you installed: the usage object has inputTokens, outputTokens and nested detail objects, and any of them can be undefined. Treat missing numbers as unknown, not as zero. The context limit is a property of the model, which you hold on your side.
The demo uses fixed sample numbers, with no stream behind them. createChat in lib/ai.ts does not script usage; attach it to the messages you create.
Accessibility
| Key | Action |
|---|---|
| Tab | Moves focus to the button. The card opens on focus. |
| Esc | Closes the card. |
The composed components provide:
- A focusable button, and a preview card that opens on focus as well as hover.
- A progress bar with its value exposed to assistive technology.
You provide:
- The meaning in text. The button says "94% context"; do not rely on the bar or its colour alone.
- A label on the progress bar. The pattern sets
aria-label="Context used". - A warning in words when the limit is near, in the card or in the thread.
Guidelines
When to use
- In the header or field of a long thread, so the person sees how much room is left.
- For agents that read many files or documents, where the window fills fast.
When not to use
- For billing or cost. Show money in its own place, in plain currency.
- For task progress. Use Progress with a label for the task.
Content
- Show a percentage on the button and the tokens in the card.
- Group tokens by what the person understands: input, output, reasoning.
- Say what happens at the limit and what to do: "Start a new thread".
Human in the loop
The person decides when to start over, so tell them before the agent forgets, not after. Do not trim the thread silently. If the product compacts or drops earlier messages, show that it did, and let the person choose.
Warn at a stated point, for example 90%, with the action to take.
Don’t let the agent drop earlier messages without saying so. Its answers change and the person cannot tell why.
Composition
| Component | What it does here |
|---|---|
| Button | The trigger that shows the percentage. |
| Hover Card | The card that opens on hover and focus. |
| Progress | The bar for the share of the window used. |
The pattern exports one component, ContextDemo. usage, rows and formatTokens are plain values and a helper at the top of the file.