WO2022131954A1 - Dialogue control method and system for understanding natural language in a virtual assistant platform - Google Patents

Dialogue control method and system for understanding natural language in a virtual assistant platform Download PDF

Info

Publication number
WO2022131954A1
WO2022131954A1 PCT/RU2020/000730 RU2020000730W WO2022131954A1 WO 2022131954 A1 WO2022131954 A1 WO 2022131954A1 RU 2020000730 W RU2020000730 W RU 2020000730W WO 2022131954 A1 WO2022131954 A1 WO 2022131954A1
Authority
WO
WIPO (PCT)
Prior art keywords
user
dialog
intents
dialogue
identifier
Prior art date
Application number
PCT/RU2020/000730
Other languages
French (fr)
Russian (ru)
Inventor
Станислав Игоревич АШМАНОВ
Павел Сергеевич СУХАЧЕВ
Кирилл Федорович ЗОРКИЙ
Original Assignee
Общество с ограниченной ответственностью "Виртуальные Ассистенты"
Priority date (The priority date is an assumption and is not a legal conclusion. Google has not performed a legal analysis and makes no representation as to the accuracy of the date listed.)
Filing date
Publication date
Application filed by Общество с ограниченной ответственностью "Виртуальные Ассистенты" filed Critical Общество с ограниченной ответственностью "Виртуальные Ассистенты"
Publication of WO2022131954A1 publication Critical patent/WO2022131954A1/en

Links

Classifications

    • GPHYSICS
    • G06COMPUTING; CALCULATING OR COUNTING
    • G06FELECTRIC DIGITAL DATA PROCESSING
    • G06F3/00Input arrangements for transferring data to be processed into a form capable of being handled by the computer; Output arrangements for transferring data from processing unit to output unit, e.g. interface arrangements
    • G06F3/01Input arrangements or combined input and output arrangements for interaction between user and computer
    • G06F3/048Interaction techniques based on graphical user interfaces [GUI]
    • GPHYSICS
    • G10MUSICAL INSTRUMENTS; ACOUSTICS
    • G10LSPEECH ANALYSIS OR SYNTHESIS; SPEECH RECOGNITION; SPEECH OR VOICE PROCESSING; SPEECH OR AUDIO CODING OR DECODING
    • G10L15/00Speech recognition
    • G10L15/22Procedures used during a speech recognition process, e.g. man-machine dialogue

