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

Дятлов Е.А. Пашин Н.А. Курсовой проект Компонент создания класса сообщений и шаблона фраз #343

Open
wants to merge 18 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 13 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
48 changes: 48 additions & 0 deletions docs/agents/createMessageClassAndPhraseTemplateAgent.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# Create message class and phrase template agent

This agent creates a message class, phrase templates and a logical response rule.

**Action class:**

`action_create_message_class_and_phrase_template`

**Parameters:**

1. `messageAddr` -- an element of `concept_message`.
2. `formLinkAddr` -- link with information from popup component.

### Examples

**Example of an input structure:**

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

**Examples of an output structure:**

Output about the successful creation of structures.

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

Error output about invalid parameters.

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

Error ouput about the existence of params.

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

Output to notify when the user has completed an action.

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

The result of the agent's work depends on the data received from the component.If the received data is correct, the structures will be created. Otherwise, a corresponding error message will be displayed.

### Agent implementation language
C++

### Result

Possible result codes:

* `SC_RESULT_OK` - the constructs (message class, phrase templates and logical response rule) were successfully created or formLinkAddr contains incorrect data.
* `SC_RESULT_ERROR`- internal error.
48 changes: 48 additions & 0 deletions docs/agents/createMessageClassAndPhraseTemplateAgent.ru.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# Агент создания класса сообщений и шаблонов фраз

Данный агент создает класс сообщения, шаблоны фраз и правило логического ответа.

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

`action_create_message_class_and_phrase_template`

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

1. `messageAddr` -- элемент класса `concept_message`.
2. `formLinkAddr` -- ссылка на информацию из всплывающего компонента.

### Пример

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

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

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

Вывод об успешном создании структур.

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

Вывод ошибки о недопустимых параметрах.

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

Вывод ошибки о существовании параметров.

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

Вывод для уведомления о завершении действия пользователем.

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

Результат работы агента зависит от данных, полученных от компонента. Если полученные данные верны, структуры будут созданы. В противном случае отобразится соответствующее сообщение об ошибке.

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

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

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

* `SC_RESULT_OK` - конструкции (класс сообщения, шаблоны фраз и правило логического ответа) были успешно созданы или formLinkAddr содержит неверные данные.
* `SC_RESULT_ERROR`- внутренняя ошибка.
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.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
8 changes: 8 additions & 0 deletions docs/changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,3 +57,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Add SD of intelligent studying systems
- Add SD of dialogues
- Add SD of messages

## 25.03.2024

### Added

- Add popup components for creating message class and phrase templates
- Add help-functions for components
- Add agent for creating constructions: message class, phrase templates and logic rule
4 changes: 4 additions & 0 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@
* [Change interface color agent](agents/changeInterfaceColorAgent.md)
* [Find word in set by first letter agent](agents/findWordInSetByFirstLetter.md)
* [Weather agent](agents/weatherAgent.md)
* [Create message class and phrase template agent](agents/createMessageClassAndPhraseTemplateAgent.md)

- **User Interface**
* [Popup component for creating message class and phrase template](ui/popupComponentForCreatingMessageClassAndPhraseTemplate.md)

- **Patterns**
* [Knowledge base patterns](patterns/kb-patterns.md)
Expand Down
4 changes: 4 additions & 0 deletions docs/index.ru.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@
* [Агент смены цвета компонента интерфейса](agents/changeInterfaceColorAgent.ru.md)
* [Агент поиска слова по первой букве](agents/findWordInSetByFirstLetter.ru.md)
* [Агент прогноза погоды](agents/weatherAgent.ru.md)
* [Агент создания класса сообщений и шаблонов фраз](agents/createMessageClassAndPhraseTemplateAgent.ru.md)

- **Пользовательский интерфейс**
* [Всплывающее окно для создания класса сообщений и шаблонов фраз](agents/popupComponentForCreatingMessageClassAndPhraseTemplate.ru.md)

- **Шаблоны**
* [Шаблоны для базы знаний](patterns/kb-patterns.ru.md)
Expand Down
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.
34 changes: 34 additions & 0 deletions docs/ui/popupComponentForCreatingMessageClassAndPhraseTemplate.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# User interface component (pop-up window) for creating a message class and phrase templates

