Skip to main content

Демонстрация обработки инцидентов

В этой статье представлен пример рабочего процесса обработки инцидентов с участием Ainergy, благодаря которому пользователи портала могут создать инцидент, не заполняя поля, добавив к записи только вложение – документ, изображение, аудио- или видео запись.

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

Рабочий процесс


Ознакомьтесь с рабочим процессом обработки инцидентов при помощи Ainergy, для этого:

  1. Скачайте и установите пакет [AIN]-Demo-incidents-workflow.sop. В пакете содержится запись рабочего процесса и инцидента, обработанного при помощи ИИ.

  2. Откройте запись загруженного инцидента.

  3. Нажмите Показать рабочий процесс над областью связанных списков.

Ниже представлены шаги настройки с подробным описанием:

Схема рабочего процесса

  1. Действие Begin. Инициация рабочего процесса.

  2. Действие Timer. Укажите следующие значения в полях:

    • Задать длительность = Указать
    • Продолжительность = 5 сек.
    • Вкладка Календарь
      • Задать часовой пояс = Не учитывать
      • Задать календарь = Не учитывать

  3. Действие Assign User. Установите назначенных пользователей для созданной записи инцидента. Для этого установите следующие значения:

    • Таблица = Инциденты,
    • Присвоить значения: Кому назначить = AI Assistant.

  4. Действие AI script. Добавьте скрипт, который связывает вложенный аудиофайл с ИИ.

    Скрипт действия AI script
    if (voiceAttachmentId) {
    const attach = new SimpleRecord('sys_attachment');
    attach.get(voiceAttachmentId);
    attach.record_document_id = ss.getDocIdByIds(current.sys_db_table_id, current.sys_id);
    attach.update();
    }
  5. Действие If. Настройте проверку наличия голоса на записи при помощи ИИ. Для этого установите следующие значения:

    • Таблица = Инциденты
    • Расширенная настройка = Да
    • Скрипт

    Скрипт действия If
    attach.addQuery('record_document_id', ss.getDocIdByIds(current.sys_db_table_id, current.sys_id));
    attach.addQuery('mime_content_type', 'like', 'audio');
    attach.query();

    return attach.getRowCount() > 0;
  6. Если в результате действия If в шаге 5 было распознано наличие голоса на записи, рабочий процесс переходит к действию Transcribe. Установите следующие значения:

    • Nexus = Whisper
    • Timeout = 10 мин
    • Вкладка Source
      • Advanced = true
      • Source script, который позволяет транскрибировать аудиозаписи и сохранить результаты в текстовом формате.

    Скрипт поля Source script действия Transcribe
        /* Simple Record */
    current,
    /* Simple Record */
    activity,
    /* Object */
    ai
    ) => {
    const attach = new SimpleRecord('sys_attachment');
    attach.addQuery('record_document_id', ss.getDocIdByIds(current.sys_db_table_id, current.sys_id));
    attach.addQuery('mime_content_type', 'like', 'audio');
    attach.query();
    attach.next();

  7. Если в результате действия If в шаге 5 голос на записи не был найден, рабочий процесс переходит к действию If. Также рабочий процесс переходит к этому действию после шага 6. Установите следующие значения:

    • Таблица = Инциденты
    • Расширенная настройка = yes
    • Скрипт, который позволяет проверить, подходит ли формат.

    Скрипт действия If
    const attach = new SimpleRecord('sys_attachment');
    attach.addQuery('record_document_id', ss.getDocIdByIds(current.sys_db_table_id, current.sys_id));
    attach.query();

    while (attach.next()) {
    const parts = attach.file_name.split('.');
    const ext = parts[parts.length - 1];

    if (['doc', 'docx', 'pdf', 'png', 'jpg', 'jpeg'].includes(ext)) {
    return true;
    }
    return false;
  8. Действие OCR. Система распознает файл и конвертирует его в текст. Установите следующие значения полей:

    • Nexus = OCR Doc2Text
    • Timeout = 10 мин.
    • Вкладка Source
      • Advanced = Yes
      • Source script

    Скрипт поля Source script действия OCR
        /* Simple Record */
    current,
    /* Simple Record */
    activity,
    /* Object */
    ai
    ) => {
    const attach = new SimpleRecord('sys_attachment');
    attach.addQuery('record_document_id', ss.getDocIdByIds(current.sys_db_table_id, current.sys_id));
    attach.query();

    while (attach.next()) {
    const parts = attach.file_name.split('.');
    const ext = parts[parts.length - 1];

    if (['doc', 'docx', 'pdf', 'png', 'jpg', 'jpeg'].includes(ext)) {
    return { attachment_id: attach.sys_id };
    }
    }
    })(current, activity, ai);

    • ВкладкаTarget
      • Target script
    Скрипт поля Target script действия OCR
        /* Simple Record */
    current,
    /* Simple Record */
    activity,
    /* Object */
    ai,
    /* String */
    result
    ) => {
    const description = current.description;
    if (description.length > 0 && description !== '0') {
    current.description += `\n\nИнформация из вложения:\n${result}`;
    } else {
    current.description = result;
    }
    current.update();
    })(current, activity, ai, result);
  9. Действие Chat. Добавьте текстовое описания инцидента. Установите следующие значения полей:

    • Nexus = GPT-4 Mini
    • Timeout = 5 мин.
    • Вкладка Source
      • Source script

    Скрипт поля Source script действия Chat
    ((
    /* Simple Record */
    current,
    /* Simple Record */
    activity,
    /* Object */
    ai
    ) => {
    return [
    {
    role: 'system',
    content: 'As ITSM Analytic'
    },
    {
    role: 'user',
    content: `You've received an incident. Remove unnecessary information from its description, such as random words. Your response should ONLY contain the corrected version.

    Description:
    ${current.description}`
    }
    ];
    })(current, activity, ai);
    • Вкладка Target
      • Target column = Описание
  10. Действие Chat. Определение темы инцидента по имеющемуся описанию. Установите следующие значения полей:

    • Nexus = GPT-4 Mini
    • Timeout = 1 мин.
    • Вкладка Source
      • Source script

    Скрипт поля Source script действия Chat
    ((
    /* Simple Record */
    current,
    /* Simple Record */
    activity,
    /* Object */
    ai
    ) => {
    return [
    {
    role: 'system',
    content: 'As ITSM Analytic'
    },
    {
    role: 'user',
    content: `Generate the subject by given description. Your answer should contain ONLY subject without any additions.
    Description: ${current.description}`
    }
    ];
    })(current, activity, ai);
    • Вкладка Target
      • Target column = Тема
  11. Действие Chat. Определение и установка срочности и приоритета инцидента. Установите следующие значения полей:

    • Nexus = GPT-4 Mini
    • Timeout = 2 мин.
    • Вкладка Source
      • Source script

    Скрипт поля Source script действия Chat
    ((
    /* Simple Record */
    current,
    /* Simple Record */
    activity,
    /* Object */
    ai
    ) => {
    return [
    {
    role: 'system',
    content: 'As ITSM analytic'
    },
    {
    role: 'user',
    content: `You need to determine impact and urgency by given subject and description of incident.
    Impact indicates the measure of the potential effect on the business user, service, or CI. Urgency is the measure of how long it takes until a situation has a significant impact on the business.
    Possible values: [{"title": "Low", value: 1}, {"title": "Medium", value: 2}, {"title": "High", value: 3}, {"title": "Very High", value: 4}]. If you have difficulty defining any of the fields, choose Medium.
    Your answer should contain ONLY json with chosen values. For example: {"impact":2,"urgency":3}

    Subject: ${current.subject}
    Description: ${current.description}`
    }
    ];
    })(current, activity, ai);
    • ВкладкаTarget
      • Target script
    Скрипт поля Target script действия Chat
    ((
    /* Simple Record */
    current,
    /* Simple Record */
    activity,
    /* Object */
    ai,
    /* String */
    result
    ) => {
    const impact = parseInt(result.impact) || 2;
    if (impact > 0 && impact < 5) {
    current.impact = impact;
    }

    const urgency = parseInt(result.urgency) || 2;
    if (urgency > 0 && urgency < 5) {
    current.urgency = urgency;
    }

    current.update();
    })(current, activity, ai, result);
  12. Действие Chat. Определение услуги. Определение и установка услуги. Установите следующие значения полей:

    • Nexus = GPT-4 Mini
    • Timeout = 5 мин.
    • Вкладка Source
      • Source script

    Скрипт поля Source script действия Chat
    ((
    /* Simple Record */
    current,
    /* Simple Record */
    activity,
    /* Object */
    ai
    ) => {
    const service = new SimpleRecord('sys_cmdb_ci_service');
    service.selectAttributes(['name', 'description'])
    service.query();

    const servicesList = [];
    while (service.next()) {
    servicesList.push(service.getAttributes());
    }

    return [
    {
    role: 'system',
    content: 'As ITSM analytic'
    },
    {
    role: 'user',
    content: `You need to determine service by given subject and description of incident and list of services.
    var SERVICES = ${JSON.stringify(servicesList)};
    Your answer should contain ONLY array with SINGLE sys_id of chosen service as string. For example: ["168568946321231563"]. If you can not choose the service, answer 0.

    Subject: ${current.subject}
    Description: ${current.description}`
    }
    ];
    })(current, activity, ai);
    • Вкладка Target
      • Target script
    Скрипт поля Target script действия Chat
    ((
    /* Simple Record */
    current,
    /* Simple Record */
    activity,
    /* Object */
    ai,
    /* String */
    result
    ) => {
    if (result == 0) {
    return;
    }
    current.service = result[0];
    current.update();
    })(current, activity, ai, result);
  13. Действие AI Script. Поиск записей, похожих по содержанию, в векторной БД. Добавьте скрипт в поле Script:

