AbsoluteJS

Svelte AI

The createAIStream function connects Svelte components to the AI streaming WebSocket using reactive getter properties. Import from @absolutejs/ai/svelte.

#createAIStream

Call createAIStream with the WebSocket path and an optional conversation ID. It returns an object with getter properties that work with Svelte's reactivity system: access ai.messages, ai.isStreaming, and ai.error directly in your template.

HTML
<script lang="ts">
  import { createAIStream } from '@absolutejs/ai/svelte';

  const ai = createAIStream('/chat');

  const handleSend = (text: string) => {
    ai.send(text);
  };
</script>

<div>
  {#each ai.messages as msg (msg.id)}
    <div>
      <strong>{msg.role}:</strong> {msg.content}
      {#if msg.thinking}
        <details>
          <summary>Thinking</summary>
          <p>{msg.thinking}</p>
        </details>
      {/if}
    </div>
  {/each}

  {#if ai.isStreaming}
    <button onclick={() => ai.cancel()}>Stop</button>
  {/if}
  {#if ai.error}
    <p style="color: red">{ai.error}</p>
  {/if}
</div>

#Return Type

TS
// createAIStream return type (uses getter properties for reactivity)
{
  send: (content: string, attachments?: AIAttachment[]) => void;
  cancel: () => void;
  branch: (messageId: string, content: string) => void;
  destroy: () => void; // Clean up connection manually

  get messages(): AIMessage[];    // Reactive getter
  get isStreaming(): boolean;     // Reactive getter
  get error(): string | null;    // Reactive getter
}