This component is used to create a class of messages and phrase templates.

**Phrase for calling the component**

`Создай класс сообщений и шаблоны фраз`

**Action Class:**

`action_message_class_and_phrase_template`

### Description

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

This state of the component is a form, by filling in which data about the system class identifier, about the class identifier in Russian and about the name of the intent in the wit.ai for further processing by the appropriate agent. To move to the next state of the component and save the form data, click the "Next" button.

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

This state of the component is a form, by filling in which data is stored about the system identifier of the phrase template, about the identifier of the phrase template in Russian and about phrases for further processing by the appropriate agent. In this form, the chip component (compact elements representing input data) is used to add an arbitrary number of phrases. To save the form data and create structures, click the "Save" button.

### Component implementation language

TypeScript

### Result

Possible results:

* `Теперь я умею отвечать на новый вопрос!` - constructs (message class, phrase templates, and logical response rule) have been successfully created.
* `Ошибка. Введённые вами системные индетификаторы либо wit.ai intent уже существуют.`- the data entered by the user already exists in the knowledge base.
* `Ошибка. Вы не ввели системные индетификаторы, wit.ai intent или фразы овтетов.` - the user has not entered all the data.
* `Дейстиве прервано пользователем.` - the user has closed the component.
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# Компонент пользовательского интерфейса (всплывающее окно) для создания класса сообщений и шаблонов фраз

Данный компонент используется для создания класса сообщений и шаблонов фраз.

**Фраза для вызова компонента**

`Создай класс сообщений и шаблоны фраз`

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

`action_message_class_and_phrase_template`

### Описание

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

Данное состояние компонента представляет собой форму, посредством заполнения которой, сохраняются данные о системном индетификаторе класса, о индетификаторе класса на русском языке и о названии интента в wit.ai для дальнейшей обработки соответствующим агентом. Для перехода к следующему состоянию компонента и сохранению данных формы необходимо нажать кнопку "Далее".

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

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

### Язык реализации компонента

TypeScript

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

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

* `Теперь я умею отвечать на новый вопрос!` - конструкции (класс сообщения, шаблоны фраз и правило логического ответа) были успешно созданы.
* `Ошибка. Введённые вами системные индетификаторы либо wit.ai intent уже существуют.`- данные введённые пользователем уже существуют в базе знаний.
* `Ошибка. Вы не ввели системные индетификаторы, wit.ai intent или фразы овтетов.` - пользователь не ввёл все данные.
* `Дейстиве прервано пользователем.` - пользователь закрыл компонент.
144 changes: 144 additions & 0 deletions interface/src/api/sc/agents/helper.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
import { ScAddr, ScTemplate, ScType } from 'ts-sc-client';
import { client } from '@api/sc/client';
import { ScConstruction, ScLinkContent, ScLinkContentType, ScEventParams, ScEventType } from 'ts-sc-client';
import { makeAgent } from '@api/sc/agents/makeAgent';
import { createLinkText } from './newMessageAgent';
import React from "react";

const nrelSystemIdentifier = 'nrel_system_identifier';
const nrelAuthors = 'nrel_authors';
const nrelScTextTranslation = 'nrel_sc_text_translation';
const question = 'question';
const actionCreateMessageClassAndPhraseTemplate = 'action_create_message_class_and_phrase_template';
const rrel1 = 'rrel_1';
const rrel2 = 'rrel_2';
const conceptTextFile = 'concept_text_file';
const conceptMessage = 'concept_message';
const conceptDialogue = 'concept_dialogue';
const langRu = 'lang_ru';
const message = '_message';

const baseKeynodes = [
{ id: nrelSystemIdentifier, type: ScType.NodeConstNoRole},
{ id: nrelAuthors, type: ScType.NodeConstNoRole},
{ id: nrelScTextTranslation, type: ScType.NodeConstNoRole},
{ id: question, type: ScType.NodeConstClass },
{ id: actionCreateMessageClassAndPhraseTemplate, type: ScType.NodeConstClass },
{ id: rrel1, type: ScType.NodeConstRole },
{ id: rrel2, type: ScType.NodeConstRole },
{ id: conceptTextFile, type: ScType.NodeConstClass },
{ id: conceptMessage, type: ScType.NodeConstClass },
{ id: conceptDialogue, type: ScType.NodeConstClass },
{ id: langRu, type: ScType.NodeConstClass },
{ id: message, type: ScType.NodeVar},
];

