v2.15.0

ChatPrompt

Улучшенный Textarea для отправки запросов в чатах с AI.

Использование

Компонент ChatPrompt отрисовывает элемент <form> и расширяет компонент Textarea, поэтому ему можно передать любое свойство: icon, placeholder, autofocus и другие.

ChatPrompt обрабатывает такие события:
  • Форма отправляется по ↵ или по нажатию на кнопку отправки. Если задать submit-on-enter значение false, форма отправляется по Ctrl + ↵ (или cmd + ↵ в macOS), а ↵ вставляет перенос строки.
  • Пока status равен submitted или streaming, форма не отправляется, поэтому ↵ во время ответа не отправит второе сообщение.
  • По Esc поле теряет фокус и возникает событие close.

Вариант

Пропс variant меняет стиль поля ввода. По умолчанию — outline.

<template>
  <B24ChatPrompt variant="tinted" />
</template>

Файлы

Директива v-model:files позволяет пользователю прикреплять файлы. Их можно вставить в поле или перетащить на промпт, и каждый файл показывается над полем как ChatAttachment с кнопкой удаления. Слот #footer получает функцию open, чтобы выбрать файлы кнопкой.

<script setup lang="ts">
import AttachIcon from '@bitrix24/b24icons-vue/outline/AttachIcon'

const input = ref('')
const files = ref<File[]>([])

function onSubmit() {
  // Отправьте `input.value` и `files.value` на свой эндпоинт.

  input.value = ''
  files.value = []
}
</script>

<template>
  <B24ChatPrompt
    v-model="input"
    v-model:files="files"
    accept="image/*,application/pdf"
    placeholder="Вставьте или перетащите файлы сюда..."
    :autofocus="false"
    class="w-full"
    @submit="onSubmit"
  >
    <template #footer="{ open }">
      <B24Button
        :icon="AttachIcon"
        color="air-tertiary-no-accent"
        size="sm"
        class="me-auto"
        aria-label="Прикрепить файлы"
        @click="open"
      />
    </template>

    <B24ChatPromptSubmit size="sm" />
  </B24ChatPrompt>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import AttachIcon from '@bitrix24/b24icons-vue/outline/AttachIcon'

const input = ref('')
const files = ref<File[]>([])

function onSubmit() {
  // Отправьте `input.value` и `files.value` на свой эндпоинт.

  input.value = ''
  files.value = []
}
</script>

<template>
  <B24ChatPrompt
    v-model="input"
    v-model:files="files"
    accept="image/*,application/pdf"
    placeholder="Вставьте или перетащите файлы сюда..."
    :autofocus="false"
    class="w-full"
    @submit="onSubmit"
  >
    <template #footer="{ open }">
      <B24Button
        :icon="AttachIcon"
        color="air-tertiary-no-accent"
        size="sm"
        class="me-auto"
        aria-label="Прикрепить файлы"
        @click="open"
      />
    </template>

    <B24ChatPromptSubmit size="sm" />
  </B24ChatPrompt>
</template>
Пропс attachment настраивает вложения, например { variant: 'thumbnail', size: 'xl' } для превью картинок; слот #files позволяет отрисовать их самостоятельно.
Пропс accept ограничивает типы файлов, а multiple со значением false оставляет один файл. Форма отправляется с файлами, даже если поле пустое. Пока файл тянут над промптом, у корня стоит data-dragging="true", его можно оформить через data-[dragging=true]:.
Утилита toFileUIParts из @bxshefby/b24ui-nuxt/utils/ai превращает файлы в data URL для AI SDK, а слот #files компонента ChatMessages выводит их в беседе.
<script setup lang="ts">
import { useChat } from '@ai-sdk/vue'
import { toFileUIParts } from '@bxshefby/b24ui-nuxt/utils/ai'

const input = ref('')
const files = ref<File[]>([])

const { messages, status, sendMessage } = useChat()

async function onSubmit() {
  const text = input.value
  const submitted = files.value

  input.value = ''
  files.value = []

  const parts = await toFileUIParts(submitted)
  sendMessage(text.trim() ? { text, files: parts } : { files: parts })
}
</script>

