Skip to content

Feature/default message reply on errors #367

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

Merged
merged 5 commits into from
Jun 3, 2025
Merged
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.
67 changes: 67 additions & 0 deletions docs/agents/standardMessageReplyAgent.ru.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,73 @@
Агент, который создает ответное сообщение на основе существующих правил в базе знаний.
Агент использует генерацию фраз и агентов прямого вывода.

Сначала StandardMessageReplyAgent создает структуру ответного сообщения.
Собирает логические правила и целевой шаблон, затем пересылает информацию DirectInferenceAgent (агенту из подсистемы scl-machine) для дальнейшей обработки. Вы можете узнать больше про DirectInferenceAgent в документации [scl-machine](../subsystems/scl-machine.md). Если DirectInferenceAgent завершил работу успешно, StandardMessageReplyAgent вызывает PhraseGenerationAgent, чтобы создать sc-ссылку с текстом ответного сообщения. Если целевой шаблон ответного сообщения не был найден в качестве заключения логческого правила, StandardMessageReplyAgent создает структуру ответа по умолчанию с sc-ссылкой, содержащей текст о том, что не было найдено ответное сообщение, и перечисление классов, к которому принадлежит узел сообщения пользователя.

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

`action_standard_message_reply`

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

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

### Пример

#### 1. Генерация атомарного сообщения

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

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

1.2. Пример логического правила:

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

1.3. Пример фразы:

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

1.4. Пример выходной структуры (атомарное сообщение):

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

1.5 Пример выходной структуры ответного сообщенения по умолчанию:

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

где `{messageClasses}` - множество классов, которому принадлежит узел `messageAddr`.


#### 2. Генерация неатомарного сообщения

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

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

2.2. Пример логического правила:

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

2.3. Пример фразы:

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

2.4. Пример выходной структуры (неатомарное сообщение):

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

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

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

* `SC_RESULT_OK` - создано сообщение с ответом.
* `SC_RESULT_ERROR` - внутренняя ошибка.
* `SC_RESULT_ERROR_invalid_params` - у действия нет входящего сообщения.# Агент генерации ответа на сообщение

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

Сначала StandardMessageReplyAgent создает структуру ответного сообщения.
Собирает логические правила и целевой шаблон, затем пересылает информацию DirectInferenceAgent (агенту из подсистемы scl-machine) для дальнейшей обработки. Вы можете узнать больше про DirectInferenceAgent в документации [scl-machine](../subsystems/scl-machine.md). Затем он вызывает PhraseGenerationAgent, чтобы создать sc-ссылку с текстом ответного сообщения.

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#include "StandardMessageReplyAgent.hpp"

#include "keynodes/DialogKeynodes.hpp"
#include "keynodes/MessageKeynodes.hpp"
#include <common/utils/ActionUtils.hpp>
#include <sc-agents-common/utils/IteratorUtils.hpp>
Expand All @@ -24,9 +25,43 @@ ScResult StandardMessageReplyAgent::DoProgram(ScActionInitiatedEvent const & eve
}

ScAddr logicRuleNode = generateReplyMessage(messageNode);
if (!m_context.IsElement(logicRuleNode))
{
m_logger.Warning(
"The reply message isn't generated because reply construction wasn't found through direct inference agent. "
"Trying to generate default reply message");
std::stringstream setElementsTextStream;
ScAddrVector messageClasses;
setElementsTextStream
<< "Извините, я не нашла ответа на Ваш вопрос. Я определила, что данное сообщение является элементом классов:";
ScIterator3Ptr it3 = m_context.CreateIterator3(ScType::NodeConst, ScType::EdgeAccessConstPosPerm, messageNode);
while (it3->Next())
{
messageClasses.push_back(it3->Get(0));
}
ScAddr const & defaultReplyMessage = m_context.GenerateNode(ScType::NodeConst);
ScAddr const & defaultReplyLink = m_context.GenerateLink(ScType::LinkConst);
std::string replyText = setElementsTextStream.str();
replyText[replyText.length() - 2] = '.';
m_context.SetLinkContent(defaultReplyLink, replyText);
ScTemplate templ;
templ.Triple(ScKeynodes::lang_ru, ScType::VarPermPosArc, defaultReplyLink);
templ.Triple(ScType::VarNode >> "_link", ScType::VarPermPosArc, defaultReplyLink);
templ.Quintuple(
"_link",
ScType::VarCommonArc,
defaultReplyMessage,
ScType::VarPermPosArc,
DialogKeynodes::nrel_sc_text_translation);
templ.Quintuple(
messageNode, ScType::VarCommonArc, defaultReplyMessage, ScType::VarPermPosArc, MessageKeynodes::nrel_reply);
ScTemplateResultItem result;
m_context.GenerateByTemplate(templ, result);
action.SetResult(defaultReplyMessage);
return action.FinishSuccessfully();
}
ScAddr replyMessageNode = IteratorUtils::getAnyByOutRelation(&m_context, messageNode, MessageKeynodes::nrel_reply);
m_context.GenerateConnector(ScType::ConstPermPosArc, MessageKeynodes::concept_message, replyMessageNode);

