Generate Text
Learn how to generate text using AI models with simple prompts in SvelteKit. This guide shows you how to create a complete text generation flow using the Vercel AI SDK.
Overview
The generateText function from the Vercel AI SDK allows
you to generate text based on a prompt. This is useful for various scenarios such as answering
questions, summarizing content, generating creative text, or building conversational interfaces.
In this recipe, we'll build a simple text generation feature in SvelteKit with a client-side component that makes requests to a server endpoint, which then uses the AI SDK to generate responses.
Demo
Client Component
Now let's create a Svelte component that handles user interaction. This component uses
Svelte 5's $state rune for reactivity, includes a loading
state with skeleton animation, and makes a POST request to our API endpoint.
AI Config Setup
Before we start, let's set up the AI configuration. Create a centralized config file to manage your AI provider and model settings. This makes it easy to switch models or providers across your application.
Note: Make sure to add your OPENROUTER_API_KEY to your .env file. You can get a free API key
from OpenRouter.
Server Endpoint
Now let's create the server-side route handler that processes the request and generates text using the AI SDK. This endpoint receives the prompt from the client and returns the generated text.