---
title: Маршрутизация тикетов
url: https://platform.claude.com/docs/ru/about-claude/use-case-guides/ticket-routing
description: В этом руководстве рассматривается, как использовать продвинутые возможности Claude по пониманию естественного языка для масштабной классификации тикетов службы поддержки клиентов на основе намерений клиента, срочности, приоритизации, профиля клиента и многого другого.
---

## Предварительные требования

* Ключ API Claude и установленный Claude SDK
* Доступ к вашей существующей системе тикетов поддержки и знакомство с ней
* Выборка исторических тикетов поддержки для тестирования

## Определите, стоит ли использовать Claude для маршрутизации тикетов

Вот несколько ключевых признаков того, что для вашей задачи классификации следует использовать «large language model» (большую языковую модель), или LLM, такую как Claude, вместо традиционных подходов машинного обучения (ML):

<AccordionGroup>
  <Accordion title="У вас ограниченный объём размеченных обучающих данных">
    Традиционные процессы ML требуют огромных размеченных наборов данных. Предобученная модель Claude может эффективно классифицировать тикеты всего на нескольких десятках размеченных примеров, что значительно сокращает время и затраты на подготовку данных.
  </Accordion>

  <Accordion title="Ваши категории классификации, вероятно, будут меняться или развиваться со временем">
    После того как традиционный подход ML внедрён, его изменение становится трудоёмкой и требующей большого объёма данных задачей. С другой стороны, по мере развития вашего продукта или потребностей клиентов Claude может легко адаптироваться к изменениям в определениях классов или к новым классам без масштабной переразметки обучающих данных.
  </Accordion>

  <Accordion title="Вам нужно обрабатывать сложные неструктурированные текстовые входные данные">
    Традиционные модели ML часто испытывают трудности с неструктурированными данными и требуют обширной инженерии признаков. Продвинутое понимание языка Claude позволяет выполнять точную классификацию на основе содержания и контекста, а не полагаться на строгие онтологические структуры.
  </Accordion>

  <Accordion title="Ваши правила классификации основаны на семантическом понимании">
    Традиционные подходы ML часто опираются на модели «мешка слов» или простое сопоставление шаблонов. Claude превосходно понимает и применяет лежащие в основе правила, когда классы определяются условиями, а не примерами.
  </Accordion>

  <Accordion title="Вам требуется интерпретируемое обоснование решений о классификации">
    Многие традиционные модели ML дают мало информации о процессе принятия решений. Claude может предоставлять понятные человеку объяснения своих решений о классификации, укрепляя доверие к системе автоматизации и облегчая адаптацию при необходимости.
  </Accordion>

  <Accordion title="Вы хотите эффективнее обрабатывать пограничные случаи и неоднозначные тикеты">
    Традиционные системы ML часто испытывают трудности с выбросами и неоднозначными входными данными, нередко классифицируя их неверно или относя к универсальной категории по умолчанию. Возможности Claude по обработке естественного языка позволяют лучше интерпретировать контекст и нюансы в тикетах поддержки, потенциально сокращая количество неверно маршрутизированных или неклассифицированных тикетов, требующих ручного вмешательства.
  </Accordion>

  <Accordion title="Вам нужна многоязычная поддержка без обслуживания отдельных моделей">
    Традиционные подходы ML обычно требуют отдельных моделей или обширных процессов перевода для каждого поддерживаемого языка. Многоязычные возможности Claude позволяют классифицировать тикеты на различных языках без необходимости в отдельных моделях или обширных процессах перевода, упрощая поддержку глобальной клиентской базы.
  </Accordion>
</AccordionGroup>

***

## Создайте и разверните рабочий процесс поддержки на основе LLM

### Изучите ваш текущий подход к поддержке

Прежде чем автоматизировать, крайне важно понять вашу существующую систему тикетов. Начните с изучения того, как ваша команда поддержки в настоящее время выполняет маршрутизацию тикетов.

Рассмотрите такие вопросы, как:

* Какие критерии используются для определения применяемого SLA/предложения услуг?
* Используется ли маршрутизация тикетов для определения того, на какой уровень поддержки или к какому специалисту по продукту направляется тикет?
* Существуют ли уже какие-либо автоматизированные правила или рабочие процессы? В каких случаях они дают сбой?
* Как обрабатываются пограничные случаи или неоднозначные тикеты?
* Как команда приоритизирует тикеты?

Чем больше вы знаете о том, как люди обрабатывают определённые случаи, тем лучше вы сможете работать с Claude над выполнением задачи.

### Определите категории намерений пользователей

Чётко определённый список категорий намерений пользователей крайне важен для точной классификации тикетов поддержки с помощью Claude. Способность Claude эффективно маршрутизировать тикеты в вашей системе прямо пропорциональна тому, насколько чётко определены категории вашей системы.

Вот несколько примеров категорий и подкатегорий намерений пользователей.

<AccordionGroup>
  <Accordion title="Техническая проблема">
    * Проблема с оборудованием
    * Программная ошибка
    * Проблема совместимости
    * Проблема производительности
  </Accordion>

  <Accordion title="Управление учётной записью">
    * Сброс пароля
    * Проблемы с доступом к учётной записи
    * Вопросы по выставлению счетов
    * Изменения подписки
  </Accordion>

  <Accordion title="Информация о продукте">
    * Вопросы о функциях
    * Вопросы о совместимости продукта
    * Информация о ценах
    * Вопросы о наличии
  </Accordion>

  <Accordion title="Руководство для пользователей">
    * Вопросы «как сделать»
    * Помощь в использовании функций
    * Советы по лучшим практикам
    * Руководство по устранению неполадок
  </Accordion>

  <Accordion title="Обратная связь">
    * Отчёты об ошибках
    * Запросы функций
    * Общие отзывы или предложения
    * Жалобы
  </Accordion>

  <Accordion title="Связанное с заказами">
    * Вопросы о статусе заказа
    * Информация о доставке
    * Возвраты и обмены
    * Изменения заказа
  </Accordion>

  <Accordion title="Запрос на обслуживание">
    * Помощь с установкой
    * Запросы на обновление
    * Планирование технического обслуживания
    * Отмена услуги
  </Accordion>

  <Accordion title="Вопросы безопасности">
    * Вопросы о конфиденциальности данных
    * Сообщения о подозрительной активности
    * Помощь с функциями безопасности
  </Accordion>

  <Accordion title="Соответствие требованиям и юридические вопросы">
    * Вопросы о соответствии нормативным требованиям
    * Вопросы об условиях обслуживания
    * Запросы юридической документации
  </Accordion>

  <Accordion title="Экстренная поддержка">
    * Критические сбои системы
    * Срочные проблемы безопасности
    * Проблемы, требующие срочного решения
  </Accordion>

  <Accordion title="Обучение и образование">
    * Запросы на обучение по продукту
    * Вопросы о документации
    * Информация о вебинарах или семинарах
  </Accordion>

  <Accordion title="Интеграция и API">
    * Помощь с интеграцией
    * Вопросы об использовании API
    * Вопросы о совместимости со сторонними решениями
  </Accordion>
</AccordionGroup>

Помимо намерения, на маршрутизацию и приоритизацию тикетов могут также влиять другие факторы, такие как срочность, тип клиента, SLA или язык. Обязательно учитывайте другие критерии маршрутизации при создании вашей автоматизированной системы маршрутизации.

### Установите критерии успеха

