---
title: "ChatTool"
description: "Раскрывающийся раздел: показывает, вызван ли инструмент AI и в каком он состоянии."
canonical_url: "https://b24-ui.bx-shef.by/docs/components/chat-tool"
---
# ChatTool

> Раскрывающийся раздел: показывает, вызван ли инструмент AI и в каком он состоянии.

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

Компонент ChatTool отрисовывает сворачиваемый блок со статусом вызова инструмента AI, например «Searching components» или «Reading documentation». Если задан слот по умолчанию, блок сворачивается и раскрывает вывод инструмента.

```vue [ChatToolExample.vue]
<script setup lang="ts">
import TerminalIcon from '@bitrix24/b24icons-vue/file-type/TerminalIcon'

const streaming = ref(true)
const result = ref(`$ pnpm run lint

> eslint .

✔ Ошибок линтера не найдено.
`)

let timer: ReturnType<typeof setTimeout> | undefined

onMounted(() => {
  timer = setTimeout(() => {
    streaming.value = false
  }, 5000)
})

onUnmounted(() => {
  clearTimeout(timer)
})
</script>

<template>
  <B24ChatTool
    :text="streaming ? 'Идёт проверка линтером' : 'Проверка линтером завершена'"
    suffix="cd, pnpm run"
    :streaming="streaming"
    :icon="TerminalIcon"
    variant="card"
    chevron="leading"
    class="w-80"
  >
    <pre language="bash" v-text="result" />
  </B24ChatTool>
</template>
```

> [!TIP]
> Если результат приходит позже, ставьте `v-if` на сам слот, а не на его содержимое: слот, который ничего не рисует, всё равно делает блок раскрываемым — с пустой панелью.
> ```vue
> <template>
>   <B24ChatTool :text="getToolName(part)" :streaming="isToolStreaming(part)">
>     <template v-if="part.state === 'output-available'" #default>
>       <pre>{{ part.output }}</pre>
>     </template>
>   </B24ChatTool>
> </template>
> ```

### Текст

Пропс `text` задаёт текст статуса инструмента.

```vue
<template>
  <B24ChatTool text="Поиск компонентов выполнен" />
</template>
```

### Суффикс

Пропс `suffix` показывает дополнительный текст после основной подписи.

```vue
<template>
  <B24ChatTool text="Чтение компонента" suffix="Button" />
</template>
```

### Поток

Пропс `streaming` показывает, что инструмент сейчас работает. Текст мерцает.

```vue
<template>
  <B24ChatTool streaming text="Ищем компоненты..." />
</template>
```

> [!TIP]
> Утилита `isToolStreaming` из `@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>
  <B24ChatTool streaming text="Ищем компоненты..." :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>
  <B24ChatTool :icon="RocketIcon" text="Поиск компонентов выполнен" />
</template>
```

### Загрузка

Пропс `loading` показывает индикатор загрузки, а пропс `loading-icon` задаёт его иконку.

```vue
<template>
  <B24ChatTool loading text="Ищем компоненты..." />
</template>
```

### Иконка загрузки

Пропсы `use-clock` и `use-wait` показывают разные иконки загрузки.

Пропс `loading-icon` задаёт иконку загрузки.

```vue
<template>
  <B24ChatTool loading text="Ищем компоненты..." />
</template>
```

```vue
<template>
  <B24ChatTool loading use-wait text="Ищем компоненты..." />
</template>
```

### Ошибка

Пропс `error` показывает, что вызов инструмента завершился ошибкой, например когда состояние части — `output-error`.

```vue
<template>
  <B24ChatTool error text="Не удалось найти компоненты" />
</template>
```

### Иконка ошибки

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

```vue
<template>
  <B24ChatTool error text="Не удалось найти компоненты" />
</template>
```

### Шеврон

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

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

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

<template>
  <B24ChatTool chevron="leading" :icon="RocketIcon" text="Поиск компонентов выполнен">
Вывод инструмента
</B24ChatTool>
</template>
```

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

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

```vue
<template>
  <B24ChatTool chevron-icon="RocketIcon" text="Поиск компонентов выполнен">
Вывод инструмента
</B24ChatTool>
</template>
```

### Вариант

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

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

<template>
  <B24ChatTool variant="card" text="Поиск компонентов выполнен" :icon="RocketIcon" chevron="trailing">
Вывод инструмента
</B24ChatTool>
</template>
```

### Действия

