v2.15.0

ChatReasoning

Раскрывающаяся панель с промежуточными шагами рассуждений AI.

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

Компонент ChatReasoning отрисовывает сворачиваемый блок с рассуждениями AI. Он сам раскрывается во время потока ответа и сворачивается после него.

<script setup lang="ts">
const streaming = ref(false)
const text = ref('')

async function simulateStreaming() {
  streaming.value = true
  text.value = ''

  const content =
    'Пользователь спрашивает про Vue-компоненты. Нужно объяснить паттерн Composition API и как он связан с вопросом о реактивном управлении состоянием. Подумаю, как лучше выстроить ответ.\n\nСначала нужно учесть ключевые отличия Options API от Composition API. Composition API появился во Vue 3, чтобы снять ограничения Options API при создании крупных приложений.\n\nДля реактивного управления состоянием Composition API предлагает ref() для примитивных значений и reactive() для объектов.'

  for (const char of content) {
    text.value += char
    await new Promise((resolve) => setTimeout(resolve, 10))
  }

  streaming.value = false
}

onMounted(simulateStreaming)
</script>

<template>
  <B24ChatReasoning :text="text" :streaming="streaming" class="w-60" />
</template>
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'

const streaming = ref(false)
const text = ref('')

async function simulateStreaming() {
  streaming.value = true
  text.value = ''

  const content =
    'Пользователь спрашивает про Vue-компоненты. Нужно объяснить паттерн Composition API и как он связан с вопросом о реактивном управлении состоянием. Подумаю, как лучше выстроить ответ.\n\nСначала нужно учесть ключевые отличия Options API от Composition API. Composition API появился во Vue 3, чтобы снять ограничения Options API при создании крупных приложений.\n\nДля реактивного управления состоянием Composition API предлагает ref() для примитивных значений и reactive() для объектов.'

  for (const char of content) {
    text.value += char
    await new Promise((resolve) => setTimeout(resolve, 10))
  }

  streaming.value = false
}

onMounted(simulateStreaming)
</script>

<template>
  <B24ChatReasoning :text="text" :streaming="streaming" class="w-60" />
</template>
Тело блока использует композабл useScrollShadow: при переполнении по краям появляются затухающие тени.

Текст

Пропс text задаёт текст рассуждений. Он показывается внутри сворачиваемого блока.

<template>
  <B24ChatReasoning text="Пользователь спрашивает про компоненты Vue..." />
</template>

Поток 2.15+

Пропс streaming показывает, что рассуждение идёт. Компонент раскрывается при начале потока и сворачивается при его окончании.

Пользователь спрашивает про компоненты Vue...
<template>
  <B24ChatReasoning streaming text="Пользователь спрашивает про компоненты Vue..." />
</template>
Пропс auto-open со значением false оставляет компонент свёрнутым при начале потока, а auto-close-delay со значением 0 оставляет его раскрытым после окончания. Если пользователь переключил блок во время потока, блок остаётся в выбранном им состоянии.
Утилита isPartStreaming из @bxshefby/b24ui-nuxt/utils/ai определяет, идёт ли сейчас поток для части с рассуждениями. Передайте ей слот-пропс streaming компонента ChatMessages, чтобы она остановилась вместе с чатом.

Мерцание

Во время потока подпись триггера использует компонент ChatShimmer. Пропс shimmer настраивает его duration и spread.

Пользователь спрашивает про компоненты Vue...
<template>
  <B24ChatReasoning
    streaming
    text="Пользователь спрашивает про компоненты Vue..."
    :shimmer="{
      duration: 2,
      spread: 2
    }"
  />
</template>

Иконка

Пропс icon показывает иконку рядом с триггером.

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

<template>
  <B24ChatReasoning :icon="RocketIcon" text="Пользователь спрашивает про компоненты Vue..." />
</template>

Шеврон

Пропс chevron меняет положение иконки-шеврона.

Если у chevron значение leading и задан icon, иконка заменяется шевроном при наведении и в раскрытом состоянии.
<script setup lang="ts">
import RocketIcon from '@bitrix24/b24icons-vue/main/RocketIcon'
</script>

<template>
  <B24ChatReasoning
    chevron="leading"
    :icon="RocketIcon"
    text="Пользователь спрашивает про компоненты Vue..."
  />
</template>

Иконка шеврона

Пропс chevron-icon задаёт иконку шеврона.