Совместно с вашей командой поддержки [определите чёткие критерии успеха](https://platform.claude.com/docs/ru/test-and-evaluate/develop-tests) с измеримыми ориентирами, пороговыми значениями и целями.

Вот несколько стандартных критериев и ориентиров при использовании LLM для маршрутизации тикетов поддержки:

<AccordionGroup>
  <Accordion title="Согласованность классификации">
    Эта метрика оценивает, насколько согласованно Claude классифицирует похожие тикеты с течением времени. Это крайне важно для поддержания надёжности маршрутизации. Измеряйте её, периодически тестируя модель на наборе стандартизированных входных данных и стремясь к уровню согласованности 95% или выше.
  </Accordion>

  <Accordion title="Скорость адаптации">
    Эта метрика измеряет, насколько быстро Claude может адаптироваться к новым категориям или меняющимся шаблонам тикетов. Проверяйте это, вводя новые типы тикетов и измеряя время, необходимое модели для достижения удовлетворительной точности (например, >90%) по этим новым категориям. Стремитесь к адаптации в пределах 50–100 примеров тикетов.
  </Accordion>

  <Accordion title="Многоязычная обработка">
    Эта метрика оценивает способность Claude точно маршрутизировать тикеты на нескольких языках. Измеряйте точность маршрутизации для разных языков, стремясь к снижению точности не более чем на 5–10% для неосновных языков.
  </Accordion>

  <Accordion title="Обработка пограничных случаев">
    Эта метрика оценивает работу Claude с необычными или сложными тикетами. Создайте тестовый набор пограничных случаев и измерьте точность маршрутизации, стремясь к точности не менее 80% на этих сложных входных данных.
  </Accordion>

  <Accordion title="Снижение предвзятости">
    Эта метрика измеряет справедливость маршрутизации Claude для различных демографических групп клиентов. Регулярно проверяйте решения о маршрутизации на предмет потенциальной предвзятости, стремясь к согласованной точности маршрутизации (в пределах 2–3%) для всех групп клиентов.
  </Accordion>

  <Accordion title="Эффективность подсказки">
    В ситуациях, когда минимизация количества токенов крайне важна, этот критерий оценивает, насколько хорошо Claude работает с минимальным контекстом. Измеряйте точность маршрутизации при различном объёме предоставленного контекста, стремясь к точности 90%+ при наличии только заголовка тикета и краткого описания.
  </Accordion>

  <Accordion title="Оценка объяснимости">
    Эта метрика оценивает качество и релевантность объяснений Claude своих решений о маршрутизации. Оценщики-люди могут оценивать объяснения по шкале (например, 1–5) с целью достижения средней оценки 4 или выше.
  </Accordion>
</AccordionGroup>

Вот несколько общих критериев успеха, которые могут быть полезны независимо от того, используется ли LLM:

<AccordionGroup>
  <Accordion title="Точность маршрутизации">
    Точность маршрутизации измеряет, как часто тикеты правильно назначаются соответствующей команде или сотруднику с первой попытки. Обычно она измеряется как процент правильно маршрутизированных тикетов от общего числа тикетов. Отраслевые ориентиры часто нацелены на точность 90–95%, хотя это может варьироваться в зависимости от сложности структуры поддержки.
  </Accordion>

  <Accordion title="Время до назначения">
    Эта метрика отслеживает, насколько быстро тикеты назначаются после подачи. Более быстрое назначение обычно приводит к более быстрому решению и повышению удовлетворённости клиентов. Лучшие в своём классе системы часто достигают среднего времени назначения менее 5 минут, а многие стремятся к практически мгновенной маршрутизации (что возможно при реализации на основе LLM).
  </Accordion>

  <Accordion title="Доля перемаршрутизации">
    Доля перемаршрутизации показывает, как часто тикеты необходимо переназначать после первоначальной маршрутизации. Более низкий показатель свидетельствует о более точной первоначальной маршрутизации. Стремитесь к доле перемаршрутизации ниже 10%, при этом лучшие системы достигают показателей 5% или ниже.
  </Accordion>

  <Accordion title="Доля решений при первом контакте">
    Эта метрика измеряет процент тикетов, решённых в ходе первого взаимодействия с клиентом. Более высокие показатели свидетельствуют об эффективной маршрутизации и хорошо подготовленных командах поддержки. Отраслевые ориентиры обычно находятся в диапазоне 70–75%, а лучшие исполнители достигают показателей 80% или выше.
  </Accordion>

  <Accordion title="Среднее время обработки">
    Среднее время обработки измеряет, сколько времени требуется для решения тикета от начала до конца. Эффективная маршрутизация может значительно сократить это время. Ориентиры сильно различаются в зависимости от отрасли и сложности, но многие организации стремятся удерживать среднее время обработки менее 24 часов для некритических проблем.
  </Accordion>

  <Accordion title="Оценки удовлетворённости клиентов">
    Эти оценки, часто измеряемые с помощью опросов после взаимодействия, отражают общую удовлетворённость клиентов процессом поддержки. Эффективная маршрутизация способствует более высокой удовлетворённости. Стремитесь к показателям CSAT 90% или выше, при этом лучшие исполнители часто достигают уровня удовлетворённости 95%+.
  </Accordion>

  <Accordion title="Доля эскалаций">
    Эта метрика измеряет, как часто тикеты необходимо эскалировать на более высокие уровни поддержки. Более низкая доля эскалаций часто свидетельствует о более точной первоначальной маршрутизации. Стремитесь к доле эскалаций ниже 20%, при этом лучшие в своём классе системы достигают показателей 10% или ниже.
  </Accordion>

  <Accordion title="Продуктивность агентов">
    Эта метрика показывает, сколько тикетов агенты могут эффективно обрабатывать после внедрения решения для маршрутизации. Улучшенная маршрутизация должна повысить продуктивность. Измеряйте её, отслеживая количество решённых тикетов на агента в день или в час, стремясь к улучшению на 10–20% после внедрения новой системы маршрутизации.
  </Accordion>

  <Accordion title="Доля отклонения через самообслуживание">
    Эта метрика измеряет процент потенциальных тикетов, решённых с помощью средств самообслуживания до попадания в систему маршрутизации. Более высокие показатели свидетельствуют об эффективной предварительной сортировке. Стремитесь к доле отклонения 20–30%, при этом лучшие исполнители достигают показателей 40% или выше.
  </Accordion>

  <Accordion title="Стоимость одного тикета">
    Эта метрика рассчитывает среднюю стоимость решения каждого тикета поддержки. Эффективная маршрутизация должна со временем помочь снизить эту стоимость. Хотя ориентиры сильно различаются, многие организации стремятся снизить стоимость одного тикета на 10–15% после внедрения улучшенной системы маршрутизации.
  </Accordion>
</AccordionGroup>

### Выберите подходящую модель Claude

Выбор модели зависит от компромиссов между стоимостью, точностью и временем ответа.

Claude Haiku 5.5 (`claude-haiku-5-5`) хорошо подходит для маршрутизации тикетов: это самая быстрая и экономичная из текущих моделей, и при уровне усилий `low` она справляется с простыми запросами большого объёма, такими как классификация. Если ваша задача классификации требует глубокой предметной экспертизы, большого количества категорий намерений или сложных рассуждений, вы можете выбрать [более крупную модель Sonnet](https://platform.claude.com/docs/ru/models/overview).

### Создайте сильную подсказку

Маршрутизация тикетов — это разновидность задачи классификации. Claude анализирует содержимое тикета поддержки и относит его к предопределённым категориям на основе типа проблемы, срочности, требуемой экспертизы или других релевантных факторов.

Напишите подсказку для классификации тикетов. Начальная подсказка должна содержать содержимое запроса пользователя и возвращать как рассуждение, так и намерение.

<Tip>
  Попробуйте [рецепт метаподсказки из Claude Cookbook](https://colab.research.google.com/github/anthropics/claude-cookbooks/blob/main/misc/metaprompt.ipynb), чтобы Claude написал для вас первый черновик.
</Tip>

Вот пример подсказки для классификации при маршрутизации тикетов:

<CodeGroup exclude="shell">
  <CodeGroupItem language="cURL">
    Создайте подсказку в коде.
  </CodeGroupItem>

  <CodeGroupItem language="CLI">
    Создайте подсказку в коде.
  </CodeGroupItem>

  ```python Python
  def classify_support_request(ticket_contents):
      # Определяем подсказку для задачи классификации
      classification_prompt = f"""You will be acting as a customer support ticket classification system. Your task is to analyze customer support requests and output the appropriate classification intent for each request, along with your reasoning.

          Here is the customer support request you need to classify:

          <request>{ticket_contents}</request>

          Please carefully analyze the above request to determine the customer's core intent and needs. Consider what the customer is asking for has concerns about.

          First, write out your reasoning and analysis of how to classify this request inside <reasoning> tags.

          Then, output the appropriate classification label for the request inside a <intent> tag. The valid intents are:
          <intents>
          <intent>Support, Feedback, Complaint</intent>
          <intent>Order Tracking</intent>
          <intent>Refund/Exchange</intent>
          </intents>

          A request may have ONLY ONE applicable intent. Only include the intent that is most applicable to the request.

          As an example, consider the following request:
          <request>Hello! I had high-speed fiber internet installed on Saturday and my installer, Kevin, was absolutely fantastic! Where can I send my positive review? Thanks for your help!</request>

          Here is an example of how your output should be formatted (for the above example request):
          <reasoning>The user seeks information in order to leave positive feedback.</reasoning>
          <intent>Support, Feedback, Complaint</intent>

          Here are a few more examples:
          <examples>
          <example 2>
          Example 2 Input:
          <request>I wanted to write and personally thank you for the compassion you showed towards my family during my father's funeral this past weekend. Your staff was so considerate and helpful throughout this whole process; it really took a load off our shoulders. The visitation brochures were beautiful. We'll never forget the kindness you showed us and we are so appreciative of how smoothly the proceedings went. Thank you, again, Amarantha Hill on behalf of the Hill Family.</request>

          Example 2 Output:
          <reasoning>User leaves a positive review of their experience.</reasoning>
          <intent>Support, Feedback, Complaint</intent>
          </example 2>
          <example 3>

          […]

          </example 8>
          <example 9>
          Example 9 Input:
          <request>Your website keeps sending ad-popups that block the entire screen. It took me twenty minutes just to finally find the phone number to call and complain. How can I possibly access my account information with all of these popups? Can you access my account for me, since your website is broken? I need to know what the address is on file.</request>

          Example 9 Output:
          <reasoning>The user requests help accessing their web account information.</reasoning>
          <intent>Support, Feedback, Complaint</intent>
          </example 9>

          Remember to always include your classification reasoning before your actual intent output. The reasoning should be enclosed in <reasoning> tags and the intent in <intent> tags. Return only the reasoning and the intent.
          """
  ```

  ```typescript TypeScript
  function classifySupportRequest(ticketContents: string) {
    // Определите подсказку для задачи классификации
    const classificationPrompt = `You will be acting as a customer support ticket classification system. Your task is to analyze customer support requests and output the appropriate classification intent for each request, along with your reasoning.

      Here is the customer support request you need to classify:

      <request>${ticketContents}</request>

      Please carefully analyze the above request to determine the customer's core intent and needs. Consider what the customer is asking for has concerns about.

      First, write out your reasoning and analysis of how to classify this request inside <reasoning> tags.

      Then, output the appropriate classification label for the request inside a <intent> tag. The valid intents are:
      <intents>
      <intent>Support, Feedback, Complaint</intent>
      <intent>Order Tracking</intent>
      <intent>Refund/Exchange</intent>
      </intents>

      A request may have ONLY ONE applicable intent. Only include the intent that is most applicable to the request.

      As an example, consider the following request:
      <request>Hello! I had high-speed fiber internet installed on Saturday and my installer, Kevin, was absolutely fantastic! Where can I send my positive review? Thanks for your help!</request>

      Here is an example of how your output should be formatted (for the above example request):
      <reasoning>The user seeks information in order to leave positive feedback.</reasoning>
      <intent>Support, Feedback, Complaint</intent>

      Here are a few more examples:
      <examples>
      <example 2>
      Example 2 Input:
      <request>I wanted to write and personally thank you for the compassion you showed towards my family during my father's funeral this past weekend. Your staff was so considerate and helpful throughout this whole process; it really took a load off our shoulders. The visitation brochures were beautiful. We'll never forget the kindness you showed us and we are so appreciative of how smoothly the proceedings went. Thank you, again, Amarantha Hill on behalf of the Hill Family.</request>

      Example 2 Output:
      <reasoning>User leaves a positive review of their experience.</reasoning>
      <intent>Support, Feedback, Complaint</intent>
      </example 2>
      <example 3>

      […]

      </example 8>
      <example 9>
      Example 9 Input:
      <request>Your website keeps sending ad-popups that block the entire screen. It took me twenty minutes just to finally find the phone number to call and complain. How can I possibly access my account information with all of these popups? Can you access my account for me, since your website is broken? I need to know what the address is on file.</request>

      Example 9 Output:
      <reasoning>The user requests help accessing their web account information.</reasoning>
      <intent>Support, Feedback, Complaint</intent>
      </example 9>

      Remember to always include your classification reasoning before your actual intent output. The reasoning should be enclosed in <reasoning> tags and the intent in <intent> tags. Return only the reasoning and the intent.
      `;
  }
  ```

  ```csharp C#
  void ClassifySupportRequest(string ticketContents)
  {
      // Определяем подсказку для задачи классификации
      var classificationPrompt = $"""
          You will be acting as a customer support ticket classification system. Your task is to analyze customer support requests and output the appropriate classification intent for each request, along with your reasoning.

          Here is the customer support request you need to classify:

          <request>{ticketContents}</request>

          Please carefully analyze the above request to determine the customer's core intent and needs. Consider what the customer is asking for has concerns about.

          First, write out your reasoning and analysis of how to classify this request inside <reasoning> tags.

          Then, output the appropriate classification label for the request inside a <intent> tag. The valid intents are:
          <intents>
          <intent>Support, Feedback, Complaint</intent>
          <intent>Order Tracking</intent>
          <intent>Refund/Exchange</intent>
          </intents>

          A request may have ONLY ONE applicable intent. Only include the intent that is most applicable to the request.

          As an example, consider the following request:
          <request>Hello! I had high-speed fiber internet installed on Saturday and my installer, Kevin, was absolutely fantastic! Where can I send my positive review? Thanks for your help!</request>

          Here is an example of how your output should be formatted (for the above example request):
          <reasoning>The user seeks information in order to leave positive feedback.</reasoning>
          <intent>Support, Feedback, Complaint</intent>

          Here are a few more examples:
          <examples>
          <example 2>
          Example 2 Input:
          <request>I wanted to write and personally thank you for the compassion you showed towards my family during my father's funeral this past weekend. Your staff was so considerate and helpful throughout this whole process; it really took a load off our shoulders. The visitation brochures were beautiful. We'll never forget the kindness you showed us and we are so appreciative of how smoothly the proceedings went. Thank you, again, Amarantha Hill on behalf of the Hill Family.</request>

          Example 2 Output:
          <reasoning>User leaves a positive review of their experience.</reasoning>
          <intent>Support, Feedback, Complaint</intent>
          </example 2>
          <example 3>

          […]

          </example 8>
          <example 9>
          Example 9 Input:
          <request>Your website keeps sending ad-popups that block the entire screen. It took me twenty minutes just to finally find the phone number to call and complain. How can I possibly access my account information with all of these popups? Can you access my account for me, since your website is broken? I need to know what the address is on file.</request>

          Example 9 Output:
          <reasoning>The user requests help accessing their web account information.</reasoning>
          <intent>Support, Feedback, Complaint</intent>
          </example 9>

          Remember to always include your classification reasoning before your actual intent output. The reasoning should be enclosed in <reasoning> tags and the intent in <intent> tags. Return only the reasoning and the intent.
          """;
  }
  ```

  ```go Go
  func classifySupportRequest(ticketContents string) {
  	// Определяем подсказку для задачи классификации
  	classificationPrompt := `You will be acting as a customer support ticket classification system. Your task is to analyze customer support requests and output the appropriate classification intent for each request, along with your reasoning.

  		Here is the customer support request you need to classify:

  		<request>` + ticketContents + `</request>

  		Please carefully analyze the above request to determine the customer's core intent and needs. Consider what the customer is asking for has concerns about.

  		First, write out your reasoning and analysis of how to classify this request inside <reasoning> tags.

  		Then, output the appropriate classification label for the request inside a <intent> tag. The valid intents are:
  		<intents>
  		<intent>Support, Feedback, Complaint</intent>
  		<intent>Order Tracking</intent>
  		<intent>Refund/Exchange</intent>
  		</intents>

  		A request may have ONLY ONE applicable intent. Only include the intent that is most applicable to the request.

  		As an example, consider the following request:
  		<request>Hello! I had high-speed fiber internet installed on Saturday and my installer, Kevin, was absolutely fantastic! Where can I send my positive review? Thanks for your help!</request>

  		Here is an example of how your output should be formatted (for the above example request):
  		<reasoning>The user seeks information in order to leave positive feedback.</reasoning>
  		<intent>Support, Feedback, Complaint</intent>

  		Here are a few more examples:
  		<examples>
  		<example 2>
  		Example 2 Input:
  		<request>I wanted to write and personally thank you for the compassion you showed towards my family during my father's funeral this past weekend. Your staff was so considerate and helpful throughout this whole process; it really took a load off our shoulders. The visitation brochures were beautiful. We'll never forget the kindness you showed us and we are so appreciative of how smoothly the proceedings went. Thank you, again, Amarantha Hill on behalf of the Hill Family.</request>

  		Example 2 Output:
  		<reasoning>User leaves a positive review of their experience.</reasoning>
  		<intent>Support, Feedback, Complaint</intent>
  		</example 2>
  		<example 3>

  		[…]

  		</example 8>
  		<example 9>
  		Example 9 Input:
  		<request>Your website keeps sending ad-popups that block the entire screen. It took me twenty minutes just to finally find the phone number to call and complain. How can I possibly access my account information with all of these popups? Can you access my account for me, since your website is broken? I need to know what the address is on file.</request>

  		Example 9 Output:
  		<reasoning>The user requests help accessing their web account information.</reasoning>
  		<intent>Support, Feedback, Complaint</intent>
  		</example 9>

  		Remember to always include your classification reasoning before your actual intent output. The reasoning should be enclosed in <reasoning> tags and the intent in <intent> tags. Return only the reasoning and the intent.
  		`
  // ...
  }
  ```

  ```java Java
  void classifySupportRequest(String ticketContents) {
      // Определите подсказку для задачи классификации
      String classificationPrompt = """
          You will be acting as a customer support ticket classification system. Your task is to analyze customer support requests and output the appropriate classification intent for each request, along with your reasoning.

          Here is the customer support request you need to classify:

          <request>%s</request>

          Please carefully analyze the above request to determine the customer's core intent and needs. Consider what the customer is asking for has concerns about.

          First, write out your reasoning and analysis of how to classify this request inside <reasoning> tags.

          Then, output the appropriate classification label for the request inside a <intent> tag. The valid intents are:
          <intents>
          <intent>Support, Feedback, Complaint</intent>
          <intent>Order Tracking</intent>
          <intent>Refund/Exchange</intent>
          </intents>

          A request may have ONLY ONE applicable intent. Only include the intent that is most applicable to the request.

          As an example, consider the following request:
          <request>Hello! I had high-speed fiber internet installed on Saturday and my installer, Kevin, was absolutely fantastic! Where can I send my positive review? Thanks for your help!</request>

          Here is an example of how your output should be formatted (for the above example request):
          <reasoning>The user seeks information in order to leave positive feedback.</reasoning>
          <intent>Support, Feedback, Complaint</intent>

          Here are a few more examples:
          <examples>
          <example 2>
          Example 2 Input:
          <request>I wanted to write and personally thank you for the compassion you showed towards my family during my father's funeral this past weekend. Your staff was so considerate and helpful throughout this whole process; it really took a load off our shoulders. The visitation brochures were beautiful. We'll never forget the kindness you showed us and we are so appreciative of how smoothly the proceedings went. Thank you, again, Amarantha Hill on behalf of the Hill Family.</request>

          Example 2 Output:
          <reasoning>User leaves a positive review of their experience.</reasoning>
          <intent>Support, Feedback, Complaint</intent>
          </example 2>
          <example 3>

          […]

          </example 8>
          <example 9>
          Example 9 Input:
          <request>Your website keeps sending ad-popups that block the entire screen. It took me twenty minutes just to finally find the phone number to call and complain. How can I possibly access my account information with all of these popups? Can you access my account for me, since your website is broken? I need to know what the address is on file.</request>

          Example 9 Output:
          <reasoning>The user requests help accessing their web account information.</reasoning>
          <intent>Support, Feedback, Complaint</intent>
          </example 9>

          Remember to always include your classification reasoning before your actual intent output. The reasoning should be enclosed in <reasoning> tags and the intent in <intent> tags. Return only the reasoning and the intent.
          """.formatted(ticketContents);
  }
  ```

  ```php PHP
  function classifySupportRequest(string $ticketContents): void
  {
      // Определяем подсказку для задачи классификации
      $classificationPrompt = <<<PROMPT
          You will be acting as a customer support ticket classification system. Your task is to analyze customer support requests and output the appropriate classification intent for each request, along with your reasoning.

          Here is the customer support request you need to classify:

          <request>{$ticketContents}</request>

          Please carefully analyze the above request to determine the customer's core intent and needs. Consider what the customer is asking for has concerns about.

          First, write out your reasoning and analysis of how to classify this request inside <reasoning> tags.

          Then, output the appropriate classification label for the request inside a <intent> tag. The valid intents are:
          <intents>
          <intent>Support, Feedback, Complaint</intent>
          <intent>Order Tracking</intent>
          <intent>Refund/Exchange</intent>
          </intents>

          A request may have ONLY ONE applicable intent. Only include the intent that is most applicable to the request.

          As an example, consider the following request:
          <request>Hello! I had high-speed fiber internet installed on Saturday and my installer, Kevin, was absolutely fantastic! Where can I send my positive review? Thanks for your help!</request>

          Here is an example of how your output should be formatted (for the above example request):
          <reasoning>The user seeks information in order to leave positive feedback.</reasoning>
          <intent>Support, Feedback, Complaint</intent>

          Here are a few more examples:
          <examples>
          <example 2>
          Example 2 Input:
          <request>I wanted to write and personally thank you for the compassion you showed towards my family during my father's funeral this past weekend. Your staff was so considerate and helpful throughout this whole process; it really took a load off our shoulders. The visitation brochures were beautiful. We'll never forget the kindness you showed us and we are so appreciative of how smoothly the proceedings went. Thank you, again, Amarantha Hill on behalf of the Hill Family.</request>

          Example 2 Output:
          <reasoning>User leaves a positive review of their experience.</reasoning>
          <intent>Support, Feedback, Complaint</intent>
          </example 2>
          <example 3>

          […]

          </example 8>
          <example 9>
          Example 9 Input:
          <request>Your website keeps sending ad-popups that block the entire screen. It took me twenty minutes just to finally find the phone number to call and complain. How can I possibly access my account information with all of these popups? Can you access my account for me, since your website is broken? I need to know what the address is on file.</request>

          Example 9 Output:
          <reasoning>The user requests help accessing their web account information.</reasoning>
          <intent>Support, Feedback, Complaint</intent>
          </example 9>

          Remember to always include your classification reasoning before your actual intent output. The reasoning should be enclosed in <reasoning> tags and the intent in <intent> tags. Return only the reasoning and the intent.
          PROMPT;
  }
  ```

  ```ruby Ruby
  def classify_support_request(ticket_contents)
    # Определяем подсказку для задачи классификации
    classification_prompt = <<~PROMPT
      You will be acting as a customer support ticket classification system. Your task is to analyze customer support requests and output the appropriate classification intent for each request, along with your reasoning.

      Here is the customer support request you need to classify:

      <request>#{ticket_contents}</request>

      Please carefully analyze the above request to determine the customer's core intent and needs. Consider what the customer is asking for has concerns about.

      First, write out your reasoning and analysis of how to classify this request inside <reasoning> tags.

      Then, output the appropriate classification label for the request inside a <intent> tag. The valid intents are:
      <intents>
      <intent>Support, Feedback, Complaint</intent>
      <intent>Order Tracking</intent>
      <intent>Refund/Exchange</intent>
      </intents>

      A request may have ONLY ONE applicable intent. Only include the intent that is most applicable to the request.

      As an example, consider the following request:
      <request>Hello! I had high-speed fiber internet installed on Saturday and my installer, Kevin, was absolutely fantastic! Where can I send my positive review? Thanks for your help!</request>

      Here is an example of how your output should be formatted (for the above example request):
      <reasoning>The user seeks information in order to leave positive feedback.</reasoning>
      <intent>Support, Feedback, Complaint</intent>

      Here are a few more examples:
      <examples>
      <example 2>
      Example 2 Input:
      <request>I wanted to write and personally thank you for the compassion you showed towards my family during my father's funeral this past weekend. Your staff was so considerate and helpful throughout this whole process; it really took a load off our shoulders. The visitation brochures were beautiful. We'll never forget the kindness you showed us and we are so appreciative of how smoothly the proceedings went. Thank you, again, Amarantha Hill on behalf of the Hill Family.</request>

      Example 2 Output:
      <reasoning>User leaves a positive review of their experience.</reasoning>
      <intent>Support, Feedback, Complaint</intent>
      </example 2>
      <example 3>

      […]

      </example 8>
      <example 9>
      Example 9 Input:
      <request>Your website keeps sending ad-popups that block the entire screen. It took me twenty minutes just to finally find the phone number to call and complain. How can I possibly access my account information with all of these popups? Can you access my account for me, since your website is broken? I need to know what the address is on file.</request>

      Example 9 Output:
      <reasoning>The user requests help accessing their web account information.</reasoning>
      <intent>Support, Feedback, Complaint</intent>
      </example 9>

      Remember to always include your classification reasoning before your actual intent output. The reasoning should be enclosed in <reasoning> tags and the intent in <intent> tags. Return only the reasoning and the intent.
    PROMPT
  end
  ```
</CodeGroup>

<Note>
  Эта подсказка написана для Claude Haiku 5.5, которая здесь работает с уровнем усилий `low`. Для Claude Fable 5.1, Claude Fable 5, Claude Opus 5.5, Claude Opus 5 и Claude Sonnet 5.5 вместо этого запрашивайте намерение и краткое изложение запроса в одном предложении. См. [Храните рассуждения в блоках размышлений](https://platform.claude.com/docs/ru/build-with-claude/refusals-and-fallback#keep-reasoning-in-thinking-blocks).
</Note>

Вот ключевые компоненты этой подсказки:

* Шаблон подсказки вставляет `ticket_contents` (typescript, csharp, go, java: `ticketContents`; php: `$ticketContents`) в теги `<request>`.
* Подсказка даёт Claude чётко определённую роль системы классификации, которая тщательно анализирует содержимое тикета, чтобы определить основное намерение и потребности клиента.
* Подсказка инструктирует Claude о правильном форматировании вывода — в данном случае предоставлять рассуждения и анализ внутри тегов `<reasoning>`, а затем соответствующую метку классификации внутри тегов `<intent>`.
* Подсказка указывает допустимые категории намерений: «Support, Feedback, Complaint», «Order Tracking» и «Refund/Exchange».
* Подсказка включает несколько примеров (так называемый «few-shot prompting» — подсказки с несколькими примерами), чтобы проиллюстрировать, как должен быть отформатирован вывод, что повышает точность и согласованность.

Если Claude разделяет свой ответ на отдельные разделы с XML-тегами, вы можете использовать регулярные выражения, чтобы независимо извлекать из вывода рассуждение и намерение. Это позволяет создавать целевые следующие шаги в рабочем процессе маршрутизации тикетов, например использовать только намерение для решения о том, какому сотруднику направить тикет.

### Разверните вашу подсказку

Трудно понять, насколько хорошо работает ваша подсказка, не развернув её в тестовой производственной среде и не [проведя оценки](https://platform.claude.com/docs/ru/test-and-evaluate/develop-tests).

Создайте структуру развёртывания. Начните с определения сигнатуры метода, оборачивающего вызов Claude. Расширьте метод, который вы начали писать ранее и который принимает `ticket_contents` (typescript, csharp, go, java: `ticketContents`; php: `$ticketContents`) в качестве входных данных, чтобы теперь он возвращал рассуждение и намерение в качестве выходных данных. Если у вас есть существующая автоматизация на основе традиционного ML, вам следует придерживаться её сигнатуры метода.

<CodeGroup exclude="shell">
  <CodeGroupItem language="cURL">
    Этот рабочий процесс требует больше логики, чем одна команда оболочки. Используйте Claude SDK для его запуска.
  </CodeGroupItem>

  <CodeGroupItem language="CLI">
    Этот рабочий процесс требует больше логики, чем одна команда оболочки. Используйте Claude SDK для его запуска.
  </CodeGroupItem>

  ```python Python
  import re

  # Создаём экземпляр клиента Claude API
  client = anthropic.Anthropic()

  # Задаём модель по умолчанию
  DEFAULT_MODEL = "claude-haiku-5-5"


  def classify_support_request(ticket_contents):
      # Определяем подсказку для задачи классификации
      classification_prompt = f"""You will be acting as a customer support ticket classification system.
          […]
          ... The reasoning should be enclosed in <reasoning> tags and the intent in <intent> tags. Return only the reasoning and the intent.
          """
      # Отправляем подсказку в API для классификации запроса в поддержку.
      message = client.messages.create(
          model=DEFAULT_MODEL,
          max_tokens=2048,
          output_config={"effort": "low"},
          messages=[{"role": "user", "content": classification_prompt}],
          stream=False,
      )
      reasoning_and_intent = next(
          (block.text for block in message.content if block.type == "text"), ""
      )

      # Используем библиотеку регулярных выражений Python для извлечения `reasoning`.
      reasoning_match = re.search(
          r"<reasoning>(.*?)</reasoning>", reasoning_and_intent, re.DOTALL
      )
      reasoning = reasoning_match.group(1).strip() if reasoning_match else ""

      # Аналогично извлекаем также `intent`.
      intent_match = re.search(r"<intent>(.*?)</intent>", reasoning_and_intent, re.DOTALL)
      intent = intent_match.group(1).strip() if intent_match else ""

      return reasoning, intent
  ```

  ```typescript TypeScript
  // Создаём экземпляр клиента Claude API
  const client = new Anthropic();

  // Задаём модель по умолчанию
  const DEFAULT_MODEL = "claude-haiku-5-5";

  async function classifySupportRequest(
    ticketContents: string
  ): Promise<{ reasoning: string; intent: string }> {
    // Определяем подсказку для задачи классификации
    const classificationPrompt = `You will be acting as a customer support ticket classification system.
      […]
      ... The reasoning should be enclosed in <reasoning> tags and the intent in <intent> tags. Return only the reasoning and the intent.
      `;
    // Отправляем подсказку в API для классификации запроса в поддержку.
    const message = await client.messages.create({
      model: DEFAULT_MODEL,
      max_tokens: 2048,
      output_config: { effort: "low" },
      messages: [{ role: "user", content: classificationPrompt }]
    });
    const textBlock = message.content.find(
      (block): block is Anthropic.TextBlock => block.type === "text"
    );
    const reasoningAndIntent = textBlock?.text ?? "";

    // С помощью регулярного выражения извлекаем `reasoning`.
    const reasoningMatch = /<reasoning>(.*?)<\/reasoning>/s.exec(reasoningAndIntent);
    const reasoning = reasoningMatch?.[1].trim() ?? "";

    // Аналогично извлекаем и `intent`.
    const intentMatch = /<intent>(.*?)<\/intent>/s.exec(reasoningAndIntent);
    const intent = intentMatch?.[1].trim() ?? "";

    return { reasoning, intent };
  }
  ```

  ```csharp C#
  using System.Text.RegularExpressions;
  // ...

  // Создайте экземпляр клиента Claude API
  AnthropicClient client = new();

  // Задайте модель по умолчанию
  const Model DefaultModel = Model.ClaudeHaiku5_5;

  async Task<(string Reasoning, string Intent)> ClassifySupportRequest(string ticketContents)
  {
      // Определите подсказку для задачи классификации
      var classificationPrompt = """
          You will be acting as a customer support ticket classification system.
          […]
          ... The reasoning should be enclosed in <reasoning> tags and the intent in <intent> tags. Return only the reasoning and the intent.
          """;
      // Отправьте подсказку в API, чтобы классифицировать запрос в поддержку.
      var message = await client.Messages.Create(new MessageCreateParams
      {
          Model = DefaultModel,
          MaxTokens = 2048,
          OutputConfig = new OutputConfig { Effort = Effort.Low },
          Messages = [new() { Role = Role.User, Content = classificationPrompt }],
      });
      var reasoningAndIntent = "";
      foreach (var block in message.Content)
      {
          if (block.TryPickText(out var textBlock))
          {
              reasoningAndIntent = textBlock.Text;
              break;
          }
      }

      // Используйте регулярное выражение, чтобы извлечь `reasoning`.
      var reasoningMatch = Regex.Match(reasoningAndIntent, "<reasoning>(.*?)</reasoning>", RegexOptions.Singleline);
      var reasoning = reasoningMatch.Success ? reasoningMatch.Groups[1].Value.Trim() : "";

      // Аналогичным образом извлеките также `intent`.
      var intentMatch = Regex.Match(reasoningAndIntent, "<intent>(.*?)</intent>", RegexOptions.Singleline);
      var intent = intentMatch.Success ? intentMatch.Groups[1].Value.Trim() : "";

      return (reasoning, intent);
  }
  ```

  ```go Go
  import (
  	"context"
  	"regexp"
  	"strings"
  // ...
  )

  // Создайте экземпляр клиента Claude API
  var client = anthropic.NewClient()

  // Задайте модель по умолчанию
  const defaultModel = anthropic.ModelClaudeHaiku5_5

  func classifySupportRequest(ctx context.Context, ticketContents string) (reasoning, intent string, err error) {
  	// Определите подсказку для задачи классификации
  	classificationPrompt := `You will be acting as a customer support ticket classification system.
  		[…]
  		... The reasoning should be enclosed in <reasoning> tags and the intent in <intent> tags. Return only the reasoning and the intent.
  		`
  	// Отправьте подсказку в API, чтобы классифицировать запрос в поддержку.
  	message, err := client.Messages.New(ctx, anthropic.MessageNewParams{
  		Model:        defaultModel,
  		MaxTokens:    2048,
  		OutputConfig: anthropic.OutputConfigParam{Effort: anthropic.OutputConfigEffortLow},
  		Messages: []anthropic.MessageParam{
  			anthropic.NewUserMessage(anthropic.NewTextBlock(classificationPrompt)),
  		},
  	})
  	if err != nil {
  		return "", "", err
  	}
  	var reasoningAndIntent string
  	for _, block := range message.Content {
  		if textBlock, ok := block.AsAny().(anthropic.TextBlock); ok {
  			reasoningAndIntent = textBlock.Text
  			break
  		}
  	}

  	// Используйте регулярное выражение, чтобы извлечь `reasoning`.
  	reasoningMatch := regexp.MustCompile(`(?s)<reasoning>(.*?)</reasoning>`).FindStringSubmatch(reasoningAndIntent)
  	if reasoningMatch != nil {
  		reasoning = strings.TrimSpace(reasoningMatch[1])
  	}

  	// Аналогичным образом извлеките также `intent`.
  	intentMatch := regexp.MustCompile(`(?s)<intent>(.*?)</intent>`).FindStringSubmatch(reasoningAndIntent)
  	if intentMatch != nil {
  		intent = strings.TrimSpace(intentMatch[1])
  	}

  	return reasoning, intent, nil
  }
  ```

  ```java Java
  import java.util.regex.Matcher;
  import java.util.regex.Pattern;

  // Создайте экземпляр клиента Claude API
  final AnthropicClient client = AnthropicOkHttpClient.fromEnv();

  // Задайте модель по умолчанию
  static final Model DEFAULT_MODEL = Model.CLAUDE_HAIKU_5_5;

  record Classification(String reasoning, String intent) {}

  Classification classifySupportRequest(String ticketContents) {
      // Определите подсказку для задачи классификации
      String classificationPrompt = """
          You will be acting as a customer support ticket classification system.
          […]
          ... The reasoning should be enclosed in <reasoning> tags and the intent in <intent> tags. Return only the reasoning and the intent.
          """;
      // Отправьте подсказку в API, чтобы классифицировать запрос в поддержку.
      Message message = client.messages().create(MessageCreateParams.builder()
          .model(DEFAULT_MODEL)
          .maxTokens(2048L)
          .outputConfig(OutputConfig.builder().effort(OutputConfig.Effort.LOW).build())
          .addUserMessage(classificationPrompt)
          .build());
      String reasoningAndIntent = message.content().stream()
          .flatMap(block -> block.text().stream())
          .map(textBlock -> textBlock.text())
          .findFirst()
          .orElse("");

      // Используйте регулярное выражение, чтобы извлечь `reasoning`.
      Matcher reasoningMatch = Pattern.compile("<reasoning>(.*?)</reasoning>", Pattern.DOTALL)
          .matcher(reasoningAndIntent);
      String reasoning = reasoningMatch.find() ? reasoningMatch.group(1).strip() : "";

      // Аналогичным образом извлеките также `intent`.
      Matcher intentMatch = Pattern.compile("<intent>(.*?)</intent>", Pattern.DOTALL)
          .matcher(reasoningAndIntent);
      String intent = intentMatch.find() ? intentMatch.group(1).strip() : "";

      return new Classification(reasoning, intent);
  }
  ```

  ```php PHP
  // Создаём экземпляр клиента Claude API
  $client = new Client();

  // Задаём модель по умолчанию
  const DEFAULT_MODEL = Model::CLAUDE_HAIKU_5_5;

  /**
   * @return array{string, string} the reasoning and the intent
   */
  function classifySupportRequest(Client $client, string $ticketContents): array
  {
      // Определяем подсказку для задачи классификации
      $classificationPrompt = <<<PROMPT
          You will be acting as a customer support ticket classification system.
          […]
          ... The reasoning should be enclosed in <reasoning> tags and the intent in <intent> tags. Return only the reasoning and the intent.
          PROMPT;
      // Отправляем подсказку в API для классификации запроса в поддержку.
      $message = $client->messages->create(
          model: DEFAULT_MODEL,
          maxTokens: 2048,
          outputConfig: ['effort' => 'low'],
          messages: [['role' => 'user', 'content' => $classificationPrompt]],
      );
      $reasoningAndIntent = '';
      foreach ($message->content as $block) {
          if ($block instanceof \Anthropic\Messages\TextBlock) {
              $reasoningAndIntent = $block->text;
              break;
          }
      }

      // Извлекаем `reasoning` с помощью регулярного выражения.
      $reasoning = preg_match('/<reasoning>(.*?)<\/reasoning>/s', $reasoningAndIntent, $reasoningMatch)
          ? trim($reasoningMatch[1])
          : '';

      // Аналогично извлекаем и `intent`.
      $intent = preg_match('/<intent>(.*?)<\/intent>/s', $reasoningAndIntent, $intentMatch)
          ? trim($intentMatch[1])
          : '';

      return [$reasoning, $intent];
  }
  ```

  ```ruby Ruby
  # Создаём экземпляр клиента Claude API
  client = Anthropic::Client.new

  # Задаём модель по умолчанию
  DEFAULT_MODEL = Anthropic::Model::CLAUDE_HAIKU_5_5

  def classify_support_request(client, ticket_contents)
    # Определяем подсказку для задачи классификации
    classification_prompt = <<~PROMPT
      You will be acting as a customer support ticket classification system.
      […]
      ... The reasoning should be enclosed in <reasoning> tags and the intent in <intent> tags. Return only the reasoning and the intent.
    PROMPT
    # Отправляем подсказку в API для классификации запроса в поддержку.
    message = client.messages.create(
      model: DEFAULT_MODEL,
      max_tokens: 2048,
      output_config: { effort: "low" },
      messages: [{ role: "user", content: classification_prompt }]
    )
    reasoning_and_intent = message.content.grep(Anthropic::Models::TextBlock).first&.text || ""

    # Извлекаем `reasoning` с помощью регулярного выражения.
    reasoning = reasoning_and_intent[%r{<reasoning>(.*?)</reasoning>}m, 1]&.strip || ""

    # Аналогично извлекаем и `intent`.
    intent = reasoning_and_intent[%r{<intent>(.*?)</intent>}m, 1]&.strip || ""

    [reasoning, intent]
  end
  ```
</CodeGroup>

Этот код:

* Создаёт экземпляр клиента с использованием вашего ключа API.
* Определяет функцию `classify_support_request` (typescript, go, java, php: `classifySupportRequest`; csharp: `ClassifySupportRequest`), которая принимает строку `ticket_contents` (typescript, csharp, go, java: `ticketContents`; php: `$ticketContents`).
* Отправляет `ticket_contents` (typescript, csharp, go, java: `ticketContents`; php: `$ticketContents`) в Claude для классификации с использованием `classification_prompt` (typescript, csharp, go, java: `classificationPrompt`; php: `$classificationPrompt`).
* Возвращает рассуждение и намерение модели, извлечённые из ответа.

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

***

## Оцените вашу подсказку

Подсказки часто требуют тестирования и оптимизации, чтобы быть готовыми к производственному использованию. Чтобы определить готовность вашего решения, оцените производительность на основе критериев успеха и пороговых значений, которые вы установили ранее.

Чтобы провести оценку, вам нужны тестовые случаи, на которых её можно запустить. В оставшейся части этого руководства предполагается, что вы уже [разработали свои тестовые случаи](https://platform.claude.com/docs/ru/test-and-evaluate/develop-tests).

### Создайте функцию оценки

Пример оценки в этом руководстве измеряет производительность Claude по трём ключевым метрикам:

* Точность
* Стоимость одной классификации

Возможно, вам потребуется оценивать Claude и по другим параметрам в зависимости от того, какие факторы важны для вас.

Для этого сначала измените скрипт, добавив функцию, которая сравнивает предсказанное намерение с фактическим и вычисляет процент правильных предсказаний. Затем добавьте функциональность расчёта стоимости и измерения времени.

<CodeGroup exclude="shell">
  <CodeGroupItem language="cURL">
    Этот рабочий процесс требует больше логики, чем одна команда оболочки. Используйте Claude SDK для его запуска.
  </CodeGroupItem>

  <CodeGroupItem language="CLI">
    Этот рабочий процесс требует больше логики, чем одна команда оболочки. Используйте Claude SDK для его запуска.
  </CodeGroupItem>

  ```python Python
  import re

  # Создаём экземпляр клиента Claude API
  client = anthropic.Anthropic()

  # Задаём модель по умолчанию
  DEFAULT_MODEL = "claude-haiku-5-5"


  def classify_support_request(request, actual_intent):
      # Определяем подсказку для задачи классификации
      classification_prompt = f"""You will be acting as a customer support ticket classification system.
          […]
          ...The reasoning should be enclosed in <reasoning> tags and the intent in <intent> tags. Return only the reasoning and the intent.
          """

      message = client.messages.create(
          model=DEFAULT_MODEL,
          max_tokens=2048,
          output_config={"effort": "low"},
          messages=[{"role": "user", "content": classification_prompt}],
      )
      usage = message.usage  # Get the usage statistics for the API call for how many input and output tokens were used.
      reasoning_and_intent = next(
          (block.text for block in message.content if block.type == "text"), ""
      )

      # Используем библиотеку регулярных выражений Python для извлечения `reasoning`.
      reasoning_match = re.search(
          r"<reasoning>(.*?)</reasoning>", reasoning_and_intent, re.DOTALL
      )
      reasoning = reasoning_match.group(1).strip() if reasoning_match else ""

      # Аналогично извлекаем и `intent`.
      intent_match = re.search(r"<intent>(.*?)</intent>", reasoning_and_intent, re.DOTALL)
      intent = intent_match.group(1).strip() if intent_match else ""

      # Проверяем, верно ли предсказание модели.
      correct = actual_intent.strip() == intent.strip()

      # Возвращаем reasoning, intent, correct и usage.
      return reasoning, intent, correct, usage
  ```

  ```typescript TypeScript
  // Создаём экземпляр клиента Claude API
  const client = new Anthropic();

  // Задаём модель по умолчанию
  const DEFAULT_MODEL = "claude-haiku-5-5";

  async function classifySupportRequest(
    request: string,
    actualIntent: string
  ): Promise<{ reasoning: string; intent: string; correct: boolean; usage: Anthropic.Usage }> {
    // Определяем подсказку для задачи классификации
    const classificationPrompt = `You will be acting as a customer support ticket classification system.
      […]
      ...The reasoning should be enclosed in <reasoning> tags and the intent in <intent> tags. Return only the reasoning and the intent.
      `;

    const message = await client.messages.create({
      model: DEFAULT_MODEL,
      max_tokens: 2048,
      output_config: { effort: "low" },
      messages: [{ role: "user", content: classificationPrompt }]
    });
    // Получаем статистику использования вызова API: сколько входных и выходных токенов было израсходовано.
    const usage = message.usage;
    const textBlock = message.content.find(
      (block): block is Anthropic.TextBlock => block.type === "text"
    );
    const reasoningAndIntent = textBlock?.text ?? "";

    // Извлекаем `reasoning` с помощью регулярного выражения.
    const reasoningMatch = /<reasoning>(.*?)<\/reasoning>/s.exec(reasoningAndIntent);
    const reasoning = reasoningMatch?.[1].trim() ?? "";

    // Аналогично извлекаем и `intent`.
    const intentMatch = /<intent>(.*?)<\/intent>/s.exec(reasoningAndIntent);
    const intent = intentMatch?.[1].trim() ?? "";

    // Проверяем, верно ли предсказание модели.
    const correct = actualIntent.trim() === intent.trim();

    // Возвращаем reasoning, intent, correct и usage.
    return { reasoning, intent, correct, usage };
  }
  ```

  ```csharp C#
  using System.Text.RegularExpressions;
  // ...

  // Создаём экземпляр клиента Claude API
  AnthropicClient client = new();

  // Задаём модель по умолчанию
  const Model DefaultModel = Model.ClaudeHaiku5_5;

  async Task<(string Reasoning, string Intent, bool Correct, Usage Usage)> ClassifySupportRequest(string request, string actualIntent)
  {
      // Определяем подсказку для задачи классификации
      var classificationPrompt = """
          You will be acting as a customer support ticket classification system.
          […]
          ...The reasoning should be enclosed in <reasoning> tags and the intent in <intent> tags. Return only the reasoning and the intent.
          """;

      var message = await client.Messages.Create(new MessageCreateParams
      {
          Model = DefaultModel,
          MaxTokens = 2048,
          OutputConfig = new OutputConfig { Effort = Effort.Low },
          Messages = [new() { Role = Role.User, Content = classificationPrompt }],
      });
      // Получаем статистику использования вызова API: сколько входных и выходных токенов было израсходовано.
      var usage = message.Usage;
      var reasoningAndIntent = "";
      foreach (var block in message.Content)
      {
          if (block.TryPickText(out var textBlock))
          {
              reasoningAndIntent = textBlock.Text;
              break;
          }
      }

      // С помощью регулярного выражения извлекаем `reasoning`.
      var reasoningMatch = Regex.Match(reasoningAndIntent, "<reasoning>(.*?)</reasoning>", RegexOptions.Singleline);
      var reasoning = reasoningMatch.Success ? reasoningMatch.Groups[1].Value.Trim() : "";

      // Аналогично извлекаем и `intent`.
      var intentMatch = Regex.Match(reasoningAndIntent, "<intent>(.*?)</intent>", RegexOptions.Singleline);
      var intent = intentMatch.Success ? intentMatch.Groups[1].Value.Trim() : "";

      // Проверяем, верно ли предсказание модели.
      var correct = actualIntent.Trim() == intent.Trim();

      // Возвращаем reasoning, intent, correct и usage.
      return (reasoning, intent, correct, usage);
  }
  ```

  ```go Go
  import (
  	"context"
  	"regexp"
  	"strings"
  // ...
  )

  // Создаём экземпляр клиента Claude API
  var client = anthropic.NewClient()

  // Задаём модель по умолчанию
  const defaultModel = anthropic.ModelClaudeHaiku5_5

  func classifySupportRequest(ctx context.Context, request, actualIntent string) (reasoning, intent string, correct bool, usage anthropic.Usage, err error) {
  	// Определяем подсказку для задачи классификации
  	classificationPrompt := `You will be acting as a customer support ticket classification system.
  		[…]
  		...The reasoning should be enclosed in <reasoning> tags and the intent in <intent> tags. Return only the reasoning and the intent.
  		`
  	message, err := client.Messages.New(ctx, anthropic.MessageNewParams{
  		Model:        defaultModel,
  		MaxTokens:    2048,
  		OutputConfig: anthropic.OutputConfigParam{Effort: anthropic.OutputConfigEffortLow},
  		Messages: []anthropic.MessageParam{
  			anthropic.NewUserMessage(anthropic.NewTextBlock(classificationPrompt)),
  		},
  	})
  	if err != nil {
  		return "", "", false, anthropic.Usage{}, err
  	}
  	// Получаем статистику использования вызова API: сколько входных и выходных токенов было израсходовано.
  	usage = message.Usage
  	var reasoningAndIntent string
  	for _, block := range message.Content {
  		if textBlock, ok := block.AsAny().(anthropic.TextBlock); ok {
  			reasoningAndIntent = textBlock.Text
  			break
  		}
  	}

  	// Извлекаем `reasoning` с помощью регулярного выражения.
  	reasoningMatch := regexp.MustCompile(`(?s)<reasoning>(.*?)</reasoning>`).FindStringSubmatch(reasoningAndIntent)
  	if reasoningMatch != nil {
  		reasoning = strings.TrimSpace(reasoningMatch[1])
  	}

  	// Аналогично извлекаем и `intent`.
  	intentMatch := regexp.MustCompile(`(?s)<intent>(.*?)</intent>`).FindStringSubmatch(reasoningAndIntent)
  	if intentMatch != nil {
  		intent = strings.TrimSpace(intentMatch[1])
  	}

  	// Проверяем, верен ли прогноз модели.
  	correct = strings.TrimSpace(actualIntent) == strings.TrimSpace(intent)

  	// Возвращаем рассуждение, намерение, признак правильности и статистику использования.
  	return reasoning, intent, correct, usage, nil
  }
  ```

  ```java Java
  import java.util.regex.Matcher;
  import java.util.regex.Pattern;

  // Создаём экземпляр клиента Claude API
  final AnthropicClient client = AnthropicOkHttpClient.fromEnv();

  // Задаём модель по умолчанию
  static final Model DEFAULT_MODEL = Model.CLAUDE_HAIKU_5_5;

  record Classification(String reasoning, String intent, boolean correct, Usage usage) {}

  Classification classifySupportRequest(String request, String actualIntent) {
      // Определяем подсказку для задачи классификации
      String classificationPrompt = """
          You will be acting as a customer support ticket classification system.
          […]
          ...The reasoning should be enclosed in <reasoning> tags and the intent in <intent> tags. Return only the reasoning and the intent.
          """;

      Message message = client.messages().create(MessageCreateParams.builder()
          .model(DEFAULT_MODEL)
          .maxTokens(2048L)
          .outputConfig(OutputConfig.builder().effort(OutputConfig.Effort.LOW).build())
          .addUserMessage(classificationPrompt)
          .build());
      // Получаем статистику использования вызова API: сколько входных и выходных токенов было израсходовано.
      Usage usage = message.usage();
      String reasoningAndIntent = message.content().stream()
          .flatMap(block -> block.text().stream())
          .map(textBlock -> textBlock.text())
          .findFirst()
          .orElse("");

      // С помощью регулярного выражения извлекаем `reasoning`.
      Matcher reasoningMatch = Pattern.compile("<reasoning>(.*?)</reasoning>", Pattern.DOTALL)
          .matcher(reasoningAndIntent);
      String reasoning = reasoningMatch.find() ? reasoningMatch.group(1).strip() : "";

      // Аналогично извлекаем и `intent`.
      Matcher intentMatch = Pattern.compile("<intent>(.*?)</intent>", Pattern.DOTALL)
          .matcher(reasoningAndIntent);
      String intent = intentMatch.find() ? intentMatch.group(1).strip() : "";

      // Проверяем, верно ли предсказание модели.
      boolean correct = actualIntent.strip().equals(intent.strip());

      // Возвращаем reasoning, intent, correct и usage.
      return new Classification(reasoning, intent, correct, usage);
  }
  ```

  ```php PHP
  // Создаём экземпляр клиента Claude API
  $client = new Client();

  // Задаём модель по умолчанию
  const DEFAULT_MODEL = Model::CLAUDE_HAIKU_5_5;

  /**
   * @return array{string, string, bool, Usage} the reasoning, the intent, whether the intent is correct, and the usage
   */
  function classifySupportRequest(Client $client, string $request, string $actualIntent): array
  {
      // Определяем подсказку для задачи классификации
      $classificationPrompt = <<<PROMPT
          You will be acting as a customer support ticket classification system.
          […]
          ...The reasoning should be enclosed in <reasoning> tags and the intent in <intent> tags. Return only the reasoning and the intent.
          PROMPT;

      $message = $client->messages->create(
          model: DEFAULT_MODEL,
          maxTokens: 2048,
          outputConfig: ['effort' => 'low'],
          messages: [['role' => 'user', 'content' => $classificationPrompt]],
      );
      // Получаем статистику использования вызова API: сколько входных и выходных токенов израсходовано.
      $usage = $message->usage;
      $reasoningAndIntent = '';
      foreach ($message->content as $block) {
          if ($block instanceof \Anthropic\Messages\TextBlock) {
              $reasoningAndIntent = $block->text;
              break;
          }
      }

      // Извлекаем `reasoning` с помощью регулярного выражения.
      $reasoning = preg_match('/<reasoning>(.*?)<\/reasoning>/s', $reasoningAndIntent, $reasoningMatch)
          ? trim($reasoningMatch[1])
          : '';

      // Аналогично извлекаем `intent`.
      $intent = preg_match('/<intent>(.*?)<\/intent>/s', $reasoningAndIntent, $intentMatch)
          ? trim($intentMatch[1])
          : '';

      // Проверяем, верен ли прогноз модели.
      $correct = trim($actualIntent) === trim($intent);

      // Возвращаем рассуждение, намерение, признак правильности и статистику использования.
      return [$reasoning, $intent, $correct, $usage];
  }
  ```

  ```ruby Ruby
  # Создаём экземпляр клиента Claude API
  client = Anthropic::Client.new

  # Задаём модель по умолчанию
  DEFAULT_MODEL = Anthropic::Model::CLAUDE_HAIKU_5_5

  def classify_support_request(client, request, actual_intent)
    # Определяем подсказку для задачи классификации
    classification_prompt = <<~PROMPT
      You will be acting as a customer support ticket classification system.
      […]
      ...The reasoning should be enclosed in <reasoning> tags and the intent in <intent> tags. Return only the reasoning and the intent.
    PROMPT

    message = client.messages.create(
      model: DEFAULT_MODEL,
      max_tokens: 2048,
      output_config: { effort: "low" },
      messages: [{ role: "user", content: classification_prompt }]
    )
    # Получаем статистику использования вызова API: сколько входных и выходных токенов было израсходовано.
    usage = message.usage
    reasoning_and_intent = message.content.grep(Anthropic::Models::TextBlock).first&.text || ""

    # Извлекаем `reasoning` с помощью регулярного выражения.
    reasoning = reasoning_and_intent[%r{<reasoning>(.*?)</reasoning>}m, 1]&.strip || ""

    # Аналогично извлекаем и `intent`.
    intent = reasoning_and_intent[%r{<intent>(.*?)</intent>}m, 1]&.strip || ""

    # Проверяем, верно ли предсказание модели.
    correct = actual_intent.strip == intent.strip

    # Возвращаем reasoning, intent, correct и usage.
    [reasoning, intent, correct, usage]
  end
  ```
</CodeGroup>

Вот разбор внесённых изменений:

* Метод `classify_support_request` (typescript, go, java, php: `classifySupportRequest`; csharp: `ClassifySupportRequest`) теперь принимает `actual_intent` (typescript, csharp, go, java: `actualIntent`; php: `$actualIntent`) из тестовых случаев и сравнивает его с классификацией намерения, выполненной Claude, чтобы оценить, совпадают ли они.
* Метод извлекает статистику использования для вызова API, чтобы рассчитать стоимость на основе использованных входных и выходных токенов.

### Запустите вашу оценку

Правильная оценка требует чётких пороговых значений и ориентиров для определения того, что является хорошим результатом. Приведённый выше скрипт возвращает значения точности, времени отклика и стоимости одной классификации во время выполнения, но вам всё ещё нужны чётко установленные пороговые значения. Например:

* **Точность:** 95% (из 100 тестов)
* **Стоимость одной классификации:** снижение в среднем на 50% (по 100 тестам) по сравнению с текущим методом маршрутизации

Наличие этих пороговых значений позволяет вам быстро и легко, в масштабе и с беспристрастным эмпиризмом определить, какой метод лучше всего подходит для вас и какие изменения, возможно, потребуется внести, чтобы лучше соответствовать вашим требованиям.

***

## Повысьте производительность

В сложных сценариях может быть полезно рассмотреть дополнительные стратегии повышения производительности помимо стандартных [техник инженерии подсказок](https://platform.claude.com/docs/ru/build-with-claude/prompt-engineering/overview) и [стратегий внедрения защитных механизмов](https://platform.claude.com/docs/ru/test-and-evaluate/strengthen-guardrails/reduce-hallucinations). Вот несколько распространённых сценариев:

### Используйте таксономическую иерархию для случаев с 20+ категориями намерений

По мере роста числа классов растёт и количество необходимых примеров, что может сделать подсказку громоздкой. В качестве альтернативы вы можете рассмотреть внедрение иерархической системы классификации с использованием комбинации классификаторов.

1. Организуйте ваши намерения в виде таксономической древовидной структуры.
2. Создайте серию классификаторов на каждом уровне дерева, обеспечивая каскадный подход к маршрутизации.

Например, у вас может быть классификатор верхнего уровня, который в общих чертах распределяет тикеты по категориям «Technical Issues», «Billing Questions» и «General Inquiries». Каждая из этих категорий затем может иметь собственный подклассификатор для дальнейшего уточнения классификации.

```mermaid
---
config:
  flowchart:
    nodeSpacing: 10
    rankSpacing: 60
    padding: 8
    wrappingWidth: 300
---
flowchart LR
  accTitle: Hierarchy of ticket classifiers
  accDescr: Classifier hierarchy routing tickets to Technical Issues, Billing Questions, or General Inquiries, each with a sub-classifier
  tickets[Support Tickets] --> technical[Technical Issues]
  tickets --> billing[Billing Questions]
  tickets --> general[General Inquiries]
  technical --> software[Software Installation]
  technical --> hardware[Hardware Troubleshooting]
  technical --> network[Network Connectivity]
  technical --> technicalMore[...]
  billing --> invoice[Invoice Clarification]
  billing --> payment[Payment Processing]
  billing --> refund[Refund Requests]
  general --> product[Product Information]
  general --> order[Order Status]
  general --> partnership[Partnership Opportunities]
  general --> generalMore[...]
```

* **Плюсы — больше нюансов и выше точность:** вы можете создавать разные подсказки для каждого родительского пути, что обеспечивает более целенаправленную и контекстно-зависимую классификацию. Это может привести к повышению точности и более тонкой обработке запросов клиентов.

* **Минусы — увеличенная «latency» (задержка):** имейте в виду, что несколько классификаторов могут привести к увеличению задержки, и Anthropic рекомендует реализовывать этот подход с самой быстрой моделью — Haiku.

### Используйте векторные базы данных и поиск по сходству для обработки сильно варьирующихся тикетов

Несмотря на то что предоставление примеров — самый эффективный способ повысить производительность, если запросы в поддержку сильно варьируются, может быть трудно включить достаточное количество примеров в одну подсказку.

В этом сценарии вы можете использовать векторную базу данных для поиска по сходству в наборе примеров и извлечения наиболее релевантных примеров для данного запроса.

Этот подход, подробно описанный в [рецепте классификации](https://platform.claude.com/cookbook/capabilities-classification-guide), как было показано, повышает производительность с 71% точности до 93% точности.

### Специально учитывайте ожидаемые пограничные случаи

Вот несколько сценариев, в которых Claude может неверно классифицировать тикеты (могут быть и другие, уникальные для вашей ситуации). В этих сценариях рассмотрите возможность предоставления в подсказке явных инструкций или примеров того, как Claude должен обрабатывать пограничный случай:

<AccordionGroup>
  <Accordion title="Клиенты делают неявные запросы">
    Клиенты часто выражают потребности косвенно. Например, «Я жду свою посылку уже больше двух недель» может быть косвенным запросом о статусе заказа.

    * **Решение:** предоставьте Claude несколько реальных примеров таких запросов от клиентов вместе с указанием лежащего в их основе намерения. Вы можете получить ещё лучшие результаты, если включите обоснование классификации для особенно тонких намерений тикетов, чтобы Claude мог лучше обобщать логику на другие тикеты.
  </Accordion>

  <Accordion title="Claude отдаёт приоритет эмоциям, а не намерению">
    Когда клиенты выражают недовольство, Claude может отдавать приоритет реагированию на эмоции, а не решению лежащей в основе проблемы.

    * **Решение:** дайте Claude указания о том, когда следует отдавать приоритет настроению клиента, а когда нет. Это может быть что-то простое, например: «Игнорируй все эмоции клиента. Сосредоточься только на анализе намерения запроса клиента и на том, какую информацию клиент может запрашивать».
  </Accordion>

  <Accordion title="Несколько проблем вызывают путаницу в приоритизации">
    Когда клиенты излагают несколько проблем в одном обращении, Claude может испытывать трудности с определением основной проблемы.

    * **Решение:** уточните приоритизацию намерений, чтобы Claude мог лучше ранжировать извлечённые намерения и определять основную проблему.
  </Accordion>
</AccordionGroup>

***

## Интегрируйте Claude в ваш более широкий рабочий процесс поддержки

Правильная интеграция требует принятия некоторых решений относительно того, как ваш скрипт маршрутизации тикетов на основе Claude вписывается в архитектуру вашей более широкой системы маршрутизации тикетов. Есть два способа сделать это:

* **Push-модель:** используемая вами система тикетов поддержки (например, Zendesk) запускает ваш код, отправляя событие webhook в ваш сервис маршрутизации, который затем классифицирует намерение и маршрутизирует тикет.
  * Этот подход лучше масштабируется в веб-среде, но требует от вас предоставления публичной конечной точки.
* **Pull-модель:** ваш код запрашивает последние тикеты по заданному расписанию и маршрутизирует их в момент запроса.
  * Этот подход проще в реализации, но может приводить к ненужным вызовам системы тикетов поддержки при слишком высокой частоте запросов или быть чрезмерно медленным при слишком низкой частоте запросов.

Для любого из этих подходов вам нужно обернуть ваш скрипт в сервис. Выбор подхода зависит от того, какие API предоставляет ваша система тикетов поддержки.

***

<CardGroup cols={2}>
  <Card title="Cookbook по классификации" icon="link" href="https://platform.claude.com/cookbook/capabilities-classification-guide">
    Посетите cookbook по классификации, чтобы найти больше примеров кода и подробные рекомендации по оценке.
  </Card>

  <Card title="Claude Console" icon="link" href="https://platform.claude.com/dashboard">
    Начните создавать и оценивать ваш рабочий процесс в Claude Console.
  </Card>
</CardGroup>