Пропс `actions` показывает под триггером список [кнопок](https://b24-ui.bx-shef.by/raw/docs/components/button.md). Это удобно для инструментов, которым перед запуском нужно подтверждение пользователя.

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

<template>
  <B24ChatTool :actions="{'0':{label:'Разрешить'},'1':{label:'Отклонить',color:'air-secondary'}}" text="Выполнить команду в терминале" variant="card" :icon="RocketIcon">
$ pnpm run lint
</B24ChatTool>
</template>
```

## Примеры

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

### С веб-поиском

Некоторые провайдеры предлагают встроенные инструменты веб-поиска: [Anthropic](https://ai-sdk.dev/providers/ai-sdk-providers/anthropic#web-search-tool), [Google](https://ai-sdk.dev/providers/ai-sdk-providers/google#google-search), [OpenAI](https://ai-sdk.dev/providers/ai-sdk-providers/openai#web-search-tool). Их вызовы приходят на клиент как части-инструменты, поэтому отрисовываются компонентом ChatTool, как любой другой инструмент.

Каждый инструмент берётся из пакета своего провайдера, поэтому установите нужный: `@ai-sdk/anthropic`, `@ai-sdk/google` или `@ai-sdk/openai`.

```ts [Anthropic]
import { defineEventHandler, readBody } from 'nuxt/server'
import { streamText, convertToModelMessages, toUIMessageStream, createUIMessageStreamResponse } from 'ai'
import { anthropic } from '@ai-sdk/anthropic'

export default defineEventHandler(async (event) => {
  const { messages } = await readBody(event)

  const result = streamText({
    model: 'anthropic/claude-sonnet-5.5',
    instructions: 'You are a helpful assistant.',
    messages: await convertToModelMessages(messages),
    tools: {
      web_search: anthropic.tools.webSearch_20260209({})
    }
  })

  const stream = toUIMessageStream({ stream: result.stream })
  return createUIMessageStreamResponse({ stream })
})
```

```ts [Google]
import { defineEventHandler, readBody } from 'nuxt/server'
import { streamText, convertToModelMessages, toUIMessageStream, createUIMessageStreamResponse } from 'ai'
import { google } from '@ai-sdk/google'

export default defineEventHandler(async (event) => {
  const { messages } = await readBody(event)

  const result = streamText({
    model: 'google/gemini-3-flash',
    instructions: 'You are a helpful assistant.',
    messages: await convertToModelMessages(messages),
    tools: {
      google_search: google.tools.googleSearch({})
    }
  })

  const stream = toUIMessageStream({ stream: result.stream })
  return createUIMessageStreamResponse({ stream })
})
```

```ts [OpenAI]
import { defineEventHandler, readBody } from 'nuxt/server'
import { streamText, convertToModelMessages, toUIMessageStream, createUIMessageStreamResponse } from 'ai'
import { openai } from '@ai-sdk/openai'

export default defineEventHandler(async (event) => {
  const { messages } = await readBody(event)

  const result = streamText({
    model: 'openai/gpt-5.6-luna',
    instructions: 'You are a helpful assistant.',
    messages: await convertToModelMessages(messages),
    tools: {
      web_search: openai.tools.webSearch({})
    }
  })

  const stream = toUIMessageStream({ stream: result.stream })
  return createUIMessageStreamResponse({ stream })
})
```

### С инструментами MCP

Пакет `@ai-sdk/mcp` даёт чат-боту инструменты сервера [Model Context Protocol (MCP)](https://ai-sdk.dev/docs/ai-sdk-core/mcp-tools): например, поиск по документации или собственные задачи перед ответом.

Установите пакет MCP:

```bash [pnpm]
pnpm add @ai-sdk/mcp
```

```bash [yarn]
yarn add @ai-sdk/mcp
```

```bash [npm]
npm install @ai-sdk/mcp
```

```bash [bun]
bun add @ai-sdk/mcp
```

Затем передайте инструменты MCP в `streamText` в серверном обработчике:

```ts [server/api/chat.post.ts]
import { defineEventHandler, readBody } from 'nuxt/server'
import { streamText, convertToModelMessages, isStepCount, toUIMessageStream, createUIMessageStreamResponse } from 'ai'
import { createMCPClient } from '@ai-sdk/mcp'

export default defineEventHandler(async (event) => {
  const { messages } = await readBody(event)

  const httpClient = await createMCPClient({
    transport: { type: 'http', url: 'https://your-app.com/mcp' }
  })
  try {
    const tools = await httpClient.tools()

    const result = streamText({
      model: 'anthropic/claude-sonnet-5.5',
      maxOutputTokens: 10000,
      instructions: 'You are a helpful assistant. Use your tools to search for relevant information before answering questions.',
      messages: await convertToModelMessages(messages),
      stopWhen: isStepCount(6),
      tools
    })

    const stream = toUIMessageStream({
      stream: result.stream,
      // Вызывается, когда поток закончился: завершился, упал или был остановлен
      onEnd: async () => {
        await httpClient.close()
      }
    })
    return createUIMessageStreamResponse({ stream })
  } catch (error) {
    // Закрываем клиент MCP, если подготовка упала до начала потока
    await httpClient.close()
    throw error
  }
})
```

## API

### Пропсы

```ts
/**
 * Props for the ChatTool component
 */
interface ChatToolProps {
  /**
   * The text content to display.
   */
  text?: string | undefined;
  /**
   * The suffix text displayed after the main text.
   */
  suffix?: string | 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;
  /**
   * Whether the tool is in a loading state.
   * @default false
   */
  loading?: boolean | undefined;
  /**
   * Shows LoaderWaitIcon in loading mode
   * @default false
   */
  useWait?: boolean | undefined;
  /**
   * Shows LoaderClockIcon icon in loading mode
   * @default false
   */
  useClock?: boolean | undefined;
  /**
   * The icon displayed when loading. Overrides `useWait` / `useClock`.
   * @default `specialized/SpinnerIcon`
   */
  loadingIcon?: (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 the tool call failed.
   * @default false
   */
  error?: boolean | undefined;
  /**
   * The icon displayed when the tool call failed.
   * @default icons.caution
   */
  errorIcon?: (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 the tool content is currently streaming.
   * @default false
   */
  streaming?: boolean | undefined;
  /**
   * The visual variant of the tool display.
   * @default 'inline'
   */
  variant?: "inline" | "card" | 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;
  /**
   * Customize the [`ChatShimmer`](https://bitrix24.github.io/b24ui/docs/components/chat-shimmer/) component when streaming.
   */
  shimmer?: Partial<Omit<ChatShimmerProps, "text">> | undefined;
  /**
   * Display a list of actions below the trigger, useful for tool approval flows.
   * `{ size: 'xs' }`
   */
  actions?: ButtonProps[] | undefined;
  b24ui?: { root?: SlotClass; trigger?: SlotClass; leading?: SlotClass; leadingIcon?: SlotClass; chevronIcon?: SlotClass; label?: SlotClass; suffix?: SlotClass; trailingIcon?: SlotClass; content?: SlotClass; body?: SlotClass; actions?: 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 ChatTool component
 */
interface ChatToolSlots {
  default(): any;
  actions(): any;
}
```

### События

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

## Тема

```ts [app.config.ts]
export default defineAppConfig({
  b24ui: {
    chatTool: {
      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 shrink-0 size-5',
        leadingIcon: 'shrink-0 size-5',
        chevronIcon: 'shrink-0 group-data-[state=open]:rotate-180 transition-transform duration-200 motion-reduce:transition-none',
        label: 'truncate',
        suffix: 'text-dimmed ms-1',
        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: 'text-sm text-dimmed whitespace-pre-wrap',
        actions: 'flex items-center justify-end gap-1.5'
      },
      variants: {
        variant: {
          inline: {
            body: 'pt-2',
            actions: 'pt-2'
          },
          card: {
            root: 'light:[--leftmenu-group-stroke:var(--ui-color-base-30)] rounded-md ring ring-(--leftmenu-group-stroke) overflow-hidden',
            trigger: 'px-2 py-1',
            trailingIcon: 'ms-auto',
            body: 'border-t border-(--leftmenu-group-stroke) p-2 max-h-[200px] overflow-y-auto',
            actions: 'border-t border-(--leftmenu-group-stroke) p-2'
          }
        },
        chevron: {
          leading: '',
          trailing: ''
        },
        useWait: {
          true: ''
        },
        useClock: {
          true: ''
        },
        loading: {
          true: {}
        },
        error: {
          true: {
            trigger: 'text-(--ui-color-accent-main-alert) hover:text-(--ui-color-accent-main-alert) disabled:hover:text-(--ui-color-accent-main-alert)'
          }
        },
        alone: {
          false: {
            leadingIcon: 'absolute inset-0 group-hover:opacity-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'
          }
        }
      },
      compoundVariants: [
        {
          loading: true,
          useWait: false,
          useClock: false,
          class: {
            leadingIcon: 'm-0.5 size-4 animate-spin stroke-2'
          }
        }
      ]
    }
  }
})
```

## Sitemap

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