<template>
  <B24ChatMessages :messages="messages" :status="status">
    <template #files="{ parts }">
      <B24ChatAttachment
        v-for="(part, index) in parts"
        :key="index"
        :name="part.filename"
        :type="part.mediaType"
        :url="part.url"
      />
    </template>
  </B24ChatMessages>

  <B24ChatPrompt v-model="input" v-model:files="files" @submit="onSubmit">
    <B24ChatPromptSubmit :status="status" />
  </B24ChatPrompt>
</template>

Очередь {#queue} Soon

Директива v-model:queue ставит в очередь сообщения, отправленные, пока чат в статусе submitted или streaming, вместо того чтобы игнорировать их. Очередь показывается панелью над промптом: пользователь может отправить сообщение сразу, вернуть его в поле для правки или удалить. Событие send срабатывает, когда сообщение выбрано для немедленной отправки, после того как оно переместилось в начало очереди. Пока в поле есть сообщение для очереди, ChatPromptSubmit внутри него ставит сообщение в очередь, а не останавливает ответ.

  • Можешь ещё добавить переключатель тёмной темы?
  • И напиши для него тесты
<script setup lang="ts">
import type { ChatPromptQueueItem } from '@bxshefby/b24ui-nuxt'

const input = ref('')
const queue = ref<ChatPromptQueueItem[]>([
  { text: 'Можешь ещё добавить переключатель тёмной темы?' },
  { text: 'И напиши для него тесты' }
])
</script>

<template>
  <B24ChatPrompt
    v-model="input"
    v-model:queue="queue"
    status="streaming"
    placeholder="Отправьте сообщение, пока идёт ответ..."
    :autofocus="false"
    class="w-full"
  >
    <B24ChatPromptSubmit status="streaming" />
  </B24ChatPrompt>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import type { ChatPromptQueueItem } from '@bxshefby/b24ui-nuxt'

const input = ref('')
const queue = ref<ChatPromptQueueItem[]>([
  { text: 'Можешь ещё добавить переключатель тёмной темы?' },
  { text: 'И напиши для него тесты' }
])
</script>

<template>
  <B24ChatPrompt
    v-model="input"
    v-model:queue="queue"
    status="streaming"
    placeholder="Отправьте сообщение, пока идёт ответ..."
    :autofocus="false"
    class="w-full"
  >
    <B24ChatPromptSubmit status="streaming" />
  </B24ChatPrompt>
</template>
Отправка сообщений из очереди остаётся за вами, рецепт с AI SDK — в примере С очередью сообщений.

Примеры

Установка, настройка сервера и примеры использования — на обзорной странице Chat.

Как отправная точка

ChatPrompt можно взять за основу интерфейса чата.

pages/index.vue
<script setup lang="ts">
import { useChat } from '@ai-sdk/vue'

const input = ref('')

const { messages, status, sendMessage } = useChat()

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

  // После первого сообщения переходим на страницу чата
  if (messages.value.length === 1) {
    await navigateTo('/chat')
  }
}
</script>

<template>
  <B24DashboardPanel>
    <template #body>
      <B24Container>
        <h1>How can I help you today?</h1>
  
        <B24ChatPrompt v-model="input" :status="status" @submit="onSubmit">
          <B24ChatPromptSubmit :status="status" />
        </B24ChatPrompt>
      </B24Container>
    </template>
  </B24DashboardPanel>
</template>

Распознавание речи

Композабл useSpeechRecognition добавляет распознавание речи на основе Web Speech API.

<script setup lang="ts">
import MicrophoneOnIcon from '@bitrix24/b24icons-vue/outline/MicrophoneOnIcon'
import StopLIcon from '@bitrix24/b24icons-vue/outline/StopLIcon'

const input = ref('')

const appLocale = useLocale()

function onSubmit() {
  // Отправьте `input.value` на свой эндпоинт.

  stop()
  input.value = ''
}

const {
  isAvailable,
  isListening,
  start,
  stop
} = useSpeechRecognition({
  lang: appLocale.locale.value.locale,
  continuous: true,
  interimResults: true
}, {
  onStart: () => {
    if (input.value === '') {
      return
    }

    input.value += ' '
  },
  onResult: (result) => {
    input.value += result.text
  }
})

