The ModelRiver Svelte SDK leverages Svelte's native store system for ultra-fast, reactive AI updates. It provides a simple createModelRiver function that returns writable stores for the AI response and connection state.
Installation
npm install @modelriver/clientThe Svelte integration is included in the core @modelriver/client package.
Quick Start (Svelte 4 & 5)
1<script>2 import { createModelRiver } from '@modelriver/client/svelte';3 4 let prompt = '';5 6 const { 7 response, 8 error, 9 isConnected, 10 steps, 11 status, 12 connect 13 } = createModelRiver({14 baseUrl: 'wss://api.modelriver.com/socket'15 });16 17 async function generate() {18 // 1. Get Token from backend19 const res = await fetch('/api/chat', { 20 method: 'POST', 21 body: JSON.stringify({ prompt }) 22 });23 const { ws_token } = await res.json();24 25 // 2. Connect26 connect({ wsToken: ws_token });27 }28</script>29 30<div class="ai-box">31 <div class="status-indicator">32 {#each $steps as step}33 <span class="badge {step.status}">{step.name}</span>34 {/each}35 </div>36 37 <div class="display">38 {#if $status === 'loading'}39 <p>AI is assembling your request...</p>40 {/if}41 42 {#if $response}43 <div class="content">44 {$response.content}45 </div>46 {/if}47 </div>48 49 <textarea bind:value={prompt}></textarea>50 <button on:click={generate} disabled={$status === 'loading'}>51 Send to AI52 </button>53 54 {#if $error}55 <p class="error">{$error}</p>56 {/if}57</div>58 59<style>60 .badge.success { background: #4CAF50; color: white; }61 .badge.loading { animation: pulse 1s infinite; }62</style>Why Svelte for AI?
Native Stores
By returning true Svelte stores ($response, $status, etc.), the SDK eliminates the need for complex state management boilerplate. UI updates are instantaneous as the WebSocket delivers new data.
SvelteKit Support
The SDK is fully compatible with SvelteKit. Create the store in the browser (for example in onMount): it calls reconnect() when created, so a request that was pending when the page reloaded resumes on its own if the reload happens within about 5 minutes. It also reconnects by itself after network drops; $connectionState is 'reconnecting' meanwhile (SDK 1.8.0+). For longer gaps and ModelRiver restarts, pass getToken to fetch a new token from your backend. See Reconnecting.
Small Footprint
Because Svelte is a compiler, the additional bundle size for AI features is minimal, keeping your pages incredibly fast and SEO-friendly.
Streaming Tokens and Live Sessions
The store tracks the request's steps and final response. For token-by-token text (async requests sent with "stream": true, SDK 1.6.0+), listen to the client's stream_* events; to follow a whole conversation live (session memory, SDK 1.7.0+), use subscribeToSession. Both come from the core package and work alongside the adapter. See Streaming Tokens and Live Sessions for the details.
1<script lang="ts">2 import { onMount } from 'svelte';3 import { writable } from 'svelte/store';4 import { ModelRiverClient, subscribeToSession, type SessionMessage } from '@modelriver/client';5 6 export let chatId: string;7 const messages = writable<SessionMessage[]>([]);8 const streamed = writable('');9 10 // The answer as it streams in. `ticket` is your backend's /v1/ai/async response.11 const client = new ModelRiverClient({ persist: false });12 client.on('stream_delta', (_chunk, soFar) => streamed.set(soFar));13 export function follow(ticket) {14 client.connect({15 channelId: ticket.channel_id,16 wsToken: ticket.ws_token,17 websocketUrl: ticket.websocket_url,18 websocketChannel: ticket.websocket_channel,19 });20 }21 22 // The conversation, live.23 onMount(() => {24 const subscription = subscribeToSession({25 getSubscription: () => fetch(`/api/chats/${chatId}/live`, { method: 'POST' }).then((r) => r.json()),26 onMessage: (message) => messages.update((list) => [...list, message]),27 });28 return () => {29 subscription.close();30 client.disconnect();31 };32 });33</script>SEO and Performance with Svelte
- Hydration: SvelteKit's hydration ensures that your AI dashboard is interactive as soon as the JavaScript loads, while serving a meaningful initial HTML shell for search engines.
- Transition Effects: Use Svelte's built-in transitions (
fade,fly,blur) alongside the$responsestore to create smooth, professional-looking AI text streams. - Structured Data: Leverage the
$response.datastore to dynamically generate meta tags or microdata as the AI finishes its work.
Next Steps
- Integrate Workflow Steps for better UX.
- Learn how to handle Custom Callbacks.
- Read the Privacy Policy.