Definitions

  • This technical solution generally relates to the field of computing, and in particular to methods for managing dialogue and natural language understanding systems in a virtual assistant platform.
  • information dialogue systems have become widespread and are used in various areas of public life, for example, for organizing automatic knowledge testing, automated user support, for diagnosing diseases, and so on.
  • the existing information dialogue systems are designed to solve problems of a narrow profile, that is, they are able to support only a dialogue on a given topic.
  • most of them do not have the ability to form a response in natural language, give an emotional coloring to the generated response, perform any additional actions, including interacting with other information systems and subsystems.
  • the closest analogue of the claimed invention is an adaptive natural language interface and a method for receiving, interpreting and performing user input in natural language, described in patent US7216080B2 "Natural-language voice-activated personal assistant", copyright holder: INDNER ROBERT D JR Nuance Communications Inc Vlingo Corp, publ. 05/08/2007.
  • the method includes user input of a request, receiving and converting the user request into text, processing the text and generating a response in the form of an output command, converting the output command into an executive command, outputting the executive command to an additional system and/or subsystems for execution.
  • the technical problem or technical problem solved in this technical solution is the implementation of a dialogue control method and a natural language understanding system in a virtual assistant platform.
  • the technical result achieved in solving the above technical problem is to increase the accuracy of generating responses to the user by a virtual assistant through the use of machine learning algorithms.
  • the specified technical result is achieved by implementing a dialog control method executed by at least one processor, in which at least one request is received from at least one user to initiate a dialog, containing a unique virtual assistant identifier and a dialog identifier; searching the database of the virtual assistant based on the assistant identifier obtained in the previous step; searching the database for a previously initiated dialog based on the dialog identifier obtained in the previous step, and if the dialog was found, then searching the database for the active session associated with the found dialog; if the session is not found, then a new session is created in the database for the found dialog, which is determined by a new unique session identifier, an identifier of the created dialog, an empty session context; receive from the user a request in the dialog containing the identifier of the dialog with the virtual assistant received when the dialog was initiated, at least one text user message, request context; carry out detection of user intents by means of machine learning algorithms that receive a virtual assistant identifier and a text message from the user's request as input, as
  • the virtual assistant contains a unique assistant identifier and a set of named parameters.
  • the classification confidence is multiplied by the configuration parameter and rounded to the accuracy determined by the configuration parameter.
  • the weight of its match with the user's message is determined.
  • the weight is a 32-bit unsigned integer.
  • templates of the same weight are selected by selecting from the found all question templates and intents with the maximum weight, while the selected templates are removed from the search list.
  • FIG. 1 shows an implementation of a dialog control method in a virtual assistant platform.
  • FIG. 2 shows a variant of the implementation of the interaction between the user and the virtual assistant in the form of a block diagram.
  • FIG. 3 shows an example of the implementation of the context of the user's dialogue with the virtual assistant.
  • FIG. 4 shows an example of the implementation of a natural language understanding system in the virtual assistant platform.
  • the system refers to a computer system, a computer (electronic computer), CNC (numerical control), PLC (programmable logic controller), computerized control systems and any other devices capable of performing a given, well-defined sequence of operations (actions, instructions), centralized and distributed databases, smart contracts.
  • a computer electronic computer
  • CNC numerical control
  • PLC programmable logic controller
  • computerized control systems and any other devices capable of performing a given, well-defined sequence of operations (actions, instructions), centralized and distributed databases, smart contracts.
  • a command processing device means an electronic unit or an integrated circuit (microprocessor) executing machine instructions (programs), a smart contract, an Ethereum virtual machine (EVM), or the like.
  • An instruction processing device reads and executes machine instructions (programs) from one or more data storage devices.
  • the role of a storage device can be, but not limited to, hard disk drives (HDD), flash memory, ROM (read only memory), solid state drives (SSD), optical drives.
  • a program is a sequence of instructions intended to be executed by a computer control device or command processing device.
  • NLU Natural Language Understanding
  • the NLU part of this technical solution consists of components for determining the user's intentions (Intent Classification, abbr. IC) and extracting named entities (Named Entity Recognition, abbr. NER) from the text of the user's message .
  • the task of classification is a task in which there are many objects divided in some way into classes (categories). A finite set of objects is given for which it is known which classes they belong to. This set is called a sample. The class affiliation of the rest of the objects is unknown. It is required to construct an algorithm capable of classifying (categorizing) an arbitrary object from the initial set. To classify an object means to indicate the number (or name) of the class to which the given object belongs.
  • Classification of an object is the number or name of the class produced by the classification algorithm as a result of its application to this particular object.
  • the accuracy of an algorithm within a class is the proportion of objects in a classification that actually belong to a given class relative to all objects that the algorithm assigned to that class.
  • the completeness of the algorithm is the proportion of objects belonging to the class found by the classifier relative to all objects of this class in the test data set.
  • the E-measure is a common quality metric for categorization tasks and is the harmonic mean between precision and recall.
  • the search query intent is the user's intent that he puts into the query; the goal that drives a person when he enters a query into the search box.
  • Extraction of named entities the process of extracting boundaries and categorizing words or phrases in the text of user calls to the chatbot that are related in meaning to one of the predefined categories that are interesting for possible further processing by the chatbot. It is also a classification algorithm at the level of individual words and phrases in the user's remarks. For example, in the user replica “I want to transfer 1000 rubles from a savings account to a debit card”, you can select the entities “1000 rubles” - “amount of money”, “savings account” - “bank product”, “debit card” - “bank cards”.
  • a dialogue is an exchange of related messages between two participants in this process, for example, between two users.
  • the platform of virtual assistants (hereinafter referred to as the platform) is a software package that implements the functionality of conducting dialogues between users and in an automated mode.
  • Dialogues are conducted in text format in natural language between the user of the platform and dialogue robots (chat bots), called within the framework of the platform - virtual assistants (hereinafter - assistants).
  • a virtual assistant is a software agent that can perform tasks for the user based on information entered by the user, data about his location, as well as information obtained from various Internet resources.
  • Various text communication channels can serve as channels (transports) for conducting dialogues within the framework of a technical solution. (such as a widget on a website, instant messengers, etc.) connected to the platform through a server API based on the HTTP protocol.
  • Step 110 At least one dialog initiation request is received from at least one user, containing a unique virtual assistant identifier and a dialog identifier.
  • the user 210 interacts with the virtual assistant 230 through the user communication device 220, as shown in FIG. 2.
  • Each assistant 230 is defined by the following data:
  • assistant context 230 • a set of named parameters called assistant context 230.
  • All context parameters are a pair of values: a unique parameter name; about the value of the parameter, which may be different for different assistants 230 and can be changed.
  • the assistant's knowledge base (hereinafter referred to as the knowledge base) is a set of rules and dictionaries, including: o descriptions of intentions (intents) in the form of a set of examples for training a neural network and rules in a specialized dialogue description language DL, o descriptions of selected entities in in the form of a set of labeled examples for training a neural network.
  • Assistant 230 context parameters can be defined as system parameters - such parameters are used in the dialogue algorithm and directly affect the choice of priorities when generating responses to user 210 requests. [0047] This technical solution uses the following system parameters (the use of such parameters is described later in the current document):
  • the dialogue between the user 210 and the assistant 230 consists of the following steps:
  • a session is a segment of the dialogue, determined by the fact that during its duration the time between user messages 210 did not exceed a predetermined value, called the maximum allowable idle time (hereinafter referred to as the idle limit).
  • Each dialog identifier may contain dialog variables - these are variables used within the dialog. Their values persist for the duration of the dialog, but are reset when the dialog ends.
  • the criterion for terminating the dialog is the set timeout for the user's silence period.
  • the response generation instruction (line #) specifies the command to assign the variable var1 the value that was extracted from the user's replica at the stage of its processing by the rule (line $).
  • variable var1 in the response generation instruction, a check is made that the variable var1 is not empty (has a value). If the value of var1 exists at that particular moment in the dialog, then it is used to generate the response.
  • a conversation session is defined by the following data:
  • Session context parameters can be defined as dialog level parameters - such parameters retain their values between sessions, other parameters lose them, as shown in FIG. 3.
  • a session in which there is no message from user 210, or for which the time elapsed since the last message from user 210 is less than the idle limit, is called an active session.
  • Dialog initiation is the first step in a dialog that defines all the data of the dialog and forms it within the technical solution, the result of which is the provision of a dialog identifier necessary for exchanging messages with an assistant.
  • the conversation ID is transmitted if the initiated conversation is a continuation of a conversation that took place previously between the same user 210 and assistant 230.
  • Step 120 The virtual assistant database is searched based on the assistant ID obtained in the previous step.
  • the assistant 230 is searched.
  • the assistant 230 with the received identifier is searched in the database for the technical solution. If the assistant 230 is not found in the database, then the technical solution returns error information and completes the initiation.
  • Step 130 Search the database for a previously initiated conversation based on the conversation ID obtained in the previous step.
  • a dialogue search is performed. This step is only carried out if a dialog ID has been obtained. It produces search in the database of a technical solution for a previously initiated dialogue with the corresponding identifier.
  • Each user 210 has its own variables.
  • User variables 210 are variables that store values between dialogs with the same user. Variable name format: user X.
  • Virtual assistant (rule 2 worked, part of the answer under the condition on a non-empty user name variable): You are Vasya.
  • Virtual assistant (rule 2 worked, part of the answer under the condition on the non-empty variable user_name, because the value of this variable is saved between dialogs): You are Vasya.
  • the active session database associated with the found dialog is searched. If the session is not found, then a new session (automatically active) is created in the database for the found dialog, defined by the following data:
  • the technical solution returns the identifier of the found dialog and completes the initiation.
  • the next step is to create a dialogue. This step is carried out if the previous step was skipped or the target dialog was not found on it. It performs the following steps.
  • a new dialog is created in the solution database, defined by the following data:
  • the technical solution returns the identifier of the created dialog and completes the initiation.
  • Step 140 a dialog request is received from the user, containing the virtual assistant dialog identifier received when the dialog was initiated, at least one user text message, the request context.
  • the user 210 of the technical solution sends a request that contains the following data:
  • the request context • a set of named parameters, called the user request context 210 (hereinafter the request context).
  • All context parameters are a pair of values: a unique parameter name, a parameter value.
  • the task of the technical solution is to process such a request, generate the most suitable response to it and transfer it to the user.
  • a database is searched for a previously initiated dialogue with the corresponding identifier.
  • This step searches the database for the active session associated with the found dialog. If the session is not found, then a new session (automatically active) is created in the database for the found dialog, defined by the following data:
  • This step is only performed if the request context is not empty. It updates the session context according to the following algorithm:
  • the search context is then generated.
  • the search context is a set of named parameters obtained from the context of the assistant 230 and the context of the session according to the following algorithm.
  • the context of the assistant 230 is copied to the search context. All parameters whose names are not in the search context but are present in the session context are added to the search context with the corresponding values from the session context. All parameters whose names are present in both the search context and the session context, the corresponding values from the session context are assigned to the search context.
  • This step searches for all occurrences of DL dictionaries in user message 210 using the following algorithm.
  • entries are selected for which the number of words in the DL template when instead of substituting all inline dictionaries with their specific values is the maximum for this dictionary.
  • Such entries are called distinguished named dictionary entities, whose name is the same as the name of the DL dictionary in which they appear.
  • Step 150 User intents are detected using machine learning algorithms that receive a virtual assistant ID and a text message from the user's request as input, resulting in a list of intents and degrees of confidence that these intents are present in the user's message.
  • the neural network algorithms described below are used to detect possible intentions, which receive the assistant ID 230 and the text message from the user request 210 as input, and the result of their execution is a list of possible intentions and degrees of confidence that this intention is valid present in user message 210.
  • the confidence is multiplied by a special configuration parameter (Multiplier) and rounded with the accuracy determined by the configuration parameter (Accuracy). If confidence exceeds the value of the configuration parameter (Limit), then the confidence value is set to Limit. The resulting value is considered further as the certainty of this intent.
  • Multiplier a special configuration parameter
  • named entities are extracted based on the neural network.
  • the neural network algorithms described below are used to extract named entities, which receive the assistant identifier 230 and a text message from the user request 210 as input, and the result of their execution is a list of selected entities indicating their roles and the degree of confidence that they were highlighted correctly.
  • All selected entities are grouped by the name of the role assigned to them. For each name, the entity with the highest confidence score is selected. For each such entity, it is checked whether there is an entity with the same name in the set of selected entities, previously formed. If there is no such entity, then it is added to the set of selected entities.
  • Step 160 The most appropriate rule is searched for generating a response based on the user's intents obtained in the previous step.
  • the next step is to search for the most appropriate rule to generate a response.
  • the weight of its match with the user's message 210 is determined.
  • the weight is a 32-bit unsigned integer determined according to the following principles:
  • the 30th bit is always 0; for pattern questions that do not have asterisks or programming, the 30th bit is 1.
  • the 16-bit number, located from bits 14 to 29, is defined as follows: o for intents, it is equal to the number of words in the user's message multiplied by the confidence of the intent. If the value of 2 L 16-1 is exceeded, the value is set to 2 L 16-1. For template-questions, it is equal to the number of words in the template-question in expanded form (after substituting specific values for DL language elements such as dictionaries or inline dictionaries), including asterisks and choosings. If the value of 2 L 16-1 is exceeded, the value is set to 2 L 16-1.
  • An 8-bit number ranging from 0th to 13th bit, is defined as the number of pattern-conditions in the pattern. If the number of condition-patterns exceeds 2 L 8-1 , then the value is set to 2 L 8-1.
  • templates of the same weight are sampled by selecting from all found question templates and intents with the maximum weight, while the selected templates are removed from the search list. If the list is empty, then consider that an empty response is generated and skip the next two steps.
  • a list of template-answers is compiled that relates to the template-questions and intents selected in the previous step, the possibility of generating a non-empty response is checked, where an empty response is a response that does not contain any text output element (text, inline dictionary, dictionary, etc. .P.). If the list is empty, then return to the previous step.
  • the session context is then saved. For each instruction to change the session, change the context of the session in accordance with this instruction.
  • the updated session context is stored in the solution database.
  • the last step is the transmission of the response to the user 210.
  • the generated response is transmitted to the user 210.
  • the machine learning algorithms used in this technical solution will be described below.
  • Feature extraction is a type of abstraction, a dimensionality reduction process in which the original set of original variables is reduced to more manageable groups (features) for further processing, while remaining a sufficient set to accurately and completely describe the original data set.
  • Text data vectorization is a way of representing selected features through transformation into numerical vectors of some multidimensional space.
  • a function that vectorizes text data is called a vectorizer (embedder), and the resulting features corresponding to the original phrase are called a vector (sentence embedding).
  • a vectorizer embedder
  • the resulting features corresponding to the original phrase are called a vector (sentence embedding).
  • Some of the best vectorizers in terms of quality are ELMo (Embeddings from Language Models) and BERT (Bidirectional Encoder Representations from Transformers).
  • ELMo is a more productive option (capable of processing more text replicas per second), built on the basis of Bi-LSTM networks (Bidirectional Long-Short-Term-Memory, bidirectional recurrent artificial neural networks, consisting of LSTM layers, layers of long short-term memory).
  • ELMo looks at the whole sentence before assigning each word its embedding.
  • the neural network of such a vectorizer is trained (selects and optimizes the coefficients of some complex numerical function to better approximate the expected behavior of the algorithm) specifically for the task of creating such embeddings.
  • the model while training on a large set of texts, tries to predict the next word in sentences, as well as the previous one when it backwards through the sentence.
  • BERT is a heavier version (has less performance), the architecture of which consists of parts with sequence-to-sequence neural networks (models that take sequences of elements, words, letters, other signs as input, and return a different sequence of elements), based on the mechanism of attention.
  • This is a neural network-transformer, consisting of a whole stack of sequence-to-sequence network encoders. It is possible to train such a model by "masking" individual words in sentences without any markup.
  • a model that has broken several records for the success of solving a number of NLP tasks.
  • pre-trained models for different languages in the public domain including multilingual ones for solving various problems.
  • Bayesian optimization is a global optimization technique for an unknown function.
  • the Neural Network Architecture Search (NNAS) task involves automatic selection of the neural network architecture. This is the task of neural network morphism (English, "network morphism"), when the functionality of the neural network is preserved, but the architecture of the neural network is selected differently.
  • the key idea of the proposed method is to explore the architecture search space using the Bayesian Optimization (BO) algorithm.
  • Bayesian optimization consists of a 3-step loop: update, generate, and observe.
  • the cycle consists of the following steps:
  • the final optimal neural network for classifying intents is selected automatically for each data set, in the example with the considered representative data set, an architecture was obtained, consisting of a sequence of layers: the first fully connected layer, batch normalization, Dropout layer, Elu activation layer, second fully connected layer , batch normalization, Dropout layer, Elu activation layer, third fully connected layer, total - 233 neurons in fully connected layers.
  • a neural network is a hybrid of the FFNN network.
  • the output of this neural network is a probability distribution vector for each of the classes (the number of vector elements is equal to the number of classes).
  • each word is marked with a special tag - the name of the class to which the word belongs, and the position of the word in relation to the entire marked entity in the form of a prefix:
  • Bi-LSTM Encoder + CRF conditional random field
  • the output of this neural network is a probability distribution vector for each of the tags for each word (the number of vector elements is equal to the number of tags).
  • Vectorization models are not further trained within the platform, but are prepared and delivered by developers for each specific application. Such models are trained in advance without markup on large text arrays of target content. For example, large corpora of the Russian language, such as Wikipedia and news sites, expanded with logs of communication between bank customers in chats with operators for training vectorizers for banking topics. Then, in the case of the BERT model for use in classification, a one-time additional training can be performed together with the classifier on the target training data (replica-intent pairs), which significantly increases the final quality metrics.
  • Classification models for intents and entity tags are trained as part of the interaction of the operator with the platform on operator-tagged user data entered through the platform IDE interface in sections with “examples”.
  • the platform has the following adjustable learning hyperparameters that can be changed in a text configuration file: learning rate, loss function selection, optimization metrics, number of training epochs, and batch size.
  • the data is stratified divided into training and validation samples (the proportion of splitting into these parts is also set in the configuration file with training hyperparameters, and this proportion is observed for each intent and entity tag), then for the problem of classifying intents, the classes are automatically balanced by the number of examples.
  • oversampling artificial expansion of the number of examples in classes with a small number of examples
  • SMOTE Synthetic Minority Oversampling TEchnique
  • This is a special generation technique synthetic (fake) data in the embedding space received from the vectorizer (and not at the level of text generation fed into the vectorizer).
  • Requests to services must contain user replicas, and service responses are lists of most likely intents with their respective probability levels from 0.0 to 1.0, and sets of words that may be representatives of the named entities being searched for. For each such highlighted word in the response of the named entity extraction service, there is its position in the text (indentation from the beginning of the replica in characters) and a list of entities with their probability levels. The most likely intents and entities can be used in further processing of the user's response by the platform.
  • Learning services in the body of requests to start learning take paths to text files with sets of examples marked up by IDE replica operators and form model files. If necessary, training can be stopped, request the training status (find out at what stage the process is), or upon completion, use the generated model files to initialize new runtime services.
  • the present technical solution can be implemented as a computer system 400 for implementing a dialog control method and a natural language understanding system in a virtual assistant platform, which includes one or more of the following components:
  • a processing component 401 comprising at least one processor 402
  • the processing component 401 mainly manages all operations of the system 400, such as processing user data or a chat request, as well as managing the display, phone call, data transmission, camera operation, and recording operation of the mobile communication device.
  • Processing component 401 may include one or more processors 402 executing instructions for completing all or part of the steps from the above methods.
  • the processing component 401 may include one or more modules for convenient interaction between other processing modules 401 and other modules.
  • the processing component 401 may include a multimedia module for convenient, lightweight interaction between the multimedia component 405 and the processing component 401.
  • the memory 403 is configured to store various types of data to support the operation of the system 400, such as a database with user profiles. Examples of such data include instructions from any application or method, contact data, address book data, messages, images, videos, etc., all of which run on system 400.
  • Memory 403 may be implemented as any type of volatile memory, non-volatile memory, or a combination thereof, e.g., static random access memory (SRAM), Electrically Erasable Programmable Read Only Memory (EEPROM), Erasable Programmable Read Only Memory (EPROM), Programmable Read Only Memory (PROM), Read Only Memory device (ROM), magnetic memory, flash memory, magnetic disk or optical disk, and others, without being limited.
  • SRAM static random access memory
  • EEPROM Electrically Erasable Programmable Read Only Memory
  • EPROM Erasable Programmable Read Only Memory
  • PROM Programmable Read Only Memory
  • ROM Read Only Memory device
  • magnetic memory flash memory
  • flash memory magnetic disk or optical disk, and others, without being limited.
  • the media component 405 includes a screen providing an output interface between the system 400, which may be installed on a user's mobile communications device, and the user.
  • the screen may be a liquid crystal display (LCD) or a touch panel (TP). If the screen includes a touch panel, the screen may be implemented as a touch screen to receive input from a user.
  • the touchpad includes one or more touch sensors in terms of gestures, touching and sliding on the touchpad. The touch sensor can not only sense the subject's touch boundary or swipe gesture, but also determine the length of time and pressure associated with the touch and slide operation mode.
  • media component 405 includes one front camera and/or one rear camera. When the system 400 is in an operating mode, such as shooting mode or video mode, the front camera and/or rear camera can receive media data from outside. Each front camera and rear camera can be one fixed lens optics system or can have focal length or optical zoom.
  • the audio component 406 is configured to output and/or input an audio signal.
  • the audio component 406 includes one microphone (MIC) that is configured to receive an external audio signal when the system 400 is in an operating mode, such as call mode, recording mode, and speech recognition mode.
  • the received audio signal may be further stored in the memory 403 or routed through the communication component 409 .
  • the audio component 406 also includes a single speaker configured to output an audio signal.
  • An input/output (I/O) interface 407 provides an interface between the processing component 401 and any peripheral interface module.
  • the above peripheral interface module may be a keyboard, steering wheel, button, etc. These buttons may include, but are not limited to, a start button, a volume button, a home button, and a lock button.
  • the touch component 408 includes one or more sensors and is configured to provide various aspects of assessing the state of the system 400.
  • the touch component 408 can detect the on/off states of the system 400, the relative position of components, such as a display and a keypad, of a single component system 400, the presence or absence of contact between a subject and system 400, as well as the orientation or acceleration/deceleration and temperature change of system 400.
  • Sensor component 408 includes a proximity sensor configured to detect the presence of a nearby object when there is no physical contact.
  • the sensor component 408 includes an optical sensor (eg, CMOS or CCD image sensor) configured for use in rendering an application.
  • the sensor component 408 includes an acceleration sensor, a gyroscope sensor, a magnetic sensor, a pressure sensor, or a temperature sensor.
  • the communication component 409 is configured to facilitate wired or wireless communication between the system 400 and other devices.
  • System 400 may access a wireless network based on a communication standard such as WiFi, 2G, 3G, 5G, or combinations thereof.
  • the communication component 409 receives a broadcast signal or a broadcast associated therewith. information from the external broadcast control system via the broadcast channel.
  • communication component 409 includes a Near Field Communication (NFC) module to facilitate near field communications.
  • the NFC module may be based on radio frequency identification (RFID) technology, infrared data association (IrDA) technology, ultra-wideband (UWB) technology, Bluetooth (BT) technology, and other technologies.
  • RFID radio frequency identification
  • IrDA infrared data association
  • UWB ultra-wideband
  • Bluetooth Bluetooth
  • system 400 may be implemented by one or more Application-Specific Integrated Circuits (ASICs), a Digital Signal Processor (DSP), a Digital Signal Processor (DSP), a Programmable Logic Unit (PLU), a logic chip programmable in operating environment (FPGA), controller, microcontroller, microprocessor, or other electronic components, and may be configured to implement the dialog control method 100 and natural language understanding system in the virtual assistant platform.
  • ASICs Application-Specific Integrated Circuits
  • DSP Digital Signal Processor
  • DSP Digital Signal Processor
  • PLU Programmable Logic Unit
  • FPGA logic chip programmable in operating environment
  • the non-volatile computer-readable medium includes a memory 403 that includes instructions, where the instructions are executed by the processor 401 of the system 400 to implement the dialog control methods described above.
  • a non-volatile computer-readable medium can be ROM, random access memory (RAM), compact disc, magnetic tape, floppy disks, optical storage devices, and the like.
  • Computing system 400 may include a display interface that transmits graphics, text, and other data from a communications infrastructure (or framebuffer, not shown) for display on media component 405.
  • Computing system 400 further includes input devices or peripherals.
  • Peripheral devices may include one or more devices for interacting with a mobile communications device. user, such as a keyboard, microphone, wearable device, camera, one or more audio speakers, and other sensors. Peripherals may be external or internal to the user's mobile communications device.
  • the touch screen may display, typically, graphics and text, and also provides a user interface (such as, but not limited to, a graphical user interface (GUI)) through which a subject may interact with the user's mobile communications device, such as accessing and interacting with with applications running on the device.
  • GUI graphical user interface
  • All blocks used in the system can be implemented using electronic components used to create digital integrated circuits, which is obvious to a person skilled in the art. Not limited to, microcircuits can be used, the logic of which is determined during manufacture, or programmable logic integrated circuits (FPGA), the logic of which is set by programming. Programmers and debugging environments are used for programming, allowing you to set the desired structure of a digital device in the form of a circuit diagram or a program in special hardware description languages: Verilog, VHDL, AHDL, etc.
  • FPGAs programmable logic controllers
  • BMK basic matrix crystals
  • LSI custom-made large integrated circuits
  • the FPGA chip itself consists of the following components: configurable logic blocks that implement the required logic function; • programmable electronic links between configurable logic blocks;
  • Blocks can also be implemented using read-only memories.
  • aspects of the present technical solution may be implemented as a system, method, or computer program product. Accordingly, various aspects of the present technical solution may be implemented solely as hardware, as software (including application software, etc.), or as an embodiment combining software and hardware aspects, which may be generally referred to as a "module” , "system” or “architecture”. In addition, aspects of the present technical solution may take the form of a computer program product implemented on one or more computer-readable media having computer-readable program code embodied thereon.
  • the computer-readable storage medium can be, without limitation, an electronic, magnetic, optical, electromagnetic, infrared, or semiconductor system, apparatus, device, or any suitable combination thereof. More specifically, examples (non-exhaustive list) of a computer-readable storage medium include: an electrical connection using one or more wires, a portable computer diskette; hard disk, random access memory (RAM), read only memory (ROM), erasable programmable read only memory (EPROM or Flash memory), fiber optic connection, compact disc read only memory (CD-ROM), optical storage device, magnetic storage device, or any combination of the above.
  • a computer-readable storage medium can be any flexible storage medium that can contain or store a program for use by or in connection with a system, device, apparatus, or in connection with them.
  • Program code embedded in a computer-readable medium may be transmitted using any medium, including, without limitation, wireless, wired, fiber optic, infrared, and any other suitable network, or a combination of the foregoing.
  • the computer program code for performing the operations for the steps of the present technical solution may be written in any programming language or combinations of programming languages, including an object-oriented programming language such as Python, R, Java, Smalltalk, C++, and so on, and conventional procedural programming languages, such as the "C" programming language or similar programming languages.
  • the program code may be executed in whole, in part on the user's computer, or as a separate software package, in part on the user's computer and in part on a remote computer, or entirely on a remote computer.
  • the remote computer may be connected to the user's computer via any type of network, including a local area network (LAN), a wide area network (WAN), or a connection to an external computer (eg, via the Internet via ISPs).
  • LAN local area network
  • WAN wide area network
  • ISPs Internet via ISPs
  • These computer program instructions may also be stored on a computer-readable medium that can control a computer other than a programmable data processing device or other than devices that operate in a particular manner such that the instructions stored on the computer-readable medium create a device including instructions that perform the functions/actions indicated in the block diagram and/or diagram.

Abstract

The technical solution relates to dialogue control methods and systems for understanding natural language in a virtual assistant platform. The claimed method is implemented by a processor and includes: receiving from a user a dialogue initiation request containing a unique virtual assistant identifier and a dialogue identifier; conducting a database search for an assistant on the basis of the identifier received; conducting a database search for a dialogue on the basis of the dialogue identifier, wherein if a dialogue is found, a database search is conducted for an active session related to said dialogue, and if a session is not found, a new session is created in the database; receiving from the user a request in the dialogue, said request containing an identifier of the dialogue with an assistant, a text message from the user, and the context of the request; identifying the user's intents by means of machine learning algorithms which receive, on the input side, the virtual assistant identifier and the text message from the user request, resulting in the generation of a list of intents and of the degree of certainty that said intents are present in the user's message; searching for the most suitable rules for generating a response based on the user's intents.

Description

СПОСОБ УПРАВЛЕНИЯ ДИАЛОГОМ И СИСТЕМА ПОНИМАНИЯ ЕСТЕСТВЕННОГО ЯЗЫКА В ПЛАТФОРМЕ ВИРТУАЛЬНЫХ АССИСТЕНТОВ DIALOGUE CONTROL METHOD AND NATURAL LANGUAGE UNDERSTANDING SYSTEM IN VIRTUAL ASSISTANT PLATFORM
ОБЛАСТЬ ТЕХНИКИ FIELD OF TECHNOLOGY
[001] Данное техническое решение в общем относится к области вычислительной техники, а в частности к способам управления диалогом и системам понимания естественного языка в платформе виртуальных ассистентов. [001] This technical solution generally relates to the field of computing, and in particular to methods for managing dialogue and natural language understanding systems in a virtual assistant platform.
УРОВЕНЬ ТЕХНИКИ BACKGROUND OF THE INVENTION
[002] На сегодняшний день информационные диалоговые системы получили широкое распространение и используются в различных областях общественной жизни, например для организации автоматической проверки знаний, автоматизированной службы поддержки пользователей, для диагностики заболеваний и прочее. Однако существующие информационные диалоговые системы предназначены для решения задач узкого профиля, то есть они способны поддерживать только диалог на заданную тему. Кроме того, большинство из них не имеет возможности формировать ответ на естественном языке, придавать эмоциональную окраску формируемому ответу, выполнять какие-либо дополнительные действия, в том числе взаимодействовать с другими информационными системами и подсистемами. Наличие таких возможностей позволило бы выполнять не только двухсторонний обмен информацией, инструкциями и командами между пользователем и системой, но и вести полноценный диалог, создавая у пользователя впечатление общения с живым собеседником, а также решать поставленные пользователем задачи гораздо эффективнее. Поэтому на данный момент остается актуальной разработка такого способа коммуникации пользователя с информационной диалоговой системой, который расширил бы возможности взаимодействия пользователя с информационной диалоговой системой. [002] To date, information dialogue systems have become widespread and are used in various areas of public life, for example, for organizing automatic knowledge testing, automated user support, for diagnosing diseases, and so on. However, the existing information dialogue systems are designed to solve problems of a narrow profile, that is, they are able to support only a dialogue on a given topic. In addition, most of them do not have the ability to form a response in natural language, give an emotional coloring to the generated response, perform any additional actions, including interacting with other information systems and subsystems. The presence of such capabilities would allow not only a two-way exchange of information, instructions and commands between the user and the system, but also conduct a full-fledged dialogue, giving the user the impression of communicating with a live interlocutor, and also solve the tasks set by the user much more efficiently. Therefore, at the moment, it remains relevant to develop such a method of user communication with an information dialogue system that would expand the possibilities of user interaction with an information dialogue system.
[003] Ближайшим аналогом заявляемого изобретения является адаптивный естественно-языковой интерфейс и способ получения, интерпретации и выполнения пользовательского ввода на естественном языке, описанные в патенте US7216080B2 «Natural-language voice-activated personal assistant», правообладатель: INDNER ROBERT D JR Nuance Communications Inc Vlingo Corp, опубл. 08.05.2007. Способ включает ввод пользователем запроса, прием и преобразование запроса пользователя в текст, обработку текста и формирование ответа в виде выходной команды, преобразование выходной команды в исполнительную, выведение исполнительной команды в дополнительную систему и/или подсистемы для исполнения. [003] The closest analogue of the claimed invention is an adaptive natural language interface and a method for receiving, interpreting and performing user input in natural language, described in patent US7216080B2 "Natural-language voice-activated personal assistant", copyright holder: INDNER ROBERT D JR Nuance Communications Inc Vlingo Corp, publ. 05/08/2007. The method includes user input of a request, receiving and converting the user request into text, processing the text and generating a response in the form of an output command, converting the output command into an executive command, outputting the executive command to an additional system and/or subsystems for execution.
СУЩНОСТЬ ИЗОБРЕТЕНИЯ SUMMARY OF THE INVENTION
[004] Технической проблемой или технической задачей, решаемой в данном техническом решении, является осуществление способа управления диалогом и система понимания естественного языка в платформе виртуальных ассистентов. [004] The technical problem or technical problem solved in this technical solution is the implementation of a dialogue control method and a natural language understanding system in a virtual assistant platform.
[005] Техническим результатом, достигаемым при решении вышеуказанной технической проблемы, является повышение точности формирования ответов пользователю виртуальным ассистентом посредством применения алгоритмов машинного обучения. [005] The technical result achieved in solving the above technical problem is to increase the accuracy of generating responses to the user by a virtual assistant through the use of machine learning algorithms.
[006] Указанный технический результат достигается посредством реализации способа управления диалогом, выполняемый по меньшей мере одним процессором, в котором получают от по меньшей мере одного пользователя по меньшей мере один запрос на инициацию диалога, содержащий уникальный идентификатор виртуального ассистента и идентификатор диалога; осуществляют поиск в базе данных виртуального ассистента на основании полученного на предыдущем шаге идентификатора ассистента; осуществляют поиск в базе данных ранее инициированного диалога на основании идентификатора диалога, полученного на предыдущем шаге, причем если диалог был найден, то выполняют поиск в базе данных активной сессии, связанной с найденным диалогом; если сессия не обнаружена, то в базе данных для найденного диалога создают новую сессию, которая определяется новым уникальным идентификатором сессии, идентификатором созданного диалога, пустым контекстом сессии; получают от пользователя запрос в диалоге, содержащий идентификатор диалога с виртуальным ассистентом, полученный при инициации диалога, по меньшей мере одно текстовое сообщение пользователя, контекст запроса; осуществляют обнаружение интентов пользователя посредством алгоритмов машинного обучения, которые получают на вход идентификатор виртуального ассистента и текстовое сообщение из запроса пользователя, в результате чего формируют список интентов и степени уверенности в том, что данные интенты присутствуют в сообщении пользователя; выполняют поиск наиболее подходящего правила для формирования ответа на основании интентов пользователя, полученных на предыдущем шаге. [006] The specified technical result is achieved by implementing a dialog control method executed by at least one processor, in which at least one request is received from at least one user to initiate a dialog, containing a unique virtual assistant identifier and a dialog identifier; searching the database of the virtual assistant based on the assistant identifier obtained in the previous step; searching the database for a previously initiated dialog based on the dialog identifier obtained in the previous step, and if the dialog was found, then searching the database for the active session associated with the found dialog; if the session is not found, then a new session is created in the database for the found dialog, which is determined by a new unique session identifier, an identifier of the created dialog, an empty session context; receive from the user a request in the dialog containing the identifier of the dialog with the virtual assistant received when the dialog was initiated, at least one text user message, request context; carry out detection of user intents by means of machine learning algorithms that receive a virtual assistant identifier and a text message from the user's request as input, as a result of which a list of intents and degrees of confidence that these intents are present in the user's message are formed; searching for the most appropriate rule for generating a response based on the user's intents obtained in the previous step.
[007] В некоторых вариантах реализации технического решения виртуальный ассистент содержит уникальный идентификатор ассистента и набор именованных параметров. [007] In some implementations of the technical solution, the virtual assistant contains a unique assistant identifier and a set of named parameters.
[008] В некоторых вариантах реализации технического решения при получении запроса от пользователя в диалоге осуществляют поиск вхождений словарей языка DL в сообщении пользователя по следующему способу: [008] In some embodiments of a technical solution, upon receiving a request from a user in a dialog, they search for occurrences of DL dictionaries in the user's message in the following way:
• определяют все вхождения текстовых элементов строк словарей DL с использованием заранее подготовленного префиксного дерева; • determine all occurrences of text elements of strings of DL dictionaries using a previously prepared prefix tree;
• выбирают все строки словарей, которые отвечают следующим эвристикам: a. в сообщении пользователя есть все текстовые элементы входящие в строку словаря DL, b. существует порядок найденных вхождений текстовых элементов, соответствующий строке словаря DL, о если нет текстовых элементов, располагающихся в самом начале сообщения пользователя, то в строке словаря DL в начале должна стоять звездочка или суперзвездочка, о если нет текстовых элементов, располагающихся в самом конце сообщения пользователя, то в строке словаря DL в конце должна стоять звездочка или суперзвездочка. • select all dictionary strings that match the following heuristics: a. the user's message contains all the text elements included in the DL dictionary string, b. there is an order of found occurrences of text elements corresponding to the DL dictionary string, o if there are no text elements located at the very beginning of the user's message, then an asterisk or superstar must be at the beginning in the DL dictionary string, o if there are no text elements located at the very end of the user's message , then the string in the DL dictionary must end with an asterisk or a superstar.
[009] В некоторых вариантах реализации технического решения при обнаружении интентов, если их уверенность классификации ниже конфигурационного параметра, они отбрасываются. [0010] В некоторых вариантах реализации технического решения для каждого интента уверенность классификации умножается на конфигурационный параметр и округляется с точностью, определяемой конфигурационным параметром. [009] In some implementations of the technical solution, when intents are detected, if their classification confidence is below the configuration parameter, they are discarded. [0010] In some embodiments of the technical solution for each intent, the classification confidence is multiplied by the configuration parameter and rounded to the accuracy determined by the configuration parameter.
[0011] В некоторых вариантах реализации технического решения после обнаружения интентов они группируются по имени роли, присвоенной им. [0011] In some embodiments of the technical solution, after the discovery of intents, they are grouped by the name of the role assigned to them.
[0012] В некоторых вариантах реализации технического решения при осуществлении поиска подходящего правила для формирования ответа для каждого шаблон-вопроса и интента, входящего в шаблон языка DL, определяется вес его совпадения с сообщением пользователя. [0012] In some embodiments of a technical solution, when searching for a suitable rule for generating an answer for each template-question and intent included in the template of the DL language, the weight of its match with the user's message is determined.
[0013] В некоторых вариантах реализации технического решения весом является 32х битовое беззнаковое целое число. [0013] In some implementations of the technical solution, the weight is a 32-bit unsigned integer.
[0014] В некоторых вариантах реализации технического решения осуществляют выборку шаблонов одинакового веса посредством выбора из найденных всех шаблонов-вопросов и интентов с максимальным весом, при этом выбранные шаблоны удаляются из списка поиска. [0014] In some implementations of the technical solution, templates of the same weight are selected by selecting from the found all question templates and intents with the maximum weight, while the selected templates are removed from the search list.
[0015] В некоторых вариантах реализации технического решения при осуществлении поиска подходящего правила для формирования ответа[0015] In some embodiments of a technical solution, when searching for a suitable rule to generate a response
- составляют список шаблон-ответов, относящихся к выбранным шаблон-вопросам и интентам; - make a list of template-answers related to the selected template-questions and intents;
■ проверяют возможность генерации непустого ответа, где пустым ответом считается ответ, не содержащий ни одного текстового элемента вывода; ■ check the possibility of generating a non-empty response, where an empty response is a response that does not contain any text output element;
■ осуществляют рандомизацию, причем выбирают случайно один из отобранных ранее шаблон-ответов и определяют его ответом на сообщение пользователя; ■ carry out randomization, and randomly choose one of the previously selected template-responses and determine it as a response to the user's message;
■ формируют ответ по выбранному правилу, причем для выбранного шаблон-ответа обрабатываются все функциональные элементы языка DL в соответствии с их описанием; ■ form a response according to the selected rule, and for the selected response template, all functional elements of the DL language are processed in accordance with their description;
■ записывают журнал диалога и сформированный ответ записывается в базу данных. ■ write the conversation log and the generated response is written to the database.
КРАТКОЕ ОПИСАНИЕ ЧЕРТЕЖЕЙ [0016] Признаки и преимущества настоящего технического решения станут очевидными из приведенного ниже подробного описания и прилагаемых чертежей, на которых: BRIEF DESCRIPTION OF THE DRAWINGS [0016] The features and advantages of the present technical solution will become apparent from the following detailed description and the accompanying drawings, in which:
[0017] На Фиг. 1 показан вариант реализации способа управления диалогом в платформе виртуальных ассистентов. [0017] In FIG. 1 shows an implementation of a dialog control method in a virtual assistant platform.
[0018] На Фиг. 2 показан вариант реализации взаимодействия пользователя и виртуального ассистента в виде блок-схемы. [0018] In FIG. 2 shows a variant of the implementation of the interaction between the user and the virtual assistant in the form of a block diagram.
[0019] На Фиг. 3 показан пример реализации контекста диалога пользователя с виртуальным ассистентом. [0019] In FIG. 3 shows an example of the implementation of the context of the user's dialogue with the virtual assistant.
[0020] На Фиг. 4 показан пример реализации системы понимания естественного языка в платформе виртуальных ассистентов. [0020] In FIG. 4 shows an example of the implementation of a natural language understanding system in the virtual assistant platform.
ПОДРОБНОЕ ОПИСАНИЕ ИЗОБРЕТЕНИЯ DETAILED DESCRIPTION OF THE INVENTION
[0021] Ниже будут подробно рассмотрены термины и их определения, используемые в описании технического решения. [0021] Below will be discussed in detail the terms and their definitions used in the description of the technical solution.
[0022] В данном изобретении под системой подразумевается компьютерная система, ЭВМ (электронно-вычислительная машина), ЧПУ (числовое программное управление), ПЛК (программируемый логический контроллер), компьютеризированные системы управления и любые другие устройства, способные выполнять заданную, четко определенную последовательность операций (действий, инструкций), централизованные и распределенные базы данных, смарт-контракты. [0022] In this invention, the system refers to a computer system, a computer (electronic computer), CNC (numerical control), PLC (programmable logic controller), computerized control systems and any other devices capable of performing a given, well-defined sequence of operations (actions, instructions), centralized and distributed databases, smart contracts.
[0023] Под устройством обработки команд подразумевается электронный блок либо интегральная схема (микропроцессор), исполняющая машинные инструкции (программы), смарт-контракт, виртуальная машина Ethereum (EVM) или подобное. Устройство обработки команд считывает и выполняет машинные инструкции (программы) с одного или более устройства хранения данных. В роли устройства хранения данных могут выступать, но, не ограничиваясь, жесткие диски (HDD), флеш-память, ПЗУ (постоянное запоминающее устройство), твердотельные накопители (SSD), оптические приводы. [0024] Программа - последовательность инструкций, предназначенных для исполнения устройством управления вычислительной машины или устройством обработки команд. [0023] A command processing device means an electronic unit or an integrated circuit (microprocessor) executing machine instructions (programs), a smart contract, an Ethereum virtual machine (EVM), or the like. An instruction processing device reads and executes machine instructions (programs) from one or more data storage devices. The role of a storage device can be, but not limited to, hard disk drives (HDD), flash memory, ROM (read only memory), solid state drives (SSD), optical drives. [0024] A program is a sequence of instructions intended to be executed by a computer control device or command processing device.
[0025] NLU (англ. «Natural Language Understanding») - понимание естественного языка или интерпретация естественного языка [0025] NLU (Natural Language Understanding) - natural language understanding or natural language interpretation
[0026] NLU часть данного технического решения состоит из компонент определения намерений пользователя (классификация интентов, англ. «Intent Classification», сокр. IC) и извлечения именованных сущностей (англ. «Named Entity Recognition», сокр. NER) из текста сообщения пользователя. [0027] Задача классификации (категоризации) — задача, в которой имеется множество объектов, разделённых некоторым образом на классы (категории). Задано конечное множество объектов, для которых известно, к каким классам они относятся. Это множество называется выборкой. Классовая принадлежность остальных объектов неизвестна. Требуется построить алгоритм, способный классифицировать (категоризировать) произвольный объект из исходного множества. Классифицировать объект — значит, указать номер (или наименование) класса, к которому относится данный объект. [0026] The NLU part of this technical solution consists of components for determining the user's intentions (Intent Classification, abbr. IC) and extracting named entities (Named Entity Recognition, abbr. NER) from the text of the user's message . [0027] The task of classification (categorization) is a task in which there are many objects divided in some way into classes (categories). A finite set of objects is given for which it is known which classes they belong to. This set is called a sample. The class affiliation of the rest of the objects is unknown. It is required to construct an algorithm capable of classifying (categorizing) an arbitrary object from the initial set. To classify an object means to indicate the number (or name) of the class to which the given object belongs.
[0028] Классификация объекта — номер или наименование класса, выдаваемый алгоритмом классификации в результате его применения к данному конкретному объекту. [0028] Classification of an object is the number or name of the class produced by the classification algorithm as a result of its application to this particular object.
[0029] Точность (англ, «precision») и полнота (англ, «recall») являются метриками, которые используются при оценке большей части алгоритмов извлечения информации. [0029] Accuracy (eng, "precision") and recall (eng, "recall") are metrics that are used in evaluating most of the information extraction algorithms.
[0030] Точность алгоритма в пределах класса - это доля объектов классификации, действительно принадлежащих данному классу, относительно всех объектов, которые алгоритм отнес к этому классу. Полнота алгоритма - это доля найденных классификатором объектов, принадлежащих классу, относительно всех объектов этого класса в тестовом наборе данных. [0030] The accuracy of an algorithm within a class is the proportion of objects in a classification that actually belong to a given class relative to all objects that the algorithm assigned to that class. The completeness of the algorithm is the proportion of objects belonging to the class found by the classifier relative to all objects of this class in the test data set.
[0031] Е-мера является общепринятой метрикой качества для задач категоризации и представляет собой гармоническое среднее между точностью и полнотой. [0032] Определение намерения пользователя - категоризация того, что пользователь хотел узнать, когда вводил текст запроса в обращении к чат- боту. Категоризация реплик происходит по заранее заданному списку возможных намерений пользователей. Является алгоритмом классификации на уровне коротких текстов (реплик пользователя). Например, пользовательская реплика «хочу открыть вклад в вашем банке» может быть категоризирована как намерение «открытие вкладов». [0031] The E-measure is a common quality metric for categorization tasks and is the harmonic mean between precision and recall. [0032] Determination of user intent - categorization of what the user wanted to know when he entered the query text in a call to the chatbot. Replicas are categorized according to a predefined list of possible user intentions. It is a classification algorithm at the level of short texts (user replies). For example, the user response "I want to open a deposit in your bank" can be categorized as the intention "opening deposits".
[0033] Интент поискового запроса — это намерение пользователя, которое он вкладывает в запрос; та цель, которая движет человеком, когда он вводит запрос в поисковую строку. [0033] The search query intent is the user's intent that he puts into the query; the goal that drives a person when he enters a query into the search box.
[0034] Извлечение именованных сущностей - процесс выделения границ и категоризации в тексте пользовательских обращений к чат-боту слов или словосочетаний, относящихся по смыслу к одной из заданных заранее категорий, интересных для возможной дальнейшей обработки чат-ботом. Является также алгоритмом классификации на уровне отдельных слов и словосочетаний в репликах пользователя. Например, в пользовательской реплике «хочу перевести 1000 рублей со сберегательного счёта на дебетовую карту» можно выделить сущности «1000 рублей» - «денежная сумма», «сберегательного счёта» - «продукт банка», «дебетовую карту» - «банковские карты». [0034] Extraction of named entities - the process of extracting boundaries and categorizing words or phrases in the text of user calls to the chatbot that are related in meaning to one of the predefined categories that are interesting for possible further processing by the chatbot. It is also a classification algorithm at the level of individual words and phrases in the user's remarks. For example, in the user replica “I want to transfer 1000 rubles from a savings account to a debit card”, you can select the entities “1000 rubles” - “amount of money”, “savings account” - “bank product”, “debit card” - “bank cards”.
[0035] Диалогом называется обмен связанными сообщениями между двумя участниками этого процесса, например, между двумя пользователями. [0035] A dialogue is an exchange of related messages between two participants in this process, for example, between two users.
[0036] Платформа виртуальных ассистентов (далее - платформа) - это программный комплекс, реализующий функционал ведения диалогов между пользователями и в автоматизированном режиме. [0036] The platform of virtual assistants (hereinafter referred to as the platform) is a software package that implements the functionality of conducting dialogues between users and in an automated mode.
[0037] Диалоги ведутся в текстовом формате на естественном языке между пользователем платформы и диалоговыми роботами (чат-ботами), называемыми в рамках платформы - виртуальными ассистентами (далее - ассистенты). Виртуальный ассистент — программный агент, который может выполнять задачи для пользователя на основе информации, введенной пользователем, данных о его местонахождении, а также информации, полученной из различных интернет-ресурсов. [0037] Dialogues are conducted in text format in natural language between the user of the platform and dialogue robots (chat bots), called within the framework of the platform - virtual assistants (hereinafter - assistants). A virtual assistant is a software agent that can perform tasks for the user based on information entered by the user, data about his location, as well as information obtained from various Internet resources.
[0038] Каналами (транспортами) для ведения диалогов в рамках технического решения могут служить различные текстовые каналы связи (такие как виджет на сайте, мессенджеры и т.п.), подключенные к платформе через серверное API на основе протокола HTTP. [0038] Various text communication channels can serve as channels (transports) for conducting dialogues within the framework of a technical solution. (such as a widget on a website, instant messengers, etc.) connected to the platform through a server API based on the HTTP protocol.
[0039] Данное техническое решение предоставляет возможность одновременного ведения множества диалогов между различными пользователями и различными ассистентами. [0039] This technical solution allows for the simultaneous conduct of multiple dialogues between different users and different assistants.
[0040] Ниже будет подробно раскрыт способ управления диалогом в платформе виртуальных ассистентов, показанный в виде последовательности шагов. [0040] Below, a method for controlling a dialogue in a virtual assistant platform will be described in detail, shown as a sequence of steps.
[0041] Шаг 110: получают от по меньшей мере одного пользователя по меньшей мере один запрос на инициацию диалога, содержащий уникальный идентификатора виртуального ассистента и идентификатор диалога. [0041] Step 110: At least one dialog initiation request is received from at least one user, containing a unique virtual assistant identifier and a dialog identifier.
[0042] В данном техническом решении пользователь 210 осуществляет взаимодействие с виртуальным ассистентом 230 посредством устройства связи пользователя 220, как это показано на Фиг. 2. [0042] In this technical solution, the user 210 interacts with the virtual assistant 230 through the user communication device 220, as shown in FIG. 2.
[0043] Каждый ассистент 230 определяется следующими данными: [0043] Each assistant 230 is defined by the following data:
• уникальным идентификатором ассистента 230, • a unique assistant identifier 230,
• набором именованных параметров, называемым контекстом ассистента 230. • a set of named parameters called assistant context 230.
[0044] Все параметры контекста представляют из себя пару значений: о уникальное имя параметра; о значение параметра, которое может быть различным для разных ассистентов 230 и может быть изменено. [0044] All context parameters are a pair of values: a unique parameter name; about the value of the parameter, which may be different for different assistants 230 and can be changed.
[0045] База знаний ассистента (далее - база знаний) - набор правил и словарей, включающих в себя: о описания намерений (интентов) в виде набора примеров для обучения нейронной сети и правил на специализированном языке описания диалога DL, о описания выделяемых сущностей в виде набор размеченных примеров для обучения нейронной сети. [0045] The assistant's knowledge base (hereinafter referred to as the knowledge base) is a set of rules and dictionaries, including: o descriptions of intentions (intents) in the form of a set of examples for training a neural network and rules in a specialized dialogue description language DL, o descriptions of selected entities in in the form of a set of labeled examples for training a neural network.
[0046] Параметры контекста ассистента 230 могут быть определены как системными - такие параметры используются в алгоритме ведения диалога и прямым образом влияют на выбор приоритетов при генерации ответов на запросы пользователя 210. [0047] Данное техническое решение использует следующие системные параметры (использование таких параметров описано далее в текущем документе): [0046] Assistant 230 context parameters can be defined as system parameters - such parameters are used in the dialogue algorithm and directly affect the choice of priorities when generating responses to user 210 requests. [0047] This technical solution uses the following system parameters (the use of such parameters is described later in the current document):
• that_anchor. • that_anchor.
[0048] Все данные виртуальных ассистентов 230 хранятся в базе данных технического решения. [0048] All data of the virtual assistants 230 is stored in the solution database.
[0049] Диалог пользователя 210 с ассистентом 230 состоит из следующих этапов: [0049] The dialogue between the user 210 and the assistant 230 consists of the following steps:
1. Инициация диалога между пользователем 210 и ассистентом 230,1. Initiation of a dialogue between the user 210 and the assistant 230,
2. Обмен сообщениями в текстовой форме между участниками диалога, и определяется следующими данными: 2. The exchange of messages in text form between the participants in the dialogue, and is determined by the following data:
• уникальным идентификатором диалога, определенным на этапе инициации диалога. • a unique dialog identifier defined at the dialog initiation stage.
• уникальным идентификатором ассистента 230, с которым ведется диалог. • the unique identifier of the assistant 230 with whom the dialogue is being conducted.
• уникальным идентификатором пользователя 210, ведущего диалог с ассистентом 230. • a unique identifier of the user 210 conducting a dialogue with the assistant 230.
• уникальным идентификатором сессии, где сессия — это отрезок диалога, определяемый тем, что на его протяжении время между сообщениями пользователя 210 не превышало заранее заданное значение, называемое - максимально допустимое время бездействия (далее - предел бездействия). • a unique session identifier, where a session is a segment of the dialogue, determined by the fact that during its duration the time between user messages 210 did not exceed a predetermined value, called the maximum allowable idle time (hereinafter referred to as the idle limit).
[0050] Каждый идентификатор диалога может содержать переменные диалога - это переменные, используемые в рамках диалога. Их значения сохраняются в течение диалога, но сбрасываются, когда диалог завершается. Критерием завершения диалога является установленный таймаут для периода молчания пользователя. [0050] Each dialog identifier may contain dialog variables - these are variables used within the dialog. Their values persist for the duration of the dialog, but are reset when the dialog ends. The criterion for terminating the dialog is the set timeout for the user's silence period.
[0051] Примеры правил показаны ниже: [0051] Examples of rules are shown below:
[0052] //правило 1 $ меня зовут [-**-] [0052] //rule 1 $ my name is [-**-]
# Приятно познакомиться, [&1]. [%var1="[&1]"] # Nice to meet you, [&1]. [%var1="[&1]"]
//правило 2 $ * как * меня * зовут * //rule 2 $*what is*my*name*
#[if(%var1 )]{Вы [%уаг1].}[е1зе]{Я не знаю, как Вас зовут.} #[if(%var1 )]{You are [%var1].}[e1se]{I don't know your name.}
[0053] В правиле 1 в инструкции по генерации ответа (строка #) указана команда присвоить переменной var1 значение, которое было выделено из реплики пользователя на этапе ее обработки правилом (строка $). [0053] In rule 1, the response generation instruction (line #) specifies the command to assign the variable var1 the value that was extracted from the user's replica at the stage of its processing by the rule (line $).
[0054] В правиле 2 в инструкции по генерации ответа производится проверка того, что переменная var1 не пустая (имеет значение). Если значение переменной var1 существует в этот конкретный момент диалога, то оно используется для генерации ответа. [0054] In rule 2, in the response generation instruction, a check is made that the variable var1 is not empty (has a value). If the value of var1 exists at that particular moment in the dialog, then it is used to generate the response.
[0055] Пример диалога с использованием данных правил: [0055] An example of a dialogue using these rules:
• Пользователь: меня зовут Вася • User: my name is Vasya
• Бот (сработало правило 1 ): приятно познакомиться, Вася. • Bot (rule 1 worked): Nice to meet you, Vasya.
• Пользователь: как меня зовут? • User: what is my name?
• Бот (сработало правило 2): Вы Вася. • Bot (rule 2 worked): You are Vasya.
[0056] Диалог завершился. Если через какое-то время тот же пользователь 210 начнет новый диалог, то значения переменных будут «сброшены», и бот не будет «помнить» имя пользователя: [0056] The dialogue has ended. If after some time the same user 210 starts a new dialog, then the values of the variables will be "reset", and the bot will not "remember" the username:
• Пользователь: как меня зовут? • User: what is my name?
• Бот (сработало правило 2, часть ответа в else, поскольку значение переменной var1 сбросилось по окончании прошлого диалога): Я не знаю, как Вас зовут. • Bot (rule 2 worked, part of the answer in else, because the value of the var1 variable was reset at the end of the last dialogue): I don't know your name.
[0057] Сессия диалога определяется следующими данными: [0057] A conversation session is defined by the following data:
• уникальным идентификатором сессии. • a unique session identifier.
• уникальным идентификатором диалога, к которому относится сессия. • a unique identifier for the dialog to which the session belongs.
• набором именованных параметров, называемым контекстом сессии. [0058] Все параметры контекста представляют из себя пару значений: о уникальное имя параметра. о значение параметра, которое может быть изменено в ходе диалога. [0059] Параметры контекста сессии могут быть определены как параметры уровня диалога - такие параметры сохраняют свои значения между сессиями, остальные параметры их теряют, как показано на Фиг. 3. • a set of named parameters, called the session context. [0058] All context parameters are a pair of values: a unique parameter name. o the value of the parameter, which can be changed during the dialog. [0059] Session context parameters can be defined as dialog level parameters - such parameters retain their values between sessions, other parameters lose them, as shown in FIG. 3.
[0060] Сессия, в рамках которой нет ни одного сообщения пользователя 210, либо для которой время прошедшее с последнего сообщения пользователя 210 меньше предела бездействия, называется активной сессией. [0060] A session in which there is no message from user 210, or for which the time elapsed since the last message from user 210 is less than the idle limit, is called an active session.
[0061] Все данные диалогов и сессий хранятся в базе данных технического решения. [0061] All dialogue and session data is stored in the solution database.
[0062] Инициация диалога — это первый этап в диалоге, определяющий все данные диалога и формирующий его внутри технического решения, результатом которого является предоставление идентификатора диалога, необходимого для обмена сообщениями с ассистентом. [0062] Dialog initiation is the first step in a dialog that defines all the data of the dialog and forms it within the technical solution, the result of which is the provision of a dialog identifier necessary for exchanging messages with an assistant.
[0063] Для инициации диалога необходимы следующие параметры, принимаемые в решении: [0063] To initiate a dialogue, the following parameters are required, accepted in the decision:
• идентификатор ассистента (обязательный параметр), • assistant ID (mandatory parameter),
• идентификатор диалога. • dialog ID.
[0064] Идентификатор диалога передается, если инициируемый диалог является продолжением диалога, имевшего место быть ранее между теми же пользователем 210 и ассистентом 230. [0064] The conversation ID is transmitted if the initiated conversation is a continuation of a conversation that took place previously between the same user 210 and assistant 230.
[0065] При получении запроса на инициацию диалога выполняются следующие шаги. [0065] Upon receipt of a request to initiate a dialogue, the following steps are performed.
[0066] Шаг 120: осуществляют поиск в базе данных виртуального ассистента на основании полученного на предыдущем шаге идентификатора ассистента. [0066] Step 120: The virtual assistant database is searched based on the assistant ID obtained in the previous step.
[0067] На первом шаге осуществляется поиск ассистента 230. Таким образом производится поиск в базе данных технического решения ассистента 230 с полученным идентификатором. Если ассистент 230 в базе не найден, то техническое решение возвращает информацию об ошибке и завершает инициацию. [0067] At the first step, the assistant 230 is searched. Thus, the assistant 230 with the received identifier is searched in the database for the technical solution. If the assistant 230 is not found in the database, then the technical solution returns error information and completes the initiation.
[0068] Шаг 130: осуществляют поиск в базе данных ранее инициированного диалога на основании идентификатора диалога, полученного на предыдущем шаге. [0068] Step 130: Search the database for a previously initiated conversation based on the conversation ID obtained in the previous step.
[0069] Затем выполняют поиск диалога. Этот шаг осуществляется только в случае, если был получен идентификатор диалога. На нем производится поиск в базе данных технического решения ранее инициированного диалога с соответствующим идентификатором. [0069] Then, a dialogue search is performed. This step is only carried out if a dialog ID has been obtained. It produces search in the database of a technical solution for a previously initiated dialogue with the corresponding identifier.
[0070] Каждый пользователь 210 имеет свои переменные. Переменные пользователя 210 - переменные, сохраняющие значения между диалогами с одним и тем же пользователем. Формат имени переменной: user X. [0070] Each user 210 has its own variables. User variables 210 are variables that store values between dialogs with the same user. Variable name format: user X.
[0071] Примеры шаблонов показаны ниже. [0071] Template examples are shown below.
//шаблон 1 //template 1
$ меня зовут [-**-] $ my name is [-**-]
# Приятно познакомиться, [&1]. [%user_name="[&1]"] # Nice to meet you, [&1]. [%user_name="[&1]"]
//шаблон 2 //template 2
$ * как * меня * зовут * $*what is*my*name*
#[if(%user_name)]{Bbi [%user_name].}[else]^ не знаю, как Вас зовут.} #[if(%user_name)]{Bbi [%user_name].}[else]^ don't know your name.}
[0072] Пример диалога показан ниже: [0072] An example dialog is shown below:
[0073] Пользователь: меня зовут Вася [0073] User: my name is Vasya
[0074] Виртуальный ассистент (сработало правило 1 ): Приятно познакомиться, Вася. [0074] Virtual Assistant (rule 1 worked): Nice to meet you, Vasya.
[0075] Пользователь: Как меня зовут? [0075] User: What's my name?
[0076] Виртуальный ассистент (сработало правило 2, часть ответа под условием на непустую переменную user name): Вы Вася. [0076] Virtual assistant (rule 2 worked, part of the answer under the condition on a non-empty user name variable): You are Vasya.
[0077] Диалог завершился. Через день пользователь 210 приходит с того же компьютера поговорить с виртуальным ассистентом 230, который «понимает», что это тот же самый пользователь 210. [0077] The dialogue has ended. A day later, user 210 comes from the same computer to talk to virtual assistant 230, who "understands" that this is the same user 210.
[0078] Пользователь: Как меня зовут? [0078] User: What's my name?
[0079] Виртуальный ассистент (сработало правило 2, часть ответа под условием на непустую переменную user_name, потому что значение этой переменной сохраняется между диалогами): Вы Вася. [0079] Virtual assistant (rule 2 worked, part of the answer under the condition on the non-empty variable user_name, because the value of this variable is saved between dialogs): You are Vasya.
[0080] Если диалог был найден, то производится поиск в базе данных активной сессии, связанной с найденным диалогом. Если сессия не обнаружена, то в базе данных для найденного диалога создается новая сессия (автоматически являющаяся активной), определяемая следующими данными: [0080] If the dialog was found, then the active session database associated with the found dialog is searched. If the session is not found, then a new session (automatically active) is created in the database for the found dialog, defined by the following data:
• новым уникальным идентификатором сессии. • new unique session identifier.
• идентификатором созданного диалога. • пустым контекстом сессии. • ID of the created dialog. • an empty session context.
[0081] Техническое решение возвращает идентификатор найденного диалога и завершает инициацию. [0081] The technical solution returns the identifier of the found dialog and completes the initiation.
[0082] На следующем шаге осуществляют создание диалога. Этот шаг осуществляется, если предыдущий шаг был пропущен или на нем не был найден целевой диалог. На нем выполняются следующие действия. [0082] The next step is to create a dialogue. This step is carried out if the previous step was skipped or the target dialog was not found on it. It performs the following steps.
[0083] В базе данных технического решения создается новый диалог, определяемый следующими данными: [0083] A new dialog is created in the solution database, defined by the following data:
• новым уникальным идентификатором диалога. • a new unique dialog identifier.
• полученным идентификатором ассистента. • received assistant ID.
[0084] Для созданного диалога в базе данных технического решения создается новая сессия, определяемая следующими данными: [0084] For the created dialog, a new session is created in the solution database, defined by the following data:
• новым уникальным идентификатором сессии. • new unique session identifier.
• идентификатором созданного диалога. • ID of the created dialog.
• пустым контекстом сессии. • an empty session context.
[0085] Техническое решение возвращает идентификатор созданного диалога и завершает инициацию. [0085] The technical solution returns the identifier of the created dialog and completes the initiation.
[0086] Затем будет ниже более подробно раскрыт обмен сообщениями. [0086] Messaging will then be discussed in more detail below.
[0087] Шаг 140: получают от пользователя запрос в диалоге, содержащий идентификатор диалога с виртуальным ассистентом, полученный при инициации диалога, по меньшей мере одно текстовое сообщение пользователя, контекст запроса. [0087] Step 140: a dialog request is received from the user, containing the virtual assistant dialog identifier received when the dialog was initiated, at least one user text message, the request context.
[0088] Пользователь 210 технического решения отправляет запрос, который содержит следующие данные: [0088] The user 210 of the technical solution sends a request that contains the following data:
• идентификатор диалога с ассистентом 230, полученный при инициации диалога. • identifier of the dialogue with the assistant 230, received when the dialogue was initiated.
• текстовое сообщение пользователя 210. • user text message 210.
• набором именованных параметров, называемым контекстом запроса пользователя 210 (далее контекстом запроса).• a set of named parameters, called the user request context 210 (hereinafter the request context).
[0089] Все параметры контекста представляют из себя пару значений: уникальное имя параметра, значение параметра. [0090] Задачей технического решения является обработать такой запрос, сформировать максимально подходящий ответ на него и передать его пользователю. [0089] All context parameters are a pair of values: a unique parameter name, a parameter value. [0090] The task of the technical solution is to process such a request, generate the most suitable response to it and transfer it to the user.
[0091] В рамках этой задачи выполняются следующие шаги. [0091] As part of this task, the following steps are performed.
[0092] На первом этапе осуществляется поиск в базе данных ранее инициированного диалога с соответствующим идентификатором. [0092] At the first stage, a database is searched for a previously initiated dialogue with the corresponding identifier.
[0093] Если диалог не был найден, то техническое решение возвращает ошибку и завершает обработку запроса пользователя 210. [0093] If the dialog was not found, then the solution returns an error and ends processing the user's request 210.
[0094] Далее происходит получение сессии. [0094] Next is getting the session.
[0095] На этом шаге производится поиск в базе данных активной сессии, связанной с найденным диалогом. Если сессия не обнаружена, то в базе данных для найденного диалога создается новая сессия (автоматически являющаяся активной), определяемая следующими данными: [0095] This step searches the database for the active session associated with the found dialog. If the session is not found, then a new session (automatically active) is created in the database for the found dialog, defined by the following data:
• новым уникальным идентификатором сессии. • new unique session identifier.
• идентификатором созданного диалога. • ID of the created dialog.
• пустым контекстом сессии. • an empty session context.
[0096] Далее происходит обновление контекста сессии. [0096] Next, the session context is updated.
[0097] Этот шаг производится только, если контекст запроса не пуст. На нем производится обновление контекста сессии по следующему алгоритму: [0097] This step is only performed if the request context is not empty. It updates the session context according to the following algorithm:
• все параметры, имена которых отсутствуют в контексте сессии, но присутствуют в контексте запроса, добавляются в контекст сессии с соответствующими значениями из контекста запроса. • all parameters whose names do not exist in the session context but are present in the request context are added to the session context with the corresponding values from the request context.
• всем параметрам, имена которых присутствуют как в контексте сессии, так и в контексте запроса, в контексте сессии присваиваются соответствующие значения из контекста запроса. • all parameters whose names are present both in the session context and in the request context are assigned the corresponding values from the request context in the session context.
[0098] Затем осуществляется формирование контекста поиска. Контекстом поиска называется набор именованных параметров, получаемый из контекста ассистента 230 и контекста сессии по следующему алгоритму. [0098] The search context is then generated. The search context is a set of named parameters obtained from the context of the assistant 230 and the context of the session according to the following algorithm.
[0099] Контекст ассистента 230 копируется в контекст поиска. Все параметры, имена которых отсутствуют в контексте поиска, но присутствуют в контексте сессии, добавляются в контекст поиска с соответствующими значениями из контекста сессии. Всем параметрам, имена которых присутствуют как в контексте поиска, так и в контексте сессии, в контексте поиска присваиваются соответствующие значения из контекста сессии. [0099] The context of the assistant 230 is copied to the search context. All parameters whose names are not in the search context but are present in the session context are added to the search context with the corresponding values from the session context. All parameters whose names are present in both the search context and the session context, the corresponding values from the session context are assigned to the search context.
[00100] Далее осуществляют поиск вхождений словарей DL. [00100] Next, search for occurrences of DLs.
[00101] На этом шаге производится поиск всех вхождений словарей языка DL в сообщение пользователя 210 по следующему алгоритму. [00101] This step searches for all occurrences of DL dictionaries in user message 210 using the following algorithm.
• ищутся всех вхождения текстовых элементов строк словарей DL (не содержащих элементов языка DL) с использованием заранее подготовленного префиксного дерева. • all occurrences of text elements of strings of DL dictionaries (not containing elements of the DL language) are searched using a prefix tree prepared in advance.
• выбираются все строки словарей, которые отвечают следующим эвристикам: о в сообщении пользователя 210 есть все текстовые элементы входящие в строку словаря DL, о существует порядок найденных вхождений текстовых элементов, соответствующий строке словаря DL, о если нет текстовых элементов, располагающихся в самом начале сообщения пользователя 210, то в строке словаря DL в начале должна стоять звездочка или суперзвездочка. о если нет текстовых элементов, располагающихся в самом конце сообщения пользователя, то в строке словаря DL в конце должна стоять звездочка или суперзвездочка. • all dictionary strings are selected that correspond to the following heuristics: o User message 210 contains all text elements included in the DL dictionary string, o There is an order of found occurrences of text elements corresponding to the DL dictionary string, o If there are no text elements located at the very beginning of the message user 210, then the DL dictionary line must start with an asterisk or superstar. o If there are no text elements located at the very end of the user's message, then the DL dictionary line must end with an asterisk or superstar.
• все выбранные строки словаря проверяются на точное соответствие сообщению пользователя. • all selected dictionary strings are checked for exact match to the user's message.
[00102] Ниже описано начало формирования пула выделенных именованных сущностей. [00102] Described below is how to start pooling dedicated named entities.
[00103] Для каждого словаря DL, вхождения из которых были найдены на прошлом шаге, выбираются вхождения, для которых количество слов в шаблоне DL при вместо подстановки всех inline-словарей их конкретных значений, максимальное для данного словаря. Такие вхождения называются выделенными именованными словарными сущностями, имя которых совпадает с именем словаря DL, в которые они входят. [00103] For each DL dictionary whose entries were found in the previous step, entries are selected for which the number of words in the DL template when instead of substituting all inline dictionaries with their specific values is the maximum for this dictionary. Such entries are called distinguished named dictionary entities, whose name is the same as the name of the DL dictionary in which they appear.
[00104] Набор выделенных именованных словарных сущностей образует множество выделенных сущностей для сообщения пользователя 210. [00105] Шаг 150: осуществляют обнаружение интентов пользователя посредством алгоритмов машинного обучения, которые получают на вход идентификатор виртуального ассистента и текстовое сообщение из запроса пользователя, в результате чего формируют список интентов и степени уверенности в том, что данные интенты присутствуют в сообщении пользователя. [00104] The set of distinguished named vocabulary entities forms the set of distinguished entities for user message 210. [00105] Step 150: User intents are detected using machine learning algorithms that receive a virtual assistant ID and a text message from the user's request as input, resulting in a list of intents and degrees of confidence that these intents are present in the user's message.
[00106] Далее осуществляют обнаружение возможных намерений пользователя 210 (интентов). [00106] Next, the possible intentions of the user 210 (intents) are detected.
[00107] На этом шаге для обнаружения возможных намерений используются нейросетевые алгоритмы, описанные ниже, которые получают на вход идентификатор ассистента 230 и текстовое сообщение из запроса пользователя 210, а результатом их выполнения является список возможных намерений и степени уверенности в том, что это намерение действительно присутствует в сообщении пользователя 210. [00107] At this step, the neural network algorithms described below are used to detect possible intentions, which receive the assistant ID 230 and the text message from the user request 210 as input, and the result of their execution is a list of possible intentions and degrees of confidence that this intention is valid present in user message 210.
[00108] Все интенты, уверенность классификации которых ниже конфигурационного параметра (например, значение Threshold), отбрасываются. [00108] All intents whose classification confidence is below a configuration parameter (eg, Threshold value) are discarded.
[00109] Для каждого интента уверенность умножается на специальный конфигурационный параметр (Multiplier) и округляется с точностью, определяемой конфигурационным параметром (Accuracy). Если уверенность превышает значение конфигурационного параметра (Limit), то значение уверенности устанавливается в Limit. Полученное значение считается далее уверенностью данного интента. [00109] For each intent, the confidence is multiplied by a special configuration parameter (Multiplier) and rounded with the accuracy determined by the configuration parameter (Accuracy). If confidence exceeds the value of the configuration parameter (Limit), then the confidence value is set to Limit. The resulting value is considered further as the certainty of this intent.
[00110] Затем осуществляют выделение именованных сущностей на основе нейронной сети. На этом шаге для выделения именованных сущностей используются нейросетевые алгоритмы, описанные ниже, которые получают на вход идентификатор ассистента 230 и текстовое сообщение из запроса пользователя 210, а результатом их выполнения является список выделенных сущностей с указанием их ролей и степени уверенности в том, что они были выделены корректно. [00110] Then, named entities are extracted based on the neural network. At this step, the neural network algorithms described below are used to extract named entities, which receive the assistant identifier 230 and a text message from the user request 210 as input, and the result of their execution is a list of selected entities indicating their roles and the degree of confidence that they were highlighted correctly.
[00111] Все выделенные сущности группируются по имени роли, присвоенной им. Для каждого имени выбирается сущность с максимальным показателем уверенности. Для каждой такой сущности проверяется, есть ли сущность с таким именем в множестве выделенных сущностей, сформированных ранее. Если такая сущность отсутствует, то она добавляется в множество выделенных сущностей. [00111] All selected entities are grouped by the name of the role assigned to them. For each name, the entity with the highest confidence score is selected. For each such entity, it is checked whether there is an entity with the same name in the set of selected entities, previously formed. If there is no such entity, then it is added to the set of selected entities.
[00112] Шаг 160: выполняют поиск наиболее подходящего правила для формирования ответа на основании интентов пользователя, полученных на предыдущем шаге. [00112] Step 160: The most appropriate rule is searched for generating a response based on the user's intents obtained in the previous step.
[00113] На следующем шаге выполняют поиск наиболее подходящего правила для формирования ответа. Для каждого шаблон-вопроса и интента, входящего в шаблон языка DL, определяется вес его совпадения с сообщением пользователя 210. Весом является 32х битовое беззнаковое целое число определяющиеся по следующим принципам: [00113] The next step is to search for the most appropriate rule to generate a response. For each question template and intent included in the DL language template, the weight of its match with the user's message 210 is determined. The weight is a 32-bit unsigned integer determined according to the following principles:
• если в шаблоне DL есть условия на специальную переменную that anchor, то 31-й бит принимает значение 1 , иначе 0. • if the DL template has conditions on the special variable that anchor, then the 31st bit takes the value 1 , otherwise 0.
• для интентов и шаблон-вопросов, в которых есть звездочки и суперзвездочки 30-й бит всегда равен 0, для шаблон-вопросов в которых звездочек и суперзвездочек нет, 30-й бит равен 1. • for intents and pattern questions that contain asterisks and superstars, the 30th bit is always 0; for pattern questions that do not have asterisks or superstars, the 30th bit is 1.
• 16-ти битное число, расположенное с 14-го по 29-й бит, определяется следующим образом: о для интентов оно равно числу слов в сообщении пользователя, умноженное на уверенность интента. При превышении значения 2Л16-1 , значение устанавливается в 2Л16-1. о для шаблон-вопросов оно равно числу слов в шаблон- вопросе в раскрытом виде (после подстановки конкретных значений вместо элементов языка DL таких как словари или inline-словари), включая звездочки и суперзвездочки. При превышении значения 2Л16-1 , значение устанавливается в 2Л16-1. • The 16-bit number, located from bits 14 to 29, is defined as follows: o for intents, it is equal to the number of words in the user's message multiplied by the confidence of the intent. If the value of 2 L 16-1 is exceeded, the value is set to 2 L 16-1. For template-questions, it is equal to the number of words in the template-question in expanded form (after substituting specific values for DL language elements such as dictionaries or inline dictionaries), including asterisks and superstars. If the value of 2 L 16-1 is exceeded, the value is set to 2 L 16-1.
• 8ми битное число, расположенное с бого по 13ый бит, определяется как число шаблон-условий в шаблоне. Если число шаблон-условий превышает 2л8-1 , то значение устанавливается в 2Л8-1. • An 8-bit number, ranging from 0th to 13th bit, is defined as the number of pattern-conditions in the pattern. If the number of condition-patterns exceeds 2 L 8-1 , then the value is set to 2 L 8-1.
[00114] Далее выполняется следующий алгоритм выбора. [00114] Next, the following selection algorithm is executed.
[00115] На первом шаге осуществляют выборку шаблонов одинакового веса посредством выбора из найденных всех шаблонов-вопросов и интентов с максимальным весом, при этом выбранные шаблоны удаляются из списка поиска. Если список пуст, то считают, что порождается пустой ответ и пропускают следующие два шага. [00115] In the first step, templates of the same weight are sampled by selecting from all found question templates and intents with the maximum weight, while the selected templates are removed from the search list. If the list is empty, then consider that an empty response is generated and skip the next two steps.
[00116] Далее формируют выборку всех реально возможных шаблон- ответов. [00116] Next, a sample of all realistically possible template responses is formed.
[00117] Составляется список шаблон-ответов, относящегося к выбранным на предыдущем шаге шаблон-вопросам и интентам, проверяется возможность генерации непустого ответа, где пустым ответом считается ответ, не содержащий ни одного текстового элемента вывода (текста, inline-словаря, словаря и т.п.). Если список оказывается пустым, то возвращаются к предыдущему шагу. [00117] A list of template-answers is compiled that relates to the template-questions and intents selected in the previous step, the possibility of generating a non-empty response is checked, where an empty response is a response that does not contain any text output element (text, inline dictionary, dictionary, etc. .P.). If the list is empty, then return to the previous step.
[00118] Далее осуществляется рандомизация. Выбирают случайно один из отобранных ранее шаблон-ответов и определяют его ответом на сообщение пользователя. [00118] Next is randomization. Randomly choose one of the previously selected template-responses and determine it as a response to the user's message.
[00119] Затем формируют ответ по выбранному правилу. Для выбранного шаблон-ответа обрабатываются все функциональные элементы языка DL в соответствии с их описанием. [00119] Then a response is generated according to the selected rule. For the selected response template, all functional elements of the DL language are processed in accordance with their description.
[00120] Далее записывают журнал диалога. Сформированный ответ записывается в базу данных технического решения. [00120] Next, a dialogue log is recorded. The generated response is recorded in the technical solution database.
[00121] Затем сохраняют контекст сессии. Для каждой инструкции по изменению сессии, изменяют контекст сессии в соответствии с этой инструкций. Обновленный контекст сессии сохраняется в базу данных технического решения. [00121] The session context is then saved. For each instruction to change the session, change the context of the session in accordance with this instruction. The updated session context is stored in the solution database.
[00122] На последнем шаге осуществляется передача ответа пользователю 210. Сформированный ответ передается пользователю 210. [00123] Ниже будут описаны алгоритмы машинного обучения, используемые в данном техническом решении. [00122] The last step is the transmission of the response to the user 210. The generated response is transmitted to the user 210. [00123] The machine learning algorithms used in this technical solution will be described below.
[00124] Современные алгоритмы классификации интентов и извлечения именованных сущностей традиционно состоят из двух частей, а именно выделения признаков из текста в некотором числовом векторном виде и применения специальной решающей функции к этим числовым векторам, которая даёт в результате номер класса в списке классов намерений для задачи классификации интентов и метки с номерами названий сущностей из списка сущностей для всех слов исходной реплики пользователя. [00124] Modern algorithms for classifying intents and extracting named entities traditionally consist of two parts, namely extracting features from text in some numeric vector form and applying a special decision function to these numeric vectors, which results in a class number in the list of intent classes for the task classification of intents and labels with numbers names of entities from the list of entities for all words of the user's original replica.
[00125] Выделение признаков — это разновидность абстрагирования, процесс снижения размерности, в котором исходный набор исходных переменных сокращается до более управляемых групп (признаков) для дальнейшей обработки, оставаясь при этом достаточным набором для точного и полного описания исходного набора данных. [00125] Feature extraction is a type of abstraction, a dimensionality reduction process in which the original set of original variables is reduced to more manageable groups (features) for further processing, while remaining a sufficient set to accurately and completely describe the original data set.
[00126] Векторизация текстовых данных - способ представления выделенных признаков через преобразование в числовые векторы некоторого многомерного пространства. [00126] Text data vectorization is a way of representing selected features through transformation into numerical vectors of some multidimensional space.
[00127] Функция, производящая векторизацию текстовых данных, называется векторизатором (эмбеддером), а полученные признаки, соответствующие исходной фразе - вектором (эмбеддингом предложения). [00128] Одни из лучших векторизаторов по качественным показателям (по итоговой F-мере полного алгоритма классификации интентов или извлечения именованных сущностей на произвольных наборах данных) на данный момент являются ELMo (Embeddings from Language Models) и BERT (Bidirectional Encoder Representations from Transformers). [00127] A function that vectorizes text data is called a vectorizer (embedder), and the resulting features corresponding to the original phrase are called a vector (sentence embedding). [00128] Some of the best vectorizers in terms of quality (by the final F-measure of a complete algorithm for classifying intents or extracting named entities on arbitrary data sets) at the moment are ELMo (Embeddings from Language Models) and BERT (Bidirectional Encoder Representations from Transformers).
[00129] ELMo - более производительный вариант (способный обрабатывать большее количество текстовых реплик в секунду), построенный на основе Bi-LSTM сетей (Bidirectional Long-Short-Term- Memory, двунаправленных рекуррентных искусственных нейронных сетей, состоящих из LSTM слоёв, слоёв долгой краткосрочной памяти). ELMo смотрит на целое предложение, прежде чем присвоить каждому слову его эмбеддинг. Нейронная сеть такого векторизатора обучается (подбирает и оптимизирует коэффициенты некоторой сложной числовой функции для лучшей аппроксимации ожидаемого поведения алгоритма) специально под задачу создания таких эмбеддингов. Модель во время обучения на большом наборе текстов пытается предсказывать следующее слово в предложениях, а также и предыдущее при обратном проходе по предложению. Предварительное обучение происходит на текстах без разметки, автоматически генерируя пары «часть предложения» - «следующее или предыдущее слово». Таким образом, модель запоминает совместно встречающиеся слова и устойчивые языковые конструкции. [00130] BERT - более тяжелый вариант (обладает меньшей производительностью), архитектура которого состоит из частей с sequence- to-sequence нейронными сетями (моделями, принимающими на вход последовательности элементов, слов, букв, иных признаков, и возвращающая другую последовательность элементов), использующими в своей основе механизм внимания. Это нейронная сеть-трансформер, состоящая из целого стека энкодеров sequence-to-sequence сетей. Можно обучать такую модель «маскированием» отдельных слов в предложениях без какой-либо разметки. Модель, побившая несколько рекордов по успешности решения ряда NLP-задач. В открытом доступе есть и большое количество предобученных моделей для разных языков, в том числе и мультиязычные для решения всевозможных задач. [00129] ELMo is a more productive option (capable of processing more text replicas per second), built on the basis of Bi-LSTM networks (Bidirectional Long-Short-Term-Memory, bidirectional recurrent artificial neural networks, consisting of LSTM layers, layers of long short-term memory). ELMo looks at the whole sentence before assigning each word its embedding. The neural network of such a vectorizer is trained (selects and optimizes the coefficients of some complex numerical function to better approximate the expected behavior of the algorithm) specifically for the task of creating such embeddings. The model, while training on a large set of texts, tries to predict the next word in sentences, as well as the previous one when it backwards through the sentence. Preliminary training takes place on texts without markup, automatically generating pairs “part of a sentence” - “next or previous word”. Thus, the model remembers co-occurring words and stable language constructs. [00130] BERT is a heavier version (has less performance), the architecture of which consists of parts with sequence-to-sequence neural networks (models that take sequences of elements, words, letters, other signs as input, and return a different sequence of elements), based on the mechanism of attention. This is a neural network-transformer, consisting of a whole stack of sequence-to-sequence network encoders. It is possible to train such a model by "masking" individual words in sentences without any markup. A model that has broken several records for the success of solving a number of NLP tasks. There are also a large number of pre-trained models for different languages in the public domain, including multilingual ones for solving various problems.
[00131] В NLU части данного технического решения в качестве векторизаторов, исходя из показателей качества и производительности, может использоваться облегчённая реализация BERT (DistilBERT) для классификации интентов и ELMo для извлечения именованных сущностей. Специальные предобработки текстов отсутствуют, поскольку обе эти модели лучше работают с исходными текстами и умеют учитывать части речи, формы слова, знаки препинания и прочую дополнительную информацию, которая может быть потеряна во время предобработки, и на основе знаний о сочетаниях слов и языковых конструкциях делают свои предсказания. [00131] In the NLU part of this technical solution, as vectorizers, based on quality and performance indicators, a lightweight implementation of BERT (DistilBERT) for classifying intents and ELMo for extracting named entities can be used. There are no special text preprocessing, since both of these models work better with source texts and are able to take into account parts of speech, word forms, punctuation marks and other additional information that may be lost during preprocessing, and based on knowledge of word combinations and language constructs, they make their own predictions.
[00132] После получения эмбеддинга для целиковой реплики пользователя остаётся классифицировать этот эмбеддинг в векторном пространстве. Эту задачу в данном техническом решении могут решать как средствами классического машинного обучения, так и при помощи неглубоких нейронных сетей, состоящих из 2-3 полносвязных слоев. Опытным путём на репрезентативных наборах данных (порядка 500 интентов, минимум по 50 примеров на каждый интент) было произведено сравнение по качеству и производительности алгоритмов (k-NN, Random Forest, SVM, XGBoost, их композиции, неглубокие нейронные сети), в результате которого был отобран подход с Feed-Forward Neural Network (FFNN) из трёх полносвязных слоёв с выходным слоем равным количеству требуемых классов и параметрами архитектуры, полученными при помощи байесовской оптимизации. [00132] After receiving the embedding for the entire replica of the user, it remains to classify this embedding in vector space. This problem in this technical solution can be solved both by means of classical machine learning and by using shallow neural networks consisting of 2-3 fully connected layers. Empirically, on representative data sets (about 500 intents, at least 50 examples for each intent), a comparison was made in terms of the quality and performance of algorithms (k-NN, Random Forest, SVM, XGBoost, their compositions, shallow neural networks), as a result of which was selected approach with Feed-Forward Neural Network (FFNN) of three fully connected layers with an output layer equal to the number required classes and architecture parameters obtained using Bayesian optimization.
[00133] Байесовская оптимизация — это метод глобальной оптимизации для неизвестной функции. Задача поиска архитектуры нейросети (NNAS) предполагает автоматический подбор архитектуры нейросети. Это задача морфизма нейросети (англ, «network morphism»), когда функциональность нейросети сохраняется, но архитектура нейросети подбирается другая. Ключевая идея предлагаемого метода в том, чтобы исследовать пространство поиска архитектур с помощью алгоритма байесовской оптимизации (ВО). Традиционно байесовская оптимизация состоит из цикла с 3 шагами: обновление, генерация и наблюдение. В контексте поиска нейросетевой архитектуры цикл состоит из следующих шагов: [00133] Bayesian optimization is a global optimization technique for an unknown function. The Neural Network Architecture Search (NNAS) task involves automatic selection of the neural network architecture. This is the task of neural network morphism (English, "network morphism"), when the functionality of the neural network is preserved, but the architecture of the neural network is selected differently. The key idea of the proposed method is to explore the architecture search space using the Bayesian Optimization (BO) algorithm. Traditionally, Bayesian optimization consists of a 3-step loop: update, generate, and observe. In the context of searching for a neural network architecture, the cycle consists of the following steps:
• Обновление: обучается гауссовский процесс на существующих архитектурах и их результатах; • Update: Gaussian process is trained on existing architectures and their results;
• Генерация: генерируется новая архитектура через оптимизацию функции исследования (англ, «acquisition function»); • Generation: a new architecture is generated through the optimization of the acquisition function;
• Наблюдение: записать результаты новой архитектуры. • Observation: record the results of the new architecture.
[00134] Так подбирается количество слоёв, нейронов на каждом слое, тип используемой нормализации, активация, вероятность выключения нейронов в Dropout слоях. [00134] This selects the number of layers, neurons on each layer, the type of normalization used, activation, the probability of turning off neurons in Dropout layers.
[00135] Итоговая оптимальная нейронная сеть для классификации интентов подбирается автоматически под каждый набор данных, в примере с рассмотренным репрезентативным набором данных была получена архитектура, состоящая из последовательности слоёв: первый полносвязный слой, нормализация батча, Dropout слой, слой Elu активации, второй полносвязный слой, нормализация батча, Dropout слой, слой Elu активации, третий полносвязный слой, всего - 233 нейрона в полносвязных слоях. По сути своей такая нейронная сеть есть гибрид FFNN сети. На выходе из этой нейронной сети получается вектор распределения вероятностей для каждого из классов (количество элементов вектора равно количеству классов). [00136] В итоге получается следующая последовательность обработки реплик пользователей: реплика -> DistilBERT -> эмбеддинг -> FFNN -> распределение вероятности принадлежности реплики интентам. [00135] The final optimal neural network for classifying intents is selected automatically for each data set, in the example with the considered representative data set, an architecture was obtained, consisting of a sequence of layers: the first fully connected layer, batch normalization, Dropout layer, Elu activation layer, second fully connected layer , batch normalization, Dropout layer, Elu activation layer, third fully connected layer, total - 233 neurons in fully connected layers. In essence, such a neural network is a hybrid of the FFNN network. The output of this neural network is a probability distribution vector for each of the classes (the number of vector elements is equal to the number of classes). [00136] As a result, the following sequence of processing user replicas is obtained: replica -> DistilBERT -> embedding -> FFNN -> probability distribution of replica belonging to intents.
[00137] После получения эмбеддингов слов пользовательской реплики дальше происходит их классификация по заданному набору меток (тегов) сущностей. При разметке текста для обучения каждое слово отмечается специальным тегом - именем класса, к которому слово относится, и положением слова по отношению к целиковой отмечаемой сущности в виде префикса: [00137] After receiving the embeddings of the words of the user replica, they are further classified according to a given set of labels (tags) of entities. When marking text for training, each word is marked with a special tag - the name of the class to which the word belongs, and the position of the word in relation to the entire marked entity in the form of a prefix:
[00138] В - от слова beginning - первое слово в сущности, состоящей из больше, чем 1 слова. [00138] B - from the word beginning - the first word in an entity consisting of more than 1 word.
[00139] I - от слова inside - слова, находящиеся в середине сущности, состоящей из больше, чем 1 слова. [00139] I - from the word inside - words that are in the middle of an entity consisting of more than 1 word.
[00140] О - от слова out - если слово не относится ни к какой сущности, он помечается этой меткой. [00140] O - from the word out - if the word does not refer to any entity, it is marked with this label.
[00141] Для каждого слова нужно получить тег. Это можно сделать разными способами. Более простой и очевидный способ - использовать некоторую нейронную сеть, в качестве последнего слоя которой будет использован полносвязный слой размерности d, где d — количество возможных меток слова. Таким образом, получают вероятности слова иметь каждую из возможных меток (и можем выбрать самую вероятную из них). Но, чтобы учесть в финальных тегах их взаимную зависимость, этого недостаточно. [00141] For each word, you need to get a tag. This can be done in many ways. A simpler and more obvious way is to use some neural network, the last layer of which will be a fully connected layer of dimension d, where d is the number of possible word labels. Thus, we get the probabilities of the word to have each of the possible labels (and we can choose the most probable of them). But to take into account their mutual dependence in the final tags, this is not enough.
[00142] После сравнения по метрикам качества различных алгоритмов классического машинного обучения (k-NN, Random Forest, SVM, XGBoost, их композиции) и архитектур нейронных сетей (Bi-LSTM Encoder + CRF, sequence-to-sequence модели) в качестве классификатора был выбран Bi- LSTM Encoder с дополнительным CRF (conditional random field) слоем, учитывающим соотношения тегов друг с другом для правильной расстановки префиксов. На выходе из этой нейронной сети получается вектор распределения вероятностей для каждого из тегов для каждого слова (количество элементов вектора равно количеству тегов). [00142] After comparing the quality metrics of various classical machine learning algorithms (k-NN, Random Forest, SVM, XGBoost, their compositions) and neural network architectures (Bi-LSTM Encoder + CRF, sequence-to-sequence models) as a classifier Bi-LSTM Encoder was chosen with an additional CRF (conditional random field) layer that takes into account the relationship of tags with each other for the correct placement of prefixes. The output of this neural network is a probability distribution vector for each of the tags for each word (the number of vector elements is equal to the number of tags).
[00143] В итоге получается следующая последовательность обработки реплик пользователей: реплика -> ELMo -> эмбеддинги слов -> Bi-LSTM Encoder + CRF -> рапределение вероятностей принадлежности слов реплики тегам сущностей. [00143] As a result, the following sequence of processing user replicas is obtained: replica -> ELMo -> word embeddings -> Bi-LSTM Encoder + CRF -> distribution of probabilities that words of a replica belong to entity tags.
[00144] Модели векторизации не дообучаются в рамках платформы, а подготавливаются и поставляются разработчиками под каждую конкретную область применения. Такие модели заранее обучаются без разметки на больших текстовых массивах целевого содержания. Например, большие корпуса русского языка, такие как Википедия и новостные сайты, расширенные логами общения клиентов банка в чатах с операторами для обучения векторизаторов для банковской тематики. Затем в случае с моделью BERT для использования в классификации может быть произведено разовое дополнительное дообучение в составе вместе с классификатором на целевых обучающих данных (парах «реплика» - «интент»), что существенно повышает итоговые метрики качества. [00144] Vectorization models are not further trained within the platform, but are prepared and delivered by developers for each specific application. Such models are trained in advance without markup on large text arrays of target content. For example, large corpora of the Russian language, such as Wikipedia and news sites, expanded with logs of communication between bank customers in chats with operators for training vectorizers for banking topics. Then, in the case of the BERT model for use in classification, a one-time additional training can be performed together with the classifier on the target training data (replica-intent pairs), which significantly increases the final quality metrics.
[00145] Модели классификации интентов и тегов сущностей обучаются в рамках взаимодействия оператора с платформой на размеченных операторами пользовательских данных, вносимых через интерфейс IDE платформы в разделах с “примерами”. В платформе есть следующие регулируемые гиперпараметры обучения, изменяемые в текстовом конфигурационном файле: скорость обучения (англ, «learning rate»), выбор функции потерь, метрики для оптимизации, количество эпох обучения и размер батча. При запуске обучения из IDE происходит сбор всех примеров с отметками их интентов и тегов сущностей, данные проходят через векторизаторы и собираются эмбеддинги фраз для последующей классификации интентов и эмбеддинги слов для извлечения именованных сущностей. Данные стратифицировано разбиваются на обучающую и валидационную выборки (пропорция разбиения на эти части также задаётся в конфигурационном файле с гиперпараметрами обучения, и эта пропорция соблюдается для каждого интента и тега сущности), затем для задачи классификации интентов происходит автоматическая балансировка классов по количеству примеров. Для этой задачи используется оверсемплинг (искусственное расширение количества примеров в классах с маленьким количеством примеров) обучающей части выборки при помощи техники SMOTE (Synthetic Minority Oversampling TEchnique) малых классов до размера самого большого. Это специальная техника генерации синтетических (ненастоящих) данных в пространстве эмбеддингов, полученных из векторизатора (а не на уровне генерации текстов, подаваемых в векторизатор). Таким образом, мы повышаем чувствительность классификатора к маленьким классам. [00145] Classification models for intents and entity tags are trained as part of the interaction of the operator with the platform on operator-tagged user data entered through the platform IDE interface in sections with “examples”. The platform has the following adjustable learning hyperparameters that can be changed in a text configuration file: learning rate, loss function selection, optimization metrics, number of training epochs, and batch size. When training is started from the IDE, all examples are collected with marks of their intents and entity tags, the data is passed through vectorizers and phrase embeddings are collected for subsequent intent classification and word embeddings to extract named entities. The data is stratified divided into training and validation samples (the proportion of splitting into these parts is also set in the configuration file with training hyperparameters, and this proportion is observed for each intent and entity tag), then for the problem of classifying intents, the classes are automatically balanced by the number of examples. For this task, oversampling (artificial expansion of the number of examples in classes with a small number of examples) of the training part of the sample using the SMOTE (Synthetic Minority Oversampling TEchnique) technique of small classes to the size of the largest is used. This is a special generation technique synthetic (fake) data in the embedding space received from the vectorizer (and not at the level of text generation fed into the vectorizer). Thus, we increase the sensitivity of the classifier to small classes.
[00146] Дальше происходит непосредственное обучение классификатора (интентов и сущностей). Во время обучения скорость обучения регулируется автоматически, а также может быть произведена ранняя остановка в случае быстрой сходимости (чтобы не проходить все заданные эпохи впустую), либо если алгоритм не может существенно оптимизироваться на текущем наборе данных. [00146] Next is the direct training of the classifier (intents and entities). During training, the learning rate is automatically adjusted, and an early stop can be made in case of fast convergence (so as not to go through all the given epochs in vain), or if the algorithm cannot significantly optimize on the current data set.
[00147] По окончании обучения все полученные параметры моделей сериализуются в файлы моделей, которые можно использовать для создания новых экземпляров классификаторов интентов и моделей извлечения именованных сущностей. [00147] At the end of training, all received model parameters are serialized into model files that can be used to create new instances of intent classifiers and named entity extraction models.
[00148] Все компоненты NLU части технического решения работают внутри отдельных сервисов, являющихся обёртками вокруг нейросетевых модулей. В них входит отдельный сервис с векторизаторами (в целях оптимизации все более тяжёлые нейронные сети, векторизаторы, были вынесены в отдельный сервис), сервисы классификации интентов, обучения классификаторов интентов, извлечения именованных сущностей и обучения моделей извлечения именованных сущностей. [00148] All components of the NLU part of the technical solution work inside separate services, which are wrappers around neural network modules. They include a separate service with vectorizers (in order to optimize, increasingly heavier neural networks, vectorizers, were moved to a separate service), services for classifying intents, training intent classifiers, extracting named entities, and training models for extracting named entities.
[00149] Для инициализации сервисов рантайма необходимо указать путь к файлам соответствующих моделей, из которых поднимаются сервисы. Запросы к сервисам должны содержать реплики пользователей, и ответы сервисов представляют из себя списки наиболее вероятных интентов с их соответствующими уровнями вероятности от 0.0 до 1.0, и наборы слов, которые могут являться представителями искомых именованных сущностей. Для каждого такого выделенного слова в ответе сервиса извлечения именованных сущностей присутствует его положение в тексте (отступ от начала реплики в символах) и список сущностей с их уровнями вероятности. Наиболее вероятные интенты и сущности могут быть использованы в дальнейшей обработке реплики пользователя платформой. [00150] Сервисы обучения в теле запросов на старт обучения принимают пути к текстовым файлам с наборами примеров, размеченных операторами IDE реплик и формируют файлы моделей. При необходимости обучение можно остановить, запросить статус обучения (узнать на какой стадии процесс), либо по окончании использовать сформированные файлы моделей для инициализации новых сервисов рантайма. [00149] To initialize runtime services, you must specify the path to the files of the corresponding models from which the services are raised. Requests to services must contain user replicas, and service responses are lists of most likely intents with their respective probability levels from 0.0 to 1.0, and sets of words that may be representatives of the named entities being searched for. For each such highlighted word in the response of the named entity extraction service, there is its position in the text (indentation from the beginning of the replica in characters) and a list of entities with their probability levels. The most likely intents and entities can be used in further processing of the user's response by the platform. [00150] Learning services in the body of requests to start learning take paths to text files with sets of examples marked up by IDE replica operators and form model files. If necessary, training can be stopped, request the training status (find out at what stage the process is), or upon completion, use the generated model files to initialize new runtime services.
[00151] Ссылаясь на Фиг. 4, данное техническое решение может быть реализовано в виде вычислительной системы 400 осуществления способа управления диалогом и системы понимания естественного языка в платформе виртуальных ассистентов, которая содержит один или более из следующих компонентов: [00151] Referring to FIG. 4, the present technical solution can be implemented as a computer system 400 for implementing a dialog control method and a natural language understanding system in a virtual assistant platform, which includes one or more of the following components:
• компонент 401 обработки, содержащий по меньшей мере один процессор 402, • a processing component 401 comprising at least one processor 402,
• память 403, • memory 403,
• компонент 405 мультимедиа, • multimedia component 405,
• компонент 406 аудио, • audio component 406,
• интерфейс 407 ввода / вывода (I / О), • interface 407 input / output (I / O),
• сенсорный компонент 408, • sensor component 408,
• компонент 409 передачи данных. • component 409 data.
[00152] Компонент 401 обработки в основном управляет всеми операциями системы 400, например, осуществляет обработку данных о пользователе или его запросе в чате, а также управляет дисплеем, телефонным звонком, передачей данных, работой камеры и операцией записи мобильного устройства связи. Компонент 401 обработки может включать в себя один или более процессоров 402, реализующих инструкции для завершения всех или части шагов из указанных выше способов. Кроме того, компонент 401 обработки может включать в себя один или более модулей для удобного процесса взаимодействия между другими модулями 401 обработки и другими модулями. Например, компонент 401 обработки может включать в себя мультимедийный модуль для удобного облегченного взаимодействия между компонентом 405 мультимедиа и компонентом 401 обработки. [00152] The processing component 401 mainly manages all operations of the system 400, such as processing user data or a chat request, as well as managing the display, phone call, data transmission, camera operation, and recording operation of the mobile communication device. Processing component 401 may include one or more processors 402 executing instructions for completing all or part of the steps from the above methods. In addition, the processing component 401 may include one or more modules for convenient interaction between other processing modules 401 and other modules. For example, the processing component 401 may include a multimedia module for convenient, lightweight interaction between the multimedia component 405 and the processing component 401.
[00153] Память 403 выполнена с возможностью хранения различных типов данных для поддержки работы системы 400, например, базу данных с профилями пользователей. Примеры таких данных включают в себя инструкции из любого приложения или способа, контактные данные, данные адресной книги, сообщения, изображения, видео, и т. д., и все они работают на системе 400. Память 403 может быть реализована в виде любого типа энергозависимого запоминающего устройства, энергонезависимого запоминающего устройства или их комбинации, например, статического оперативного запоминающего устройства (СОЗУ), Электрически- Стираемого Программируемого постоянного запоминающего устройства (ЭСППЗУ), Стираемого Программируемого постоянного запоминающего устройства (СППЗУ), Программируемого постоянного запоминающего устройства (ППЗУ), постоянного запоминающего устройства (ПЗУ), магнитной памяти, флэш-памяти, магнитного диска или оптического диска и другого, не ограничиваясь. [00153] The memory 403 is configured to store various types of data to support the operation of the system 400, such as a database with user profiles. Examples of such data include instructions from any application or method, contact data, address book data, messages, images, videos, etc., all of which run on system 400. Memory 403 may be implemented as any type of volatile memory, non-volatile memory, or a combination thereof, e.g., static random access memory (SRAM), Electrically Erasable Programmable Read Only Memory (EEPROM), Erasable Programmable Read Only Memory (EPROM), Programmable Read Only Memory (PROM), Read Only Memory device (ROM), magnetic memory, flash memory, magnetic disk or optical disk, and others, without being limited.
[00154] Компонент 405 мультимедиа включает в себя экран, обеспечивающий выходной интерфейс между системой 400, которая может быть установлена на мобильном устройстве связи пользователя и пользователем. В некоторых вариантах реализации, экран может быть жидкокристаллическим дисплеем (ЖКД) или сенсорной панелью (СП). Если экран включает в себя сенсорную панель, экран может быть реализован в виде сенсорного экрана для приема входного сигнала от пользователя. Сенсорная панель включает один или более сенсорных датчиков в смысле жестов, прикосновения и скольжения по сенсорной панели. Сенсорный датчик может не только чувствовать границу прикосновения субъекта или жест перелистывания, но и определять длительность времени и давления, связанных с режимом работы на прикосновение и скольжение. В некоторых вариантах осуществления компонент 405 мультимедиа включает одну фронтальную камеру и/или одну заднюю камеру. Когда система 400 находится в режиме работы, например, режиме съемки или режиме видео, фронтальная камера и/или задняя камера могут получать данные мультимедиа извне. Каждая фронтальная камера и задняя камера может быть одной фиксированной оптической системой объектива или может иметь фокусное расстояние или оптический зум. [00154] The media component 405 includes a screen providing an output interface between the system 400, which may be installed on a user's mobile communications device, and the user. In some implementations, the screen may be a liquid crystal display (LCD) or a touch panel (TP). If the screen includes a touch panel, the screen may be implemented as a touch screen to receive input from a user. The touchpad includes one or more touch sensors in terms of gestures, touching and sliding on the touchpad. The touch sensor can not only sense the subject's touch boundary or swipe gesture, but also determine the length of time and pressure associated with the touch and slide operation mode. In some embodiments, media component 405 includes one front camera and/or one rear camera. When the system 400 is in an operating mode, such as shooting mode or video mode, the front camera and/or rear camera can receive media data from outside. Each front camera and rear camera can be one fixed lens optics system or can have focal length or optical zoom.
[00155] Компонент 406 аудио выполнен с возможностью выходного и/или входного аудио сигнала. Например, компонент 406 аудио включает один микрофон (MIC), который выполнен с возможностью получать внешний аудио сигнал, когда система 400 находится в режиме работы, например, режиме вызова, режима записи и режима распознавания речи. Полученный аудио сигнал может быть далее сохранен в памяти 403 или направлен по компоненту 409 передачи данных. В некоторых вариантах осуществления компонент 406 аудио также включает в себя один динамик, выполненный с возможностью вывода аудио сигнала. [00155] The audio component 406 is configured to output and/or input an audio signal. For example, the audio component 406 includes one microphone (MIC) that is configured to receive an external audio signal when the system 400 is in an operating mode, such as call mode, recording mode, and speech recognition mode. The received audio signal may be further stored in the memory 403 or routed through the communication component 409 . In some embodiments, the audio component 406 also includes a single speaker configured to output an audio signal.
[00156] Интерфейс 407 ввода / вывода (I / О) обеспечивает интерфейс между компонентом 401 обработки и любым периферийным интерфейсным модулем. Вышеуказанным периферийным интерфейсным модулем может быть клавиатура, руль, кнопка, и т. д. Эти кнопки могут включать, но не ограничиваясь, кнопку запуска, кнопку регулировки громкости, начальную кнопку и кнопку блокировки. [00156] An input/output (I/O) interface 407 provides an interface between the processing component 401 and any peripheral interface module. The above peripheral interface module may be a keyboard, steering wheel, button, etc. These buttons may include, but are not limited to, a start button, a volume button, a home button, and a lock button.
[00157] Сенсорный компонент 408 содержит один или более сенсоров и выполнен с возможностью обеспечения различных аспектов оценки состояния системы 400. Например, сенсорный компонент 408 может обнаружить состояния вкл/выкл системы 400, относительное расположение компонентов, например, дисплея и кнопочной панели, одного компонента системы 400, наличие или отсутствие контакта между субъектом и системой 400, а также ориентацию или ускорение/замедление и изменение температуры системы 400. Сенсорный компонент 408 содержит бесконтактный датчик, выполненный с возможностью обнаружения присутствия объекта, находящегося поблизости, когда нет физического контакта. Сенсорный компонент 408 содержит оптический датчик (например, КМОП или ПЗС-датчик изображения) выполненный с возможностью использования в визуализации приложения. В некоторых вариантах сенсорный компонент 408 содержит датчик ускорения, датчик гироскопа, магнитный датчик, датчик давления или датчик температуры. [00157] The touch component 408 includes one or more sensors and is configured to provide various aspects of assessing the state of the system 400. For example, the touch component 408 can detect the on/off states of the system 400, the relative position of components, such as a display and a keypad, of a single component system 400, the presence or absence of contact between a subject and system 400, as well as the orientation or acceleration/deceleration and temperature change of system 400. Sensor component 408 includes a proximity sensor configured to detect the presence of a nearby object when there is no physical contact. The sensor component 408 includes an optical sensor (eg, CMOS or CCD image sensor) configured for use in rendering an application. In some embodiments, the sensor component 408 includes an acceleration sensor, a gyroscope sensor, a magnetic sensor, a pressure sensor, or a temperature sensor.
[00158] Компонент 409 передачи данных выполнен с возможностью облегчения проводной или беспроводной связи между системой 400 и другими устройствами. Система 400 может получить доступ к беспроводной сети на основе стандарта связи, таких как WiFi, 2G, 3G, 5G, или их комбинации. В одном примерном варианте компонент 409 передачи данных получает широковещательный сигнал или трансляцию, связанную с ними информацию из внешней широковещательной системы управления через широковещательный канал. В одном варианте осуществления компонент 409 передачи данных содержит модуль коммуникации ближнего поля (NFC), чтобы облегчить ближнюю связь. Например, модуль NFC может быть основан на технологии радиочастотной идентификации (RFID), технологии ассоциации передачи данных в инфракрасном диапазоне (IrDA), сверхширокополосных (UWB) технологии, Bluetooth (ВТ) технологии и других технологиях. [00158] The communication component 409 is configured to facilitate wired or wireless communication between the system 400 and other devices. System 400 may access a wireless network based on a communication standard such as WiFi, 2G, 3G, 5G, or combinations thereof. In one exemplary embodiment, the communication component 409 receives a broadcast signal or a broadcast associated therewith. information from the external broadcast control system via the broadcast channel. In one embodiment, communication component 409 includes a Near Field Communication (NFC) module to facilitate near field communications. For example, the NFC module may be based on radio frequency identification (RFID) technology, infrared data association (IrDA) technology, ultra-wideband (UWB) technology, Bluetooth (BT) technology, and other technologies.
[00159] В примерном варианте осуществления система 400 может быть реализована посредством одной или более Специализированных Интегральных Схем (СИС), Цифрового Сигнального Процессора (ЦСП), Устройств Цифровой Обработки Сигнала (УЦОС), Программируемым Логическим Устройством (ПЛУ), логической микросхемой, программируемой в условиях эксплуатации (ППВМ), контроллера, микроконтроллера, микропроцессора или других электронных компонентов, и может быть сконфигурирован для реализации способа 100 управления диалогом и системы понимания естественного языка в платформе виртуальных ассистентов. [00159] In an exemplary embodiment, system 400 may be implemented by one or more Application-Specific Integrated Circuits (ASICs), a Digital Signal Processor (DSP), a Digital Signal Processor (DSP), a Programmable Logic Unit (PLU), a logic chip programmable in operating environment (FPGA), controller, microcontroller, microprocessor, or other electronic components, and may be configured to implement the dialog control method 100 and natural language understanding system in the virtual assistant platform.
[00160] В примерном варианте осуществления энергонезависимый машиночитаемый носитель содержит память 403, которая включает инструкции, где инструкции выполняются процессором 401 системы 400 для реализации описанных выше способов осуществления управления диалогом. [00160] In an exemplary embodiment, the non-volatile computer-readable medium includes a memory 403 that includes instructions, where the instructions are executed by the processor 401 of the system 400 to implement the dialog control methods described above.
[00161] . Например, энергонезависимым машиночитаемым носителем может быть ПЗУ, оперативное запоминающее устройство (ОЗУ), компакт- диск, магнитная лента, дискеты, оптические устройства хранения данных и тому подобное. [00161] . For example, a non-volatile computer-readable medium can be ROM, random access memory (RAM), compact disc, magnetic tape, floppy disks, optical storage devices, and the like.
[00162] Вычислительная система 400 может включать в себя интерфейс дисплея, который передает графику, текст и другие данные из коммуникационной инфраструктуры (или из буфера кадра, не показан) для отображения на компоненте 405 мультимедиа. Вычислительная система 400 дополнительно включает в себя устройства ввода или периферийные устройства. Периферийные устройства могут включать в себя одно или несколько устройств для взаимодействия с мобильным устройством связи пользователя, такие как клавиатура, микрофон, носимое устройство, камера, один или более звуковых динамиков и другие датчики. Периферийные устройства могут быть внешними или внутренними по отношению к мобильному устройству связи пользователя. Сенсорный экран может отображать, как правило, графику и текст, а также предоставляет пользовательский интерфейс (например, но не ограничиваясь ими, графический пользовательский интерфейс (GUI)), через который субъект может взаимодействовать с мобильным устройством связи пользователя, например, получать доступ и взаимодействовать с приложениями, запущенными на устройстве. [00162] Computing system 400 may include a display interface that transmits graphics, text, and other data from a communications infrastructure (or framebuffer, not shown) for display on media component 405. Computing system 400 further includes input devices or peripherals. Peripheral devices may include one or more devices for interacting with a mobile communications device. user, such as a keyboard, microphone, wearable device, camera, one or more audio speakers, and other sensors. Peripherals may be external or internal to the user's mobile communications device. The touch screen may display, typically, graphics and text, and also provides a user interface (such as, but not limited to, a graphical user interface (GUI)) through which a subject may interact with the user's mobile communications device, such as accessing and interacting with with applications running on the device.
[00163] Элементы заявляемого технического решения находятся в функциональной взаимосвязи, а их совместное использование приводит к созданию нового и уникального технического решения. Таким образом, все блоки функционально связаны. [00163] The elements of the proposed technical solution are in a functional relationship, and their joint use leads to the creation of a new and unique technical solution. Thus, all blocks are functionally connected.
[00164] Все блоки, используемые в системе, могут быть реализованы с помощью электронных компонент, используемых для создания цифровых интегральных схем, что очевидно для специалиста в данном уровне техники. Не ограничиваюсь, могут использоваться микросхемы, логика работы которых определяется при изготовлении, или программируемые логические интегральные схемы (ПЛИС), логика работы которых задаётся посредством программирования. Для программирования используются программаторы и отладочные среды, позволяющие задать желаемую структуру цифрового устройства в виде принципиальной электрической схемы или программы на специальных языках описания аппаратуры: Verilog, VHDL, AHDL и др. Альтернативой ПЛИС могут быть программируемые логические контроллеры (ПЛК), базовые матричные кристаллы (БМК), требующие заводского производственного процесса для программирования; ASIC - специализированные заказные большие интегральные схемы (БИС), которые при мелкосерийном и единичном производстве существенно дороже. [00164] All blocks used in the system can be implemented using electronic components used to create digital integrated circuits, which is obvious to a person skilled in the art. Not limited to, microcircuits can be used, the logic of which is determined during manufacture, or programmable logic integrated circuits (FPGA), the logic of which is set by programming. Programmers and debugging environments are used for programming, allowing you to set the desired structure of a digital device in the form of a circuit diagram or a program in special hardware description languages: Verilog, VHDL, AHDL, etc. An alternative to FPGAs can be programmable logic controllers (PLCs), basic matrix crystals ( BMK), requiring a factory production process for programming; ASIC - specialized custom-made large integrated circuits (LSI), which are significantly more expensive for small-scale and single-piece production.
[00165] Обычно, сама микросхема ПЛИС состоит из следующих компонент: конфигурируемых логических блоков, реализующих требуемую логическую функцию; • программируемых электронных связей между конфигурируемыми логическими блоками; [00165] Usually, the FPGA chip itself consists of the following components: configurable logic blocks that implement the required logic function; • programmable electronic links between configurable logic blocks;
• программируемых блоков ввода/вывода, обеспечивающих связь внешнего вывода микросхемы с внутренней логикой. • programmable input/output blocks that provide communication between the external output of the microcircuit and the internal logic.
[00166] Также блоки могут быть реализованы с помощью постоянных запоминающих устройств. [00166] Blocks can also be implemented using read-only memories.
[00167] Таким образом, реализация всех используемых блоков достигается стандартными средствами, базирующимися на классических принципах реализации основ вычислительной техники. [00167] Thus, the implementation of all used blocks is achieved by standard means based on the classical principles of implementing the fundamentals of computer technology.
[00168] Как будет понятно специалисту в данной области техники, аспекты настоящего технического решения могут быть выполнены в виде системы, способа или компьютерного программного продукта. Соответственно, различные аспекты настоящего технического решения могут быть реализованы исключительно как аппаратное обеспечение, как программное обеспечение (включая прикладное программное обеспечение и так далее) или как вариант осуществления, сочетающий в себе программные и аппаратные аспекты, которые в общем случае могут упоминаться как «модуль», «система» или «архитектура». Кроме того, аспекты настоящего технического решения могут принимать форму компьютерного программного продукта, реализованного на одном или нескольких машиночитаемых носителях, имеющих машиночитаемый программный код, который на них реализован. [00168] As one of skill in the art will appreciate, aspects of the present technical solution may be implemented as a system, method, or computer program product. Accordingly, various aspects of the present technical solution may be implemented solely as hardware, as software (including application software, etc.), or as an embodiment combining software and hardware aspects, which may be generally referred to as a "module" , "system" or "architecture". In addition, aspects of the present technical solution may take the form of a computer program product implemented on one or more computer-readable media having computer-readable program code embodied thereon.
[00169] Также может быть использована любая комбинация одного или нескольких машиночитаемых носителей. Машиночитаемый носитель хранилища может представлять собой, без ограничений, электронную, магнитную, оптическую, электромагнитную, инфракрасную или полупроводниковую систему, аппарат, устройство или любую подходящую их комбинацию. Конкретнее, примеры (неисчерпывающий список) машиночитаемого носителя хранилища включают в себя: электрическое соединение с помощью одного или нескольких проводов, портативную компьютерную дискету; жесткий диск, оперативную память (ОЗУ), постоянную память (ПЗУ), стираемую программируемую постоянную память (EPROM или Flash-память), оптоволоконное соединение, постоянную память на компакт-диске (CD-ROM), оптическое устройство хранения, магнитное устройство хранения или любую комбинацию вышеперечисленного. В контексте настоящего описания, машиночитаемый носитель хранилища может представлять собой любой гибкий носитель данных, который может содержать или хранить программу для использования самой системой, устройством, аппаратом или в соединении с ними. [00169] Any combination of one or more computer-readable media can also be used. The computer-readable storage medium can be, without limitation, an electronic, magnetic, optical, electromagnetic, infrared, or semiconductor system, apparatus, device, or any suitable combination thereof. More specifically, examples (non-exhaustive list) of a computer-readable storage medium include: an electrical connection using one or more wires, a portable computer diskette; hard disk, random access memory (RAM), read only memory (ROM), erasable programmable read only memory (EPROM or Flash memory), fiber optic connection, compact disc read only memory (CD-ROM), optical storage device, magnetic storage device, or any combination of the above. As used herein, a computer-readable storage medium can be any flexible storage medium that can contain or store a program for use by or in connection with a system, device, apparatus, or in connection with them.
[00170] Программный код, встроенный в машиночитаемый носитель, может быть передан с помощью любого носителя, включая, без ограничений, беспроводную, проводную, оптоволоконную, инфракрасную и любую другую подходящую сеть или комбинацию вышеперечисленного. [00170] Program code embedded in a computer-readable medium may be transmitted using any medium, including, without limitation, wireless, wired, fiber optic, infrared, and any other suitable network, or a combination of the foregoing.
[00171] Компьютерный программный код для выполнения операций для шагов настоящего технического решения может быть написан на любом языке программирования или комбинаций языков программирования, включая объектно-ориентированный язык программирования, например Python, R, Java, Smalltalk, C++ и так далее, и обычные процедурные языки программирования, например язык программирования «С» или аналогичные языки программирования. Программный код может выполняться на компьютере пользователя полностью, частично, или же как отдельный пакет программного обеспечения, частично на компьютере пользователя и частично на удаленном компьютере, или же полностью на удаленном компьютере. В последнем случае, удаленный компьютер может быть соединен с компьютером пользователя через сеть любого типа, включая локальную сеть (LAN), глобальную сеть (WAN) или соединение с внешним компьютером (например, через Интернет с помощью Интернет- провайдеров). [00171] The computer program code for performing the operations for the steps of the present technical solution may be written in any programming language or combinations of programming languages, including an object-oriented programming language such as Python, R, Java, Smalltalk, C++, and so on, and conventional procedural programming languages, such as the "C" programming language or similar programming languages. The program code may be executed in whole, in part on the user's computer, or as a separate software package, in part on the user's computer and in part on a remote computer, or entirely on a remote computer. In the latter case, the remote computer may be connected to the user's computer via any type of network, including a local area network (LAN), a wide area network (WAN), or a connection to an external computer (eg, via the Internet via ISPs).
[00172] Аспекты настоящего технического решения были описаны подробно со ссылкой на блок-схемы, принципиальные схемы и/или диаграммы способов, устройств (систем) и компьютерных программных продуктов в соответствии с вариантами осуществления настоящего технического решения. Следует иметь в виду, что каждый блок из блок- схемы и/или диаграмм, а также комбинации блоков из блок-схемы и/или диаграмм, могут быть реализованы компьютерными программными инструкциями. Эти компьютерные программные инструкции могут быть предоставлены процессору компьютера общего назначения, компьютера специального назначения или другому устройству обработки данных для создания процедуры, таким образом, чтобы инструкции, выполняемые процессором компьютера или другим программируемым устройством обработки данных, создавали средства для реализации функций/действий, указанных в блоке или блоках блок-схемы и/или диаграммы. [00172] Aspects of the present technical solution have been described in detail with reference to block diagrams, circuit diagrams and/or diagrams of methods, devices (systems), and computer program products in accordance with embodiments of the present technical solution. It should be appreciated that each block from the block diagram and/or diagrams, as well as combinations of blocks from the block diagram and/or diagrams, may be implemented by computer program instructions. These computer program instructions can be provided to the processor of a general purpose computer, special purpose computer, or other data processing device to create a procedure, so that instructions executed by the computer processor or other programmable data processing device create the means to implement the functions/actions indicated in the block or blocks of the block diagram and/or charts.
[00173] Эти компьютерные программные инструкции также могут храниться на машиночитаемом носителе, который может управлять компьютером, отличным от программируемого устройства обработки данных или отличным от устройств, которые функционируют конкретным образом, таким образом, что инструкции, хранящиеся на машиночитаемом носителе, создают устройство, включающее инструкции, которые осуществляют функции/действия, указанные в блоке блок-схемы и/или диаграммы. [00173] These computer program instructions may also be stored on a computer-readable medium that can control a computer other than a programmable data processing device or other than devices that operate in a particular manner such that the instructions stored on the computer-readable medium create a device including instructions that perform the functions/actions indicated in the block diagram and/or diagram.

Claims

ФОРМУЛА Способ управления диалогом, выполняемый по меньшей мере одним процессором и включающий следующие шаги: FORMULA Dialog control method executed by at least one processor and including the following steps:
• получают от по меньшей мере одного пользователя по меньшей мере один запрос на инициацию диалога, содержащий уникальный идентификатора виртуального ассистента и идентификатор диалога; • receive from at least one user at least one request to initiate a dialogue containing a unique virtual assistant identifier and a dialogue identifier;
• осуществляют поиск в базе данных виртуального ассистента на основании полученного на предыдущем шаге идентификатора ассистента; • perform a database search for a virtual assistant based on the assistant ID obtained in the previous step;
• осуществляют поиск в базе данных ранее инициированного диалога на основании идентификатора диалога, полученного на предыдущем шаге, причем a. если диалог был найден, то выполняют поиск в базе данных активной сессии, связанной с найденным диалогом. b. если сессия не обнаружена, то в базе данных для найденного диалога создают новую сессию, которая определяется новым уникальным идентификатором сессии, идентификатором созданного диалога, пустым контекстом сессии. • search the database for a previously initiated dialog based on the dialog ID obtained in the previous step, where a. if the dialog was found, then search the active session database associated with the found dialog. b. if the session is not found, then a new session is created in the database for the found dialog, which is determined by a new unique session identifier, the identifier of the created dialog, and an empty session context.
• получают от пользователя запрос в диалоге, содержащий идентификатор диалога с виртуальным ассистентом, полученный при инициации диалога, по меньшей мере одно текстовое сообщение пользователя, контекст запроса; • receive from the user a request in the dialog, containing the ID of the dialog with the virtual assistant received when the dialog was initiated, at least one text message of the user, the context of the request;
• осуществляют обнаружение интентов пользователя посредством алгоритмов машинного обучения, которые получают на вход идентификатор виртуального ассистента и текстовое сообщение из запроса пользователя, в результате чего формируют список интентов и степени уверенности в том, что данные интенты присутствуют в сообщении пользователя; • detecting user intents by means of machine learning algorithms that receive a virtual assistant identifier and a text message from the user's request as input, as a result of which a list of intents and degrees of confidence that these intents are present in the user's message are formed;
• выполняют поиск наиболее подходящего правила для формирования ответа на основании интентов пользователя, полученных на предыдущем шаге. • search for the most appropriate rule for generating a response based on the user's intents obtained in the previous step.
33 Способ по п. 1 , характеризующийся тем, что виртуальный ассистент содержит уникальный идентификатор ассистента и набор именованных параметров. Способ по п. 1 , характеризующийся тем, что при получении запроса от пользователя в диалоге осуществляют поиск вхождений словарей языка DL в сообщение пользователя по следующему способу: 33 The method according to claim 1, characterized in that the virtual assistant contains a unique assistant identifier and a set of named parameters. The method according to claim 1, characterized in that upon receiving a request from the user in the dialog, they search for occurrences of DL language dictionaries in the user's message according to the following method:
• определяют все вхождения текстовых элементов строк словарей DL с использованием заранее подготовленного префиксного дерева; • determine all occurrences of text elements of strings of DL dictionaries using a previously prepared prefix tree;
• выбирают все строки словарей, которые отвечают следующим эвристикам: a. в сообщении пользователя есть все текстовые элементы входящие в строку словаря DL, b. существует порядок найденных вхождений текстовых элементов, соответствующий строке словаря DL, о если нет текстовых элементов, располагающихся в самом начале сообщения пользователя, то в строке словаря DL в начале должна стоять звездочка или суперзвездочка. о если нет текстовых элементов, располагающихся в самом конце сообщения пользователя, то в строке словаря DL в конце должна стоять звездочка или суперзвездочка. Способ по п. 1 , характеризующийся тем, что при обнаружении интентов, если их уверенность классификации ниже конфигурационного параметра, они отбрасываются. Способ по п. 1 , характеризующийся тем, что для каждого интента уверенность классификации умножается на конфигурационный параметр и округляется с точностью, определяемой конфигурационным параметром. Способ по п. 1 , характеризующийся тем, что после обнаружения интентов они группируются по имени роли, присвоенной им. Способ по п. 1 , характеризующийся тем, что при осуществлении поиска подходящего правила для формирования ответа для каждого шаблон- вопроса и интента, входящего в шаблон языка DL, определяется вес его совпадения с сообщением пользователя. • select all dictionary strings that match the following heuristics: a. the user's message contains all the text elements included in the DL dictionary string, b. there is an order of found occurrences of text elements corresponding to the DL dictionary string, but if there are no text elements located at the very beginning of the user's message, then the DL dictionary string must have an asterisk or superstar at the beginning. o If there are no text elements located at the very end of the user's message, then the DL dictionary line must end with an asterisk or superstar. The method according to claim 1, characterized in that when intents are detected, if their classification confidence is lower than the configuration parameter, they are discarded. The method according to claim 1, characterized in that for each intent the classification confidence is multiplied by the configuration parameter and rounded with the accuracy determined by the configuration parameter. The method according to claim 1, characterized in that after the discovery of intents, they are grouped by the name of the role assigned to them. The method according to claim 1, characterized in that when searching for a suitable rule for generating an answer for each question template and intent included in the DL language template, the weight of its match with the user's message is determined.
34 Способ по п. 7, характеризующийся тем, что весом является 32х битовое беззнаковое целое число. Способ по п. 7, характеризующийся тем, что осуществляют выборку шаблонов одинакового веса посредством выбора из найденных всех шаблонов-вопросов и интентов с максимальным весом, при этом выбранные шаблоны удаляются из списка поиска. Способ по п. 1 , характеризующийся тем, что при осуществлении поиска подходящего правила для формирования ответа 34 The method according to claim 7, characterized in that the weight is a 32-bit unsigned integer. The method according to claim 7, characterized in that templates of the same weight are selected by selecting from the found all question templates and intents with the maximum weight, while the selected templates are removed from the search list. The method according to claim 1, characterized in that when searching for a suitable rule for generating a response
- составляют список шаблон-ответов, относящихся к выбранным шаблон-вопросам и интентам; - make a list of template-answers related to the selected template-questions and intents;
■ проверяют возможность генерации непустого ответа, где пустым ответом считается ответ, не содержащий ни одного текстового элемента вывода; ■ check the possibility of generating a non-empty response, where an empty response is a response that does not contain any text output element;
• осуществляют рандомизацию, причем выбирают случайно один из отобранных ранее шаблон-ответов и определяют его ответом на сообщение пользователя; • Randomization is carried out, and one of the previously selected template-responses is chosen randomly and determined by its response to the user's message;
• формируют ответ по выбранному правилу, причем для выбранного шаблон-ответа обрабатываются все функциональные элементы языка DL в соответствии с их описанием; • form a response according to the selected rule, and for the selected response template, all functional elements of the DL language are processed in accordance with their description;
■ записывают журнал диалога и сформированный ответ записывается в базу данных. ■ write the conversation log and the generated response is written to the database.
PCT/RU2020/000730 2020-12-18 2020-12-18 Dialogue control method and system for understanding natural language in a virtual assistant platform WO2022131954A1 (en)

Applications Claiming Priority (2)

Application Number Priority Date Filing Date Title
RU2020141962 2020-12-18
RU2020141962A RU2759090C1 (en) 2020-12-18 2020-12-18 Method for controlling a dialogue and natural language recognition system in a platform of virtual assistants

Publications (1)

Publication Number Publication Date
WO2022131954A1 true WO2022131954A1 (en) 2022-06-23

Family

ID=78466900

Family Applications (1)

Application Number Title Priority Date Filing Date
PCT/RU2020/000730 WO2022131954A1 (en) 2020-12-18 2020-12-18 Dialogue control method and system for understanding natural language in a virtual assistant platform

Country Status (2)

Country Link
RU (1) RU2759090C1 (en)
WO (1) WO2022131954A1 (en)

Citations (5)

* Cited by examiner, † Cited by third party
Publication number Priority date Publication date Assignee Title
US20120016678A1 (en) * 2010-01-18 2012-01-19 Apple Inc. Intelligent Automated Assistant
US20140040748A1 (en) * 2011-09-30 2014-02-06 Apple Inc. Interface for a Virtual Digital Assistant
RU2509350C2 (en) * 2008-11-07 2014-03-10 Матрокс Профешнл Инк Method for semantic processing of natural language using graphic intermediary language
US20140074454A1 (en) * 2012-09-07 2014-03-13 Next It Corporation Conversational Virtual Healthcare Assistant
US20190179890A1 (en) * 2013-06-09 2019-06-13 Apple Inc. System and method for inferring user intent from speech inputs

Patent Citations (5)

* Cited by examiner, † Cited by third party
Publication number Priority date Publication date Assignee Title
RU2509350C2 (en) * 2008-11-07 2014-03-10 Матрокс Профешнл Инк Method for semantic processing of natural language using graphic intermediary language
US20120016678A1 (en) * 2010-01-18 2012-01-19 Apple Inc. Intelligent Automated Assistant
US20140040748A1 (en) * 2011-09-30 2014-02-06 Apple Inc. Interface for a Virtual Digital Assistant
US20140074454A1 (en) * 2012-09-07 2014-03-13 Next It Corporation Conversational Virtual Healthcare Assistant
US20190179890A1 (en) * 2013-06-09 2019-06-13 Apple Inc. System and method for inferring user intent from speech inputs

Also Published As

Publication number Publication date
RU2759090C1 (en) 2021-11-09

Similar Documents

Publication Publication Date Title
Poongodi et al. Chat-bot-based natural language interface for blogs and information networks
CN108847241B (en) Method for recognizing conference voice as text, electronic device and storage medium
Williams et al. A broad-coverage challenge corpus for sentence understanding through inference
CN110462730B (en) Facilitating end-to-end communication with automated assistants in multiple languages
WO2020147428A1 (en) Interactive content generation method and apparatus, computer device, and storage medium
CN107330120B (en) Inquire answer method, inquiry answering device and computer readable storage medium
US20150279366A1 (en) Voice driven operating system for interfacing with electronic devices: system, method, and architecture
JP2020140210A (en) Method and system to handle queries whose intention are unclear in conversational system
US20230080671A1 (en) User intention recognition method and apparatus based on statement context relationship prediction
CN107818781A (en) Intelligent interactive method, equipment and storage medium
WO2020056621A1 (en) Learning method and apparatus for intention recognition model, and device
US11593572B2 (en) System and method for language processing using adaptive regularization
US11861315B2 (en) Continuous learning for natural-language understanding models for assistant systems
CN108345612A (en) A kind of question processing method and device, a kind of device for issue handling
Windiatmoko et al. Developing facebook chatbot based on deep learning using rasa framework for university enquiries
WO2021063089A1 (en) Rule matching method, rule matching apparatus, storage medium and electronic device
Windiatmoko et al. Developing FB chatbot based on deep learning using RASA framework for university enquiries
JP2019185737A (en) Search method and electronic device using the same
CN116615727A (en) Keyword data augmentation tool for natural language processing
WO2021129411A1 (en) Text processing method and device
CN112818096A (en) Dialog generating method and device
US10282417B2 (en) Conversational list management
CN110020429B (en) Semantic recognition method and device
CN112001167A (en) Punctuation mark adding method, system, equipment and medium
RU2759090C1 (en) Method for controlling a dialogue and natural language recognition system in a platform of virtual assistants

Legal Events

Date Code Title Description
121 Ep: the epo has been informed by wipo that ep was designated in this application

Ref document number: 20966099

Country of ref document: EP

Kind code of ref document: A1

NENP Non-entry into the national phase

Ref country code: DE

122 Ep: pct application non-entry in european phase

Ref document number: 20966099

Country of ref document: EP

Kind code of ref document: A1