const startDictation = async () => {
  await start()
}

const stopDictation = async () => {
  await stop()
}
</script>

<template>
  <B24Card class="w-full">
    <template #footer>
      <B24Container class="pb-4 sm:pb-6">
        <B24ChatPrompt v-model="input" :autofocus="false" @submit="onSubmit">
          <template v-if="isAvailable">
            <B24Button
              v-if="!isListening"
              :icon="MicrophoneOnIcon"
              color="air-tertiary-no-accent"
              size="sm"
              class="shrink-0"
              @click="startDictation"
            />
            <B24Button
              v-if="isListening"
              :icon="StopLIcon"
              color="air-secondary"
              size="sm"
              class="shrink-0 rounded-lg"
              @click="stopDictation"
            />
          </template>
          <B24ChatPromptSubmit status="ready" />
        </B24ChatPrompt>
      </B24Container>
    </template>
  </B24Card>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import MicrophoneOnIcon from '@bitrix24/b24icons-vue/outline/MicrophoneOnIcon'
import StopLIcon from '@bitrix24/b24icons-vue/outline/StopLIcon'

const input = ref('')

const appLocale = useLocale()

function onSubmit() {
  // Отправьте `input.value` на свой эндпоинт.

  stop()
  input.value = ''
}

const {
  isAvailable,
  isListening,
  start,
  stop
} = useSpeechRecognition({
  lang: appLocale.locale.value.locale,
  continuous: true,
  interimResults: true
}, {
  onStart: () => {
    if (input.value === '') {
      return
    }

    input.value += ' '
  },
  onResult: (result) => {
    input.value += result.text
  }
})

const startDictation = async () => {
  await start()
}

const stopDictation = async () => {
  await stop()
}
</script>

<template>
  <B24Card class="w-full">
    <template #footer>
      <B24Container class="pb-4 sm:pb-6">
        <B24ChatPrompt v-model="input" :autofocus="false" @submit="onSubmit">
          <template v-if="isAvailable">
            <B24Button
              v-if="!isListening"
              :icon="MicrophoneOnIcon"
              color="air-tertiary-no-accent"
              size="sm"
              class="shrink-0"
              @click="startDictation"
            />
            <B24Button
              v-if="isListening"
              :icon="StopLIcon"
              color="air-secondary"
              size="sm"
              class="shrink-0 rounded-lg"
              @click="stopDictation"
            />
          </template>
          <B24ChatPromptSubmit status="ready" />
        </B24ChatPrompt>
      </B24Container>
    </template>
  </B24Card>
</template>

С очередью сообщений {#with-queued-messages} Soon

AI SDK не ставит сообщения в очередь: вызов sendMessage во время ответа запускает второй запрос рядом с текущим. С пропсом status B24ChatPrompt игнорирует отправку, пока чат в статусе submitted или streaming. Чтобы сохранить такие сообщения, привяжите v-model:queue: промпт покажет очередь панелью над собой, где пользователь может отправить сообщение сразу, изменить или удалить его, а следующее вы отправляете, когда чат снова станет ready.

<script setup lang="ts">
import { ref, watch } from 'vue'
import type { ChatPromptQueueItem } from '@bxshefby/b24ui-nuxt'
import { useChat } from '@ai-sdk/vue'

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

const { status, error, sendMessage, regenerate, stop } = useChat()

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()
  }
})

// Сообщение, выбранное для немедленной отправки, стоит в начале очереди
function onSend() {
  if (status.value === 'submitted' || status.value === 'streaming') {
    stop()
  } else {
    sendNext()
  }
}
</script>

<template>
  <B24ChatPrompt
    v-model="input"
    v-model:queue="queue"
    :status="status"
    :error="error"
    @submit="onSubmit"
    @send="onSend"
  >
    <B24ChatPromptSubmit :status="status" @stop="stop()" @reload="regenerate()" />
  </B24ChatPrompt>
</template>

