Sina UI

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.

New chat

How can I help you today?

<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.

Librarian

Answers come from a short script in this demo.

Ask the librarian

How can I help you today?

<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.

Librarian — ~/house-of-wisdom

✻ Welcome to Librarian

/help for commands · cwd: ~/house-of-wisdom

↵ send · esc interrupt · ↑ history · /help claude-sonnet-5
<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/chat

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

PropTypeDefault
connectionTanStack AI connection (required)
assistantNamestring: what screen readers call the replies'Assistant'
titlestringthe assistant's name
suggestionsstring[]: questions offered when empty
placeholderstring'Ask anything…'
failure{ message: string }: why the last reply failed, in your server's words
failureActionsSnippet: shown beside the failure message, such as a link
threadIdstring: names the conversation for your server; kept across reloads with persistenceone made up per chat
initialMessagesUIMessage[]: what the conversation opens with, such as a greeting
toolSnippet<[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
attachmentsboolean: the paperclip, drop and pastefalse; true in Assistant
fillboolean: fill the container's height, such as a side sheet, instead of a 34rem cardfalse; true in Assistant
bareboolean: no card of its own (corners, background, shadow), inside something that already provides the surfacefalse; true in Assistant

Keyboard

KeyDoes
EnterSend
Shift + EnterA 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.
Introduction
Theming
Changelog
Button
Action button
Confirm button
Copy button
Hold to confirm
Split button
Theme toggle
Calendar
Checkbox
Color picker
Combobox
Date picker
Date range picker
File drop
Form
Input
Mention input
Multi select
Number field
OTP input
Password input
Phone input
Radio cards
Radio group
Rich text editor
Search field
Segmented control
Select
Signature pad
Slider
Switch
Tag input
Upload
Wheel picker
Textarea
Time field
Toggle group
Toolbar
Alert dialog
Command palette
Context menu
Dialog
Drawer
Account menu
Dropdown
Hover card
Popover
Tooltip
Announcement bar
Alert
Empty state
Meter
Progress
Rolling number
Skeleton
Spinner
Toast
Avatar
Avatar group
Badge
Card
Carousel
Chart
Sparkline
World map
Chat
Code block
Data table
Folder
Kbd
Mind map
Resizable panels
Scroll area
Separator
Sortable
Table
Tag group
Virtual list
Audio player
Image
Image compare
Video
Visualizer
Breadcrumb
File tree
Docs navigation
Menubar
Navigation menu
Pagination
Sidebar layout
Stat tabs
Stepper
Tabs
Table of contents
Alarm clock
Clock
Dynamic island
Fluid orb
Hourglass
Stopwatch
Timer
AI chat
AI media
Auth
Board
Booking
Dashboard
Docs
File explorer
Messaging
Notifications
Settings
Studio
Team
Overview
Pricing
Agent chat
Calendar
Voice agent
Mail inbox
CMS
Blog
Marketing site
E-commerce
AI agents
SaaS landing page
SaaS app
Accordion
Dark theme
Light theme