---
title: "ChatPrompt"
description: "Улучшенный Textarea для отправки запросов в чатах с AI."
canonical_url: "https://b24-ui.bx-shef.by/docs/components/chat-prompt"
---
# ChatPrompt

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

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

Компонент ChatPrompt отрисовывает элемент `<form>` и расширяет компонент [Textarea](https://b24-ui.bx-shef.by/raw/docs/components/textarea.md), поэтому ему можно передать любое свойство: `icon`, `placeholder`, `autofocus` и другие.

```vue
<template>
  <b24-chat-prompt variant=outline />
  <b24-chat-prompt-submit color=air-primary />
  <template v-slot:footer=>
  <b24-select :items=[{"label":"BitrixGPT 5","value":"bitrix-gpt-5"},{"label":"Claude Opus 5.5","value":"claude-opus-5.5"},{"label":"Gemini 3 Pro","value":"gemini-3-pro"},{"label":"GPT-5","value":"gpt-5"},{"label":"DeepSeek","value":"deepseek"}] modelValue=deepseek placeholder=Выберите модель size=sm />
  <p>
  :::</p></template>
</template>
```

> [!NOTE]
> ChatPrompt обрабатывает такие события:
> - Форма отправляется по <kbd value="enter">
> </kbd>
> или по нажатию на кнопку отправки. Если задать `submit-on-enter` значение `false`, форма отправляется по <kbd value="ctrl">
> </kbd>
> + <kbd value="enter">
> </kbd>
> (или <kbd value="cmd">
> </kbd>
> + <kbd value="enter">
> </kbd>
> в macOS), а <kbd value="enter">
> </kbd>
> вставляет перенос строки.
> - Пока `status` равен `submitted` или `streaming`, форма не отправляется, поэтому <kbd value="enter">
> </kbd>
> во время ответа не отправит второе сообщение.
> - По <kbd value="escape">
> </kbd>
> поле теряет фокус и возникает событие `close`.

### Вариант

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

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

### Файлы

Директива `v-model:files` позволяет пользователю прикреплять файлы. Их можно вставить в поле или перетащить на промпт, и каждый файл показывается над полем как [ChatAttachment](https://b24-ui.bx-shef.by/raw/docs/components/chat-attachment.md) с кнопкой удаления. Слот `#footer` получает функцию `open`, чтобы выбрать файлы кнопкой.

```vue [ChatPromptFilesExample.vue]
<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>
```

> [!TIP]
> Пропс `attachment` настраивает вложения, например `{ variant: 'thumbnail', size: 'xl' }` для превью картинок; слот `#files` позволяет отрисовать их самостоятельно.

> [!NOTE]
> Пропс `accept` ограничивает типы файлов, а `multiple` со значением `false` оставляет один файл. Форма отправляется с файлами, даже если поле пустое. Пока файл тянут над промптом, у корня стоит `data-dragging="true"`, его можно оформить через `data-[dragging=true]:`.

> [!TIP]
> Утилита `toFileUIParts` из `@bxshefby/b24ui-nuxt/utils/ai` превращает файлы в data URL для AI SDK, а слот `#files` компонента [ChatMessages](https://b24-ui.bx-shef.by/raw/docs/components/chat-messages.md) выводит их в беседе.
> ```vue
> <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](https://b24-ui.bx-shef.by/raw/docs/components/chat-prompt-submit.md) внутри него ставит сообщение в очередь, а не останавливает ответ.

```vue [ChatPromptQueueExample.vue]
<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>
```

> [!TIP]
> See: #with-queued-messages
> Отправка сообщений из очереди остаётся за вами, рецепт с AI SDK — в примере **С очередью сообщений**.

## Примеры

> [!TIP]
> See: /docs/components/chat/
> Установка, настройка сервера и примеры использования — на обзорной странице **Chat**.

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

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

```vue [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](https://b24-ui.bx-shef.by/raw/docs/composables/use-speech-recognition.md) добавляет распознавание речи на основе [Web Speech API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Speech_API).

```vue [ChatPromptSpeechRecognitionExample.vue]
<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>
```

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

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

```vue
<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` промпт отключается, а очередь ждёт, пока пользователь не перезапустит неудавшийся ответ. Остановка ответа сразу отправляет следующее сообщение из очереди.

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

## API

### Пропсы

```ts
/**
 * Props for the ChatPrompt component
 */
interface ChatPromptProps {
  /**
   * The element or component this component should render as.
   * @default 'form'
   */
  as?: any;
  /**
   * The placeholder text for the textarea.
   * @default t('chatPrompt.placeholder')
   */
  placeholder?: string | undefined;
  /**
   * @default 'outline'
   */
  variant?: "outline" | "tinted" | "filled" | "plain" | undefined;
  /**
   * When `true`, pressing `Enter` submits and `Shift+Enter` inserts a newline.
   * When `false`, pressing `Enter` inserts a newline and `Ctrl+Enter` / `Cmd+Enter` submits.
   * @default true
   */
  submitOnEnter?: boolean | undefined;
  /**
   * The status of the chat. Submitting while it is `submitted` or `streaming` is ignored, or queued with `v-model:queue`.
   */
  status?: "error" | "submitted" | "streaming" | "ready" | undefined;
  error?: Error | undefined;
  /**
   * The file types accepted when pasting or dropping files, used with `v-model:files`.
   * @default '*'
   */
  accept?: string | undefined;
  /**
   * Allow more than one file, used with `v-model:files`.
   * @default true
   */
  multiple?: boolean | undefined;
  /**
   * The props of the attachments displayed above the textarea, used with `v-model:files`.
   * `{ removable: true }`
   */
  attachment?: Pick<ChatAttachmentProps, "icon" | "variant" | "class" | "b24ui" | "size" | "orientation" | "removable" | "removeIcon"> | undefined;
  /**
   * The icon displayed to collapse the queue, used with `v-model:queue`.
   * @default icons.chevronDown
   */
  queueIcon?: (props: HTMLAttributes & VNodeProps & {}, ctx: Omit<{ attrs: Attrs; slots: Readonly<InternalSlots>; emit: (event: string, ...args: any[]) => void; expose: <Exposed extends Record<string, any> = Record<...>>(exposed?: Exposed | undefined) => void; }, "expose">): any | undefined;
  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; } | undefined;
  /**
   * @default 1
   */
  rows?: number | undefined;
  /**
   * @default true
   */
  autofocus?: boolean | undefined;
  autofocusDelay?: number | undefined;
  /**
   * @default true
   */
  autoresize?: boolean | undefined;
  autoresizeDelay?: number | undefined;
  maxrows?: number | undefined;
  /**
   * Display an icon on the left side.
   */
  icon?: (props: HTMLAttributes & VNodeProps & {}, ctx: Omit<{ attrs: Attrs; slots: Readonly<InternalSlots>; emit: (event: string, ...args: any[]) => void; expose: <Exposed extends Record<string, any> = Record<...>>(exposed?: Exposed | undefined) => void; }, "expose">): any | undefined;
  /**
   * Display an avatar on the left side.
   */
  avatar?: AvatarProps | undefined;
  /**
   * When `true`, the loading icon will be displayed.
   */
  loading?: boolean | undefined;
  disabled?: boolean | undefined;
  /**
   * @default ''
   */
  modelValue?: string | undefined;
  files?: File[] | undefined;
  queue?: ChatPromptQueueItem[] | undefined;
}
```

> [!NOTE]
> See: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea#attributes
> Компонент поддерживает и все нативные HTML-атрибуты `<textarea>`.

### Слоты

```ts
/**
 * Slots for the ChatPrompt component
 */
interface ChatPromptSlots {
  header(): any;
  /**
   * Replace the queued messages rendered above the textarea when using `v-model:queue`.
   */
  queue(): any;
  default(): any;
  /**
   * Replace the attachments rendered above the textarea when using `v-model:files`.
   */
  files(): any;
  footer(): any;
  /**
   * Replace the internal textarea, e.g. to render an [Editor](/docs/components/editor/) with mentions.
   */
  body(): any;
  trailing(): any;
  leading(): any;
}
```

### События

```ts
/**
 * Emitted events for the ChatPrompt component
 */
interface ChatPromptEmits {
  close: (payload: [event: Event]) => void;
  submit: (payload: [event: Event]) => void;
  update:modelValue: (payload: [value: string]) => void;
  send: (payload: [item: ChatPromptQueueItem]) => void;
  update:files: (payload: [value: File[] | undefined]) => void;
  update:queue: (payload: [value: ChatPromptQueueItem[] | undefined]) => void;
}
```

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

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

| Имя | Тип |
| --- | --- |
| `textareaRef` | `Ref<HTMLTextAreaElement \| null>` |
| `open()` | `void` |

## Тема

```ts [app.config.ts]
export default defineAppConfig({
  b24ui: {
    chatPrompt: {
      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'
      }
    }
  }
})
```

## Sitemap

See the full [sitemap](/sitemap.md) for all pages.
