页面简介
Learn how to build your first agent with the AI SDK and Svelte.
正文摘录
Getting StartedMenuSvelteCopy for LLMView MarkdownAsk AI about this pageThe AI SDK is a powerful TypeScript library designed to help developers build AI-powered applications. In this quickstart tutorial, you'll build a simple agent with a streaming chat user interface. Along the way, you'll learn key concepts and techniques that are fundamental to using the SDK in your own projects. If you are unfamiliar with the concepts of Prompt Engineering and HTTP Streaming, you can optionally read these documents first. Prerequisites To follow this quickstart, you'll need: Node.js 22+ and pnpm installed on your local development machine. A Vercel AI Gateway API key. If you haven't obtained your Vercel AI Gateway API key, you can do so by signing up on the Vercel website. Set Up Your Application Start by creating a new SvelteKit application. This command will create a new directory named my-ai-app and set up a basic SvelteKit application inside it. $ npx sv create my-ai-app Navigate to the newly created directory: $ cd my-ai-app Install Dependencies Install ai and @ai-sdk/svelte, the AI package and AI SDK's Svelte bindings. The AI SDK's Vercel AI Gateway provider ships with the ai package. You'll also install zod, a schema validation library used for defining tool inputs. This guide uses the Vercel AI Gateway provider so you can access hundreds of models from different providers with one API key, but you can switch to any provider or model by installing its package. Check out available AI SDK providers for more information. pnpmnpmyarnbun$ pnpm add -D ai @ai-sdk/svelte zod Configure your AI Gateway API key Create a .env.local file in your project root and add your AI Gateway API key. This key authenticates your application with the Vercel AI Gateway. $ touch .env.local Edit the .env.local file: .env.localAI_GATEWAY_API_KEY=xxxxxxxxx Replace xxxxxxxxx with your actual Vercel AI Gateway API key. The AI SDK's Vercel AI Gateway Provider will default to using the AI_GATEWAY_API_KEY environment variable. Vite does not automatically load environment variables onto process.env, so you'll need to import AI_GATEWAY_API_KEY from $env/static/private in your code (see below). Create an API route Create a SvelteKit Endpoint, src/routes/api/chat/+server.ts and add the following code: src/routes/api/chat/+server.tsimport { streamText, type UIMessage, convertToModelMessages, createGateway, createUIMessageStreamResponse, toUIMessageStream, } from 'ai'; import { AI_GATEWAY_API_KEY } from '$env/static/private'; const gateway = createGateway({ apiKey: AI_GATEWAY_API_KEY, }); export async function POST({ request }) { const { messages }: { messages: UIMessage[] } = await request.json(); const result = streamText({ model: gateway('anthropic/claude-sonnet-5.5'), messages: await convertToModelMessages(messages), }); return createUIMessageStreamResponse({ stream: toUIMessageStream({ stream: result.stream }), }); } If you see type errors with AI_GATEWAY_API_KEY or your POST function, run the dev server. Let's take a look at what is happening in this code: Create a gateway provider instance with the createGateway function from the ai package. Define a POST request handler and extract messages from the body of the request. The messages variable contains a history of the conversation between you and the chatbot and provides the chatbot with the necessary context to make the next generation. The messages are of UIMessage type, which are designed for use in application UI - they contain the entire message history and associated metadata like timestamps. Call streamText, which is imported from the ai package. This function accepts a configuration object that contains a model provider (defined in step 1) and messages (defined in step 2). You can pass additional settings to further customize the model's behavior. The messages key expects a ModelMessage[] array. This type is different from UIMessage in that it does not include metadata, such as timestamps or sender information. To convert between these types, we use the convertToModelMessages function, which strips the UI-specific metadata and transforms the UIMessage[] array into the ModelMessage[] format that the model expects. The streamText function returns a StreamTextResult. Pass its stream to toUIMessageStream and return it with createUIMessageStreamResponse to create a streamed response object. Return the result to the client to stream the response. Choosing a Provider The AI SDK supports dozens of model providers through first-party, OpenAI-compatible, and community packages. This quickstart uses the Vercel AI Gateway provider, which is the default global provider. This means you can access models using a simple string in the model configuration: GatewayProviderCustomClaude Sonnet 5.5model: "anthropic/claude-sonnet-5.5"; You can also explicitly import and use the gateway provider in two other equivalent ways: // Option 1: Import from 'ai' package (included by default) import { gateway } from 'ai'; model: gateway('anthropic/claude-sonnet-5.5'); // Option 2: Install and import from '@ai-sdk/gateway' package import { gateway } from '@ai-sdk/gateway'; model: gateway('anthropic/claude-sonnet-5.5'); Using other providers To use a different provider, install its package and create a provider instance. For example, to use OpenAI directly: pnpmnpmyarnbun$ pnpm add @ai-sdk/openai import { openai } from '@ai-sdk/openai'; model: openai('gpt-6-astra'); Updating the global provider You can change the default global provider so string model references use your preferred provider everywhere in your application. Learn more about provider management. Pick the approach that best matches how you want to manage providers across your application. Wire up the UI Now that you have an API route that can query an LLM, it's time to set up your frontend. The AI SDK's UI package abstracts the complexity of a chat interface into one class, Chat. Its properties and API are largely the same as React's useChat. Update your root page (src/routes/+page.svelte) with the following code to show a list of chat messages and provide a user message input: src/routes/+page.svelte<script lang="ts"> import { Chat } from '@ai-sdk/svelte'; let input = ''; const chat = new Chat({}); function handleSubmit(event: SubmitEvent) { event.preventDefault(); chat.sendMessage({ text: input }); input = ''; } </script> <main> <ul> {#each chat.messages as message, messageIndex (messageIndex)} <li> <div>{message.role}</div> <div> {#each message.parts as part, partIndex (partIndex)} {#if part.type === 'text'} <div>{part.text}</div> {/if} {/each} </div> </li> {/each} </ul> <form onsubmit={handleSubmit}> <input bind:value={input} /> <button type="submit">Send</button> </form> </main> This page utilizes the Chat class, which will, by default, use the POST route handler you created earlier. The class provides functions and state for handling user input and form submission. The Chat class provides multiple utility functions and state variables: messages - the current chat messages (an array of objects with id, role, and parts properties). sendMessage - a function to send a message to the chat API. The component uses local state to manage the input field value, and handles form submission by calling sendMessage with the input text and then clearing the input field. The LLM's response is accessed through the message parts array. Each message contains an ordered array of parts that represents everything the model generated in its response. These parts can include plain text, reasoning tokens, and more that you will see later. The parts array preserves the sequence of the model's outputs, allowing you to display or process each component in the order it was generated. Running Your Application With that, you have built everything you need for your chatbot! To start your application, use the command: $ pnpm run dev Head to your browser and open http://localhost:5173. You should see an input field. Test it out by entering a message and see the AI chatbot respond in real-time! The AI SDK makes it fast and easy to build AI chat interfaces with Svelte. Enhance Your Chatbot with Tools While large language models (LLMs) have incredible generation capabilities, they struggle with discrete tasks (e.g. mathematics) and interacting with the outside world (e.g. getting the weather). This is where tools come in. Tools are actions that an LLM can invoke. The results of these actions can be reported back to the LLM to be considered in the next response. For example, if a user asks about the current weather, without tools, the model would only be able to provide general information based on its training data. But with a weather tool, it can fetch and provide up-to-date, location-specific weather information. Let's enhance your chatbot by adding a simple weather tool. Update Your API Route Modify your src/routes/api/chat/+server.ts file to include the new weather tool: src/routes/api/chat/+server.tsimport { createGateway, streamText, type UIMessage, convertToModelMessages, tool, isStepCount, createUIMessageStreamResponse, toUIMessageStream, } from 'ai'; import { z } from 'zod'; import { AI_GATEWAY_API_KEY } from '$env/static/private'; const gateway = createGateway({ apiKey: AI_GATEWAY_API_KEY, }); export async function POST({ request }) { const { messages }: { messages: UIMessage[] } = await request.json(); const result = streamText({ model: gateway('anthropic/claude-sonnet-5.5'), messages: await convertToModelMessages(messages), tools: { weather: tool({ description: 'Get the weather in a location (fahrenheit)', inputSchema: z.object({ location: z.string().describe('The location to get the weather for'), }), execute: async ({ location }) => { const temperature = Math.round(Math.random() * (90 - 32) + 32); return { location, temperature, }; }, }), }, }); return createUIMessageStreamResponse({ stream: toUIMessageStream({ stream: result.stream }), }); } In this updated code: You import the