---
title: "ChatReasoning"
description: "Раскрывающаяся панель с промежуточными шагами рассуждений AI."
canonical_url: "https://b24-ui.bx-shef.by/docs/components/chat-reasoning"
---
# ChatReasoning

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

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

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

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

> [!NOTE]
> See: /docs/composables/use-scroll-shadow/
> Тело блока использует композабл `useScrollShadow`: при переполнении по краям появляются затухающие тени.

### Текст

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

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

### Поток `2.15+`

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

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

> [!TIP]
> Пропс `auto-open` со значением `false` оставляет компонент свёрнутым при начале потока, а `auto-close-delay` со значением `0` оставляет его раскрытым после окончания. Если пользователь переключил блок во время потока, блок остаётся в выбранном им состоянии.

> [!TIP]
> Утилита `isPartStreaming` из `@bxshefby/b24ui-nuxt/utils/ai` определяет, идёт ли сейчас поток для части с рассуждениями. Передайте ей слот-пропс `streaming` компонента [ChatMessages](https://b24-ui.bx-shef.by/raw/docs/components/chat-messages.md#slots), чтобы она остановилась вместе с чатом.

### Мерцание

Во время потока подпись триггера использует компонент [`ChatShimmer`](https://b24-ui.bx-shef.by/raw/docs/components/chat-shimmer.md). Пропс `shimmer` настраивает его `duration` и `spread`.

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

### Иконка

Пропс `icon` показывает [иконку](https://bitrix24.github.io/b24icons/icons/) рядом с триггером.

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

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

### Шеврон

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

> [!NOTE]
> Если у `chevron` значение `leading` и задан `icon`, иконка заменяется шевроном при наведении и в раскрытом состоянии.

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

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

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

Пропс `chevron-icon` задаёт [иконку](https://bitrix24.github.io/b24icons/icons/) шеврона.

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

## Примеры

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

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

Чтобы получать [рассуждения](https://ai-sdk.dev/docs/ai-sdk-ui/chatbot#reasoning) потоком, задайте `providerOptions` для своего провайдера ([Anthropic](https://ai-sdk.dev/providers/ai-sdk-providers/anthropic#reasoning), [Google](https://ai-sdk.dev/providers/ai-sdk-providers/google#thinking), [OpenAI](https://ai-sdk.dev/providers/ai-sdk-providers/openai#reasoning)):

```ts [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

### Пропсы

```ts
/**
 * Props for the ChatReasoning component
 */
interface ChatReasoningProps {
  /**
   * The reasoning text content to display.
   */
  text?: string | undefined;
  /**
   * Whether the reasoning content is currently streaming.
   * @default false
   */
  streaming?: boolean | undefined;
  /**
   * The duration in seconds that the AI spent reasoning.
   * If not provided, it will be calculated automatically based on streaming time.
   */
  duration?: number | undefined;
  /**
   * The icon displayed next to the trigger.
   */
  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;
  /**
   * The position of the chevron icon.
   * @default 'trailing'
   */
  chevron?: "trailing" | "leading" | undefined;
  /**
   * The icon displayed as the chevron.
   * @default icons.chevronDown
   */
  chevronIcon?: (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;
  /**
   * Whether to automatically open when streaming starts.
   * @default true
   */
  autoOpen?: boolean | undefined;
  /**
   * 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.
   * @default 500
   */
  autoCloseDelay?: number | undefined;
  /**
   * Customize the [`ChatShimmer`](https://bitrix24.github.io/b24ui/docs/components/chat-shimmer/) component when streaming.
   */
  shimmer?: Partial<Omit<ChatShimmerProps, "text">> | undefined;
  b24ui?: { root?: SlotClass; trigger?: SlotClass; leading?: SlotClass; leadingIcon?: SlotClass; chevronIcon?: SlotClass; label?: SlotClass; trailingIcon?: SlotClass; content?: SlotClass; body?: SlotClass; } | undefined;
  /**
   * When `true`, prevents the user from interacting with the collapsible.
   */
  disabled?: boolean | undefined;
  /**
   * The controlled open state of the collapsible. Can be binded with `v-model`.
   * @default undefined
   */
  open?: boolean | undefined;
  /**
   * The open state of the collapsible when it is initially rendered. <br> Use when you do not need to control its open state.
   */
  defaultOpen?: boolean | undefined;
  /**
   * When `true`, the element will be unmounted on closed state.
   * @default false
   */
  unmountOnHide?: boolean | undefined;
}
```

### Слоты

```ts
/**
 * Slots for the ChatReasoning component
 */
interface ChatReasoningSlots {
  default(): any;
}
```

### События

```ts
/**
 * Emitted events for the ChatReasoning component
 */
interface ChatReasoningEmits {
  update:open: (payload: [value: boolean]) => void;
}
```

## Тема

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

## Sitemap

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