Скрипт действия AI Script
const collection = ss.getProperty('ain.relevant_incidents.collection_name');
ss.importIncludeScript('AIVector');
const vector = new AIVector(collection);
const relevantIncs = vector.search(`Тема: ${current.subject}
Описание: ${current.description}`, 15);

if (!Array.isArray(relevantIncs)) {
ai.relevant_incidents = '[]';
} else {
ai.relevant_incidents = JSON.stringify(relevantIncs.map(el => {
return JSON.stringify({
content: el.document,
record_id: el.metadata.record_id
})
}));
}

  1. Действие Chat. Подбор релевантных записей инцидентов из тех, которые были получены из векторной БД в шаге 13. Установите следующие значения полей:

    • Nexus = GPT-4 Mini
    • Timeout = 3 мин.
    • Вкладка Source
      • Source script

    Скрипт поля Source script действия Chat
    ((
    /* Simple Record */
    current,
    /* Simple Record */
    activity,
    /* Object */
    ai
    ) => {
    return [
    {
    role: 'system',
    content: 'As ITSM Analytic'
    },
    {
    role: 'user',
    content: `You have received an incident about which we know that its topic is a ${current.subject}, and its description is a
    ${current.description}.
    I will show you incidents presented as an array of objects, where the value of the "content" key is the accumulation of their content.
    List of incidents:
    ${JSON.parse(ai.relevant_incidents)}

    You need to select from this array the 5 most suitable incidents that can help us resolve our incident, and return an array of values for their "record_id". Answer must contains ONLY array of values.
    If there are no matching incidents, return an empty array
    For example
    ["158936517011086946", "159679715022180246", "159680246022180246", "159679715080246246", "80246715022180246"]`
    }
    ];
    })(current, activity, ai);
    • Вкладка Target
      • Target script
    Скрипт поля Target script действия Chat
    ((
    /* Simple Record */
    current,
    /* Simple Record */
    activity,
    /* Object */
    ai,
    /* String */
    result
    ) => {
    current.relevant_incidents = result.join(',');
    current.update();
    })(current, activity, ai, result);
  2. Действие END. Завершение рабочего процесса.