robert 2.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- robert/__init__.py +9 -0
- robert/__main__.py +20 -0
- robert/_version.py +3 -0
- robert/api.py +646 -0
- robert/aqme.py +280 -0
- robert/argument_parser.py +98 -0
- robert/checkml.py +433 -0
- robert/checkml_score.py +50 -0
- robert/curate.py +217 -0
- robert/evaluate_bot_retrieval.py +125 -0
- robert/evaluate_bot_support.py +102 -0
- robert/evaluate_workflow_summaries.py +87 -0
- robert/export_bot_docs_knowledge.py +1632 -0
- robert/generate.py +249 -0
- robert/generate_utils.py +311 -0
- robert/gui_easyrob/__init__.py +0 -0
- robert/gui_easyrob/assets/gif_easyrob.gif +0 -0
- robert/gui_easyrob/bot/__init__.py +47 -0
- robert/gui_easyrob/bot/answer_metadata.py +198 -0
- robert/gui_easyrob/bot/bot_context.py +679 -0
- robert/gui_easyrob/bot/bot_engine.py +1100 -0
- robert/gui_easyrob/bot/bot_panel.py +1231 -0
- robert/gui_easyrob/bot/bot_rag.py +1178 -0
- robert/gui_easyrob/bot/bot_window.py +39 -0
- robert/gui_easyrob/bot/bot_worker.py +149 -0
- robert/gui_easyrob/bot/credential_store.py +143 -0
- robert/gui_easyrob/bot/error_parser.py +105 -0
- robert/gui_easyrob/bot/evidence_policy.py +164 -0
- robert/gui_easyrob/bot/heuristics.py +859 -0
- robert/gui_easyrob/bot/icons.py +56 -0
- robert/gui_easyrob/bot/input_csv_audit.py +212 -0
- robert/gui_easyrob/bot/knowledge/aqme_context.json +5907 -0
- robert/gui_easyrob/bot/knowledge/robert_context.json +4817 -0
- robert/gui_easyrob/bot/knowledge/ui_context.json +8293 -0
- robert/gui_easyrob/bot/knowledge_schema.py +1252 -0
- robert/gui_easyrob/bot/knowledge_sources/aqme_user_guidance.json +442 -0
- robert/gui_easyrob/bot/knowledge_sources/coverage_manifest.json +95 -0
- robert/gui_easyrob/bot/knowledge_sources/robert_user_guidance.json +471 -0
- robert/gui_easyrob/bot/knowledge_sources/ui_user_guidance.json +1312 -0
- robert/gui_easyrob/bot/llm_providers.py +1573 -0
- robert/gui_easyrob/bot/online_docs.py +105 -0
- robert/gui_easyrob/bot/prompt_policy.py +575 -0
- robert/gui_easyrob/bot/question_intent.py +562 -0
- robert/gui_easyrob/bot/response_quality.py +104 -0
- robert/gui_easyrob/bot/result_insights.py +225 -0
- robert/gui_easyrob/bot/token_usage.py +75 -0
- robert/gui_easyrob/bot/workflow_results.py +1396 -0
- robert/gui_easyrob/checkml_launcher.py +15 -0
- robert/gui_easyrob/easyrob.py +29 -0
- robert/gui_easyrob/easyrob_launcher.py +113 -0
- robert/gui_easyrob/main/__init__.py +9 -0
- robert/gui_easyrob/main/window.py +5152 -0
- robert/gui_easyrob/result_navigation.py +14 -0
- robert/gui_easyrob/tabs/__init__.py +23 -0
- robert/gui_easyrob/tabs/advanced_options.py +370 -0
- robert/gui_easyrob/tabs/aqme.py +1234 -0
- robert/gui_easyrob/tabs/checkml.py +898 -0
- robert/gui_easyrob/tabs/images.py +427 -0
- robert/gui_easyrob/tabs/interactive_predictions.py +555 -0
- robert/gui_easyrob/tabs/molssi.py +447 -0
- robert/gui_easyrob/tabs/predictions.py +484 -0
- robert/gui_easyrob/tabs/result_catalog.py +170 -0
- robert/gui_easyrob/tabs/results.py +490 -0
- robert/gui_easyrob/tabs/results_workspace.py +120 -0
- robert/gui_easyrob/test_bot_input_csv_audit.py +152 -0
- robert/gui_easyrob/test_bot_question_routing.py +383 -0
- robert/gui_easyrob/test_bot_result_analysis.py +356 -0
- robert/gui_easyrob/test_bot_retrieval_evaluation.py +110 -0
- robert/gui_easyrob/test_bot_ui_integration.py +278 -0
- robert/gui_easyrob/test_checkml_app_mode.py +124 -0
- robert/gui_easyrob/test_checkml_completion.py +57 -0
- robert/gui_easyrob/test_checkml_defaults.py +37 -0
- robert/gui_easyrob/test_checkml_result_summary.py +113 -0
- robert/gui_easyrob/test_checkml_web_mode.py +57 -0
- robert/gui_easyrob/test_dialog_layout.py +33 -0
- robert/gui_easyrob/test_gui_bot_regressions.py +320 -0
- robert/gui_easyrob/test_molssi_auto.py +569 -0
- robert/gui_easyrob/test_tutorial_view.py +215 -0
- robert/gui_easyrob/tutorials/check_model.md +25 -0
- robert/gui_easyrob/tutorials/chemdraw.md +49 -0
- robert/gui_easyrob/tutorials/csv.md +53 -0
- robert/gui_easyrob/tutorials/descriptors.md +21 -0
- robert/gui_easyrob/tutorials/overview.md +65 -0
- robert/gui_easyrob/tutorials/predictions.md +25 -0
- robert/gui_easyrob/tutorials/robbot.md +29 -0
- robert/gui_easyrob/tutorials/tutorial_images/check_model/check_model_1.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/check_model/check_model_2.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/check_model/check_model_3.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/check_model/check_model_4.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/check_model/check_model_5.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/check_model/check_model_6.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/check_model/check_model_7.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_1.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_10.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_11.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_12.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_13.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_2.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_3.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_4.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_5.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_6.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_7.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_8.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_9.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/csv/csv_1.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/csv/csv_1_1.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/csv/csv_1_2.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/csv/csv_1_3.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/csv/csv_1_4.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/csv/csv_1_5.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/csv/csv_2.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/csv/csv_3.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/csv/csv_4.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/csv/csv_5.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/csv/csv_6.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/csv/csv_7.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/csv/csv_8.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/csv/csv_9.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/descriptors/descriptors_1.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/descriptors/descriptors_2.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/descriptors/descriptors_3.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/descriptors/descriptors_4.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/descriptors/descriptors_5.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/descriptors/descriptors_6.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/overview/overview_1.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/overview/overview_1_1.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/overview/overview_1_2.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/overview/overview_1_3.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/overview/overview_1_4.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/overview/overview_1_5.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/overview/overview_1_6.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/overview/overview_1_7.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/overview/overview_1_8.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/overview/overview_2.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/overview/overview_3.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/overview/overview_4.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/overview/overview_5.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/overview/overview_5_1.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/overview/overview_5_2.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/overview/overview_5_3.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/overview/overview_6.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/predictions/predictions_1.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/predictions/predictions_1_1.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/predictions/predictions_2.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/predictions/predictions_3.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/predictions/predictions_4.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/predictions/predictions_5.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/predictions/predictions_6.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/robbot/robbot_1.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/robbot/robbot_2.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/robbot/robbot_3.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/robbot/robbot_4.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/robbot/robbot_5.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/robbot/robbot_6.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/robbot/robbot_7.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/robbot/robbot_8.png +0 -0
- robert/gui_easyrob/utils/__init__.py +0 -0
- robert/gui_easyrob/utils/aqme_utils.py +238 -0
- robert/gui_easyrob/utils/molssi_utils.py +584 -0
- robert/gui_easyrob/utils/predictions_utils.py +985 -0
- robert/gui_easyrob/utils/utils_gui.py +738 -0
- robert/gui_easyrob/version.py +68 -0
- robert/gui_easyrob/web/app.css +484 -0
- robert/gui_easyrob/web/app.html +134 -0
- robert/gui_easyrob/web/app.js +764 -0
- robert/gui_easyrob/web/checkml_brand.png +0 -0
- robert/gui_easyrob/web/easyrob_background.gif +0 -0
- robert/gui_easyrob/web/easyrob_background.png +0 -0
- robert/gui_easyrob/web/images.css +89 -0
- robert/gui_easyrob/web/images.html +39 -0
- robert/gui_easyrob/web/images.js +101 -0
- robert/gui_easyrob/web/results.js +499 -0
- robert/gui_easyrob/web/robert_brand.png +0 -0
- robert/gui_easyrob/web_dialogs.py +64 -0
- robert/gui_easyrob/web_results.py +253 -0
- robert/gui_easyrob/web_shell.py +684 -0
- robert/gui_easyrob/workflow_progress.py +89 -0
- robert/gui_easyrob/workflow_run_lock.py +27 -0
- robert/icons/CheckML_icon.png +0 -0
- robert/icons/Robert_icon.png +0 -0
- robert/icons/Robert_logo.jpg +0 -0
- robert/icons/Robert_logo_transparent.png +0 -0
- robert/icons/documentation_icon.png +0 -0
- robert/icons/info_icon.png +0 -0
- robert/icons/pdf_icon.png +0 -0
- robert/icons/play_icon.png +0 -0
- robert/icons/stop_icon.png +0 -0
- robert/icons/youtube_icon.ico +0 -0
- robert/predict.py +193 -0
- robert/predict_utils.py +410 -0
- robert/report/CheckML_logo.jpg +0 -0
- robert/report/GENERATE.png +0 -0
- robert/report/Robert_icon.ico +0 -0
- robert/report/Robert_logo.jpg +0 -0
- robert/report/Robert_logo1.jpg +0 -0
- robert/report/abbrev.png +0 -0
- robert/report/adv_anal.png +0 -0
- robert/report/checkml_pass.svg +3 -0
- robert/report/checkml_unclear.svg +3 -0
- robert/report/checkml_warning.svg +3 -0
- robert/report/features.png +0 -0
- robert/report/outliers.png +0 -0
- robert/report/pred.png +0 -0
- robert/report/repro.png +0 -0
- robert/report/robust_x.png +0 -0
- robert/report/robust_y_high.png +0 -0
- robert/report/robust_y_low.png +0 -0
- robert/report/score.png +0 -0
- robert/report/score_0.jpg +0 -0
- robert/report/score_1.jpg +0 -0
- robert/report/score_10.jpg +0 -0
- robert/report/score_2.jpg +0 -0
- robert/report/score_3.jpg +0 -0
- robert/report/score_4.jpg +0 -0
- robert/report/score_5.jpg +0 -0
- robert/report/score_6.jpg +0 -0
- robert/report/score_7.jpg +0 -0
- robert/report/score_8.jpg +0 -0
- robert/report/score_9.jpg +0 -0
- robert/report/score_gray_0.jpg +0 -0
- robert/report/score_gray_1.jpg +0 -0
- robert/report/score_gray_10.jpg +0 -0
- robert/report/score_gray_2.jpg +0 -0
- robert/report/score_gray_3.jpg +0 -0
- robert/report/score_gray_4.jpg +0 -0
- robert/report/score_gray_5.jpg +0 -0
- robert/report/score_gray_6.jpg +0 -0
- robert/report/score_gray_7.jpg +0 -0
- robert/report/score_gray_8.jpg +0 -0
- robert/report/score_gray_9.jpg +0 -0
- robert/report/score_w_1_0.jpg +0 -0
- robert/report/score_w_1_1.jpg +0 -0
- robert/report/score_w_2_0.jpg +0 -0
- robert/report/score_w_2_1.jpg +0 -0
- robert/report/score_w_2_2.jpg +0 -0
- robert/report/score_w_2_gray_0.jpg +0 -0
- robert/report/score_w_2_gray_1.jpg +0 -0
- robert/report/score_w_2_gray_2.jpg +0 -0
- robert/report/score_w_3_0.jpg +0 -0
- robert/report/score_w_3_1.jpg +0 -0
- robert/report/score_w_3_2.jpg +0 -0
- robert/report/score_w_3_3.jpg +0 -0
- robert/report/score_w_4_0.jpg +0 -0
- robert/report/score_w_4_1.JPG +0 -0
- robert/report/score_w_4_2.jpg +0 -0
- robert/report/score_w_4_3.jpg +0 -0
- robert/report/score_w_4_4.jpg +0 -0
- robert/report/transpa.png +0 -0
- robert/report/y_distrib.png +0 -0
- robert/report.py +2880 -0
- robert/report_utils.py +2270 -0
- robert/robert.py +181 -0
- robert/utils.py +4763 -0
- robert/verify.py +606 -0
- robert-2.2.0.dist-info/METADATA +55 -0
- robert-2.2.0.dist-info/RECORD +261 -0
- robert-2.2.0.dist-info/WHEEL +5 -0
- robert-2.2.0.dist-info/entry_points.txt +3 -0
- robert-2.2.0.dist-info/licenses/LICENSE +21 -0
- robert-2.2.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,1100 @@
|
|
|
1
|
+
"""Answer orchestration for the EasyROB GUI bot."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field, replace
|
|
6
|
+
from datetime import datetime
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
import re
|
|
9
|
+
from typing import Callable, Final, Mapping, Sequence
|
|
10
|
+
import unicodedata
|
|
11
|
+
|
|
12
|
+
from .answer_metadata import AnswerMetadata, EvidenceOrigin, WebSearchMode
|
|
13
|
+
from .bot_context import GuiSnapshot
|
|
14
|
+
from .workflow_results import (
|
|
15
|
+
WorkflowResultSnapshot,
|
|
16
|
+
_requested_variants,
|
|
17
|
+
render_workflow_answer,
|
|
18
|
+
scope_workflow_result_snapshot,
|
|
19
|
+
)
|
|
20
|
+
from .input_csv_audit import inspect_selected_csvs, is_selected_csv_question
|
|
21
|
+
from .bot_rag import KnowledgeBase, SearchResult, normalize_terms
|
|
22
|
+
from .heuristics import diagnose_snapshot, format_heuristic_answer
|
|
23
|
+
from .evidence_policy import EvidenceDecision, assess_evidence, sanitize_search_query
|
|
24
|
+
from .llm_providers import (
|
|
25
|
+
LLMProviderError,
|
|
26
|
+
LLMProviderErrorKind,
|
|
27
|
+
_response_language,
|
|
28
|
+
build_llm_prompts,
|
|
29
|
+
build_provider_registry,
|
|
30
|
+
)
|
|
31
|
+
from .knowledge_schema import KnowledgeLoadIssue
|
|
32
|
+
from .question_intent import (
|
|
33
|
+
classify_question_intent,
|
|
34
|
+
is_generic_question,
|
|
35
|
+
is_gui_question,
|
|
36
|
+
is_workflow_result_question,
|
|
37
|
+
select_inference_history,
|
|
38
|
+
)
|
|
39
|
+
from .prompt_policy import select_answer_depth
|
|
40
|
+
from .response_quality import result_summary_issues
|
|
41
|
+
from .token_usage import MAX_USER_PROMPT_TOKENS, TokenUsage, estimate_token_count
|
|
42
|
+
|
|
43
|
+
__all__ = ["BotAnswerResult", "BotEngine", "MAX_USER_QUESTION_TOKENS"]
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
_TUTORIALS_BY_ID = {
|
|
47
|
+
"overview": ("tutorial:overview.md", "Overview"),
|
|
48
|
+
"csv": ("tutorial:csv.md", "From CSV"),
|
|
49
|
+
"chemdraw": ("tutorial:chemdraw.md", "From ChemDraw"),
|
|
50
|
+
"predictions": ("tutorial:predictions.md", "New Predictions"),
|
|
51
|
+
"descriptors": ("tutorial:descriptors.md", "Descriptors"),
|
|
52
|
+
"check_model": ("tutorial:check_model.md", "Check ML"),
|
|
53
|
+
"robbot": ("tutorial:robbot.md", "robBOT"),
|
|
54
|
+
}
|
|
55
|
+
_EXACT_TUTORIAL_QUESTIONS = {
|
|
56
|
+
"how does the gui overview work": "overview",
|
|
57
|
+
"how do i start from a csv file": "csv",
|
|
58
|
+
"how do i start from chemdraw": "chemdraw",
|
|
59
|
+
"how do i make predictions for new molecules": "predictions",
|
|
60
|
+
"how do i generate descriptors without training a model": "descriptors",
|
|
61
|
+
"how do i check my own machine learning model": "check_model",
|
|
62
|
+
"how do i use robbot": "robbot",
|
|
63
|
+
}
|
|
64
|
+
_SENTENCE_SPLIT_RE = re.compile(r"(?<=[.!?])\s+")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _result_selection_note(snapshot: GuiSnapshot, question: str) -> str:
|
|
68
|
+
"""Explain the single overall-best report retained in the run folder."""
|
|
69
|
+
if len(snapshot.result_root_reports) != 1 or not snapshot.result_archived_report_count:
|
|
70
|
+
return ""
|
|
71
|
+
filename = snapshot.result_root_reports[0]
|
|
72
|
+
selected = ", ".join(
|
|
73
|
+
f"{variant}={model}" for variant, model in snapshot.result_selected_variants
|
|
74
|
+
)
|
|
75
|
+
if _response_language(question) == "Spanish":
|
|
76
|
+
return (
|
|
77
|
+
f"**Selección de Results:** ROBERT dejó un único informe final en la carpeta "
|
|
78
|
+
f"principal, `{filename}` ({selected}). Hay {snapshot.result_archived_report_count} "
|
|
79
|
+
"informes en `REPORT_models`; selecciona un modelo concreto para consultar sus "
|
|
80
|
+
"otras variantes."
|
|
81
|
+
)
|
|
82
|
+
return (
|
|
83
|
+
f"**Results selection:** ROBERT kept one final report in the run folder, "
|
|
84
|
+
f"`{filename}` ({selected}). There are {snapshot.result_archived_report_count} "
|
|
85
|
+
"reports in `REPORT_models`; choose a named model to inspect its other variants."
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _result_provider_fallback(
|
|
90
|
+
snapshot: GuiSnapshot, question: str, *, full: bool, reason: str = "",
|
|
91
|
+
) -> "BotAnswerResult":
|
|
92
|
+
explanation = (
|
|
93
|
+
"Cloud AI no pudo responder esta vez. Este resumen se ha creado directamente a partir "
|
|
94
|
+
"de los datos registrados del workflow, sin interpretación del modelo de IA.\n\n"
|
|
95
|
+
if _response_language(question) == "Spanish" else
|
|
96
|
+
"Cloud AI could not answer this time. This summary comes directly from recorded "
|
|
97
|
+
"workflow data, without AI interpretation.\n\n"
|
|
98
|
+
)
|
|
99
|
+
if reason:
|
|
100
|
+
if _response_language(question) == "Spanish":
|
|
101
|
+
translated = {
|
|
102
|
+
"the generated answer conflicted with the workflow evidence": "la respuesta generada contradecía los datos del workflow",
|
|
103
|
+
"rate limit": "límite de uso del proveedor",
|
|
104
|
+
"connection": "problema de conexión",
|
|
105
|
+
"timeout": "tiempo de espera agotado",
|
|
106
|
+
"authentication": "problema de autenticación",
|
|
107
|
+
"invalid request": "solicitud rechazada",
|
|
108
|
+
"invalid response": "respuesta no válida del proveedor",
|
|
109
|
+
"unavailable service": "servicio no disponible",
|
|
110
|
+
"unexpected bot error": "error interno del bot",
|
|
111
|
+
}.get(reason, "problema del proveedor")
|
|
112
|
+
explanation += f"Motivo de la respuesta local: {translated}.\n\n"
|
|
113
|
+
else:
|
|
114
|
+
explanation += f"Reason for local answer: {reason}.\n\n"
|
|
115
|
+
return BotAnswerResult(
|
|
116
|
+
explanation + "\n\n".join(part for part in (
|
|
117
|
+
_result_selection_note(snapshot, question) if snapshot.result_model == "Best models" else "",
|
|
118
|
+
render_workflow_answer(snapshot.workflow_results, question, full=full),
|
|
119
|
+
) if part),
|
|
120
|
+
memory_eligible=False,
|
|
121
|
+
metadata=AnswerMetadata(evidence_origin=EvidenceOrigin.LOCAL_SYSTEM),
|
|
122
|
+
)
|
|
123
|
+
_TUTORIAL_OVERVIEW_LIMIT = 1
|
|
124
|
+
_TUTORIAL_BULLET_LIMIT = 4
|
|
125
|
+
_POPUP_QUESTION_RE = re.compile(r"\b(pop[- ]?up|dialog|warning|message box|message|alert|window)\b", re.IGNORECASE)
|
|
126
|
+
_CURRENT_DATE_QUESTIONS = {
|
|
127
|
+
"current date",
|
|
128
|
+
"cual es la fecha de hoy",
|
|
129
|
+
"fecha actual",
|
|
130
|
+
"fecha de hoy",
|
|
131
|
+
"que dia es hoy",
|
|
132
|
+
"que fecha es hoy",
|
|
133
|
+
"todays date",
|
|
134
|
+
"what date is it",
|
|
135
|
+
"what day is it today",
|
|
136
|
+
"what day is today",
|
|
137
|
+
"what is todays date",
|
|
138
|
+
}
|
|
139
|
+
_SPANISH_DATE_QUESTIONS = {
|
|
140
|
+
"cual es la fecha de hoy",
|
|
141
|
+
"fecha actual",
|
|
142
|
+
"fecha de hoy",
|
|
143
|
+
"que dia es hoy",
|
|
144
|
+
"que fecha es hoy",
|
|
145
|
+
}
|
|
146
|
+
_CURRENT_TIME_QUESTIONS = {
|
|
147
|
+
"current time",
|
|
148
|
+
"hora actual",
|
|
149
|
+
"que hora es",
|
|
150
|
+
"que hora es ahora",
|
|
151
|
+
"what is the current time",
|
|
152
|
+
"what time is it",
|
|
153
|
+
}
|
|
154
|
+
_SPANISH_TIME_QUESTIONS = {
|
|
155
|
+
"hora actual",
|
|
156
|
+
"que hora es",
|
|
157
|
+
"que hora es ahora",
|
|
158
|
+
}
|
|
159
|
+
_SPANISH_WEEKDAYS = ("lunes", "martes", "miércoles", "jueves", "viernes", "sábado", "domingo")
|
|
160
|
+
_SPANISH_MONTHS = (
|
|
161
|
+
"enero",
|
|
162
|
+
"febrero",
|
|
163
|
+
"marzo",
|
|
164
|
+
"abril",
|
|
165
|
+
"mayo",
|
|
166
|
+
"junio",
|
|
167
|
+
"julio",
|
|
168
|
+
"agosto",
|
|
169
|
+
"septiembre",
|
|
170
|
+
"octubre",
|
|
171
|
+
"noviembre",
|
|
172
|
+
"diciembre",
|
|
173
|
+
)
|
|
174
|
+
MAX_USER_QUESTION_TOKENS: Final[int] = MAX_USER_PROMPT_TOKENS
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
@dataclass(frozen=True, slots=True)
|
|
178
|
+
class TutorialSummary:
|
|
179
|
+
source: str
|
|
180
|
+
label: str
|
|
181
|
+
overview: str
|
|
182
|
+
bullets: tuple[str, ...]
|
|
183
|
+
candidates: tuple[SearchResult, ...]
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
@dataclass(frozen=True, slots=True)
|
|
187
|
+
class BotAnswerResult:
|
|
188
|
+
text: str
|
|
189
|
+
auto_reset_context: bool = False
|
|
190
|
+
memory_eligible: bool = True
|
|
191
|
+
usage: TokenUsage = field(default_factory=TokenUsage)
|
|
192
|
+
metadata: AnswerMetadata = field(default_factory=AnswerMetadata)
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
class BotEngine:
|
|
196
|
+
def __init__(
|
|
197
|
+
self,
|
|
198
|
+
knowledge_base: KnowledgeBase | None = None,
|
|
199
|
+
provider_registry: Mapping[str, object] | None = None,
|
|
200
|
+
now_provider: Callable[[], datetime] | None = None,
|
|
201
|
+
) -> None:
|
|
202
|
+
tutorials_dir = Path(__file__).resolve().parents[1] / "tutorials"
|
|
203
|
+
self._knowledge_base = knowledge_base or KnowledgeBase.from_directory(
|
|
204
|
+
tutorials_dir=tutorials_dir,
|
|
205
|
+
strict=False,
|
|
206
|
+
)
|
|
207
|
+
self._provider_registry = dict(provider_registry or build_provider_registry())
|
|
208
|
+
self._now_provider = now_provider or (lambda: datetime.now().astimezone())
|
|
209
|
+
|
|
210
|
+
@property
|
|
211
|
+
def provider_names(self) -> tuple[str, ...]:
|
|
212
|
+
return tuple(self._provider_registry)
|
|
213
|
+
|
|
214
|
+
@property
|
|
215
|
+
def knowledge_issues(self) -> tuple[KnowledgeLoadIssue, ...]:
|
|
216
|
+
return self._knowledge_base.issues
|
|
217
|
+
|
|
218
|
+
@property
|
|
219
|
+
def knowledge_is_degraded(self) -> bool:
|
|
220
|
+
return self._knowledge_base.is_degraded
|
|
221
|
+
|
|
222
|
+
def answer(
|
|
223
|
+
self,
|
|
224
|
+
question: str,
|
|
225
|
+
snapshot: GuiSnapshot,
|
|
226
|
+
mode: str,
|
|
227
|
+
provider: str,
|
|
228
|
+
api_key: str,
|
|
229
|
+
model: str | None = None,
|
|
230
|
+
conversation_history: Sequence[Mapping[str, object]] | None = None,
|
|
231
|
+
tutorial_id: str | None = None,
|
|
232
|
+
web_search_enabled: bool = True,
|
|
233
|
+
progress_callback: Callable[[str], None] | None = None,
|
|
234
|
+
) -> str:
|
|
235
|
+
return self.answer_with_metadata(
|
|
236
|
+
question=question,
|
|
237
|
+
snapshot=snapshot,
|
|
238
|
+
mode=mode,
|
|
239
|
+
provider=provider,
|
|
240
|
+
api_key=api_key,
|
|
241
|
+
model=model,
|
|
242
|
+
conversation_history=conversation_history,
|
|
243
|
+
tutorial_id=tutorial_id,
|
|
244
|
+
web_search_enabled=web_search_enabled,
|
|
245
|
+
progress_callback=progress_callback,
|
|
246
|
+
).text
|
|
247
|
+
|
|
248
|
+
def answer_with_metadata(
|
|
249
|
+
self,
|
|
250
|
+
question: str,
|
|
251
|
+
snapshot: GuiSnapshot,
|
|
252
|
+
mode: str,
|
|
253
|
+
provider: str,
|
|
254
|
+
api_key: str,
|
|
255
|
+
model: str | None = None,
|
|
256
|
+
conversation_history: Sequence[Mapping[str, object]] | None = None,
|
|
257
|
+
tutorial_id: str | None = None,
|
|
258
|
+
web_search_enabled: bool = True,
|
|
259
|
+
progress_callback: Callable[[str], None] | None = None,
|
|
260
|
+
) -> BotAnswerResult:
|
|
261
|
+
clean_question = question.strip() if type(question) is str else ""
|
|
262
|
+
if not clean_question:
|
|
263
|
+
return BotAnswerResult("Please enter a question for the bot.", memory_eligible=False)
|
|
264
|
+
if estimate_token_count(clean_question) > MAX_USER_QUESTION_TOKENS:
|
|
265
|
+
return BotAnswerResult(
|
|
266
|
+
"Please shorten your question to 500 estimated tokens or fewer.",
|
|
267
|
+
memory_eligible=False,
|
|
268
|
+
)
|
|
269
|
+
normalized_mode = str(mode or "").strip().lower()
|
|
270
|
+
if normalized_mode not in {"cloud ai", "heuristic"}:
|
|
271
|
+
return BotAnswerResult("Unsupported bot mode.", memory_eligible=False)
|
|
272
|
+
|
|
273
|
+
local_clock_answer = self._build_local_clock_answer(clean_question)
|
|
274
|
+
if local_clock_answer:
|
|
275
|
+
return BotAnswerResult(
|
|
276
|
+
local_clock_answer,
|
|
277
|
+
metadata=AnswerMetadata(evidence_origin=EvidenceOrigin.LOCAL_SYSTEM),
|
|
278
|
+
)
|
|
279
|
+
|
|
280
|
+
selected_history = select_inference_history(clean_question, conversation_history)
|
|
281
|
+
question_intent = classify_question_intent(clean_question, conversation_history=selected_history)
|
|
282
|
+
if question_intent == "greeting":
|
|
283
|
+
return BotAnswerResult(self._build_greeting_reply(clean_question, snapshot))
|
|
284
|
+
|
|
285
|
+
gui_question = is_gui_question(clean_question)
|
|
286
|
+
input_csv_question = bool(
|
|
287
|
+
not gui_question and (snapshot.main_csv_path or snapshot.test_csv_path)
|
|
288
|
+
and is_selected_csv_question(clean_question)
|
|
289
|
+
)
|
|
290
|
+
named_model = any(re.search(
|
|
291
|
+
rf"(?<![\w]){re.escape(model)}(?![\w])", clean_question, re.IGNORECASE,
|
|
292
|
+
) for model in snapshot.result_models)
|
|
293
|
+
result_question = (
|
|
294
|
+
input_csv_question or is_workflow_result_question(clean_question, named_model=named_model)
|
|
295
|
+
or (not gui_question and bool(selected_history)
|
|
296
|
+
and is_workflow_result_question(selected_history[0]["content"]))
|
|
297
|
+
)
|
|
298
|
+
if result_question:
|
|
299
|
+
question_intent = "results"
|
|
300
|
+
elif question_intent == "results":
|
|
301
|
+
question_intent = "tutorial"
|
|
302
|
+
generic_question = not result_question and is_generic_question(
|
|
303
|
+
clean_question, question_intent, conversation_history=selected_history,
|
|
304
|
+
)
|
|
305
|
+
if (self._is_low_information_question(clean_question) and not selected_history
|
|
306
|
+
and not result_question and not generic_question):
|
|
307
|
+
return BotAnswerResult(
|
|
308
|
+
"Please ask a more specific question about the GUI, workflow, results, or the step you want help with.",
|
|
309
|
+
memory_eligible=False,
|
|
310
|
+
)
|
|
311
|
+
|
|
312
|
+
requested_variants = _requested_variants(clean_question) if result_question else ()
|
|
313
|
+
asks_all_models = bool(re.search(
|
|
314
|
+
r"\b(?:all models|todos los modelos|cada modelo)\b", clean_question.casefold(),
|
|
315
|
+
))
|
|
316
|
+
selected_variants = {variant for variant, _ in snapshot.result_selected_variants}
|
|
317
|
+
if (requested_variants and snapshot.result_models and selected_variants
|
|
318
|
+
and not named_model and not asks_all_models
|
|
319
|
+
and not set(requested_variants).issubset(selected_variants)):
|
|
320
|
+
selected = ", ".join(
|
|
321
|
+
f"{variant}={model}" for variant, model in snapshot.result_selected_variants
|
|
322
|
+
)
|
|
323
|
+
archive_note = (
|
|
324
|
+
f" Hay {snapshot.result_archived_report_count} informes archivados en REPORT_models."
|
|
325
|
+
if snapshot.result_archived_report_count else ""
|
|
326
|
+
)
|
|
327
|
+
if _response_language(clean_question) == "Spanish":
|
|
328
|
+
reply = (
|
|
329
|
+
f"La selección actual de Results ({snapshot.result_model or 'Best models'}) "
|
|
330
|
+
f"solo contiene {selected}. La variante que preguntas no está seleccionada."
|
|
331
|
+
f"{archive_note} Elige un modelo concreto en el selector Model para consultar "
|
|
332
|
+
"sus variantes disponibles."
|
|
333
|
+
)
|
|
334
|
+
else:
|
|
335
|
+
archive_note = (
|
|
336
|
+
f" There are {snapshot.result_archived_report_count} archived reports in REPORT_models."
|
|
337
|
+
if snapshot.result_archived_report_count else ""
|
|
338
|
+
)
|
|
339
|
+
reply = (
|
|
340
|
+
f"The current Results selection ({snapshot.result_model or 'Best models'}) "
|
|
341
|
+
f"contains only {selected}. The requested variant is not selected."
|
|
342
|
+
f"{archive_note} Choose a named model in the Model selector to inspect "
|
|
343
|
+
"its available variants."
|
|
344
|
+
)
|
|
345
|
+
return BotAnswerResult(
|
|
346
|
+
reply, memory_eligible=False,
|
|
347
|
+
metadata=AnswerMetadata(evidence_origin=EvidenceOrigin.LOCAL_SYSTEM),
|
|
348
|
+
)
|
|
349
|
+
|
|
350
|
+
if (result_question and len(snapshot.result_root_reports) == 1 and snapshot.result_archived_report_count
|
|
351
|
+
and re.search(r"\b(?:report|informe|pdf)\b", clean_question, re.IGNORECASE)
|
|
352
|
+
and re.search(r"\b(?:only|single|one|solo|unico|único|uno)\b", clean_question, re.IGNORECASE)):
|
|
353
|
+
return BotAnswerResult(
|
|
354
|
+
_result_selection_note(snapshot, clean_question), memory_eligible=False,
|
|
355
|
+
metadata=AnswerMetadata(evidence_origin=EvidenceOrigin.LOCAL_SYSTEM),
|
|
356
|
+
)
|
|
357
|
+
|
|
358
|
+
if not result_question:
|
|
359
|
+
snapshot = replace(snapshot, workflow_results=None)
|
|
360
|
+
elif snapshot.workflow_results is not None and snapshot.result_models:
|
|
361
|
+
snapshot = replace(snapshot, workflow_results=scope_workflow_result_snapshot(
|
|
362
|
+
snapshot.workflow_results,
|
|
363
|
+
clean_question,
|
|
364
|
+
selected_variants=snapshot.result_selected_variants,
|
|
365
|
+
available_models=snapshot.result_models,
|
|
366
|
+
prefer_root_report=(
|
|
367
|
+
snapshot.result_model == "Best models" and len(snapshot.result_root_reports) == 1
|
|
368
|
+
and not named_model and not asks_all_models
|
|
369
|
+
),
|
|
370
|
+
))
|
|
371
|
+
|
|
372
|
+
if input_csv_question:
|
|
373
|
+
input_insights = inspect_selected_csvs(
|
|
374
|
+
snapshot.main_csv_path,
|
|
375
|
+
snapshot.test_csv_path,
|
|
376
|
+
target_column=snapshot.target_column,
|
|
377
|
+
name_column=snapshot.name_column,
|
|
378
|
+
prediction_type=snapshot.prediction_type,
|
|
379
|
+
ignored_columns=snapshot.ignored_columns,
|
|
380
|
+
)
|
|
381
|
+
if input_insights:
|
|
382
|
+
workflow = snapshot.workflow_results
|
|
383
|
+
if workflow is None:
|
|
384
|
+
selected_path = snapshot.main_csv_path or snapshot.test_csv_path
|
|
385
|
+
workflow = WorkflowResultSnapshot(
|
|
386
|
+
kind="INPUT CSV", status="input_only",
|
|
387
|
+
root_name=Path(selected_path).parent.name,
|
|
388
|
+
summary_available=False,
|
|
389
|
+
insights=input_insights,
|
|
390
|
+
sources=tuple(item.source for item in input_insights),
|
|
391
|
+
)
|
|
392
|
+
else:
|
|
393
|
+
has_fresh_overlap = any(item.category == "dataset_overlap" for item in input_insights)
|
|
394
|
+
original = tuple(
|
|
395
|
+
item for item in workflow.insights
|
|
396
|
+
if item.category != "dataset_overlap" or not has_fresh_overlap
|
|
397
|
+
)
|
|
398
|
+
workflow = replace(workflow, insights=(*original, *input_insights))
|
|
399
|
+
snapshot = replace(snapshot, workflow_results=workflow)
|
|
400
|
+
|
|
401
|
+
self._emit_progress(progress_callback, "checking_documentation")
|
|
402
|
+
|
|
403
|
+
result_evidence_question = result_question and snapshot.workflow_results is not None
|
|
404
|
+
result_summary_request = result_question and bool(re.search(
|
|
405
|
+
r"\b(?:summari[sz]e|summary|resumen|resume|resumir)\b",
|
|
406
|
+
clean_question.casefold(),
|
|
407
|
+
))
|
|
408
|
+
contextual_tutorial_id = self._contextual_workflow_tutorial_id(clean_question, snapshot)
|
|
409
|
+
tutorial_summary = None if result_question else self._build_suggested_tutorial_summary(
|
|
410
|
+
clean_question, tutorial_id=tutorial_id or contextual_tutorial_id,
|
|
411
|
+
)
|
|
412
|
+
diagnosis = diagnose_snapshot(snapshot, clean_question)
|
|
413
|
+
if (normalized_mode == "heuristic" and not result_question
|
|
414
|
+
and self._should_force_popup_answer(clean_question, snapshot)):
|
|
415
|
+
return BotAnswerResult(
|
|
416
|
+
format_heuristic_answer(
|
|
417
|
+
clean_question,
|
|
418
|
+
snapshot,
|
|
419
|
+
diagnosis,
|
|
420
|
+
[],
|
|
421
|
+
intent=question_intent,
|
|
422
|
+
)
|
|
423
|
+
)
|
|
424
|
+
if (
|
|
425
|
+
question_intent == "tutorial"
|
|
426
|
+
and "check next" in clean_question.lower()
|
|
427
|
+
and not diagnosis.summary.startswith("No specific block")
|
|
428
|
+
):
|
|
429
|
+
question_intent = "diagnostic"
|
|
430
|
+
answer_depth = select_answer_depth(clean_question, question_intent)
|
|
431
|
+
# Resolve retrieval references using user evidence, never generated claims.
|
|
432
|
+
retrieval_question = self._retrieval_question(clean_question, selected_history)
|
|
433
|
+
candidates = self._retrieve_candidates(
|
|
434
|
+
retrieval_question, snapshot, question_intent, generic_question,
|
|
435
|
+
)
|
|
436
|
+
if tutorial_summary is not None:
|
|
437
|
+
candidates = self._prioritize_candidates(list(tutorial_summary.candidates), question_intent)
|
|
438
|
+
|
|
439
|
+
if normalized_mode == "heuristic":
|
|
440
|
+
if tutorial_summary is not None:
|
|
441
|
+
return BotAnswerResult(self._render_tutorial_summary(tutorial_summary))
|
|
442
|
+
if result_evidence_question:
|
|
443
|
+
result_answer = render_workflow_answer(
|
|
444
|
+
snapshot.workflow_results,
|
|
445
|
+
clean_question,
|
|
446
|
+
full=result_summary_request,
|
|
447
|
+
)
|
|
448
|
+
if (result_summary_request and snapshot.result_model == "Best models"
|
|
449
|
+
and not named_model and not asks_all_models):
|
|
450
|
+
note = _result_selection_note(snapshot, clean_question)
|
|
451
|
+
if note:
|
|
452
|
+
result_answer = f"{note}\n\n{result_answer}"
|
|
453
|
+
return BotAnswerResult(result_answer)
|
|
454
|
+
return BotAnswerResult(
|
|
455
|
+
format_heuristic_answer(
|
|
456
|
+
clean_question,
|
|
457
|
+
snapshot,
|
|
458
|
+
diagnosis,
|
|
459
|
+
candidates,
|
|
460
|
+
intent=question_intent,
|
|
461
|
+
)
|
|
462
|
+
)
|
|
463
|
+
provider_name = str(provider or "").strip() or "OpenAI"
|
|
464
|
+
if not str(api_key or "").strip():
|
|
465
|
+
return BotAnswerResult(f"Cloud AI mode requires an API key for {provider_name}.", memory_eligible=False)
|
|
466
|
+
|
|
467
|
+
adapter = self._resolve_provider(provider_name)
|
|
468
|
+
if adapter is None:
|
|
469
|
+
return BotAnswerResult(f"Unsupported LLM provider: {provider_name}.", memory_eligible=False)
|
|
470
|
+
|
|
471
|
+
assessment = assess_evidence(retrieval_question, candidates, intent=question_intent)
|
|
472
|
+
if assessment.decision is EvidenceDecision.INSUFFICIENT:
|
|
473
|
+
return BotAnswerResult(
|
|
474
|
+
"I do not have enough safe information to answer that question. Please add a little more detail.",
|
|
475
|
+
memory_eligible=False,
|
|
476
|
+
metadata=AnswerMetadata(evidence_origin=EvidenceOrigin.INSUFFICIENT),
|
|
477
|
+
)
|
|
478
|
+
|
|
479
|
+
if tutorial_summary is not None and assessment.decision is not EvidenceDecision.WEB_REQUIRED:
|
|
480
|
+
web_search_mode = WebSearchMode.OFF
|
|
481
|
+
intended_origin = EvidenceOrigin.LOCAL_DOCUMENTATION
|
|
482
|
+
else:
|
|
483
|
+
mode_by_decision = {
|
|
484
|
+
EvidenceDecision.LOCAL_ENOUGH: WebSearchMode.OFF,
|
|
485
|
+
EvidenceDecision.GENERAL_ENOUGH: WebSearchMode.OFF,
|
|
486
|
+
EvidenceDecision.WEB_OPTIONAL: WebSearchMode.AUTO,
|
|
487
|
+
EvidenceDecision.WEB_REQUIRED: WebSearchMode.REQUIRED,
|
|
488
|
+
}
|
|
489
|
+
web_search_mode = mode_by_decision[assessment.decision]
|
|
490
|
+
intended_origin = (
|
|
491
|
+
EvidenceOrigin.LOCAL_DOCUMENTATION
|
|
492
|
+
if assessment.decision is EvidenceDecision.LOCAL_ENOUGH
|
|
493
|
+
else EvidenceOrigin.GENERAL_KNOWLEDGE
|
|
494
|
+
)
|
|
495
|
+
if (result_evidence_question or gui_question) and web_search_mode is not WebSearchMode.REQUIRED:
|
|
496
|
+
web_search_mode = WebSearchMode.OFF
|
|
497
|
+
intended_origin = EvidenceOrigin.LOCAL_SYSTEM
|
|
498
|
+
limitation = ""
|
|
499
|
+
if web_search_mode is not WebSearchMode.OFF and web_search_enabled is not True:
|
|
500
|
+
web_search_mode = WebSearchMode.OFF
|
|
501
|
+
limitation = "Automatic web search is disabled, so current information was not verified."
|
|
502
|
+
|
|
503
|
+
spec = getattr(adapter, "spec", None)
|
|
504
|
+
supports_web_search = getattr(spec, "supports_web_search", False) is True
|
|
505
|
+
if web_search_mode is not WebSearchMode.OFF and not supports_web_search:
|
|
506
|
+
web_search_mode = WebSearchMode.OFF
|
|
507
|
+
limitation = (
|
|
508
|
+
f"{provider_name} does not support native web search in this configuration, "
|
|
509
|
+
"so current information was not verified."
|
|
510
|
+
)
|
|
511
|
+
|
|
512
|
+
search_query = ""
|
|
513
|
+
if web_search_mode is not WebSearchMode.OFF:
|
|
514
|
+
search_query = sanitize_search_query(
|
|
515
|
+
retrieval_question,
|
|
516
|
+
secret_values=(str(api_key).strip(),),
|
|
517
|
+
)
|
|
518
|
+
if not search_query:
|
|
519
|
+
return BotAnswerResult(
|
|
520
|
+
"I could not create a privacy-safe web query, so I cannot verify the current information.",
|
|
521
|
+
memory_eligible=False,
|
|
522
|
+
metadata=AnswerMetadata(
|
|
523
|
+
evidence_origin=EvidenceOrigin.INSUFFICIENT,
|
|
524
|
+
search_error="External verification was skipped because no safe search query remained.",
|
|
525
|
+
),
|
|
526
|
+
)
|
|
527
|
+
self._emit_progress(progress_callback, "searching_current_information")
|
|
528
|
+
|
|
529
|
+
self._emit_progress(progress_callback, "generating_answer")
|
|
530
|
+
|
|
531
|
+
try:
|
|
532
|
+
generation_kwargs = dict(
|
|
533
|
+
question=clean_question,
|
|
534
|
+
gui_context=snapshot,
|
|
535
|
+
retrieved_chunks=candidates,
|
|
536
|
+
api_key=str(api_key).strip(),
|
|
537
|
+
model=model,
|
|
538
|
+
conversation_history=selected_history,
|
|
539
|
+
question_intent=question_intent,
|
|
540
|
+
tutorial_summary=(
|
|
541
|
+
self._format_tutorial_summary_for_prompt(tutorial_summary)
|
|
542
|
+
if tutorial_summary is not None
|
|
543
|
+
else None
|
|
544
|
+
),
|
|
545
|
+
tutorial_label=tutorial_summary.label if tutorial_summary is not None else None,
|
|
546
|
+
)
|
|
547
|
+
if hasattr(adapter, "generate_answer_with_usage"):
|
|
548
|
+
documentation_attempted = False
|
|
549
|
+
if web_search_mode is not WebSearchMode.OFF and assessment.reason == "advanced_official_documentation":
|
|
550
|
+
documentation_attempted = True
|
|
551
|
+
documented = self._answer_from_online_docs(adapter, generation_kwargs, search_query, answer_depth)
|
|
552
|
+
if documented is not None:
|
|
553
|
+
return documented
|
|
554
|
+
try:
|
|
555
|
+
provider_result = adapter.generate_answer_with_usage(
|
|
556
|
+
**generation_kwargs,
|
|
557
|
+
web_search_mode=web_search_mode,
|
|
558
|
+
search_query=search_query,
|
|
559
|
+
evidence_origin=(
|
|
560
|
+
EvidenceOrigin.WEB_AND_DOCUMENTATION
|
|
561
|
+
if web_search_mode is not WebSearchMode.OFF
|
|
562
|
+
else intended_origin
|
|
563
|
+
),
|
|
564
|
+
answer_depth=answer_depth,
|
|
565
|
+
)
|
|
566
|
+
except LLMProviderError as exc:
|
|
567
|
+
if exc.status_code == 413 and web_search_mode is not WebSearchMode.OFF and not documentation_attempted:
|
|
568
|
+
fallback = self._answer_from_online_docs(adapter, generation_kwargs, search_query, answer_depth)
|
|
569
|
+
if fallback is not None:
|
|
570
|
+
return fallback
|
|
571
|
+
if web_search_mode is not WebSearchMode.AUTO or exc.status_code != 413:
|
|
572
|
+
raise
|
|
573
|
+
provider_result = adapter.generate_answer_with_usage(
|
|
574
|
+
**generation_kwargs,
|
|
575
|
+
web_search_mode=WebSearchMode.OFF,
|
|
576
|
+
search_query="",
|
|
577
|
+
evidence_origin=intended_origin,
|
|
578
|
+
answer_depth=answer_depth,
|
|
579
|
+
)
|
|
580
|
+
web_search_mode = WebSearchMode.OFF
|
|
581
|
+
limitation = (
|
|
582
|
+
"Optional web search was rejected because the provider reported an oversized request; "
|
|
583
|
+
"the answer was generated without web search."
|
|
584
|
+
)
|
|
585
|
+
usage = provider_result.usage
|
|
586
|
+
if result_evidence_question and question_intent == "results" and snapshot.workflow_results is not None:
|
|
587
|
+
result_data = snapshot.workflow_results
|
|
588
|
+
has_unresolved_verify_checks = any(
|
|
589
|
+
check[1] in {"FAILED", "UNCLEAR"}
|
|
590
|
+
for stage in result_data.stages for check in stage.checks
|
|
591
|
+
)
|
|
592
|
+
unchanged_test_set_warning = any(
|
|
593
|
+
"test_set" in warning and "0.2" in warning
|
|
594
|
+
and bool(re.search(r"(?:0\.2).*?(?:0\.2)", warning))
|
|
595
|
+
for warning in result_data.warnings
|
|
596
|
+
)
|
|
597
|
+
issues = result_summary_issues(
|
|
598
|
+
provider_result.text,
|
|
599
|
+
metrics=result_data.metrics,
|
|
600
|
+
unchanged_test_set_warning=unchanged_test_set_warning,
|
|
601
|
+
has_unresolved_verify_checks=has_unresolved_verify_checks,
|
|
602
|
+
)
|
|
603
|
+
if issues:
|
|
604
|
+
correction = "\n".join(f"- {issue}" for issue in issues)
|
|
605
|
+
retry_kwargs = dict(generation_kwargs)
|
|
606
|
+
retry_kwargs.update(
|
|
607
|
+
question=(
|
|
608
|
+
f"{clean_question}\n\nThe previous draft contradicted the recorded evidence. "
|
|
609
|
+
f"Write a fresh summary and correct these specific errors:\n{correction}"
|
|
610
|
+
),
|
|
611
|
+
retrieved_chunks=(),
|
|
612
|
+
conversation_history=(),
|
|
613
|
+
)
|
|
614
|
+
try:
|
|
615
|
+
revised = adapter.generate_answer_with_usage(
|
|
616
|
+
**retry_kwargs,
|
|
617
|
+
web_search_mode=WebSearchMode.OFF,
|
|
618
|
+
search_query="",
|
|
619
|
+
evidence_origin=intended_origin,
|
|
620
|
+
answer_depth=answer_depth,
|
|
621
|
+
)
|
|
622
|
+
usage += revised.usage
|
|
623
|
+
if not result_summary_issues(
|
|
624
|
+
revised.text,
|
|
625
|
+
metrics=result_data.metrics,
|
|
626
|
+
unchanged_test_set_warning=unchanged_test_set_warning,
|
|
627
|
+
has_unresolved_verify_checks=has_unresolved_verify_checks,
|
|
628
|
+
):
|
|
629
|
+
provider_result = revised
|
|
630
|
+
else:
|
|
631
|
+
return replace(
|
|
632
|
+
_result_provider_fallback(
|
|
633
|
+
snapshot, clean_question, full=result_summary_request,
|
|
634
|
+
reason="the generated answer conflicted with the workflow evidence",
|
|
635
|
+
),
|
|
636
|
+
usage=usage,
|
|
637
|
+
)
|
|
638
|
+
except LLMProviderError as exc:
|
|
639
|
+
return replace(
|
|
640
|
+
_result_provider_fallback(
|
|
641
|
+
snapshot, clean_question, full=result_summary_request,
|
|
642
|
+
reason=exc.kind.value.replace("_", " "),
|
|
643
|
+
),
|
|
644
|
+
usage=usage,
|
|
645
|
+
)
|
|
646
|
+
if usage.search_requests > 1:
|
|
647
|
+
raise LLMProviderError(
|
|
648
|
+
"The provider exceeded the one-search policy."
|
|
649
|
+
)
|
|
650
|
+
provider_metadata = getattr(provider_result, "metadata", None)
|
|
651
|
+
metadata = (
|
|
652
|
+
provider_metadata
|
|
653
|
+
if isinstance(provider_metadata, AnswerMetadata)
|
|
654
|
+
else AnswerMetadata(evidence_origin=intended_origin)
|
|
655
|
+
)
|
|
656
|
+
if limitation:
|
|
657
|
+
metadata = replace(metadata, evidence_origin=intended_origin, search_error=limitation)
|
|
658
|
+
elif usage.search_requests > 0:
|
|
659
|
+
if not metadata.sources:
|
|
660
|
+
return BotAnswerResult(
|
|
661
|
+
"The provider searched the web but returned no usable source citations, "
|
|
662
|
+
"so I cannot present the result as verified.",
|
|
663
|
+
memory_eligible=False,
|
|
664
|
+
usage=usage,
|
|
665
|
+
metadata=replace(
|
|
666
|
+
metadata,
|
|
667
|
+
evidence_origin=EvidenceOrigin.INSUFFICIENT,
|
|
668
|
+
search_error="Web search returned no usable source citations.",
|
|
669
|
+
),
|
|
670
|
+
)
|
|
671
|
+
metadata = replace(
|
|
672
|
+
metadata,
|
|
673
|
+
evidence_origin=EvidenceOrigin.WEB_AND_DOCUMENTATION,
|
|
674
|
+
)
|
|
675
|
+
elif web_search_mode is WebSearchMode.REQUIRED:
|
|
676
|
+
fallback = None if documentation_attempted else self._answer_from_online_docs(adapter, generation_kwargs, search_query, answer_depth, usage)
|
|
677
|
+
if fallback is not None:
|
|
678
|
+
return fallback
|
|
679
|
+
return BotAnswerResult(
|
|
680
|
+
"I could not verify the current information because the provider performed no web search.",
|
|
681
|
+
memory_eligible=False,
|
|
682
|
+
usage=usage,
|
|
683
|
+
metadata=replace(
|
|
684
|
+
metadata,
|
|
685
|
+
evidence_origin=EvidenceOrigin.INSUFFICIENT,
|
|
686
|
+
search_error="The required web search was not performed.",
|
|
687
|
+
),
|
|
688
|
+
)
|
|
689
|
+
else:
|
|
690
|
+
metadata = replace(metadata, evidence_origin=intended_origin)
|
|
691
|
+
return BotAnswerResult(provider_result.text, usage=usage, metadata=metadata)
|
|
692
|
+
return BotAnswerResult(adapter.generate_answer(**generation_kwargs))
|
|
693
|
+
except LLMProviderError as exc:
|
|
694
|
+
if result_evidence_question:
|
|
695
|
+
return _result_provider_fallback(
|
|
696
|
+
snapshot, clean_question, full=result_summary_request,
|
|
697
|
+
reason=exc.kind.value.replace("_", " "),
|
|
698
|
+
)
|
|
699
|
+
if exc.kind is LLMProviderErrorKind.RATE_LIMIT:
|
|
700
|
+
message = (
|
|
701
|
+
f"{provider_name} ha alcanzado su límite de uso. Espera un poco y vuelve a enviar la pregunta. "
|
|
702
|
+
"Si sigue ocurriendo, revisa los límites de tu cuenta del proveedor. Este aviso corresponde al chat, no al flujo de ROBERT."
|
|
703
|
+
if _response_language(clean_question) == "Spanish" else
|
|
704
|
+
f"{provider_name} has reached its usage limit. Wait a little and try again. "
|
|
705
|
+
"If this continues, check your provider account limits. This message concerns the chat, not the ROBERT workflow."
|
|
706
|
+
)
|
|
707
|
+
return BotAnswerResult(message, memory_eligible=False)
|
|
708
|
+
if tutorial_summary is not None:
|
|
709
|
+
return BotAnswerResult(self._render_tutorial_summary(tutorial_summary))
|
|
710
|
+
return BotAnswerResult(f"LLM provider error ({provider_name}): {exc}", memory_eligible=False)
|
|
711
|
+
except Exception as exc:
|
|
712
|
+
if result_evidence_question:
|
|
713
|
+
return _result_provider_fallback(
|
|
714
|
+
snapshot, clean_question, full=result_summary_request,
|
|
715
|
+
reason="unexpected bot error",
|
|
716
|
+
)
|
|
717
|
+
if tutorial_summary is not None:
|
|
718
|
+
return BotAnswerResult(self._render_tutorial_summary(tutorial_summary))
|
|
719
|
+
return BotAnswerResult(
|
|
720
|
+
f"Unexpected LLM error ({provider_name}). Please try again.",
|
|
721
|
+
memory_eligible=False,
|
|
722
|
+
)
|
|
723
|
+
|
|
724
|
+
@staticmethod
|
|
725
|
+
def _answer_from_online_docs(adapter, generation_kwargs, query, answer_depth, previous_usage=None):
|
|
726
|
+
"""Recover an unavailable native search using bounded official page reads."""
|
|
727
|
+
from .online_docs import fetch_documentation
|
|
728
|
+
chunks, sources = fetch_documentation(query)
|
|
729
|
+
if not chunks or not sources:
|
|
730
|
+
return None
|
|
731
|
+
kwargs = dict(generation_kwargs)
|
|
732
|
+
kwargs.update(retrieved_chunks=chunks, tutorial_summary=None, tutorial_label=None)
|
|
733
|
+
result = adapter.generate_answer_with_usage(
|
|
734
|
+
**kwargs, web_search_mode=WebSearchMode.OFF, search_query="",
|
|
735
|
+
evidence_origin=EvidenceOrigin.WEB_AND_DOCUMENTATION, answer_depth=answer_depth,
|
|
736
|
+
)
|
|
737
|
+
usage = previous_usage + result.usage if previous_usage and previous_usage.total_tokens else result.usage
|
|
738
|
+
return BotAnswerResult(
|
|
739
|
+
result.text, usage=usage,
|
|
740
|
+
metadata=AnswerMetadata(evidence_origin=EvidenceOrigin.WEB_AND_DOCUMENTATION, sources=sources),
|
|
741
|
+
)
|
|
742
|
+
|
|
743
|
+
@staticmethod
|
|
744
|
+
def _emit_progress(
|
|
745
|
+
callback: Callable[[str], None] | None,
|
|
746
|
+
stage: str,
|
|
747
|
+
) -> None:
|
|
748
|
+
if not callable(callback):
|
|
749
|
+
return
|
|
750
|
+
try:
|
|
751
|
+
callback(stage)
|
|
752
|
+
except Exception:
|
|
753
|
+
return
|
|
754
|
+
|
|
755
|
+
def _resolve_provider(self, provider_name: str) -> object | None:
|
|
756
|
+
if provider_name in self._provider_registry:
|
|
757
|
+
return self._provider_registry[provider_name]
|
|
758
|
+
lowered = provider_name.lower()
|
|
759
|
+
for name, adapter in self._provider_registry.items():
|
|
760
|
+
if name.lower() == lowered:
|
|
761
|
+
return adapter
|
|
762
|
+
return None
|
|
763
|
+
|
|
764
|
+
def _build_local_clock_answer(self, question: str) -> str:
|
|
765
|
+
normalized = self._normalize_clock_question(question)
|
|
766
|
+
if normalized not in _CURRENT_DATE_QUESTIONS | _CURRENT_TIME_QUESTIONS:
|
|
767
|
+
return ""
|
|
768
|
+
now = self._now_provider()
|
|
769
|
+
if normalized in _SPANISH_TIME_QUESTIONS:
|
|
770
|
+
return f"Son las {now:%H:%M} (hora local)."
|
|
771
|
+
if normalized in _CURRENT_TIME_QUESTIONS:
|
|
772
|
+
return f"It is {now:%H:%M} local time."
|
|
773
|
+
if normalized in _SPANISH_DATE_QUESTIONS:
|
|
774
|
+
weekday = _SPANISH_WEEKDAYS[now.weekday()]
|
|
775
|
+
month = _SPANISH_MONTHS[now.month - 1]
|
|
776
|
+
return f"Hoy es {weekday}, {now.day} de {month} de {now.year}."
|
|
777
|
+
return f"Today is {now.strftime('%A')}, {now.strftime('%B')} {now.day}, {now.year}."
|
|
778
|
+
|
|
779
|
+
@staticmethod
|
|
780
|
+
def _normalize_clock_question(question: str) -> str:
|
|
781
|
+
normalized = unicodedata.normalize("NFKD", str(question or ""))
|
|
782
|
+
normalized = "".join(character for character in normalized if not unicodedata.combining(character))
|
|
783
|
+
normalized = normalized.casefold().replace("'", "").replace("’", "")
|
|
784
|
+
return " ".join(re.sub(r"[^a-z0-9]+", " ", normalized).split())
|
|
785
|
+
|
|
786
|
+
@staticmethod
|
|
787
|
+
def _build_greeting_reply(question: str, snapshot: GuiSnapshot) -> str:
|
|
788
|
+
active_tab = str(getattr(snapshot, "active_tab", "") or "").strip()
|
|
789
|
+
tab_hint = f" I can see you're currently in the {active_tab} tab." if active_tab else ""
|
|
790
|
+
normalized = " ".join(str(question or "").casefold().split())
|
|
791
|
+
wellbeing = any(phrase in normalized for phrase in ("how are", "how r u", "how ar eu"))
|
|
792
|
+
opening = "Hi! I'm doing well, thanks for asking." if wellbeing else "Hi!"
|
|
793
|
+
return f"{opening} How can I help?{tab_hint}"
|
|
794
|
+
|
|
795
|
+
@staticmethod
|
|
796
|
+
def _is_low_information_question(question: str) -> bool:
|
|
797
|
+
lowered = str(question or "").strip().lower()
|
|
798
|
+
raw_tokens = re.findall(r"[a-z0-9_]+", lowered)
|
|
799
|
+
meaningful_tokens = set(normalize_terms(lowered))
|
|
800
|
+
if not raw_tokens:
|
|
801
|
+
return True
|
|
802
|
+
if lowered in {"what?", "what", "excuse me?", "excuse me", "sorry?", "sorry", "huh?", "huh"}:
|
|
803
|
+
return True
|
|
804
|
+
domain_terms = {
|
|
805
|
+
"error", "warning", "csv", "aqme", "robert", "predict", "prediction",
|
|
806
|
+
"predictions", "report", "reports", "descriptor", "descriptors", "model",
|
|
807
|
+
"regression", "classification",
|
|
808
|
+
}
|
|
809
|
+
return len(raw_tokens) <= 2 and not bool(meaningful_tokens & domain_terms)
|
|
810
|
+
|
|
811
|
+
@staticmethod
|
|
812
|
+
def _should_force_popup_answer(question: str, snapshot: GuiSnapshot) -> bool:
|
|
813
|
+
popup_available = bool(str(snapshot.popup_text or "").strip())
|
|
814
|
+
if not popup_available:
|
|
815
|
+
return False
|
|
816
|
+
return bool(_POPUP_QUESTION_RE.search(str(question or "")))
|
|
817
|
+
|
|
818
|
+
@staticmethod
|
|
819
|
+
def _contextual_workflow_tutorial_id(question: str, snapshot: GuiSnapshot) -> str | None:
|
|
820
|
+
"""Resolve a request about the selected workflow to its own tutorial."""
|
|
821
|
+
text = str(question or "").casefold()
|
|
822
|
+
if not re.search(r"\b(?:how|run|start|c[oó]mo|ejecutar|ejecuto|iniciar|inicio)\b", text):
|
|
823
|
+
return None
|
|
824
|
+
if not re.search(
|
|
825
|
+
r"\b(?:this|current|selected)\s+workflow\b|"
|
|
826
|
+
r"\b(?:este|esta|el)\s+(?:workflow|flujo(?:\s+de\s+trabajo)?)\b",
|
|
827
|
+
text,
|
|
828
|
+
):
|
|
829
|
+
return None
|
|
830
|
+
workflow = str(snapshot.workflow or "").casefold().strip()
|
|
831
|
+
if workflow == "checkml":
|
|
832
|
+
return "check_model"
|
|
833
|
+
if workflow == "full workflow":
|
|
834
|
+
return "overview"
|
|
835
|
+
return None
|
|
836
|
+
|
|
837
|
+
def _build_suggested_tutorial_summary(
|
|
838
|
+
self,
|
|
839
|
+
question: str,
|
|
840
|
+
*,
|
|
841
|
+
tutorial_id: str | None = None,
|
|
842
|
+
) -> TutorialSummary | None:
|
|
843
|
+
resolved_id = self._resolve_tutorial_id(question, tutorial_id=tutorial_id)
|
|
844
|
+
tutorial = _TUTORIALS_BY_ID.get(resolved_id)
|
|
845
|
+
if tutorial is None:
|
|
846
|
+
return None
|
|
847
|
+
|
|
848
|
+
source, label = tutorial
|
|
849
|
+
chunks = sorted(
|
|
850
|
+
self._knowledge_base.chunks_for_source(source),
|
|
851
|
+
key=self._tutorial_chunk_order,
|
|
852
|
+
)
|
|
853
|
+
if not chunks:
|
|
854
|
+
return None
|
|
855
|
+
|
|
856
|
+
section_points: list[str] = []
|
|
857
|
+
seen: set[str] = set()
|
|
858
|
+
for chunk in chunks:
|
|
859
|
+
sentences = self._sentences_from_tutorial_text(chunk.text)
|
|
860
|
+
if not sentences:
|
|
861
|
+
continue
|
|
862
|
+
sentence = " ".join(sentences[:2])
|
|
863
|
+
normalized = " ".join(sentence.lower().split())
|
|
864
|
+
if normalized in seen:
|
|
865
|
+
continue
|
|
866
|
+
seen.add(normalized)
|
|
867
|
+
section_points.append(sentence)
|
|
868
|
+
if len(section_points) >= _TUTORIAL_OVERVIEW_LIMIT + _TUTORIAL_BULLET_LIMIT:
|
|
869
|
+
break
|
|
870
|
+
|
|
871
|
+
if not section_points:
|
|
872
|
+
return None
|
|
873
|
+
|
|
874
|
+
overview = section_points[0]
|
|
875
|
+
bullets = tuple(section_points[1 : 1 + _TUTORIAL_BULLET_LIMIT]) or (overview,)
|
|
876
|
+
candidates = tuple(
|
|
877
|
+
SearchResult(chunk=chunk, score=float(len(chunks) - index))
|
|
878
|
+
for index, chunk in enumerate(chunks)
|
|
879
|
+
)
|
|
880
|
+
return TutorialSummary(
|
|
881
|
+
source=source,
|
|
882
|
+
label=label,
|
|
883
|
+
overview=overview,
|
|
884
|
+
bullets=bullets,
|
|
885
|
+
candidates=candidates,
|
|
886
|
+
)
|
|
887
|
+
|
|
888
|
+
@staticmethod
|
|
889
|
+
def _render_tutorial_summary(summary: TutorialSummary) -> str:
|
|
890
|
+
bullets = "\n".join(f"- {bullet}" for bullet in summary.bullets[:_TUTORIAL_BULLET_LIMIT])
|
|
891
|
+
return (
|
|
892
|
+
f"{summary.label} tutorial summary:\n"
|
|
893
|
+
f"{summary.overview}\n\n"
|
|
894
|
+
"Key points:\n"
|
|
895
|
+
f"{bullets}\n\n"
|
|
896
|
+
"If you want the full click-by-click tutorial, open the Tutorial panel "
|
|
897
|
+
f"and select {summary.label}."
|
|
898
|
+
)
|
|
899
|
+
|
|
900
|
+
@staticmethod
|
|
901
|
+
def _format_tutorial_summary_for_prompt(summary: TutorialSummary) -> str:
|
|
902
|
+
bullet_lines = "\n".join(
|
|
903
|
+
f"- {bullet}" for bullet in summary.bullets[:_TUTORIAL_BULLET_LIMIT]
|
|
904
|
+
)
|
|
905
|
+
return f"Purpose: {summary.overview}\nKey points:\n{bullet_lines}"
|
|
906
|
+
|
|
907
|
+
@staticmethod
|
|
908
|
+
def _tutorial_chunk_order(chunk: object) -> tuple[int, int | str]:
|
|
909
|
+
chunk_id = str(getattr(chunk, "id", "") or "")
|
|
910
|
+
match = re.search(r"-(\d+)$", chunk_id)
|
|
911
|
+
if match:
|
|
912
|
+
return 0, int(match.group(1))
|
|
913
|
+
return 1, chunk_id
|
|
914
|
+
|
|
915
|
+
@classmethod
|
|
916
|
+
def _resolve_tutorial_id(cls, question: str, *, tutorial_id: str | None = None) -> str:
|
|
917
|
+
explicit_id = tutorial_id.strip().lower() if type(tutorial_id) is str else ""
|
|
918
|
+
if explicit_id in _TUTORIALS_BY_ID:
|
|
919
|
+
return explicit_id
|
|
920
|
+
|
|
921
|
+
normalized = cls._normalize_question_key(question)
|
|
922
|
+
exact_id = _EXACT_TUTORIAL_QUESTIONS.get(normalized)
|
|
923
|
+
if exact_id:
|
|
924
|
+
return exact_id
|
|
925
|
+
|
|
926
|
+
if "chemdraw" in normalized and re.search(
|
|
927
|
+
r"\b(start|starting|begin|use|using|import|load|convert|from|guide)\b",
|
|
928
|
+
normalized,
|
|
929
|
+
):
|
|
930
|
+
return "chemdraw"
|
|
931
|
+
if re.search(r"\b(?:i have|i already have|already loaded|tengo|ya tengo)\b.*\bcsv\b", normalized):
|
|
932
|
+
# Existing data needs workflow guidance, not a CSV-creation summary.
|
|
933
|
+
return ""
|
|
934
|
+
if re.search(r"\bcsv\b", normalized) and re.search(
|
|
935
|
+
r"\b(start|starting|begin|from|load|loading|use|using|guide)\b",
|
|
936
|
+
normalized,
|
|
937
|
+
):
|
|
938
|
+
return "csv"
|
|
939
|
+
if re.search(r"\b(new|unknown|unseen)\b", normalized) and re.search(
|
|
940
|
+
r"\b(predict|prediction|predictions|molecule|molecules)\b",
|
|
941
|
+
normalized,
|
|
942
|
+
):
|
|
943
|
+
return "predictions"
|
|
944
|
+
if "overview" in normalized and re.search(r"\b(gui|easyrob|workflow|work)\b", normalized):
|
|
945
|
+
return "overview"
|
|
946
|
+
if "descriptor" in normalized and (
|
|
947
|
+
re.search(r"\bwithout\b.*\b(train|training|run|running|build|building)\b.*\b(model|robert)\b", normalized)
|
|
948
|
+
or re.search(r"\b(?:only|just)\b.*\b(?:generate|create|make)\b.*\bdescriptors?\b", normalized)
|
|
949
|
+
or re.search(r"\bdescriptors?\s+(?:only|alone)\b", normalized)
|
|
950
|
+
or re.search(r"\brun\s+aqme\s+(?:only|alone)\b", normalized)
|
|
951
|
+
):
|
|
952
|
+
return "descriptors"
|
|
953
|
+
return ""
|
|
954
|
+
|
|
955
|
+
@staticmethod
|
|
956
|
+
def _normalize_question_key(question: str) -> str:
|
|
957
|
+
lowered = str(question or "").strip().lower()
|
|
958
|
+
lowered = re.sub(r"[?.!]+$", "", lowered)
|
|
959
|
+
return " ".join(lowered.split())
|
|
960
|
+
|
|
961
|
+
@staticmethod
|
|
962
|
+
def _sentences_from_tutorial_text(text: str) -> list[str]:
|
|
963
|
+
cleaned = " ".join(str(text or "").split())
|
|
964
|
+
if not cleaned:
|
|
965
|
+
return []
|
|
966
|
+
parts = [part.strip(" -") for part in _SENTENCE_SPLIT_RE.split(cleaned) if part.strip()]
|
|
967
|
+
return [part for part in parts if len(part) > 20]
|
|
968
|
+
|
|
969
|
+
@staticmethod
|
|
970
|
+
def _infer_focus_tags(question: str, snapshot: GuiSnapshot) -> tuple[str, ...]:
|
|
971
|
+
lowered = str(question or "").lower()
|
|
972
|
+
focus: list[str] = []
|
|
973
|
+
|
|
974
|
+
aqme_terms = (
|
|
975
|
+
"aqme",
|
|
976
|
+
"smiles",
|
|
977
|
+
"descriptor generation",
|
|
978
|
+
"descriptors from smiles",
|
|
979
|
+
"qdescp",
|
|
980
|
+
"csearch",
|
|
981
|
+
"cmin",
|
|
982
|
+
"qcorr",
|
|
983
|
+
"qprep",
|
|
984
|
+
"chemdraw",
|
|
985
|
+
)
|
|
986
|
+
robert_terms = (
|
|
987
|
+
"robert",
|
|
988
|
+
"curate",
|
|
989
|
+
"generate",
|
|
990
|
+
"verify",
|
|
991
|
+
"predict",
|
|
992
|
+
"report",
|
|
993
|
+
"pfi",
|
|
994
|
+
"rmse",
|
|
995
|
+
"mae",
|
|
996
|
+
"r squared",
|
|
997
|
+
"r2",
|
|
998
|
+
"machine learning",
|
|
999
|
+
"target column",
|
|
1000
|
+
"main csv",
|
|
1001
|
+
)
|
|
1002
|
+
ui_terms = (
|
|
1003
|
+
"tab",
|
|
1004
|
+
"button",
|
|
1005
|
+
"gui",
|
|
1006
|
+
"interface",
|
|
1007
|
+
"settings",
|
|
1008
|
+
"popup",
|
|
1009
|
+
"window",
|
|
1010
|
+
"documentation",
|
|
1011
|
+
"tutorial",
|
|
1012
|
+
"dropdown",
|
|
1013
|
+
"checkbox",
|
|
1014
|
+
)
|
|
1015
|
+
|
|
1016
|
+
if any(term in lowered for term in aqme_terms):
|
|
1017
|
+
focus.append("aqme")
|
|
1018
|
+
if any(term in lowered for term in robert_terms):
|
|
1019
|
+
focus.append("robert")
|
|
1020
|
+
if any(term in lowered for term in ui_terms):
|
|
1021
|
+
focus.append("ui")
|
|
1022
|
+
|
|
1023
|
+
active_tab = str(getattr(snapshot, "active_tab", "") or "")
|
|
1024
|
+
if active_tab in {"AQME", "AQME descriptors"}:
|
|
1025
|
+
focus.extend(["aqme", "ui"])
|
|
1026
|
+
elif active_tab in {"ROBERT", "Workflow", "Advanced Options", "Advanced options", "Results", "Reports", "Predictions", "Images"}:
|
|
1027
|
+
focus.extend(["robert", "ui"])
|
|
1028
|
+
|
|
1029
|
+
if getattr(snapshot, "aqme_workflow_enabled", False) and "aqme" in lowered and "ui" not in focus:
|
|
1030
|
+
focus.append("ui")
|
|
1031
|
+
|
|
1032
|
+
if not focus:
|
|
1033
|
+
focus.extend(["robert", "ui"])
|
|
1034
|
+
|
|
1035
|
+
deduped: list[str] = []
|
|
1036
|
+
for tag in focus:
|
|
1037
|
+
if tag not in deduped:
|
|
1038
|
+
deduped.append(tag)
|
|
1039
|
+
return tuple(deduped)
|
|
1040
|
+
|
|
1041
|
+
@staticmethod
|
|
1042
|
+
def _retrieval_question(
|
|
1043
|
+
question: str, selected_history: Sequence[Mapping[str, str]],
|
|
1044
|
+
) -> str:
|
|
1045
|
+
if selected_history:
|
|
1046
|
+
# A leading Spanish conjunction is not the target variable named "y".
|
|
1047
|
+
current_question = re.sub(r"^\s*¿\s*y\s+", "¿", question, flags=re.IGNORECASE)
|
|
1048
|
+
current_question = re.sub(r"^\s*y\s+", "", current_question, flags=re.IGNORECASE)
|
|
1049
|
+
return f"{current_question}\nPrevious user question: {selected_history[0]['content'][:2000]}"
|
|
1050
|
+
return question
|
|
1051
|
+
|
|
1052
|
+
def _retrieve_candidates(
|
|
1053
|
+
self,
|
|
1054
|
+
retrieval_question: str,
|
|
1055
|
+
snapshot: GuiSnapshot,
|
|
1056
|
+
question_intent: str,
|
|
1057
|
+
generic_question: bool,
|
|
1058
|
+
) -> list[SearchResult]:
|
|
1059
|
+
candidates = self._knowledge_base.search(
|
|
1060
|
+
question=retrieval_question,
|
|
1061
|
+
active_tab=None if generic_question or question_intent == "tutorial" else snapshot.active_tab,
|
|
1062
|
+
workflow=None if generic_question else snapshot.workflow,
|
|
1063
|
+
console_terms=snapshot.console_terms if question_intent == "diagnostic" and not generic_question else [],
|
|
1064
|
+
question_intent=question_intent,
|
|
1065
|
+
focus_tags=() if generic_question else self._infer_focus_tags(retrieval_question, snapshot),
|
|
1066
|
+
)
|
|
1067
|
+
return self._prioritize_candidates(candidates, question_intent)
|
|
1068
|
+
|
|
1069
|
+
@staticmethod
|
|
1070
|
+
def _prioritize_candidates(candidates: list[object], question_intent: str) -> list[object]:
|
|
1071
|
+
if question_intent == "diagnostic":
|
|
1072
|
+
return candidates
|
|
1073
|
+
best_score = max((float(getattr(candidate, "score", 0.0)) for candidate in candidates), default=0.0)
|
|
1074
|
+
|
|
1075
|
+
def sort_key(candidate: object) -> tuple[int, int]:
|
|
1076
|
+
chunk = getattr(candidate, "chunk", candidate)
|
|
1077
|
+
source = str(getattr(chunk, "source", "") or "")
|
|
1078
|
+
source_tier = str(getattr(chunk, "source_tier", "") or "").casefold()
|
|
1079
|
+
topic = str(getattr(chunk, "topic", "") or "").lower()
|
|
1080
|
+
tab = str(getattr(chunk, "tab", "") or "")
|
|
1081
|
+
|
|
1082
|
+
if source_tier == "curated" or source == "curated_overrides":
|
|
1083
|
+
preferred = 0
|
|
1084
|
+
elif question_intent == "tutorial":
|
|
1085
|
+
preferred = 1 if source.startswith("tutorial:") or topic in {"tutorial", "concept"} else 2
|
|
1086
|
+
elif question_intent == "results":
|
|
1087
|
+
preferred_tabs = {"Results", "Reports", "Predictions", "Images"}
|
|
1088
|
+
preferred = 1 if tab in preferred_tabs or "result" in topic else 2
|
|
1089
|
+
elif question_intent == "parameter":
|
|
1090
|
+
preferred = 1 if topic == "parameter" else 2
|
|
1091
|
+
elif question_intent == "module-explanation":
|
|
1092
|
+
preferred = 1 if topic in {"concept", "tutorial"} else 2
|
|
1093
|
+
else:
|
|
1094
|
+
preferred = 1
|
|
1095
|
+
# Preserve very strong lexical matches before source preferences.
|
|
1096
|
+
# Within each relevance group, retain the search order on ties.
|
|
1097
|
+
strong_match = float(getattr(candidate, "score", 0.0)) >= best_score - 20.0
|
|
1098
|
+
return (0 if strong_match else 1, preferred)
|
|
1099
|
+
|
|
1100
|
+
return sorted(candidates, key=sort_key)
|