Blocks
AI chat
A complete chat with an AI model: replies stream in, you can stop them, copy them, and start over.
Examples
Simple
This demo answers from a small script so it runs without a key; your app streams real replies from Claude. Scroll up while it writes and it leaves you there, with a button back down.
Ask the librarian
How can I help you today?
<script lang="ts">
import Chat from '#lib/blocks/chat/Chat.svelte';
// In your app: import { fetchServerSentEvents } from '@tanstack/ai-svelte';
// and pass connection={fetchServerSentEvents('/api/chat')}.
import { demoConnection } from './demo-connection';
</script>
<Chat
connection={demoConnection}
title="Ask the librarian"
assistantName="Librarian"
suggestions={[
'What was the House of Wisdom?',
'How did Ibn al-Haytham explain sight?',
'Where does the word algebra come from?'
]}
/>Assistant with history
Conversations are kept in this browser and listed by day; reload and they're still here. Attach images, audio, video or PDFs with the paperclip, by dropping them on the chat, or by pasting.
<script lang="ts">
import Assistant from '#lib/blocks/chat/Assistant.svelte';
// In your app: connection={fetchServerSentEvents('/api/chat')}.
import { demoConnection } from './demo-connection';
</script>
<Assistant
connection={demoConnection}
assistantName="Librarian"
suggestions={[
'What was the House of Wisdom?',
'How did Ibn al-Haytham explain sight?',
'Where does the word algebra come from?'
]}
/>When a reply is turned away
Your server says why in its own words, and the chat shows them with a link of yours beside it. Without failure, a dropped reply shows a general connection message. Send a question to see it.
Ask the reading room
How can I help you today?
<script lang="ts">
import Chat from '#lib/blocks/chat/Chat.svelte';
import { fetchServerSentEvents } from '@tanstack/ai-svelte';
// Stands in for your server turning a question away: a 429 with a message written for people.
const demoFetch = async () =>
Response.json(
{ message: 'You’ve asked all 20 questions in this month’s plan.' },
{ status: 429 }
);
let failure = $state<{ message: string }>();
const connection = fetchServerSentEvents('/api/chat', {
// In your app: fetch(input, init).
fetchClient: async () => {
const res = await demoFetch();
failure = res.ok
? undefined
: await res
.clone()
.json()
.catch(() => undefined);
return res;
}
});
</script>
<Chat
{connection}
title="Ask the reading room"
assistantName="Librarian"
suggestions={['What was the House of Wisdom?']}
{failure}
>
{#snippet failureActions()}<a href="#pricing">See plans</a>{/snippet}
</Chat>In a side sheet
fill makes the chat take its container's height, and bare drops its own card since the sheet is already one. The sheet is widened with --ui-sheet-width.
<script lang="ts">
import Button from '#lib/ui/Button.svelte';
import Chat from '#lib/blocks/chat/Chat.svelte';
import Dialog from '#lib/ui/Dialog.svelte';
import { demoConnection } from './demo-connection';
let open = $state(false);
</script>
<Button variant="secondary" onclick={() => (open = true)}>Ask the librarian</Button>
<Dialog
bind:open
side="end"
title="Librarian"
description="Answers come from a short script in this demo."
style="--ui-sheet-width: 28rem"
>
<Chat
connection={demoConnection}
title="Ask the librarian"
assistantName="Librarian"
suggestions={['What was the House of Wisdom?', 'Where does the word algebra come from?']}
fill
bare
/>
</Dialog>Terminal agent
An agent in a terminal: it thinks, calls tools and shows what each returned, then answers. Try “How did Ibn al-Haytham explain sight?”, then /help. Escape interrupts a run; Up brings back what you sent.
✻ Welcome to Librarian
/help for commands · cwd: ~/house-of-wisdom
<script lang="ts">
import Terminal from '#lib/blocks/chat/Terminal.svelte';
// In your app: connection={fetchServerSentEvents('/api/agent')}, an endpoint with tools.
import { demoAgent } from './demo-agent';
</script>
<Terminal connection={demoAgent} />Installation
npx sinaui add blocks/chatCopy src/lib/blocks/chat/, and the Button, Icon and announce.ts it uses. Then install TanStack AI with its Anthropic adapter:
pnpm add @tanstack/ai@0.63.0 @tanstack/ai-svelte@0.24.3 @tanstack/ai-anthropic@0.19.3These are early versions, so they're pinned exactly: a later one may change its API. Upgrade on purpose, one at a time.
The endpoint
Add a route that streams replies from Claude:
// src/routes/api/chat/+server.ts — streams Claude's replies to the chat block.
import { chat, toServerSentEventsResponse } from '@tanstack/ai';
import { createAnthropicChat } from '@tanstack/ai-anthropic';
import { error } from '@sveltejs/kit';
import { ANTHROPIC_API_KEY } from '$app/env/private';
export async function POST({ request }) {
const body = await request.json().catch(() => undefined);
if (!Array.isArray(body?.messages)) error(400, 'Expected { messages: [...] }');
const abortController = new AbortController();
// Stop, or leaving the page, stops the model too.
request.signal.addEventListener('abort', () => abortController.abort());
const stream = chat({
adapter: createAnthropicChat('claude-sonnet-5', ANTHROPIC_API_KEY),
messages: body.messages,
systemPrompts: ['You are a helpful librarian. Answer briefly and plainly.'],
modelOptions: { max_tokens: 1024 },
abortController
});
return toServerSentEventsResponse(stream, { abortController });
}
Your API key
Declare the key, so the app refuses to start without it rather than showing a chat that never
answers. Set ANTHROPIC_API_KEY in your environment.
// src/env.ts — the app refuses to start without the key: a loud failure beats a chat that never answers.
import { defineEnvVars } from '@sveltejs/kit/env';
export const variables = defineEnvVars({
ANTHROPIC_API_KEY: { description: 'Anthropic API key, used by /api/chat' }
});
Then give the block its connection: connection={fetchServerSentEvents('/api/chat')}.
Your server's words when a reply fails
When your endpoint turns a question away (a plan limit, say) with a message written for people,
read it in fetchClient and pass it as failure, as the example above
does. Pass only copy your server wrote for people; it's shown word for word.
Agents and tools
To test an agent, start it with its greeting in initialMessages and show what it does
through tool: the snippet gets the call (its input is set once the
arguments are complete) and, when there is one, the result. onfinish tells you a
reply is complete, to refresh what the agent recorded. A stream error keeps your server's code, so onerror can pick the words for failure.
Props
| Prop | Type | Default |
|---|---|---|
connection | TanStack AI connection (required) | |
assistantName | string: what screen readers call the replies | 'Assistant' |
title | string | the assistant's name |
suggestions | string[]: questions offered when empty | |
placeholder | string | 'Ask anything…' |
failure | { message: string }: why the last reply failed, in your server's words | |
failureActions | Snippet: shown beside the failure message, such as a link | |
threadId | string: names the conversation for your server; kept across reloads with persistence | one made up per chat |
initialMessages | UIMessage[]: what the conversation opens with, such as a greeting | |
tool | Snippet<[ToolCallPart, ToolResultPart | undefined]>: shows a tool the
assistant called; without it, tool calls stay hidden | |
onfinish | (message: UIMessage) => void: each reply, once it's complete | |
onerror | (error: Error) => void: a failed reply, with your server's code, to choose failure | |
attachments | boolean: the paperclip, drop and paste | false; true in Assistant |
fill | boolean: fill the container's height, such as a side sheet, instead of a 34rem
card | false; true in Assistant |
bare | boolean: no card of its own (corners, background, shadow), inside something
that already provides the surface | false; true in Assistant |
Keyboard
| Key | Does |
|---|---|
| Enter | Send |
| Shift + Enter | A new line |
Accessibility
- The conversation is a log: each reply is read once it's complete, never word by word as it streams.
- Stop, Copy, Retry and New chat are named buttons; Send says so, and is unavailable until there's something to send.
- A failed reply is announced, in plain words, with a way to try again.
- Each reply is labeled with the assistant's name, and so is the "is writing" indicator.
- With reduced motion, messages appear without rising and the typing dots slow down.