После error промпт отключается, а очередь ждёт, пока пользователь не перезапустит неудавшийся ответ. Остановка ответа сразу отправляет следующее сообщение из очереди.

При подтверждении инструментов ответ, который ждёт решения пользователя, тоже имеет статус ready. Пропускайте sendNext, пока у последнего сообщения есть часть в состоянии approval-requested: новое сообщение оставит подтверждение без ответа.

API

Пропсы

Prop Default Type
as'form'any

The element or component this component should render as.

placeholdert('chatPrompt.placeholder') string

The placeholder text for the textarea.

variant'outline' "outline" | "tinted" | "filled" | "plain"
submitOnEntertrueboolean

When true, pressing Enter submits and Shift+Enter inserts a newline. When false, pressing Enter inserts a newline and Ctrl+Enter / Cmd+Enter submits.

status "error" | "submitted" | "streaming" | "ready"

The status of the chat. Submitting while it is submitted or streaming is ignored, or queued with v-model:queue.

error Error
accept'*' string

The file types accepted when pasting or dropping files, used with v-model:files.

multipletrueboolean

Allow more than one file, used with v-model:files.

attachment Pick<ChatAttachmentProps, "icon" | "variant" | "class" | "b24ui" | "size" | "orientation" | "removable" | "removeIcon">

The props of the attachments displayed above the textarea, used with v-model:files. { removable: true }

queueIconicons.chevronDownIconComponent

The icon displayed to collapse the queue, used with v-model:queue.

rows1 number
autofocustrueboolean
autofocusDelay number
autoresizetrueboolean
autoresizeDelay number
maxrows number
iconIconComponent

Display an icon on the left side.

avatar AvatarProps

Display an avatar on the left side.

loadingboolean

When true, the loading icon will be displayed.

disabledboolean
modelValue'' string
files File[]
queue ChatPromptQueueItem[]
b24ui { root?: SlotClass; header?: SlotClass; files?: SlotClass; queue?: SlotClass; queueTrigger?: SlotClass; queueTriggerIcon?: SlotClass; queueCount?: SlotClass; queueList?: SlotClass; queueItem?: SlotClass; queueItemLeading?: SlotClass; queueItemLabel?: SlotClass; queueItemActions?: SlotClass; body?: SlotClass; footer?: SlotClass; base?: SlotClass; } & { root?: SlotClass; base?: SlotClass; leading?: SlotClass; leadingIcon?: SlotClass; leadingAvatar?: SlotClass; leadingAvatarSize?: SlotClass; trailing?: SlotClass; trailingIcon?: SlotClass; tag?: SlotClass; }
Компонент поддерживает и все нативные HTML-атрибуты <textarea>.

Слоты

Slot Type
header{}
queue{ queue: ChatPromptQueueItem[]; send: (index: number) => void; edit: (index: number) => void; remove: (index: number) => void; }

Replace the queued messages rendered above the textarea when using v-model:queue.

default{ b24ui: object; }
files{ files: File[]; remove: (index: number) => void; }

Replace the attachments rendered above the textarea when using v-model:files.

footer{ open: () => void; }
body{ submit: (event?: Event | undefined) => void; close: (event?: Event | undefined) => void; placeholder: string; disabled: boolean; b24ui: object; }

Replace the internal textarea, e.g. to render an Editor with mentions.

trailing{ b24ui: { root: (props?: Record<string, any> | undefined) => string; base: (props?: Record<string, any> | undefined) => string; leading: (props?: Record<string, any> | undefined) => string; leadingIcon: (props?: Record<string, any> | undefined) => string; leadingAvatar: (props?: Record<string, any> | undefined) => string; leadingAvatarSize: (props?: Record<string, any> | undefined) => string; trailing: (props?: Record<string, any> | undefined) => string; trailingIcon: (props?: Record<string, any> | undefined) => string; tag: (props?: Record<string, any> | undefined) => string; }; }
leading{ b24ui: { root: (props?: Record<string, any> | undefined) => string; base: (props?: Record<string, any> | undefined) => string; leading: (props?: Record<string, any> | undefined) => string; leadingIcon: (props?: Record<string, any> | undefined) => string; leadingAvatar: (props?: Record<string, any> | undefined) => string; leadingAvatarSize: (props?: Record<string, any> | undefined) => string; trailing: (props?: Record<string, any> | undefined) => string; trailingIcon: (props?: Record<string, any> | undefined) => string; tag: (props?: Record<string, any> | undefined) => string; }; }

