SvelteKit
03 Route Handler
Return a non-streaming Anvia response from a SvelteKit endpoint.
SvelteKit endpoint modules export HTTP method functions. Use them to keep validation and agent calls on the server.
1. Create src/routes/api/support/+server.ts
import { json, type RequestHandler } from "@sveltejs/kit";
import { z } from "zod";
import { supportAgent } from "$lib/server/ai/support-agent";
const SupportRequest = z.object({
message: z.string().trim().min(1, "message is required"),
});
export const POST: RequestHandler = async ({ request }) => {
const parsed = SupportRequest.safeParse(await request.json());
if (!parsed.success) {
return json(
{ error: { code: "bad_request", message: parsed.error.issues[0]?.message } },
{ status: 400 },
);
}
const response = await supportAgent.prompt(parsed.data.message).send();
return json({
output: response.output,
usage: response.usage,
messages: response.messages,
});
};2. Call The Endpoint
const response = await fetch("/api/support", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ message: "How long does a reset link last?" }),
});
const data = await response.json();
console.log(data.output);3. Keep Errors Application-Owned
Provider and tool errors should be logged server-side and returned as a stable app error shape.
try {
const response = await supportAgent.prompt(parsed.data.message).send();
return json({ output: response.output });
} catch (error) {
console.error(error);
return json(
{ error: { code: "agent_failed", message: "The agent run failed." } },
{ status: 500 },
);
}Next
Return live run events in Streaming. For response fields, read Prompt Responses.
