AI SDK Integration

Create Chat API Route

Learn how to create a chat API route to interact with the Vercel AI SDK.

Create an API route, server/api/chat.ts and add the following code:

server/api/chat.ts
import { createOpenAI } from '@ai-sdk/openai'

export default defineLazyEventHandler(async () => {
  const apiKey = useRuntimeConfig().openaiApiKey
  if (!apiKey)
    throw new Error('Missing OpenAI API key')
  const openai = createOpenAI({
    apiKey,
  })

  return defineEventHandler(async (event: any) => {
    const { messages } = await readBody(event)

    const result = streamText({
      model: openai('gpt-4o'),
      messages,
    })

    return result.toDataStreamResponse()
  })
})

Create a chat component

Create a chat component, components/AiChat.vue and add the following code:

components/AiChat.vue
<script setup>
const { messages, input, handleSubmit } = useChat({
  api: '/api/chat'
})
</script>