События

Event Type
close[event: Event]
submit[event: Event]
update:modelValue[value: string]
send[item: ChatPromptQueueItem]
update:files[value: File[] | undefined]
update:queue[value: ChatPromptQueueItem[] | undefined]

Доступ через ref

При обращении к компоненту через ref в шаблоне доступно:

ИмяТип
textareaRefRef<HTMLTextAreaElement | null>
open()void

Тема

https://github.com/bx-shef/b24-ui/tree/main/src/theme/chat-prompt.ts
export default {
  slots: {
    root: 'relative flex flex-col items-stretch gap-[2px] ps-[12px] pe-2 py-2 w-full rounded-lg isolate mt-(--chat-prompt-queue-height)',
    header: 'flex items-center gap-2',
    files: 'flex flex-wrap items-center gap-2 mt-0.5',
    queue: 'absolute bottom-full inset-x-2.5 -z-1 flex flex-col px-1 overflow-hidden rounded-t-(--ui-border-radius-md) border border-b-0 border-(--ui-color-divider-default) bg-(--ui-color-bg-content-secondary)/50 backdrop-blur-sm',
    queueTrigger: 'flex items-center gap-1.5 w-full p-1.5 text-(length:--ui-font-size-xs) font-(--ui-font-weight-medium) text-description hover:text-(--ui-color-design-plain-content) rounded-(--ui-border-radius-sm) focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-(--ui-color-design-outline-focused-stroke)',
    queueTriggerIcon: 'shrink-0 size-4 data-[state=open]:rotate-180 transition-transform duration-200 ease-out motion-reduce:transition-none',
    queueCount: 'tabular-nums text-(--ui-color-design-plain-na-content-secondary)',
    queueList: 'flex flex-col max-h-60 overflow-y-auto pb-1',
    queueItem: 'group/queue flex items-center gap-2 h-7 ps-2 pe-0.5 rounded-(--ui-border-radius-xs) hover:bg-(--ui-color-bg-content-secondary)',
    queueItemLeading: 'shrink-0 size-3 rounded-(--ui-border-radius-pill) ring ring-(--ui-color-divider-default)',
    queueItemLabel: 'flex-1 min-w-0 truncate text-(length:--ui-font-size-sm) text-(--ui-color-design-plain-content)',
    queueItemActions: 'flex items-center shrink-0 [@media(hover:hover)]:opacity-0 group-hover/queue:opacity-100 group-focus-within/queue:opacity-100 transition-opacity ease-out',
    body: 'py-[4px] items-start',
    footer: 'flex items-center justify-end gap-2',
    base: 'pt-[1px] pb-[0px]'
  },
  variants: {
    variant: {
      outline: {
        queue: 'bottom-[calc(100%+1px)]',
        root: 'bg-(--ui-color-design-outline-bg) ring ring-(--ui-color-design-outline-stroke) ring-1 text-(--ui-color-design-outline-content)'
      },
      tinted: {
        root: 'bg-(--ui-color-design-tinted-na-bg) ring ring-(--ui-color-design-tinted-na-stroke) ring-(length:--ui-design-tinted-na-stroke-weight) text-(--ui-color-design-tinted-na-content)'
      },
      filled: {
        root: 'bg-(--ui-color-design-filled-na-bg) ring ring-(--ui-color-design-filled-na-stroke) ring-(length:--ui-design-filled-na-stroke-weight) text-(--ui-color-design-filled-na-content)'
      },
      plain: {
        root: 'bg-(--ui-color-design-plain-bg) ring ring-(--ui-color-design-plain-stroke) ring-(length:--ui-design-plain-stroke-weight) text-(--ui-color-design-plain-content)'
      }
    }
  },
  defaultVariants: {
    variant: 'outline'
  }
}