Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 34 additions & 37 deletions docs/app/components/chat/Chat.vue
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,21 @@ function processThemeToolCalls() {
}
}

const { messages: chatMessages, status, error, sendMessage, regenerate, stop, clearError } = useAIChat<DocsChatMessage>({
const {
messages: chatMessages,
status,
error,
sendMessage,
regenerate,
stop,
clearError,
experimental_queuedMessages,
experimental_removeQueuedMessage,
experimental_sendQueuedMessageNow
} = useAIChat<DocsChatMessage>({
messages: messages.value,
// Messages sent while a response streams wait in `experimental_queuedMessages`, the AI SDK sends them one at a time
experimental_queue: true,
transport: new DefaultChatTransport<DocsChatMessage>({
api: '/api/ai',
body: () => ({ framework: framework.value })
Expand Down Expand Up @@ -116,29 +129,27 @@ watchEffect(() => {

const canClear = computed(() => messages.value.length > 0)

// Messages sent while a response streams wait here: `UChatPrompt` queues a submit
// while the chat is busy, the AI SDK would otherwise start a second request
// next to the current one. A queued question keeps the page it was asked on.
const queue = ref<ChatPromptQueueItem[]>([])

watch(() => queue.value.length, () => {
for (const item of queue.value) {
item.currentPage ??= currentPage.value
}
})

function send(text: string, page: string) {
track('AI Chat Message Sent')

// A queued question keeps the page it was asked on
sendMessage({ text, metadata: { currentPage: page } })
}

function sendNext() {
const next = queue.value.shift()
if (next) {
send(next.text.trim(), next.currentPage)
// The chat holds the queue, the prompt lists it and edits it
const queue = computed<ChatPromptQueueItem[]>({
get: () => experimental_queuedMessages.value.map(message => ({ id: message.id, text: getTextFromMessage(message) })),
set: (next) => {
for (const item of queue.value.filter(item => !next.some(({ id }) => id === item.id))) {
experimental_removeQueuedMessage(item.id)
}

// A question submitted while the chat is busy
for (const item of next.filter(({ id }) => !id)) {
send(item.text.trim(), currentPage.value)
}
}
}
})

function onSubmit() {
const text = input.value.trim()
Expand All @@ -150,34 +161,18 @@ function onSubmit() {
send(text, currentPage.value)
}

watch(status, (value) => {
if (value === 'ready') {
sendNext()
}
})

// A queued message picked to be sent now is at the front of the queue, it goes
// out once the current response stops
function onSend() {
if (status.value === 'submitted' || status.value === 'streaming') {
stop()
} else {
sendNext()
}
}

// Sync external messages (e.g. from search→chat flow) into the chat instance.
// When the last synced message is from the user, auto-regenerate the assistant response.
// _skipSync prevents loops when onFinish writes back to the shared messages ref.
watch(messages, (newMessages) => {
if (_skipSync) return

// A question asked from the search palette or "Explain this page" while a
// response streams waits in the queue, syncing would restart the chat mid-answer
// response streams goes to the queue, syncing would restart the chat mid-answer
const last = newMessages.at(-1)
if (last?.role === 'user' && (status.value === 'submitted' || status.value === 'streaming')) {
pending.value = false
queue.value.push({ text: getTextFromMessage(last), currentPage: last.metadata?.currentPage ?? currentPage.value })
send(getTextFromMessage(last), last.metadata?.currentPage ?? currentPage.value)
return
}

Expand Down Expand Up @@ -308,9 +303,11 @@ function clearMessages() {
if (status.value === 'streaming' || status.value === 'submitted') {
stop()
}
for (const message of experimental_queuedMessages.value) {
experimental_removeQueuedMessage(message.id)
}
messages.value = []
chatMessages.value = []
queue.value = []
// A failed response would otherwise keep the empty prompt disabled
clearError()
_themeApplied.clear()
Expand Down Expand Up @@ -455,7 +452,7 @@ function clearMessages() {
size="sm"
autofocus
@submit="onSubmit"
@send="onSend"
@send="item => experimental_sendQueuedMessageNow(item.id)"
>
<template #footer>
<ULink to="https://vercel.com/ai-gateway" target="_blank" class="inline-flex items-center gap-1 text-xs text-dimmed hover:text-muted">
Expand Down
116 changes: 58 additions & 58 deletions docs/content/docs/2.components/chat-prompt.md
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ name: 'chat-prompt-queue-example'
::

::tip{to="#with-queued-messages"}
Sending the queued messages is up to you, check the **With queued messages** example for a recipe with the AI SDK.
The AI SDK can hold the queue for you, check the **With queued messages** example.
::

## Examples
Expand Down Expand Up @@ -184,46 +184,48 @@ async function onSubmit() {

### With queued messages :badge{label="4.13+" class="align-text-top"}

The AI SDK doesn't queue messages: calling `sendMessage` during a response starts a second request next to the current one. With `status`, `UChatPrompt` ignores submits while the chat is `submitted` or `streaming`. Bind `v-model:queue` to keep them instead: the prompt lists the queued messages in a panel above it, where the user can send one now, edit it or remove it, and you send the next one once the chat is `ready` again.
By default, calling `sendMessage` during a response starts a second request next to the current one, and with `status`, `UChatPrompt` ignores submits while the chat is `submitted` or `streaming`. Enable the experimental `experimental_queue` option of `useChat` so the chat holds these messages and sends them one at a time, then bind its queue to `v-model:queue`: the prompt lists the queued messages in a panel above it, where the user can send one now, edit it or remove it.

::framework-only
#nuxt
```vue
<script setup lang="ts">
import type { ChatPromptQueueItem } from '@nuxt/ui'
import { useChat } from '@ai-sdk/vue'
import { getTextFromMessage } from '@nuxt/ui/utils/ai'

const input = ref('')
const queue = ref<ChatPromptQueueItem[]>([])

const { status, error, sendMessage, regenerate, stop } = useChat()
const {
status,
error,
sendMessage,
regenerate,
stop,
experimental_queuedMessages,
experimental_removeQueuedMessage,
experimental_sendQueuedMessageNow
} = useChat({ experimental_queue: true })

// The chat holds the queue, the prompt lists it and edits it
const queue = computed<ChatPromptQueueItem[]>({
get: () => experimental_queuedMessages.value.map(message => ({ id: message.id, text: getTextFromMessage(message) })),
set: (next) => {
for (const item of queue.value.filter(item => !next.some(({ id }) => id === item.id))) {
experimental_removeQueuedMessage(item.id)
}

// A message submitted while the chat is busy
for (const item of next.filter(({ id }) => !id)) {
sendMessage({ text: item.text })
}
}
})

function onSubmit() {
sendMessage({ text: input.value })
input.value = ''
}

function sendNext() {
const item = queue.value.shift()
if (item) {
sendMessage({ text: item.text })
}
}

watch(status, (value) => {
if (value === 'ready') {
sendNext()
}
})

// The message picked to be sent now is at the front of the queue
function onSend() {
if (status.value === 'submitted' || status.value === 'streaming') {
stop()
} else {
sendNext()
}
}
</script>

<template>
Expand All @@ -233,7 +235,7 @@ function onSend() {
:status="status"
:error="error"
@submit="onSubmit"
@send="onSend"
@send="item => experimental_sendQueuedMessageNow(item.id)"
>
<UChatPromptSubmit :status="status" @stop="stop()" @reload="regenerate()" />
</UChatPrompt>
Expand All @@ -243,41 +245,43 @@ function onSend() {
#vue
```vue
<script setup lang="ts">
import { ref, watch } from 'vue'
import { computed, ref } from 'vue'
import type { ChatPromptQueueItem } from '@nuxt/ui'
import { useChat } from '@ai-sdk/vue'
import { getTextFromMessage } from '@nuxt/ui/utils/ai'

const input = ref('')
const queue = ref<ChatPromptQueueItem[]>([])

const { status, error, sendMessage, regenerate, stop } = useChat()
const {
status,
error,
sendMessage,
regenerate,
stop,
experimental_queuedMessages,
experimental_removeQueuedMessage,
experimental_sendQueuedMessageNow
} = useChat({ experimental_queue: true })

// The chat holds the queue, the prompt lists it and edits it
const queue = computed<ChatPromptQueueItem[]>({
get: () => experimental_queuedMessages.value.map(message => ({ id: message.id, text: getTextFromMessage(message) })),
set: (next) => {
for (const item of queue.value.filter(item => !next.some(({ id }) => id === item.id))) {
experimental_removeQueuedMessage(item.id)
}

// A message submitted while the chat is busy
for (const item of next.filter(({ id }) => !id)) {
sendMessage({ text: item.text })
}
}
})

function onSubmit() {
sendMessage({ text: input.value })
input.value = ''
}

function sendNext() {
const item = queue.value.shift()
if (item) {
sendMessage({ text: item.text })
}
}

watch(status, (value) => {
if (value === 'ready') {
sendNext()
}
})

// The message picked to be sent now is at the front of the queue
function onSend() {
if (status.value === 'submitted' || status.value === 'streaming') {
stop()
} else {
sendNext()
}
}
</script>

<template>
Expand All @@ -287,19 +291,15 @@ function onSend() {
:status="status"
:error="error"
@submit="onSubmit"
@send="onSend"
@send="item => experimental_sendQueuedMessageNow(item.id)"
>
<UChatPromptSubmit :status="status" @stop="stop()" @reload="regenerate()" />
</UChatPrompt>
</template>
```
::

After an `error`, the prompt is disabled and the queue waits until the user reloads the failed response. Stopping the response sends the next queued message right away.

::note
With [tool approval](/docs/components/chat-tool#with-approval-flow), a response waiting for the user's answer is `ready` too. Skip `sendNext` while the last message has a part in the `approval-requested` state, a new message would leave the approval unanswered.
::
The chat waits for an answer to a [tool approval](/docs/components/chat-tool#with-approval-flow) before it sends the next message. Stopping the response or an error pauses the queue until the next message is sent, and editing a message or regenerating a response clears it.

## API

Expand Down
Loading
Loading