Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Offline classification agent #365

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
10 changes: 10 additions & 0 deletions docs/agents/messageTopicClassificationAgent.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,16 @@ The agent classifies a message using Wit.ai.

* [Wit.ai](https://wit.ai/) - to classify message and get entities.

**Wit.ai features**

Unlike other available message classifier(Rasa) With.ai has the ability to determine the message trait. However, a significant disadvantage of using it is its dependence on an Internet connection. Also Wit.ai it has a pre-created interface for training an existing classifier.

The json format of the response from the classifier:

```json
{"entities":{"rrel_entity:rrel_entity":[{"body":"Ника","confidence":1,"end":23,"entities":{},"id":"545916503952309","name":"rrel_entity","role":"rrel_entity","start":19,"type":"value","value":"Ника"}]},"intents":[{"confidence":1,"id":"271954618797345","name":"about_skill"}],"text":"На что разбивается Ника?","traits":{}}
```

**Comment:**

* The input message must contain a text file with the text in Russian;
Expand Down
10 changes: 10 additions & 0 deletions docs/agents/messageTopicClassificationAgent.ru.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,16 @@

* [Wit.ai](https://wit.ai/) - для классификации сообщений и получения сущностей.

**Особенности Wit.ai**

В отличие от другого имеющегося классификатора сообщений(Rasa) Wit.ai имеет возможность определять признак сообщения. Однако существенным недостатком его использования является зависимость от Интернет соединения. Также Wit.ai имеет уже заранее созданный интерфейс для обучения имеющегося классификатора.

Формат json ответа от классификатора:

```json
{"entities":{"rrel_entity:rrel_entity":[{"body":"Ника","confidence":1,"end":23,"entities":{},"id":"545916503952309","name":"rrel_entity","role":"rrel_entity","start":19,"type":"value","value":"Ника"}]},"intents":[{"confidence":1,"id":"271954618797345","name":"about_skill"}],"text":"На что разбивается Ника?","traits":{}}
```

**Комментарий:**

* Входное сообщение должно содержать текстовый файл с текстом на русском языке;
Expand Down
63 changes: 63 additions & 0 deletions docs/agents/rasaMessageTopicClassificationAgent.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
# Message topic classification agent

This is an agent that performs the message classification by topic (greeting, about lab work condition, about entity etc.).
The agent classifies a message using Rasa.

**Action class:**

`action_rasa_message_topic_classification`

**Parameters:**

1. `messageAddr` -- an element of `concept_message`.

**Libraries used:**

* [Rasa](https://rasa.com/) - Rasa official website with documentation.

**Rasa features**

The use of the Rasa classifier is absolutely independent of the Internet connection, as well as its training and testing. Rasa does not have a pre-designed interface for training the classifier, it can be trained via .yml files. The Rasa module contains many other modules on which it depends, so it is necessary to allocate space in advance for local storage of the classifier.

The json format of the response from the classifier:

```json
{"text":"Что такое Ника?","intent":{"name":"concept_message_about_entity","confidence":1.0},"entities":[{"entity":"entity","start":10,"end":14,"confidence_entity":0.9997850060462952,"value":"Ника","extractor":"DIETClassifier"}],"text_tokens":[[0,3],[4,9],[10,14]],"intent_ranking":[{"name":"ask_definition","confidence":1.0},{"name":"goodbye","confidence":2.69290423293711e-10},{"name":"greet","confidence":1.639179937618085e-11}]}
```

**Comment:**

* The input message must contain a text file with the text in Russian;
* The excluding entity should be formalized in knowledge base.

### Examples

Examples of an input structure:

<img src="../images/rasaMessageTopicClassificationAgentInput.png"></img>

Examples of an output structure:

<img src="../images/rasaMessageTopicClassificationAgentOutput.png"></img>

Example of a structure needed to classify message by intent:

<img src="../images/rasaMessageTopicClassificationAgentIntentFormalization.png"></img>

Example of a structure needed to get message entity:

<img src="../images/rasaMessageTopicClassificationAgentEntityFormalization.png"></img>

**Message classes:**

1. `concept_message_about_entity`

### Agent implementation language
C++

### Result

Possible result codes:

* `SC_RESULT_OK` - the message is successfully classified (or there is empty classification) or the action doesn't belong to the action_message_topic_classification.
* `SC_RESULT_ERROR`- internal error.
62 changes: 62 additions & 0 deletions docs/agents/rasaMessageTopicClassificationAgent.ru.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
# Агент классификации темы сообщения

Данный агент выполняет классификацию сообщений по теме (приветствие, про условия лабораторной работы, про сущность и т.д.).
Агент классифицирует сообщение с помощью Rasa.

**Класс действий:**

`action_rasa_message_topic_classification`

**Параметры:**

1. `messageAddr` -- элемент класса `concept_message`.

**Используемые библиотеки:**

* [Rasa](https://rasa.com/) - официальный сайт Rasa с документацией.

**Особенности Rasa**

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

Формат json ответа от классификатора:

```json
{"text":"Что такое Ника?","intent":{"name":"concept_message_about_entity","confidence":1.0},"entities":[{"entity":"entity","start":10,"end":14,"confidence_entity":0.9997850060462952,"value":"Ника","extractor":"DIETClassifier"}],"text_tokens":[[0,3],[4,9],[10,14]],"intent_ranking":[{"name":"ask_definition","confidence":1.0},{"name":"goodbye","confidence":2.69290423293711e-10},{"name":"greet","confidence":1.639179937618085e-11}]}
```

**Комментарий:**

* Входное сообщение должно содержать текстовый файл с текстом на русском языке;
* Выделяемая сущность должна быть формализованна в базе знаний.

### Пример

Пример входной структуры:

<img src="../images/rasaMessageTopicClassificationAgentInput.png"></img>

Пример выходной структуры:
<img src="../images/rasaMessageTopicClassificationAgentOutput.png"></img>

Пример структуры, необходимой для классификации сообщения по теме:

<img src="../images/rasaMessageTopicClassificationAgentIntentFormalization.png"></img>

Пример структуры, необходимой для получения сущностей сообщения:

<img src="../images/rasaMessageTopicClassificationAgentEntityFormalization.png"></img>

**Текущие классифицируемые сообщения:**

1. `concept_message_about_entity`

### Язык реализации агента
C++

### Результат

Возможные результаты:

* `SC_RESULT_OK` - сообщение успешно классифицировано (или произошла пустая классификация) или действие не принадлежит action_rasa_message_topic_classification.
* `SC_RESULT_ERROR`- внутренняя ошибка.
39 changes: 39 additions & 0 deletions docs/build/linux-build.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,39 @@ git submodule update --init --recursive
./scripts/install_py_sc_server_deps.sh
```

## Rasa classifier installation

- Directory selection and creation
```sh
mkdir rasa_model
cd rasa_model
```
- Virtual environment creation and activation
```sh
sudo apt install python3.8-venv
python3.8 -m venv ./venv
source ./venv/bin/activate
```

- Rasa module installation
```sh
pip install rasa
```

- Rasa initialization
```sh
rasa init
rasa train nlu
rasa shell nlu
```

**Note**
```sh
rasa init
```

When running this command, 2 questions will be asked: choosing a folder for the classifier and offering to train the classifier immediately. There is no need to train the classifier, it should be done with the commands written above.

## Build

- Build problem solver
Expand Down Expand Up @@ -46,8 +79,14 @@ git submodule update --init --recursive

# Terminal 4
./scripts/run_interface.sh

# Terminal 5
cd rasa_model
rasa run --enable-api -m models/
```

In Terminal 5 after models/ should come name of the trained classifier model file. For example, nlu-20241129-200228-wooden-refund.tar.gz.

This commands will launch 2 Web UIs on your machine:

- sc-web - `localhost:8000`
Expand Down
39 changes: 39 additions & 0 deletions docs/build/linux-build.ru.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,39 @@ git submodule update --init --recursive
./scripts/install_py_sc_server_deps.sh
```

## Установка Rasa классификатора

- Выбор и создание папки
```sh
mkdir rasa_model
cd rasa_model
```
- Создание и активация виртуального пространства
```sh
sudo apt install python3.8-venv
python3.8 -m venv ./venv
source ./venv/bin/activate
```

- Установка Rasa модуля
```sh
pip install rasa
```

- Инициализация Rasa
```sh
rasa init
rasa train nlu
rasa shell nlu
```

**Примечание**
```sh
rasa init
```

При запускее этой команды, будет задано 2 вопроса: выбор папки для классификатора и предложение сразу тренировать классификатор. Классификатор тренировать не надо, это стоит делать указанными командами выше.

## Сборка

- Сборка решателя задач
Expand Down Expand Up @@ -43,8 +76,14 @@ git submodule update --init --recursive

# Терминал 3
./scripts/run_interface.sh

# Терминал 4
cd rasa_model
rasa run --enable-api -m models/
```

После models/ должен следовать файл заранее натренированной модели классификатора. Например, nlu-20241129-200228-wooden-refund.tar.gz.

Данные команды запустят 2 следующих web-интерфейса:

- sc-web - `localhost:8000`
Expand Down
18 changes: 12 additions & 6 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,18 @@
* [Non-atomic action interpretation agent](agents/nonAtomicActionInterpretationAgent.md)
* [Message reply agent](agents/messageReplyAgent.md)
* [Standard message reply agent](agents/standardMessageReplyAgent.md)
* [Message topic classification agent](agents/messageTopicClassificationAgent.md)
* [Alternative message topic classification agent](agents/alternativeMessageTopicClassificationAgent.md)
* [Phrase generation agent](agents/phraseGenerationAgent.md)
* [Change interface color agent](agents/changeInterfaceColorAgent.md)
* [Find word in set by first letter agent](agents/findWordInSetByFirstLetter.md)
* [Weather agent](agents/weatherAgent.md)
* <details>
<summary>Message topic classification</summary>
<ul>
<li>[Wit message topic classification agent](agents/messageTopicClassificationAgent.md)</li>
<li>[Rasa message topic classification agent](agents/rasaMessageTopicClassificationAgent.md)</li>
</ul>
</details>
* [Alternative message topic classification agent](agents/alternativeMessageTopicClassificationAgent.md)
* [Phrase generation agent](agents/phraseGenerationAgent.md)
* [Change interface color agent](agents/changeInterfaceColorAgent.md)
* [Find word in set by first letter agent](agents/findWordInSetByFirstLetter.md)
* [Weather agent](agents/weatherAgent.md)

- **Patterns**
* [Knowledge base patterns](patterns/kb-patterns.md)
Expand Down
9 changes: 8 additions & 1 deletion docs/index.ru.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,13 @@
* [Агент интерпретации неатомарных действий](agents/nonAtomicActionInterpretationAgent.ru.md)
* [Агент ответа на сообщениеt](agents/messageReplyAgent.ru.md)
* [Агент генерации ответа на сообщение](agents/standardMessageReplyAgent.ru.md)
* [Агент классификации сообщений с помощью Wit.ai](agents/messageTopicClassificationAgent.ru.md)
* <details>
<summary>Классификация сообщений по теме</summary>
<ul>
<li>[Агент классификации сообщений с помощью Wit.ai](agents/messageTopicClassificationAgent.ru.md)</li>
<li>[Агент классификации сообщений с помощью Rasa](agents/rasaMessageTopicClassificationAgent.ru.md)</li>
</ul>
</details>
* [Агент классификации сообщений с помощью логических правил](agents/alternativeMessageTopicClassificationAgent.ru.md)
* [Агент генерации фраз](agents/phraseGenerationAgent.ru.md)
* [Агент смены цвета компонента интерфейса](agents/changeInterfaceColorAgent.ru.md)
Expand All @@ -26,3 +32,4 @@

- **Подсистемы**
* [scl-machine](subsystems/scl-machine.ru.md)

8 changes: 8 additions & 0 deletions docs/messageTopicClassificationModule.ru.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# Модуль классификации сообщений

Агенты модуля классификации сообщений выполняют классификацию сообщений по теме: определяют намерение сообщения, выделяют сущностей.

На данный момент имеются следующие агенты классификации сообщений:
* [Агент классификации сообщений с помощью Wit.ai](messageTopicClassificationAgent.ru.md)
* [Агент классификации сообщений с помощью Rasa](rasaMessageTopicClasificationAgent.ru.md)

36 changes: 36 additions & 0 deletions kb/non_subject_domain_concepts/rasa/concept_rasa_entity.scs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
concept_rasa_entity
<- sc_node_class;
=> nrel_main_idtf:
[сущность Rasa]
(* <- lang_ru;; *);
[Rasa entity]
(* <- lang_en;; *);
=> nrel_rasa_idtf:
[rrel_entity];
<- rrel_key_sc_element:
...
(*
=> nrel_main_idtf:
[Опр. (сущность Rasa)]
(* <- lang_ru;; *);
[Def. (Rasa entity)]
(* <- lang_en;; *);;
<- definition;;
<= nrel_sc_text_translation:
...
(*
-> rrel_example:
[Сущность Rasa - множество сущностей, выделенных в сообщении с помощью Rasa.]
(* <- lang_ru;; *);;
*);
...
(*
-> rrel_example:
[Rasa entity is a set of entities, defined in the message using Rasa.]
(* <- lang_en;; *);;
*);;
*);
=> nrel_entity_possible_role:
{
rrel_entity
};;
Loading
Loading