页面简介
Learn how to build your first agent with the AI SDK and Vue.js (Nuxt).
正文摘录
Getting StartedMenuVue.js (Nuxt)Copy 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. Setup Your Application Start by creating a new Nuxt application. This command will create a new directory named my-ai-app and set up a basic Nuxt application inside it. $ pnpm create nuxt my-ai-app Navigate to the newly created directory: $ cd my-ai-app Install dependencies Install ai and @ai-sdk/vue. The Vercel AI Gateway provider ships with the ai package. The AI SDK is designed to be a unified interface to interact with any large language model. This means that you can change model and providers with just one line of code! Learn more about available providers and building custom providers in the providers section. pnpmnpmyarnbun$ pnpm add ai @ai-sdk/vue zod Configure Vercel AI Gateway API key Create a .env file in your project root and add your Vercel AI Gateway API Key. This key is used to authenticate your application with the Vercel AI Gateway service. $ touch .env Edit the .env file: .envNUXT_AI_GATEWAY_API_KEY=xxxxxxxxx Replace xxxxxxxxx with your actual Vercel AI Gateway API key and configure the environment variable in nuxt.config.ts: nuxt.config.tsexport default defineNuxtConfig({ // rest of your nuxt config runtimeConfig: { aiGatewayApiKey: '', }, }); This guide uses Nuxt's runtime config to manage the API key. The NUXT_ prefix in the environment variable allows Nuxt to automatically load it into the runtime config. While the AI Gateway Provider also supports a default AI_GATEWAY_API_KEY environment variable, this approach provides better integration with Nuxt's configuration system. Create an API route Create an API route, server/api/chat.ts and add the following code: server/api/chat.tsimport { streamText, UIMessage, convertToModelMessages, createGateway, createUIMessageStreamResponse, toUIMessageStream, } from 'ai'; export default defineLazyEventHandler(async () => { const apiKey = useRuntimeConfig().aiGatewayApiKey; if (!apiKey) throw new Error('Missing AI Gateway API key'); const gateway = createGateway({ apiKey: apiKey, }); return defineEventHandler(async (event: any) => { const { messages }: { messages: UIMessage[] } = await readBody(event); const result = streamText({ model: gateway('anthropic/claude-sonnet-5.5'), messages: await convertToModelMessages(messages), }); return createUIMessageStreamResponse({ stream: toUIMessageStream({ stream: result.stream }), }); }); }); 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 an Event 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'); 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 hook, useChat. Update your root page (pages/index.vue) with the following code to show a list of chat messages and provide a user message input: pages/index.vue<script setup lang="ts"> import { useChat } from "@ai-sdk/vue"; import { ref } from "vue"; const input = ref(""); const { messages, sendMessage } = useChat(); const handleSubmit = (e: Event) => { e.preventDefault(); sendMessage({ text: input.value }); input.value = ""; }; </script> <template> <div> <div v-for="(m, index) in messages" :key="m.id ? m.id : index"> {{ m.role === "user" ? "User: " : "AI: " }} <div v-for="(part, index) in m.parts" :key="`${m.id}-${part.type}-${index}`" > <div v-if="part.type === 'text'">{{ part.text }}</div> </div> </div> <form @submit="handleSubmit"> <input v-model="input" placeholder="Say something..." /> </form> </div> </template> If your project has app.vue instead of pages/index.vue, delete the app.vue file and create a new pages/index.vue file with the code above. This page utilizes the useChat hook, which will, by default, use the API route you created earlier (/api/chat). The hook provides functions and state for handling user input and form submission. The useChat hook 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 (ref) 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:3000. 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 Nuxt. 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 server/api/chat.ts file to include the new weather tool: server/api/chat.tsimport { createGateway, streamText, UIMessage, convertToModelMessages, tool, createUIMessageStreamResponse, toUIMessageStream, } from 'ai'; import { z } from 'zod'; export default defineLazyEventHandler(async () => { const apiKey = useRuntimeConfig().aiGatewayApiKey; if (!apiKey) throw new Error('Missing AI Gateway API key'); const gateway = createGateway({ apiKey: apiKey, }); return defineEventHandler(async (event: any) => { const { messages }: { messages: UIMessage[] } = await readBody(event); 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 imp