if (!replyMessageNode.IsValid())
{
m_logger.Error("The reply message isn't generated");
Expand Down Expand Up @@ -78,11 +113,24 @@ ScAddr StandardMessageReplyAgent::generateReplyMessage(const ScAddr & messageNod
bool const result = actionDirectInference.InitiateAndWait(DIRECT_INFERENCE_AGENT_WAIT_TIME);
if (result)
{
ScAddr answer = IteratorUtils::getAnyByOutRelation(&m_context, actionDirectInference, ScKeynodes::nrel_result);
ScAddr solutionNode = IteratorUtils::getAnyFromSet(&m_context, answer);
ScAddr solutionTreeRoot = IteratorUtils::getAnyByOutRelation(&m_context, solutionNode, ScKeynodes::rrel_1);
if (solutionTreeRoot.IsValid())
logicRuleNode = IteratorUtils::getAnyByOutRelation(&m_context, solutionTreeRoot, ScKeynodes::rrel_1);
if (actionDirectInference.IsFinishedSuccessfully())
{
ScAddr answer = IteratorUtils::getAnyByOutRelation(&m_context, actionDirectInference, ScKeynodes::nrel_result);
ScAddr solutionNode = IteratorUtils::getAnyFromSet(&m_context, answer);
ScAddr solutionTreeRoot = IteratorUtils::getAnyByOutRelation(&m_context, solutionNode, ScKeynodes::rrel_1);
if (solutionTreeRoot.IsValid())
{
ScAddr argNode = IteratorUtils::getAnyFromSet(&m_context, solutionTreeRoot);
ScAddrVector arguments;
ScIterator3Ptr argIt = m_context.CreateIterator3(argNode, ScType::ConstPermPosArc, ScType::VarNode);
while (argIt->Next())
{
ScAddrVector arguments;
arguments.push_back(argIt->Get(2));
}
logicRuleNode = IteratorUtils::getAnyByOutRelation(&m_context, solutionTreeRoot, ScKeynodes::rrel_1);
}
}
}
return logicRuleNode;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,8 @@ TEST_F(StandardMessageReplyTest, SystemDoesNotHaveTemplateForMessage)
context.SubscribeAgent<inference::DirectInferenceAgent>();

EXPECT_TRUE(testAction.InitiateAndWait(WAIT_TIME));
EXPECT_TRUE(testAction.IsFinishedWithError());
EXPECT_TRUE(testAction.IsFinished());
EXPECT_TRUE(testAction.IsFinishedSuccessfully());

context.UnsubscribeAgent<inference::DirectInferenceAgent>();
context.UnsubscribeAgent<StandardMessageReplyAgent>();
Expand Down
4 changes: 2 additions & 2 deletions scripts/install_cxx_problem_solver.sh
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@
set -eo pipefail

# Constants
SC_MACHINE_VERSION="0.10.0"
SC_MACHINE_VERSION="0.10.4"
SC_MACHINE_DESTINATION_DIR="install/sc-machine"

SCL_MACHINE_VERSION="0.3.0"
SCL_MACHINE_VERSION="0.3.1"
SCL_MACHINE_DESTINATION_DIR="install/scl-machine"

NIKA_VERSION="0.1.0"
Expand Down
Loading