Skip to content
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
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,14 @@
RAW_URL_PATTERN = re.compile(r'https?://[^\s)]+')


def get_km_entity(km: dict, collection: str, uuid: str) -> dict[str, Any] | None:
"""Resolve an entity reference, warning and skipping dangling references."""
entity = km.get('entities', {}).get(collection, {}).get(uuid)
if entity is None:
logger.warning('Missing knowledge model entity %s in %s; skipping reference', uuid, collection)
return entity


def _strip_markdown_images(raw_value: str) -> str:
result: list[str] = []
i = 0
Expand Down Expand Up @@ -120,7 +128,9 @@ def _parse_item_select_reply(
return ''

question_uuid = question_path.rsplit('.', 1)[-1]
question = km.get('entities', {}).get('questions', {}).get(question_uuid, {})
question = get_km_entity(km, 'questions', question_uuid)
if question is None:
return ''
list_question_uuid = question.get('listQuestionUuid')
if not list_question_uuid:
return ''
Expand All @@ -133,46 +143,51 @@ def _parse_item_select_reply(
continue

reply_question_uuid = reply_path.rsplit('.', 1)[-1]
question_type = km.get('entities', {}).get('questions', {}).get(reply_question_uuid, {}).get('questionType')
reply_question = get_km_entity(km, 'questions', reply_question_uuid)
if reply_question is None:
continue

question_type = reply_question.get('questionType')
reply_value = reply_payload.get('value', {})

if question_type == 'ValueQuestion':
value = reply_value.get('value', '')
if value:
return value
elif question_type == 'IntegrationQuestion':
value = parse_integration_reply_value(reply_value)
else:
continue

if question_type == 'IntegrationQuestion':
value = parse_integration_reply_value(reply_value)
if value:
return value
if value:
return value

return ''


def _parse_multichoice_reply(answer: dict[str, Any], km: dict[str, Any]) -> str:
labels = []
for answer_id in answer['value']:
entity = get_km_entity(km, 'choices', answer_id)
if entity is None:
continue
labels.append(entity['label'])
return ', '.join(labels)


def parse_answer( # ruff: ignore[too-many-return-statements]
answer: dict[str, Any],
km: dict[str, Any],
replies: dict[str, Any] | None = None,
question_path: str | None = None,
) -> str | None:
answer_type = answer['type']
entities = km['entities']
answer_entities = entities['answers']

if answer_type == 'AnswerReply':
entity = answer_entities.get(answer['value'], None)
entity = get_km_entity(km, 'answers', answer['value'])
if entity is None:
logger.debug(
'Entity %s has no answer in the KM, strange...',
answer['value'],
)
return ''
return entity['label'] + (f' ({entity["advice"]})' if entity['advice'] is not None else '')
if answer_type == 'MultiChoiceReply':
return ', '.join(
[km['entities']['choices'][answer_id]['label'] for answer_id in answer['value']],
)
return _parse_multichoice_reply(answer, km)
if answer_type == 'IntegrationReply':
return parse_integration_reply_value(answer)
if answer_type == 'ItemListReply':
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import logging
from collections.abc import Iterator

from haystack import component

from ai_document_plugin_service.ai.generation.parse_answers import parse_integration_reply_value
from ai_document_plugin_service.ai.generation.parse_answers import get_km_entity, parse_integration_reply_value
from ai_document_plugin_service.ai.knowledgemodel.types import (
Chapter,
Choice,
Expand Down Expand Up @@ -39,22 +38,21 @@ def run(self, data: dict) -> dict[str, list[QuestionData]]:
},
)
top_level_questions: list[QuestionData] = []
for chapter_dict in self._iterate_km_chapters():
parsed_chapter = self.parse_chapter(chapter_dict['uuid'], replies)
top_level_questions.append(parsed_chapter)
for chapter_uuid in self.km['chapterUuids']:
parsed_chapter = self.parse_chapter(chapter_uuid, replies)
if parsed_chapter is not None:
top_level_questions.append(parsed_chapter)
logger.info(
'Finished parsing knowledge model replies',
extra={'chapter_count': len(top_level_questions)},
)
return {'data': top_level_questions}

def _iterate_km_chapters(self) -> Iterator[dict]:
for chapter_uuid in self.km['chapterUuids']:
yield self.km['entities']['chapters'][chapter_uuid]

def parse_chapter(self, chapter_uuid: str, replies: dict) -> Chapter:
def parse_chapter(self, chapter_uuid: str, replies: dict) -> Chapter | None:
"""Parse a Chapter from the knowledge model."""
chapter_data = self.km['entities']['chapters'][chapter_uuid]
chapter_data = get_km_entity(self.km, 'chapters', chapter_uuid)
if chapter_data is None:
return None

# Create chapter first (without questions)
chapter = Chapter(
Expand All @@ -80,9 +78,11 @@ def parse_chapter(self, chapter_uuid: str, replies: dict) -> Chapter:
chapter.questions = questions
return chapter

def parse_choice(self, choice_uuid: str) -> Choice:
def parse_choice(self, choice_uuid: str) -> Choice | None:
"""Parse a Choice from the knowledge model."""
choice_data = self.km['entities']['choices'][choice_uuid]
choice_data = get_km_entity(self.km, 'choices', choice_uuid)
if choice_data is None:
return None
return Choice(label=choice_data['label'], uuid=choice_uuid)

def parse_options_answer(
Expand All @@ -91,9 +91,11 @@ def parse_options_answer(
replies: dict,
path: str,
parent_question: OptionsQuestion | None = None,
) -> OptionsAnswer:
) -> OptionsAnswer | None:
"""Parse an OptionsAnswer from the knowledge model."""
answer_data = self.km['entities']['answers'][answer_uuid]
answer_data = get_km_entity(self.km, 'answers', answer_uuid)
if answer_data is None:
return None

# Create answer first (without followups)
answer = OptionsAnswer(
Expand Down Expand Up @@ -249,7 +251,7 @@ def parse_options_question(
for answer_uuid in question.get('answerUuids', [])
]

options_question.answers = answers
options_question.answers = [answer for answer in answers if answer is not None]

options_question.reply = self.get_option_reply(
replies,
Expand All @@ -265,7 +267,10 @@ def get_option_reply(
) -> str:
"""Get the reply for the question."""
reply = replies.get(path, {}).get('value', {}).get('value', '')
return self.km.get('entities', {}).get('answers', {}).get(reply, {}).get('label', '')
if not reply:
return ''
answer = get_km_entity(self.km, 'answers', reply)
return answer.get('label', '') if answer is not None else ''

def parse_multi_choice_question(
self,
Expand All @@ -277,12 +282,19 @@ def parse_multi_choice_question(
parent_answer: OptionsAnswer | None = None,
) -> MultiChoiceQuestion:
"""Parse a MultiChoiceQuestion from the knowledge model."""
choices = []
for choice_uuid in question.get('choiceUuids', []):
choice = self.parse_choice(choice_uuid)
if choice is None:
continue
choices.append(choice)

multichoice_question = MultiChoiceQuestion(
path=path,
uuid=question_uuid,
title=question['title'],
text=question.get('text'),
choices=[self.parse_choice(choice_uuid) for choice_uuid in question.get('choiceUuids', [])],
choices=choices,
parent_question=parent_question,
parent_answer=parent_answer,
)
Expand All @@ -300,10 +312,13 @@ def get_multichoice_reply(
) -> list[str]:
"""Get the reply for the question."""
reply_values = replies.get(path, {}).get('value', {}).get('value', '')
return [
self.km.get('entities', {}).get('answers', {}).get(reply_value, {}).get('label', '')
for reply_value in reply_values
]
labels = []
for reply_value in reply_values:
choice = get_km_entity(self.km, 'choices', reply_value)
if choice is None:
continue
labels.append(choice.get('label', ''))
return labels

def parse_item_select_question(
self,
Expand Down Expand Up @@ -350,19 +365,22 @@ def get_item_select_question_reply(
continue

question_uuid = path_parts[-1]
question_type = self.km.get('entities', {}).get('questions', {}).get(question_uuid, {}).get('questionType')
question = get_km_entity(self.km, 'questions', question_uuid)
if question is None:
continue

question_type = question.get('questionType')

if question_type == 'ValueQuestion':
value = reply_payload.get('value', {}).get('value', '')
if value:
return value
continue

if question_type == 'IntegrationQuestion':
elif question_type == 'IntegrationQuestion':
answer = reply_payload.get('value', {})
value = parse_integration_reply_value(answer)
if value:
return value
else:
continue

if value:
return value

return ''

Expand All @@ -388,7 +406,9 @@ def parse_question(
Raises:
ValueError: If the question type is unknown.
"""
question = self.km['entities']['questions'][question_uuid]
question = get_km_entity(self.km, 'questions', question_uuid)
if question is None:
return None
question_type = question.get('questionType')
parser_by_type = {
'ValueQuestion': self.parse_value_question,
Expand Down
Loading