채팅
채팅 (Chat)
Chat은 스트리밍, 추론(reasoning), 툴 호출(tool calling)을 지원하는 AI 채팅 인터페이스를 만들기 위한 컴포넌트 모음이에요. Vercel AI SDK와 자연스럽게 통합되어 스트리밍 응답, 추론, 툴 호출 등을 처리해요.
출처: Nuxt UI
본문
[!NOTE]
프로덕션에서 바로 쓸 수 있는 구현은 GitHub의
Nuxt와VueAI Chat 템플릿을 확인해 보세요.
컴포넌트 (Components)
| Component | Description |
|---|---|
| ChatMessages | Scrollable message list with auto-scroll and loading indicator. |
| ChatMessage | Individual message bubble with avatar, actions, and slots. |
| ChatPrompt | Enhanced textarea for submitting prompts. |
| ChatPromptSubmit | Submit button with automatic status handling. |
| ChatReasoning | Collapsible block for AI reasoning / thinking process. |
| ChatTool | Collapsible block for AI tool invocation status. |
| ChatShimmer | Text shimmer animation for streaming states. |
| ChatPalette | Layout wrapper for embedding chat in modals or drawers. |
설치 (Installation)
Chat 컴포넌트들은 Vercel AI SDK, 정확히는 채팅 상태와 스트리밍 응답을 관리하는 Chat 클래스와 함께 쓰도록 설계됐어요. 이 페이지의 예시들은 AI SDK v7을 대상으로 해요.
필요한 의존성을 설치해요.
Nuxt:
pnpm add ai @ai-sdk/vue @comark/nuxt
yarn add ai @ai-sdk/vue @comark/nuxt
npm install ai @ai-sdk/vue @comark/nuxt
bun add ai @ai-sdk/vue @comark/nuxt
@comark/nuxt를 modules에 추가해요.
export default defineNuxtConfig({
modules: [
'@nuxt/ui',
'@comark/nuxt'
]
})
[!NOTE]
@comark/nuxt는 AI 응답을 스트리밍 Markdown으로 렌더링하는Markdown컴포넌트를 제공해요. 토큰이 도착하면 이를 증분 렌더링해서, 기존 Markdown 렌더러가 일으키는 깜빡임(flicker)과 재파싱을 피할 수 있어요. 또한 Nuxt UI의 prose 컴포넌트를 자동으로 활성화해서 콘텐츠가 테마에 맞게 스타일링되도록 해요.
Vue:
pnpm add ai @ai-sdk/vue @comark/vue
yarn add ai @ai-sdk/vue @comark/vue
npm install ai @ai-sdk/vue @comark/vue
bun add ai @ai-sdk/vue @comark/vue
[!NOTE]
@comark/vue는 AI 응답을 스트리밍 Markdown으로 렌더링하는Markdown컴포넌트를 제공해요. 토큰이 도착하면 이를 증분 렌더링해서, 기존 Markdown 렌더러가 일으키는 깜빡임과 재파싱을 피할 수 있어요. :br:brComark와 함께 Nuxt UI의 prose 컴포넌트를 쓰려면vite.config.ts에서prose옵션을 활성화해요.
import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import ui from '@nuxt/ui/vite' export default defineConfig({ plugins: [ vue(), ui({ prose: true }) ] })
서버 설정 (Server Setup)
streamText를 사용해 채팅 요청을 처리하는 서버 API 엔드포인트를 만들어요. Vercel AI Gateway를 사용하면 중앙 집중식 엔드포인트로 AI 모델에 접근할 수 있어요.
import { streamText, convertToModelMessages, toUIMessageStream, createUIMessageStreamResponse } from 'ai'
export default defineEventHandler(async (event) => {
const { messages } = await readBody(event)
const result = streamText({
model: 'anthropic/claude-sonnet-5.5',
maxOutputTokens: 10000,
instructions: 'You are a helpful assistant.',
messages: await convertToModelMessages(messages)
})
const stream = toUIMessageStream({ stream: result.stream })
return createUIMessageStreamResponse({ stream })
})
추론 (Reasoning)
추론을 활성화하려면 프로바이더에 맞게 providerOptions를 구성해요 (Anthropic, Google, OpenAI).
import { streamText, convertToModelMessages, toUIMessageStream, createUIMessageStreamResponse } from 'ai'
export default defineEventHandler(async (event) => {
const { messages } = await readBody(event)
const result = streamText({
model: 'anthropic/claude-sonnet-5.5',
maxOutputTokens: 10000,
instructions: 'You are a helpful assistant.',
messages: await convertToModelMessages(messages),
providerOptions: {
anthropic: {
thinking: {
type: 'adaptive'
},
effort: 'low'
},
google: {
thinkingConfig: {
includeThoughts: true,
thinkingLevel: 'low'
}
},
openai: {
reasoningEffort: 'low',
reasoningSummary: 'detailed'
}
}
})
const stream = toUIMessageStream({ stream: result.stream })
return createUIMessageStreamResponse({ stream })
})
웹 검색 (Web Search)
일부 프로바이더는 내장 웹 검색 툴을 제공해요: Anthropic, Google, OpenAI.
import { streamText, convertToModelMessages, toUIMessageStream, createUIMessageStreamResponse } from 'ai'
import { anthropic } from '@ai-sdk/anthropic'
export default defineEventHandler(async (event) => {
const { messages } = await readBody(event)
const result = streamText({
model: 'anthropic/claude-sonnet-5.5',
instructions: 'You are a helpful assistant.',
messages: await convertToModelMessages(messages),
tools: {
web_search: anthropic.tools.webSearch_20260209({})
}
})
const stream = toUIMessageStream({ stream: result.stream })
return createUIMessageStreamResponse({ stream })
})
import { streamText, convertToModelMessages, toUIMessageStream, createUIMessageStreamResponse } from 'ai'
import { google } from '@ai-sdk/google'
export default defineEventHandler(async (event) => {
const { messages } = await readBody(event)
const result = streamText({
model: 'google/gemini-3-flash',
instructions: 'You are a helpful assistant.',
messages: await convertToModelMessages(messages),
tools: {
google_search: google.tools.googleSearch({})
}
})
const stream = toUIMessageStream({ stream: result.stream })
return createUIMessageStreamResponse({ stream })
})
import { streamText, convertToModelMessages, toUIMessageStream, createUIMessageStreamResponse } from 'ai'
import { openai } from '@ai-sdk/openai'
export default defineEventHandler(async (event) => {
const { messages } = await readBody(event)
const result = streamText({
model: 'openai/gpt-5-nano',
instructions: 'You are a helpful assistant.',
messages: await convertToModelMessages(messages),
tools: {
web_search: openai.tools.webSearch({})
}
})
const stream = toUIMessageStream({ stream: result.stream })
return createUIMessageStreamResponse({ stream })
})
MCP 클라이언트 (MCP Client)
@ai-sdk/mcp의 Model Context Protocol (MCP)를 사용해 챗봇에 고급 툴 호출 기능을 더할 수 있어요. MCP를 사용하면 AI가 문서 검색이나 커스텀 작업 실행 같은 동적 작업을 수행해 더 관련성 높고 정확한 응답을 제공할 수 있어요.
먼저 MCP 패키지를 설치해요.
npm install @ai-sdk/mcp
pnpm add @ai-sdk/mcp
yarn add @ai-sdk/mcp
그런 다음 서버 엔드포인트가 MCP 툴을 사용하도록 구성해요.
import { streamText, convertToModelMessages, isStepCount, toUIMessageStream, createUIMessageStreamResponse } from 'ai'
import { createMCPClient } from '@ai-sdk/mcp'
export default defineEventHandler(async (event) => {
const { messages } = await readBody(event)
const httpClient = await createMCPClient({
transport: { type: 'http', url: 'https://your-app.com/mcp' }
})
try {
const tools = await httpClient.tools()
const result = streamText({
model: 'anthropic/claude-sonnet-5.5',
maxOutputTokens: 10000,
instructions: 'You are a helpful assistant. Use your tools to search for relevant information before answering questions.',
messages: await convertToModelMessages(messages),
stopWhen: isStepCount(6),
tools,
onEnd: async () => {
await httpClient.close()
},
onError: async (error) => {
console.error(error)
await httpClient.close()
}
})
const stream = toUIMessageStream({ stream: result.stream })
return createUIMessageStreamResponse({ stream })
} catch (error) {
// Close the MCP client if setup fails before streaming starts
await httpClient.close()
throw error
}
})
툴 승인 (Tool Approval)
toolApproval 옵션으로 툴이 실행되기 전에 사용자 확인을 요구할 수 있어요. 툴 부분은 사용자가 응답할 때까지 approval-requested 상태에서 멈춰 있어요.
import { streamText, convertToModelMessages, toUIMessageStream, createUIMessageStreamResponse, tool } from 'ai'
import { z } from 'zod'
export default defineEventHandler(async (event) => {
const { messages } = await readBody(event)
const result = streamText({
model: 'anthropic/claude-sonnet-5.5',
maxOutputTokens: 10000,
instructions: 'You are a helpful assistant.',
messages: await convertToModelMessages(messages),
tools: {
deleteFile: tool({
description: 'Delete a file from the project',
inputSchema: z.object({ path: z.string() }),
execute: async ({ path }) => ({ deleted: path })
})
},
toolApproval: {
deleteFile: 'user-approval'
}
})
const stream = toUIMessageStream({ stream: result.stream })
return createUIMessageStreamResponse({ stream })
})
클라이언트 설정 (Client Setup)
@ai-sdk/vue의 useChat 컴포저블을 사용해 채팅 상태를 관리하고 서버 엔드포인트에 연결해요.
Nuxt:
<script setup lang="ts">
import { isReasoningUIPart, isTextUIPart, isToolUIPart, getToolName, lastAssistantMessageIsCompleteWithApprovalResponses } from 'ai'
import { useChat } from '@ai-sdk/vue'
import { isPartStreaming, isToolStreaming } from '@nuxt/ui/utils/ai'
import shiki from '@comark/nuxt/plugins/shiki'
const plugins = [shiki()]
const input = ref('')
const { messages, status, error, sendMessage, regenerate, stop, addToolApprovalResponse } = useChat({
sendAutomaticallyWhen: lastAssistantMessageIsCompleteWithApprovalResponses,
onError(error) {
console.error(error)
}
})
function onSubmit() {
sendMessage({ text: input.value })
input.value = ''
}
</script>
<template>
<UChatMessages
:messages="messages"
:status="status"
>
<template #content="{ message }">
<template
v-for="(part, index) in message.parts"
:key="`${message.id}-${part.type}-${index}`"
>
<UChatReasoning
v-if="isReasoningUIPart(part)"
:text="part.text"
:streaming="isPartStreaming(part)"
>
<Markdown
:value="part.text"
:streaming="isPartStreaming(part)"
:plugins="plugins"
class="*:first:mt-0 *:last:mb-0"
/>
</UChatReasoning>
<UChatTool
v-else-if="isToolUIPart(part)"
:text="getToolName(part)"
:streaming="isToolStreaming(part)"
:actions="part.state === 'approval-requested' ? [
{ label: 'Approve', onClick: () => addToolApprovalResponse({ id: part.approval.id, approved: true }) },
{ label: 'Deny', color: 'neutral', variant: 'ghost', onClick: () => addToolApprovalResponse({ id: part.approval.id, approved: false }) }
] : undefined"
/>
<template v-else-if="isTextUIPart(part)">
<Markdown
v-if="message.role === 'assistant'"
:value="part.text"
:streaming="isPartStreaming(part)"
:plugins="plugins"
class="*:first:mt-0 *:last:mb-0"
/>
<p v-else-if="message.role === 'user'" class="whitespace-pre-wrap">
{{ part.text }}
</p>
</template>
</template>
</template>
</UChatMessages>
<UChatPrompt
v-model="input"
:error="error"
@submit="onSubmit"
>
<UChatPromptSubmit
:status="status"
@stop="stop()"
@reload="regenerate()"
/>
</UChatPrompt>
</template>
Vue:
<script setup lang="ts">
import { ref } from 'vue'
import { isReasoningUIPart, isTextUIPart, isToolUIPart, getToolName, lastAssistantMessageIsCompleteWithApprovalResponses } from 'ai'
import { useChat } from '@ai-sdk/vue'
import { isPartStreaming, isToolStreaming } from '@nuxt/ui/utils/ai'
import { Markdown } from '@comark/vue'
import shiki from '@comark/vue/plugins/shiki'
const plugins = [shiki()]
const input = ref('')
const { messages, status, error, sendMessage, regenerate, stop, addToolApprovalResponse } = useChat({
sendAutomaticallyWhen: lastAssistantMessageIsCompleteWithApprovalResponses,
onError(error) {
console.error(error)
}
})
function onSubmit() {
sendMessage({ text: input.value })
input.value = ''
}
</script>
<template>
<UChatMessages
:messages="messages"
:status="status"
>
<template #content="{ message }">
<template
v-for="(part, index) in message.parts"
:key="`${message.id}-${part.type}-${index}`"
>
<UChatReasoning
v-if="isReasoningUIPart(part)"
:text="part.text"
:streaming="isPartStreaming(part)"
>
<Markdown
:value="part.text"
:streaming="isPartStreaming(part)"
:plugins="plugins"
class="*:first:mt-0 *:last:mb-0"
/>
</UChatReasoning>
<UChatTool
v-else-if="isToolUIPart(part)"
:text="getToolName(part)"
:streaming="isToolStreaming(part)"
:actions="part.state === 'approval-requested' ? [
{ label: 'Approve', onClick: () => addToolApprovalResponse({ id: part.approval.id, approved: true }) },
{ label: 'Deny', color: 'neutral', variant: 'ghost', onClick: () => addToolApprovalResponse({ id: part.approval.id, approved: false }) }
] : undefined"
/>
<template v-else-if="isTextUIPart(part)">
<Markdown
v-if="message.role === 'assistant'"
:value="part.text"
:streaming="isPartStreaming(part)"
:plugins="plugins"
class="*:first:mt-0 *:last:mb-0"
/>
<p v-else-if="message.role === 'user'" class="whitespace-pre-wrap">
{{ part.text }}
</p>
</template>
</template>
</template>
</UChatMessages>
<UChatPrompt
v-model="input"
:error="error"
@submit="onSubmit"
>
<UChatPromptSubmit
:status="status"
@stop="stop()"
@reload="regenerate()"
/>
</UChatPrompt>
</template>
[!TIP]
재사용 가능한 Comark 설정(플러그인, 클래스 등)을 위해서는 매번 props를 인라인으로 전달하는 대신
defineMarkdownComponent를 사용해 커스텀 컴포넌트를 만드는 게 좋아요.
import shiki from '@comark/nuxt/plugins/shiki' export default defineMarkdownComponent({ name: 'ChatMarkdown', plugins: [shiki()], class: '*:first:mt-0 *:last:mb-0' })
import { defineMarkdownComponent } from '@comark/vue' import shiki from '@comark/vue/plugins/shiki' export default defineMarkdownComponent({ name: 'ChatMarkdown', plugins: [shiki()], class: '*:first:mt-0 *:last:mb-0' })
[!NOTE]
shiki플러그인을 사용할 때 다크 모드를 지원하려면 스타일시트에 다음 CSS를 추가해요.
html.dark .shiki span { color: var(--shiki-dark) !important; background-color: var(--shiki-dark-bg) !important; font-style: var(--shiki-dark-font-style) !important; font-weight: var(--shiki-dark-font-weight) !important; text-decoration: var(--shiki-dark-text-decoration) !important; }
[!NOTE] See: /blog/how-to-build-an-ai-chat
단계별 가이드는 Build an AI Chatbot 튜토리얼을 확인해 보세요.