<template>
  <B24ChatReasoning chevron-icon="function render(_ctx, _cache) {
  return (_openBlock(), _createElementBlock("svg", {
    xmlns: "http://www.w3.org/2000/svg",
    fill: "none",
    viewBox: "0 0 24 24",
    "aria-hidden": "true",
    "data-slot": "icon"
  }, [
    _createElementVNode("path", {
      fill: "currentColor",
      "fill-rule": "evenodd",
      d: "M8.292 16.885c.99.828 2.158 1.267 3.415 1.153.22.572.598 1.51 1.124 2.643 2.4-1.448 2.743-3.471 2.697-4.683q.354-.353.707-.771c2.881-3.423 3.28-10.079 2.492-10.738-.788-.66-7.295.888-10.176 4.311q-.357.425-.646.837c-1.207.17-3.134.863-4.144 3.459 1.207.318 2.195.526 2.799.643.107 1.25.743 2.32 1.732 3.146m1.718-2.041a2.056 2.056 0 0 0 2.89-.252 2.04 2.04 0 0 0-.252-2.882 2.056 2.056 0 0 0-2.89.252 2.04 2.04 0 0 0 .252 2.882m5.07-4.315a1.104 1.104 0 0 1-1.552.136 1.096 1.096 0 0 1-.136-1.548 1.104 1.104 0 0 1 1.552-.135c.466.39.527 1.083.136 1.547m-5.701 7.974a5.1 5.1 0 0 1-1.75-.933 4.9 4.9 0 0 1-1.267-1.484c-.874 2.119-1.251 3.831-.984 4.045s1.968-.438 4.001-1.628",
      "clip-rule": "evenodd"
    })
  ]))
}" text="Пользователь спрашивает про компоненты Vue..." />
</template>

Примеры

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

С моделями с рассуждением

Чтобы получать рассуждения потоком, задайте providerOptions для своего провайдера (Anthropic, Google, OpenAI):

server/api/chat.post.ts
import { defineEventHandler, readBody } from 'nuxt/server'
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 })
})

API

Пропсы

Prop Default Type
text string

The reasoning text content to display.

streamingfalseboolean

Whether the reasoning content is currently streaming.

duration number

The duration in seconds that the AI spent reasoning. If not provided, it will be calculated automatically based on streaming time.

iconIconComponent

The icon displayed next to the trigger.

chevron'trailing' "trailing" | "leading"

The position of the chevron icon.

chevronIconicons.chevronDownIconComponent

The icon displayed as the chevron.

autoOpentrueboolean

Whether to automatically open when streaming starts.

autoCloseDelay500 number

The delay in milliseconds before auto-closing when streaming ends. Set to 0 to disable auto-close. Skipped when the user toggled it while streaming.

shimmer Partial<Omit<ChatShimmerProps, "text">>

Customize the ChatShimmer component when streaming.

disabledboolean

When true, prevents the user from interacting with the collapsible.

openundefinedboolean

The controlled open state of the collapsible. Can be binded with v-model.

defaultOpenboolean

The open state of the collapsible when it is initially rendered.
Use when you do not need to control its open state.

unmountOnHidefalseboolean

When true, the element will be unmounted on closed state.

b24ui { root?: SlotClass; trigger?: SlotClass; leading?: SlotClass; leadingIcon?: SlotClass; chevronIcon?: SlotClass; label?: SlotClass; trailingIcon?: SlotClass; content?: SlotClass; body?: SlotClass; }

Слоты

Slot Type
default{ open: boolean; }

События

Event Type
update:open[value: boolean]

Тема

https://github.com/bx-shef/b24-ui/tree/main/src/theme/chat-reasoning.ts
export default {
  slots: {
    root: '',
    trigger: 'group w-full min-w-0 flex items-center gap-1.5 text-muted text-sm disabled:cursor-default disabled:hover:text-muted hover:text-default focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-(--ui-color-design-outline-focused-stroke) transition-colors',
    leading: 'relative size-5 shrink-0',
    leadingIcon: 'size-5 shrink-0',
    chevronIcon: 'size-4 shrink-0 group-data-[state=open]:rotate-180 transition-transform duration-200 motion-reduce:transition-none',
    label: 'truncate',
    trailingIcon: 'size-4 shrink-0 group-data-[state=open]:rotate-180 transition-transform duration-200 motion-reduce:transition-none',
    content: 'motion-safe:data-[state=open]:animate-[collapsible-down_200ms_var(--ease-out)] motion-safe:data-[state=closed]:animate-[collapsible-up_200ms_var(--ease-out)] overflow-hidden',
    body: 'max-h-[200px] pt-2 overflow-y-auto text-sm text-dimmed whitespace-pre-wrap'
  },
  variants: {
    chevron: {
      leading: {
        leadingIcon: 'group-hover:opacity-0'
      },
      trailing: ''
    },
    alone: {
      false: {
        leadingIcon: 'absolute inset-0 group-data-[state=open]:opacity-0 transition-opacity duration-200',
        chevronIcon: 'absolute inset-0 opacity-0 group-hover:opacity-100 group-data-[state=open]:opacity-100 transition-[rotate,opacity] duration-200 motion-reduce:transition-none'
      }
    }
  }
}