const setSystemIdtf = async (addr: ScAddr, systemIdtf: string) => {
const keynodes = await client.resolveKeynodes(baseKeynodes);

const template = new ScTemplate();
const linkAlias = "_link";

const sysIdtfLinkConstruction = new ScConstruction();
sysIdtfLinkConstruction.createLink(
ScType.LinkConst,
new ScLinkContent(systemIdtf, ScLinkContentType.String)
);
const [sysIdtfLinkNode] = await client.createElements(sysIdtfLinkConstruction);

template.tripleWithRelation(
addr,
ScType.EdgeDCommonVar,
sysIdtfLinkNode,
ScType.EdgeAccessVarPosPerm,
keynodes[nrelSystemIdentifier]
);
const result = await client.templateGenerate(template, {});
};

export const handleSave = async (
phraseSystemIdentifierRef: React.RefObject<HTMLInputElement>,
phraseRussianIdentifierRef: React.RefObject<HTMLInputElement>,
form : string,
chipsValues: string[]
) => {
const inputValues = {
phraseSystemIdentifier: phraseSystemIdentifierRef.current?.value || '',
phraseRussianIdentifier: phraseRussianIdentifierRef.current?.value || '',
};

const phrases = chipsValues.join(', ');

const result : string = form + '\n' + Object.values(inputValues).join('\n') + '\n' + phrases;

const resultLinkAddr = await createLinkText(result);

if (resultLinkAddr !== null) {
await createMessageClassAndPhraseTemplateAgent(resultLinkAddr);
}
};

export const userClose = async () => {
const result : string = "User close";

const resultLinkAddr = await createLinkText(result);

if (resultLinkAddr !== null) {
await createMessageClassAndPhraseTemplateAgent(resultLinkAddr);
}
}

const describeAgent = async (
keynodes: Record<string, ScAddr>,
linkAddr: ScAddr,
action: string
) => {
const actionNodeAlias = '_action_node';

const template = new ScTemplate();

template.triple(keynodes[question], ScType.EdgeAccessVarPosPerm, [ScType.NodeVar, actionNodeAlias]);
template.triple(keynodes[action], ScType.EdgeAccessVarPosPerm, actionNodeAlias);

template.tripleWithRelation(
actionNodeAlias,
ScType.EdgeAccessVarPosPerm,
keynodes[message],
ScType.EdgeAccessVarPosPerm,
keynodes[rrel1],
);
template.tripleWithRelation(
actionNodeAlias,
ScType.EdgeAccessVarPosPerm,
linkAddr,
ScType.EdgeAccessVarPosPerm,
keynodes[rrel2],
);
template.triple(keynodes[conceptTextFile], ScType.EdgeAccessVarPosPerm, linkAddr);
template.triple(keynodes[langRu], ScType.EdgeAccessVarPosPerm, linkAddr);

return [template, actionNodeAlias] as const;
};

const createMessageClassAndPhraseTemplateAgent = async (linkAddr: ScAddr) => {
const keynodes = await client.resolveKeynodes(baseKeynodes);

const [template, userActionNodeAlias] = await describeAgent(keynodes, linkAddr, actionCreateMessageClassAndPhraseTemplate);

await makeAgent(template, userActionNodeAlias);
};


export const createPopupCheck = async (
setCreatePopup
) => {
const concept_popup = 'concept_popup_component_for_creating_message_class_and_phrase_template';

const baseKeynodes = [
{ id: concept_popup, type: ScType.NodeConstClass},
];

const keynodes = await client.resolveKeynodes(baseKeynodes);
const eventParams = new ScEventParams(keynodes[concept_popup], ScEventType.AddOutgoingEdge, () => {setCreatePopup(true)});
await client.eventsCreate([eventParams])
}
Loading