页面简介
Learn how to build your first agent with the AI SDK and Expo.
正文摘录
Getting StartedMenuExpoCopy for LLMView MarkdownAsk AI about this pageIn this quickstart tutorial, you'll build a simple agent with a streaming chat user interface with Expo. 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. Create Your Application Start by creating a new Expo application. This command will create a new directory named my-ai-app and set up a basic Expo application inside it. $ pnpm create expo-app@latest my-ai-app Navigate to the newly created directory: $ cd my-ai-app This guide requires Expo 52 or higher. Install dependencies Install ai and @ai-sdk/react, the AI package and AI SDK's React hooks. 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 ai @ai-sdk/react 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. Create an API Route Create a route handler, app/api/chat+api.ts and add the following code: GatewayProviderCustomClaude Sonnet 5.5app/api/chat+api.tsimport { streamText, UIMessage, convertToModelMessages, createUIMessageStreamResponse, toUIMessageStream, } from 'ai'; export async function POST(req: Request) { const { messages }: { messages: UIMessage[] } = await req.json(); const result = streamText({ model: "anthropic/claude-sonnet-5.5", messages: await convertToModelMessages(messages), }); return createUIMessageStreamResponse({ stream: toUIMessageStream({ stream: result.stream }), headers: { 'Content-Type': 'application/octet-stream', 'Content-Encoding': 'none', }, }); } Let's take a look at what is happening in this code: Define an asynchronous 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. Call streamText, which is imported from the ai package. This function accepts a configuration object that contains a model ID string (resolved through AI Gateway) and messages (defined in step 1). You can pass additional settings to further customize the model's behavior. The streamText function returns a StreamTextResult. Pass its stream to toUIMessageStream and return it with createUIMessageStreamResponse to create a streamed response object. Finally, return the result to the client to stream the response. This API route creates a POST request endpoint at /api/chat. If a deployed Expo API Route buffers the response despite the streaming headers above, test the same handler without the deployment adapter to isolate the cause. As a workaround, host the chat endpoint in a separate Vercel Function and set EXPO_PUBLIC_API_BASE_URL to that function's base URL. 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 hook, useChat. Update your root page (app/(tabs)/index.tsx) with the following code to show a list of chat messages and provide a user message input: app/(tabs)/index.tsximport { generateAPIUrl } from '@/utils'; import { useChat } from '@ai-sdk/react'; import { DefaultChatTransport } from 'ai'; import { fetch as expoFetch } from 'expo/fetch'; import { useState } from 'react'; import { View, TextInput, ScrollView, Text, SafeAreaView } from 'react-native'; export default function App() { const [input, setInput] = useState(''); const { messages, error, sendMessage } = useChat({ transport: new DefaultChatTransport({ fetch: expoFetch as unknown as typeof globalThis.fetch, api: generateAPIUrl('/api/chat'), }), onError: error => console.error(error, 'ERROR'), }); if (error) return <Text>{error.message}</Text>; return ( <SafeAreaView style={{ height: '100%' }}> <View style={{ height: '95%', display: 'flex', flexDirection: 'column', paddingHorizontal: 8, }} > <ScrollView style={{ flex: 1 }}> {messages.map(m => ( <View key={m.id} style={{ marginVertical: 8 }}> <View> <Text style={{ fontWeight: 700 }}>{m.role}</Text> {m.parts.map((part, i) => { switch (part.type) { case 'text': return <Text key={`${m.id}-${i}`}>{part.text}</Text>; } })} </View> </View> ))} </ScrollView> <View style={{ marginTop: 8 }}> <TextInput style={{ backgroundColor: 'white', padding: 8 }} placeholder="Say something..." value={input} onChange={e => setInput(e.nativeEvent.text)} onSubmitEditing={e => { e.preventDefault(); sendMessage({ text: input }); setInput(''); }} autoFocus={true} /> </View> </View> </SafeAreaView> ); } This page utilizes the useChat hook, which will, by default, use the POST 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 (useState) 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. You use the expo/fetch function instead of the native node fetch to enable streaming of chat responses. This requires Expo 52 or higher. Create the API URL Generator Because you're using expo/fetch for streaming responses instead of the native fetch function, you'll need an API URL generator to ensure you are using the correct base url and format depending on the client environment (e.g. web or mobile). Create a new file called utils.ts in the root of your project and add the following code: utils.tsimport Constants from 'expo-constants'; export const generateAPIUrl = (relativePath: string) => { const origin = Constants.experienceUrl.replace('exp://', 'http://'); const path = relativePath.startsWith('/') ? relativePath : `/${relativePath}`; if (process.env.NODE_ENV === 'development') { return origin.concat(path); } if (!process.env.EXPO_PUBLIC_API_BASE_URL) { throw new Error( 'EXPO_PUBLIC_API_BASE_URL environment variable is not defined', ); } return process.env.EXPO_PUBLIC_API_BASE_URL.concat(path); }; This utility function handles URL generation for both development and production environments, ensuring your API calls work correctly across different devices and configurations. Before deploying to production, you must set the EXPO_PUBLIC_API_BASE_URL environment variable in your production environment. This variable should point to the base URL of your API server. Running Your Application With that, you have built everything you need for your chatbot! To start your application, use the command: $ pnpm expo Head to your browser and open http://localhost:8081. 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 Expo. If you experience "Property structuredClone doesn't exist" errors on mobile, add the polyfills described below. Enhance Your Chatbot with Tools While large language models (LLMs) have incredible generation capabilities, they struggle with discrete tasks (e.g. mathematics) and interacting