SvelteKit

04 Streaming

Stream Anvia run events from a SvelteKit endpoint.

SvelteKit endpoints can return standard Response objects, so Anvia streams can be returned directly.

1. Create src/routes/api/support/stream/+server.ts

import type { RequestHandler } from "@sveltejs/kit";
import { z } from "zod";
import { supportAgent } from "$lib/server/ai/support-agent";

const SupportStreamRequest = z.object({
  message: z.string().trim().min(1, "message is required"),
});

export const POST: RequestHandler = async ({ request }) => {
  const parsed = SupportStreamRequest.safeParse(await request.json());

  if (!parsed.success) {
    return Response.json(
      { error: { code: "bad_request", message: parsed.error.issues[0]?.message } },
      { status: 400 },
    );
  }

  return new Response(supportAgent.prompt(parsed.data.message).readableStream(), {
    headers: {
      "Content-Type": "application/x-ndjson",
      "Cache-Control": "no-cache",
    },
  });
};

2. Consume The Stream

const response = await fetch("/api/support/stream", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ message: "Draft a reply." }),
});

const reader = response.body?.getReader();
const decoder = new TextDecoder();

while (reader) {
  const next = await reader.read();
  if (next.done) break;

  for (const line of decoder.decode(next.value).split("\n")) {
    if (line.trim()) console.log(JSON.parse(line));
  }
}

3. Runtime Notes

Use a Node-compatible adapter when your provider client or retrieval package depends on Node APIs. Edge adapters need separate verification for each provider and integration.

Next

Add auth, tools, and retrieval in Tools and Context. Related guides: Readable Streams and Streaming Events.