diff --git a/README.md b/README.md index c63663b..ef10a13 100644 --- a/README.md +++ b/README.md @@ -97,7 +97,9 @@ s osobami a témami ZP Wiki (`PROBABLY_SAME`, `SAME_TOPIC`). - `tools/rag/` – textové a vektorové vyhľadávanie. - `tools/graphrag/` – metadátový graf a grafové dotazy. - `tools/knowledge/` – obsahový graf: extrakcia poznatkov a ich vyhľadávanie. -- `tools/answers/` – plán otázky, zostavenie a kontrola odpovede. +- `tools/answers/` – odpoveď: `answer_delivery.py` (ZP Wiki), `combined.py` (ZP Wiki + CRZP), `pages.py`, `timing.py`; + `planning/` (plán otázky, katalóg, konverzácia), `evidence/` (výber podkladov), `generation/` (text z modelu, + klient modelu), `verification/` (kontrola pred odoslaním), `presentation/` (podoba odpovede, mená). - `tools/retrieval/` – spoločné vyhľadávacie pravidlá, mená, lematizácia, reranker. - `tools/sync/` – synchronizácia s Git repozitárom a obnova indexov. - `tools/git_runner/` – Gitea runner, ktorý dopĺňa fork `jp170na/zpwiki` z `KEMT/zpwiki`. @@ -105,6 +107,6 @@ s osobami a témami ZP Wiki (`PROBABLY_SAME`, `SAME_TOPIC`). - `tools/claude/`, `packages/claude/` – zostavenie a hotové Claude Skills (`dist/rag`, `dist/graphrag`). - `deployment/` – Dockerfile, Docker Compose a závislosti. - `scripts/` – spúšťacie skripty. -- `test/`, `tools/*/tests/` – testy funkcionality jednotlivých služieb (plánovanie, - vyhľadávanie, kontrola odpovedí, API, synchronizácia, balíky Claude). +- `test/` – testy podľa oblasti: `api/`, `planning/`, `retrieval/`, `graph/`, `knowledge/`, `verification/`, + `presentation/`, `sync/`, `evaluation/`, `packages/`; testy CRZP, RAG a GraphRAG sú aj v `tools/*/tests/`. - `data/` – lokálne dáta za behu (indexy, cache); nie sú v Gite. diff --git a/app/routes.py b/app/routes.py index 7867926..5fc8531 100644 --- a/app/routes.py +++ b/app/routes.py @@ -54,7 +54,7 @@ from tools.retrieval.retrieval_contract import ( error_reason, ) from tools.answers.answer_delivery import deliver_answer -from tools.answers.answer_errors import public_failure +from tools.answers.presentation.answer_errors import public_failure logger = logging.getLogger(__name__) @@ -497,7 +497,7 @@ def health(request: Request) -> dict[str, Any]: dependencies=[Depends(require_search_api_key)]) def probe_answer_generation(): """Explicit authenticated model probe; GET /health never incurs model calls.""" - from tools.answers.model_client import probe_generation + from tools.answers.generation.model_client import probe_generation return probe_generation() diff --git a/conftest.py b/conftest.py index 99e8888..ee5d4d8 100644 --- a/conftest.py +++ b/conftest.py @@ -13,7 +13,7 @@ os.environ.setdefault("CRZP_CHECK_INTERVAL_SECONDS", "0") os.environ.setdefault("CRZP_PREPARE", "0") os.environ.setdefault("ANSWER_WITH_CRZP", "0") # tests answer from the wiki fixture only os.environ.setdefault("CRZP_GRAPH_LINKS", "0") -os.environ.setdefault("NAME_FORMS_MODEL", "0") # names declined by rules; tests of tools/answers/names.py enable it +os.environ.setdefault("NAME_FORMS_MODEL", "0") # names declined by rules; tests of tools/answers/presentation/names.py enable it # Evaluation code lives outside Git (see local/OBSAH.md). Without it, tests that # import it at module level are skipped at collection instead of failing. @@ -26,7 +26,7 @@ _ROOT = pathlib.Path(__file__).parent _EVAL_MISSING = importlib.util.find_spec("tools.evaluation") is None or importlib.util.find_spec("tools.graphrag.evaluation") is None _QUESTIONS_MISSING = not (_ROOT / "tools/knowledge/questions.json").exists() collect_ignore = [] -for _path in [*_ROOT.glob("test/test_*.py"), *_ROOT.glob("tools/*/tests/test_*.py")]: +for _path in [*_ROOT.glob("test/**/test_*.py"), *_ROOT.glob("tools/*/tests/test_*.py")]: _text = _path.read_text(encoding="utf-8") if (_EVAL_MISSING and _EVAL_IMPORT.search(_text)) or (_QUESTIONS_MISSING and "tools/knowledge/questions.json" in _text): collect_ignore.append(str(_path.relative_to(_ROOT))) diff --git a/deployment/requirements-dev.txt b/deployment/requirements-dev.txt index 4f30e2d..ce0115e 100644 --- a/deployment/requirements-dev.txt +++ b/deployment/requirements-dev.txt @@ -3,4 +3,4 @@ httpx>=0.27,<1 pytest>=8,<10 pytest-cov>=5,<8 -dspy>=3.5,<4 # offline optimization of the question catalog (tools/answers/catalog_optimize.py) +dspy>=3.5,<4 # offline optimization of the question catalog (tools/answers/planning/catalog_optimize.py) diff --git a/test/test_answer_health.py b/test/api/test_answer_health.py similarity index 97% rename from test/test_answer_health.py rename to test/api/test_answer_health.py index f3b491d..07679c5 100644 --- a/test/test_answer_health.py +++ b/test/api/test_answer_health.py @@ -2,7 +2,7 @@ import json import pytest -from tools.answers import model_client as model +from tools.answers.generation import model_client as model from tools.runtime import answer_health as health from tools.knowledge.publication import checkpoint_state, PENDING_FILE from tools.sync.index_state import durable_json, VERSION_FILE diff --git a/test/test_api.py b/test/api/test_api.py similarity index 100% rename from test/test_api.py rename to test/api/test_api.py diff --git a/test/test_configuration.py b/test/api/test_configuration.py similarity index 98% rename from test/test_configuration.py rename to test/api/test_configuration.py index 468b9be..5780b3f 100644 --- a/test/test_configuration.py +++ b/test/api/test_configuration.py @@ -3,7 +3,7 @@ from __future__ import annotations import re from pathlib import Path -PROJECT_ROOT = Path(__file__).resolve().parents[1] +PROJECT_ROOT = Path(__file__).resolve().parents[2] def read_project_file(name: str) -> str: diff --git a/test/test_contract_conversations.py b/test/api/test_contract_conversations.py similarity index 98% rename from test/test_contract_conversations.py rename to test/api/test_contract_conversations.py index d13384b..6326e94 100644 --- a/test/test_contract_conversations.py +++ b/test/api/test_contract_conversations.py @@ -13,7 +13,8 @@ import pytest import app.routes as routes from packages.claude import client from test_claude_packages import backend,ROOT -from tools.answers import answer_delivery,question_plan +from tools.answers import answer_delivery +from tools.answers.planning import question_plan from tools.knowledge import query,store from tools.knowledge.sources import profile_units from tools.knowledge.academic import answer_academic diff --git a/test/test_question_delivery.py b/test/api/test_question_delivery.py similarity index 97% rename from test/test_question_delivery.py rename to test/api/test_question_delivery.py index f6faf95..b83507a 100644 --- a/test/test_question_delivery.py +++ b/test/api/test_question_delivery.py @@ -83,7 +83,7 @@ def test_missing_question_echo_is_not_accepted(backend): @pytest.mark.parametrize('engine',['rag','graphrag']) def test_safe_request_bound_diagnostic_survives_http_and_presentation(backend,engine): - from tools.answers.delivery_contract import fingerprint + from tools.answers.verification.delivery_contract import fingerprint q='Aké práce má Eva Nová?' backend['checked']['delivery_check']={'layer':'delivery','code':'partial','request_fingerprint':fingerprint(q,engine)} result=client.answer_for_presentation(client.query_backend(q,engine)) @@ -94,7 +94,7 @@ def test_safe_request_bound_diagnostic_survives_http_and_presentation(backend,en {'layer':'SECRET PROVIDER KEY'},{'code':'PRIVATE raw model response'}, {'request_fingerprint':'0'*64},{'extra':'PRIVATE error trace'}]) def test_corrupt_or_unsafe_diagnostic_is_never_published(backend,change): - from tools.answers.delivery_contract import fingerprint + from tools.answers.verification.delivery_contract import fingerprint q='Aké práce má Eva Nová?' backend['checked']['delivery_check']={'layer':'delivery','code':'complete','request_fingerprint':fingerprint(q,'rag'),**change} result=client.query_backend(q,'rag') diff --git a/test/test_security.py b/test/api/test_security.py similarity index 100% rename from test/test_security.py rename to test/api/test_security.py diff --git a/test/test_time_budget.py b/test/api/test_time_budget.py similarity index 97% rename from test/test_time_budget.py rename to test/api/test_time_budget.py index 7e5c11e..e244267 100644 --- a/test/test_time_budget.py +++ b/test/api/test_time_budget.py @@ -4,7 +4,7 @@ import time import pytest -from tools.answers import model_client as mc +from tools.answers.generation import model_client as mc def test_parallel_map_keeps_order_and_the_callers_deadline(): @@ -51,8 +51,8 @@ def test_nested_deadline_keeps_the_outer_budget(): def test_low_budget_keeps_the_checked_answer_without_prose_synthesis(): - from tools.answers import synthesis - from tools.answers.question_plan import QuestionPlan, PersonRequest + from tools.answers.generation import synthesis + from tools.answers.planning.question_plan import QuestionPlan, PersonRequest plan = QuestionPlan(question="Na čom pracoval Ján Holp?", intent="progress", people=[PersonRequest(name="Ján Holp")]) result = {"status": "ok", "accepted_for_delivery": True, "answer": "Overené", diff --git a/test/conftest.py b/test/conftest.py index fbd1719..515ff21 100644 --- a/test/conftest.py +++ b/test/conftest.py @@ -9,6 +9,11 @@ PROJECT_ROOT = Path(__file__).resolve().parents[1] if str(PROJECT_ROOT) not in sys.path: sys.path.insert(0, str(PROJECT_ROOT)) +# Tests are grouped in folders by area (api/, planning/, …); some reuse helpers of another test module +# by its name ("from test_index_sync import …"), so every test folder is importable. +for _folder in sorted(p for p in Path(__file__).resolve().parent.iterdir() if p.is_dir() and p.name != "__pycache__"): + if str(_folder) not in sys.path: + sys.path.append(str(_folder)) @pytest.fixture(autouse=True) diff --git a/test/test_gold_set.py b/test/evaluation/test_gold_set.py similarity index 100% rename from test/test_gold_set.py rename to test/evaluation/test_gold_set.py diff --git a/test/test_graph_answer_evaluation.py b/test/evaluation/test_graph_answer_evaluation.py similarity index 100% rename from test/test_graph_answer_evaluation.py rename to test/evaluation/test_graph_answer_evaluation.py diff --git a/test/test_user_question_evaluation.py b/test/evaluation/test_user_question_evaluation.py similarity index 99% rename from test/test_user_question_evaluation.py rename to test/evaluation/test_user_question_evaluation.py index 011baf3..070df33 100644 --- a/test/test_user_question_evaluation.py +++ b/test/evaluation/test_user_question_evaluation.py @@ -149,7 +149,7 @@ def test_nearest_work_and_section_are_explicit_even_with_nested_markdown(tmp_pat @pytest.mark.parametrize('text',['Model zatiaľ nefunguje.','Nepasuje konfigurácia modelu.', 'Použitá konfigurácia je nekompatibilná.','Výsledky je ťažké porovnať pomocou BLEU.']) def test_technical_difficulty_does_not_require_the_literal_word_problem(text): - from tools.answers.content_selection import facets_for + from tools.answers.evidence.content_selection import facets_for assert 'problems' in facets_for(text,'progress','Aké problémy riešil študent?','progress') diff --git a/test/test_graph_query_regressions.py b/test/graph/test_graph_query_regressions.py similarity index 97% rename from test/test_graph_query_regressions.py rename to test/graph/test_graph_query_regressions.py index b2e4fa0..52cc5f6 100644 --- a/test/test_graph_query_regressions.py +++ b/test/graph/test_graph_query_regressions.py @@ -6,10 +6,10 @@ from pathlib import Path import pytest -from tools.answers.checked_generation import generate_checked_answer -from tools.answers.context_policy import answer_context_issues -from tools.answers.graph_context import graph_context -from tools.answers.render_answer import render_graph_answer +from tools.answers.generation.checked_generation import generate_checked_answer +from tools.answers.verification.context_policy import answer_context_issues +from tools.answers.evidence.graph_context import graph_context +from tools.answers.presentation.render_answer import render_graph_answer from tools.answers.answer_delivery import deliver_answer from tools.graphrag import graph_search as gs from tools.graphrag.tests.test_graph_search import FakeSession @@ -144,7 +144,7 @@ def test_tag_predicate_stays_bound_to_visible_records_after_truncation(tagged_pr def test_count_model_input_keeps_actual_total_and_only_claim_fields(tagged_projects): import json - from tools.answers.answer_format import Claim + from tools.answers.generation.answer_format import Claim q = "Koľko študentov má tag RAG a zároveň diplomový projekt z roku 2026?" context = graph_context(gs.search_graph_with_session(tagged_projects, q, limit=1)) diff --git a/test/test_graph_work_listing.py b/test/graph/test_graph_work_listing.py similarity index 96% rename from test/test_graph_work_listing.py rename to test/graph/test_graph_work_listing.py index df62517..defefe8 100644 --- a/test/test_graph_work_listing.py +++ b/test/graph/test_graph_work_listing.py @@ -6,11 +6,11 @@ from pathlib import Path import pytest -from tools.answers.answer_format import parse_answer -from tools.answers.checked_generation import generate_checked_answer -from tools.answers.context_policy import answer_context_issues -from tools.answers.graph_context import graph_context -from tools.answers.render_answer import render_graph_answer +from tools.answers.generation.answer_format import parse_answer +from tools.answers.generation.checked_generation import generate_checked_answer +from tools.answers.verification.context_policy import answer_context_issues +from tools.answers.evidence.graph_context import graph_context +from tools.answers.presentation.render_answer import render_graph_answer from tools.graphrag import graph_search as gs from tools.graphrag.tests.test_graph_search import FakeSession, sample_catalog @@ -298,7 +298,7 @@ def test_production_delivery_repairs_year_only_answer_and_renders_all_records( monkeypatch.setattr(store,'load_index',lambda *a,**kw:None) from contextlib import nullcontext - from tools.answers import question_plan + from tools.answers.planning import question_plan monkeypatch.setattr(question_plan,'planning_catalog',lambda db:[{'name':'Ján Holp','kind':'Person','source_document':'pages/students/2016/jan_holp/README.md'}]) monkeypatch.setattr(delivery,'index_snapshot',lambda *a,**kw:nullcontext()) monkeypatch.setattr(delivery, "search_graph", lambda query, **kwargs: retrieved) diff --git a/test/test_local_graph.py b/test/graph/test_local_graph.py similarity index 99% rename from test/test_local_graph.py rename to test/graph/test_local_graph.py index d1d8600..5b93a40 100644 --- a/test/test_local_graph.py +++ b/test/graph/test_local_graph.py @@ -5,7 +5,7 @@ import uuid import pytest -from tools.answers.question_plan import build_question_plan +from tools.answers.planning.question_plan import build_question_plan from tools.knowledge.sources import profile_units from tools.knowledge.evidence import STRUCTURAL_KINDS, relation_has_local_support from tools.knowledge import local_graph as local, store diff --git a/test/test_academic.py b/test/knowledge/test_academic.py similarity index 100% rename from test/test_academic.py rename to test/knowledge/test_academic.py diff --git a/test/test_activity_graph.py b/test/knowledge/test_activity_graph.py similarity index 98% rename from test/test_activity_graph.py rename to test/knowledge/test_activity_graph.py index eaea270..cad47b7 100644 --- a/test/test_activity_graph.py +++ b/test/knowledge/test_activity_graph.py @@ -4,8 +4,8 @@ import json import pytest from tools.knowledge import activities as A -from tools.answers import question_catalog as C -from tools.answers.question_plan import build_question_plan, direct_spec +from tools.answers.planning import question_catalog as C +from tools.answers.planning.question_plan import build_question_plan, direct_spec def unit(uid, person, phase, text, *, kind=None, work="Bakalárska práca 2021", work_id=None, date=None): @@ -268,7 +268,7 @@ def test_lemma_keys_and_reranked_record_choice(monkeypatch): def normalized_words(text): import re - from tools.answers.context_policy import normalized + from tools.answers.verification.context_policy import normalized return re.findall(r"[a-z0-9+#]+", normalized(text)) diff --git a/test/test_assertion_extraction.py b/test/knowledge/test_assertion_extraction.py similarity index 100% rename from test/test_assertion_extraction.py rename to test/knowledge/test_assertion_extraction.py diff --git a/test/test_content_publication.py b/test/knowledge/test_content_publication.py similarity index 100% rename from test/test_content_publication.py rename to test/knowledge/test_content_publication.py diff --git a/test/test_discovery_delivery.py b/test/knowledge/test_discovery_delivery.py similarity index 94% rename from test/test_discovery_delivery.py rename to test/knowledge/test_discovery_delivery.py index 351e9ef..8148b15 100644 --- a/test/test_discovery_delivery.py +++ b/test/knowledge/test_discovery_delivery.py @@ -1,8 +1,8 @@ """Whole discovery evidence reaches the same production provenance guard.""" import json import pytest -from tools.answers.question_plan import build_question_plan, QuestionPlan -from tools.answers.delivery_contract import mechanical_check, ContractError +from tools.answers.planning.question_plan import build_question_plan, QuestionPlan +from tools.answers.verification.delivery_contract import mechanical_check, ContractError from tools.knowledge.sources import profile_units from tools.knowledge.query import answer_from_index from tools.knowledge.evidence import PROVENANCE_FIELDS @@ -59,9 +59,9 @@ def test_dated_discovery_projection_preserves_source_identity_for_final_guard(en def test_selection_failure_diagnostics_survive_mcp_without_leaking_internal_fields(): - from tools.answers.delivery_contract import diagnose + from tools.answers.verification.delivery_contract import diagnose from packages.claude.client import validated_delivery_check - from tools.answers.answer_errors import public_failure + from tools.answers.presentation.answer_errors import public_failure for stage in ['planning','evidence_selection']: r=diagnose(public_failure({'reason':'answer_rejected','engine':'rag','_failure_stage':stage}),'Kto pracoval na téme?','rag') check=validated_delivery_check(r,'Kto pracoval na téme?','rag') @@ -112,7 +112,7 @@ def _chatbot_run(summary): def test_readable_discovery_wording_keeps_the_verbatim_answer_for_restoration(): - from tools.answers.delivery_contract import verbatim + from tools.answers.verification.delivery_contract import verbatim plain=_chatbot_run(None) readable=_chatbot_run('Chatbot funguje pre mestskú agendu.') assert 'Chatbot funguje pre mestskú agendu (záznam' in readable['answer'] diff --git a/test/test_discovery_expansion.py b/test/knowledge/test_discovery_expansion.py similarity index 99% rename from test/test_discovery_expansion.py rename to test/knowledge/test_discovery_expansion.py index c555b6c..c280a1a 100644 --- a/test/test_discovery_expansion.py +++ b/test/knowledge/test_discovery_expansion.py @@ -60,7 +60,7 @@ def test_primary_activity_can_include_verified_same_work_expansion(): assert len(selected) == 2 and not notes def test_discovery_seed_query_does_not_include_secondary_requirements(): - from tools.answers.question_intent import discovery_topic + from tools.answers.planning.question_intent import discovery_topic question = 'Kto označoval dáta v roku 2025? Ako ich vyhodnotil a na čo slúžili?' assert discovery_topic(question) == 'Kto označoval dáta v roku 2025' assert discovery_topic('Kto označoval dáta a ako ich vyhodnotil') == 'Kto označoval dáta a ako ich vyhodnotil' @@ -253,7 +253,7 @@ def test_planned_unit_worded_as_achievement_is_dropped(): def test_wording_is_skipped_while_another_answer_uses_the_endpoint(monkeypatch): - from tools.answers import model_client + from tools.answers.generation import model_client monkeypatch.setattr(model_client,'model_busy',lambda:True) _,(selected,_,_,prose),seen=_with_summary([('Ručne označila dáta.','unit')]) assert selected and prose=={} and seen==[] @@ -396,7 +396,7 @@ def test_summary_is_requested_per_call_and_ignored_when_not_requested(): def test_deadline_before_any_decision_falls_back_to_first_selection(): - from tools.answers.model_client import DeadlineExceeded + from tools.answers.generation.model_client import DeadlineExceeded pool,seeds=_students(['Eva Nová','Adam Nový']) def late(_):raise DeadlineExceeded('budget') selected,notes,bounded=expand_and_select(Q,seeds,pool,late) diff --git a/test/test_knowledge.py b/test/knowledge/test_knowledge.py similarity index 100% rename from test/test_knowledge.py rename to test/knowledge/test_knowledge.py diff --git a/test/test_knowledge_live.py b/test/knowledge/test_knowledge_live.py similarity index 97% rename from test/test_knowledge_live.py rename to test/knowledge/test_knowledge_live.py index 6b361c6..5e47722 100644 --- a/test/test_knowledge_live.py +++ b/test/knowledge/test_knowledge_live.py @@ -11,7 +11,7 @@ from pathlib import Path import pytest -ROOT = Path(__file__).resolve().parents[1] +ROOT = Path(__file__).resolve().parents[2] CASES = json.loads((ROOT / "tools/knowledge/questions.json").read_text())["questions"] pytestmark = pytest.mark.skipif( os.getenv("RUN_KNOWLEDGE_LIVE") != "1", reason="Explicit permission and model API required" @@ -46,7 +46,7 @@ def test_real_profile_answer_preserves_evidence(case, engine, monkeypatch): if key in allowed and value is not None: monkeypatch.setenv(key, value) from tools.answers.answer_delivery import deliver_answer - from tools.answers.context_policy import normalized + from tools.answers.verification.context_policy import normalized result = deliver_answer(case["query"], engine=engine, limit=10) assert result["accepted_for_delivery"] and result["status"] != "error", result.get("reason") diff --git a/test/test_claude_packages.py b/test/packages/test_claude_packages.py similarity index 99% rename from test/test_claude_packages.py rename to test/packages/test_claude_packages.py index 5d38f0a..d4e4a97 100644 --- a/test/test_claude_packages.py +++ b/test/packages/test_claude_packages.py @@ -24,7 +24,7 @@ import app.routes as routes from tools.claude.build_claude_packages import build_package from packages.claude import client -ROOT = Path(__file__).resolve().parents[1] +ROOT = Path(__file__).resolve().parents[2] KEY = "a" * 64 @@ -541,7 +541,7 @@ def test_mcp_stdio_initialization_discovery_call_and_rejection(backend): @pytest.mark.parametrize("provider", ["anthropic", "openai_compatible"]) def test_model_adapter_request_and_response_shapes(monkeypatch, provider): - from tools.answers.model_client import complete_with_configured_model + from tools.answers.generation.model_client import complete_with_configured_model calls = [] monkeypatch.setenv("ANSWER_PROVIDER", provider) @@ -576,7 +576,7 @@ def test_model_adapter_request_and_response_shapes(monkeypatch, provider): def test_anthropic_truncated_output_is_rejected(monkeypatch): - from tools.answers.model_client import complete_with_configured_model + from tools.answers.generation.model_client import complete_with_configured_model monkeypatch.setenv("ANSWER_PROVIDER", "anthropic") monkeypatch.setenv("ANSWER_API_KEY", KEY) diff --git a/test/test_conversation_context.py b/test/planning/test_conversation_context.py similarity index 97% rename from test/test_conversation_context.py rename to test/planning/test_conversation_context.py index 620cafe..7b88f67 100644 --- a/test/test_conversation_context.py +++ b/test/planning/test_conversation_context.py @@ -5,8 +5,8 @@ import time import pytest -from tools.answers.conversation import issue_context,resolve_question,seal,unseal,ContextError -from tools.answers.question_plan import build_question_plan,QuestionPlan,MeetingRequest,validate_model_plan,PlanRejected +from tools.answers.planning.conversation import issue_context,resolve_question,seal,unseal,ContextError +from tools.answers.planning.question_plan import build_question_plan,QuestionPlan,MeetingRequest,validate_model_plan,PlanRejected from tools.knowledge.sources import profile_units from tools.knowledge.academic import answer_academic @@ -123,7 +123,7 @@ def test_staff_role_is_preserved_in_a_year_followup(data): def test_final_scope_check_rejects_true_facts_from_wrong_person_or_meeting(data): - from tools.answers.conversation import answer_matches_scope + from tools.answers.planning.conversation import answer_matches_scope old=next(r for r in data['units'] if r.get('record_date')=='2026-10-01' and r['kind']!='meeting') wrong={'status':'ok','accepted_for_delivery':True,'evidence':[old],'claims':[]} q='Na čom pracoval Jakub Schwarc na stretnutí 5.11.2026?' @@ -225,7 +225,7 @@ def test_model_cannot_drop_meeting_or_turn_proposal_into_metadata(data): def test_same_meaning_typo_and_paraphrase_use_same_route(data): - from tools.answers.conversation import normalize_question + from tools.answers.planning.conversation import normalize_question for q in ['na com pracoval Jakub Schwarc','ma com pracoval Jakub Schwarc']: p=build_question_plan(normalize_question(q),CATALOG) assert p.spec.intent=='progress' and p.spec.answer_mode=='description' diff --git a/test/test_person_names.py b/test/planning/test_person_names.py similarity index 99% rename from test/test_person_names.py rename to test/planning/test_person_names.py index 8e142b6..9c73efc 100644 --- a/test/test_person_names.py +++ b/test/planning/test_person_names.py @@ -171,7 +171,7 @@ def test_competing_valid_inflections_require_selection(): def test_rag_evidence_uses_resolved_identity_not_another_name_inflection(): - from tools.answers.rag_evidence import rag_evidence_context + from tools.answers.evidence.rag_evidence import rag_evidence_context from tools.rag.rag_utils import build_context_text catalog = [person("Ján Novák", "jan"), person("Jana Novák", "jana")] @@ -197,7 +197,7 @@ def test_rag_evidence_uses_resolved_identity_not_another_name_inflection(): def test_canonicalized_question_keeps_natural_answer_grammar(): - from tools.answers.presentation import fact_sentences + from tools.answers.presentation.presentation import fact_sentences claim = { "person": "Ján Holp", diff --git a/test/test_question_plan.py b/test/planning/test_question_plan.py similarity index 98% rename from test/test_question_plan.py rename to test/planning/test_question_plan.py index ee178ce..e97aff3 100644 --- a/test/test_question_plan.py +++ b/test/planning/test_question_plan.py @@ -5,7 +5,7 @@ import json import pytest from pydantic import ValidationError -from tools.answers.question_plan import (QuestionPlan,build_question_plan,validate_model_plan,PlanRejected,PlanModelUnavailable) +from tools.answers.planning.question_plan import (QuestionPlan,build_question_plan,validate_model_plan,PlanRejected,PlanModelUnavailable) from tools.knowledge.sources import profile_units from tools.knowledge.planned_answers import answer_facets @@ -136,7 +136,7 @@ def test_planned_facet_output_passes_the_existing_mcp_client_contract(monkeypatc def test_no_unsupported_fields_in_provider_schema_and_full_local_validation(): - from tools.answers.model_client import strict_output_schema + from tools.answers.generation.model_client import strict_output_schema schema=strict_output_schema(QuestionPlan.model_json_schema()) assert schema['additionalProperties'] is False and set(schema['required'])==set(schema['properties']) with pytest.raises(ValidationError):QuestionPlan(question='q',intent='execute_cypher') @@ -167,7 +167,7 @@ def test_explicit_staff_role_does_not_disappear_when_staff_has_a_student_profile @pytest.mark.parametrize('provider,key',[('anthropic','output_config'),('openai_compatible','response_format')]) def test_schema_is_sent_using_provider_specific_transport(monkeypatch,provider,key): - from tools.answers import model_client + from tools.answers.generation import model_client sent=[] class Reply: def __enter__(self):return self diff --git a/test/test_question_understanding.py b/test/planning/test_question_understanding.py similarity index 96% rename from test/test_question_understanding.py rename to test/planning/test_question_understanding.py index 18f3c87..da428dd 100644 --- a/test/test_question_understanding.py +++ b/test/planning/test_question_understanding.py @@ -23,13 +23,13 @@ YEAR = date.today().year @pytest.fixture(scope="module") def catalog(): - from tools.answers.question_plan import planning_catalog + from tools.answers.planning.question_plan import planning_catalog return planning_catalog(DB_FILE) def plan(question, catalog): - from tools.answers.question_plan import build_question_plan + from tools.answers.planning.question_plan import build_question_plan return build_question_plan(question, catalog, complete=None) @@ -226,7 +226,7 @@ def test_every_student_in_every_name_form(catalog): def _pending(question, catalog, monkeypatch): monkeypatch.setenv("SEARCH_API_KEY", "k" * 40) - from tools.answers.conversation import issue_context + from tools.answers.planning.conversation import issue_context version = {"version": "test-version"} result = {"status": "ambiguous", "accepted_for_delivery": True, "index_version": version, @@ -236,7 +236,7 @@ def _pending(question, catalog, monkeypatch): @pytest.mark.parametrize("reply", ["Ján Holp", "jan holp", "toho Holpa", "Myslím Jána Holpa, prosím."]) def test_person_choice_answers_the_previous_question(reply, catalog, monkeypatch): - from tools.answers.conversation import resolve_question + from tools.answers.planning.conversation import resolve_question context, version = _pending("Na čom pracoval Ján?", catalog, monkeypatch) assert {"Ján Holp", "Ján Malinovský", "Ján Pták"} <= set(context["person_options"]) @@ -248,7 +248,7 @@ def test_person_choice_answers_the_previous_question(reply, catalog, monkeypatch def test_new_question_after_a_person_choice_stays_independent(catalog, monkeypatch): - from tools.answers.conversation import resolve_question + from tools.answers.planning.conversation import resolve_question context, version = _pending("Na čom pracoval Ján?", catalog, monkeypatch) question = "Kto pracoval na chatbotovi a čo mu fungovalo?" @@ -258,7 +258,7 @@ def test_new_question_after_a_person_choice_stays_independent(catalog, monkeypat def test_unknown_person_choice_is_not_accepted(catalog, monkeypatch): - from tools.answers.conversation import resolve_question + from tools.answers.planning.conversation import resolve_question context, version = _pending("Na čom pracoval Ján?", catalog, monkeypatch) resolved = resolve_question("Ján Novák", token=context["token"], catalog=catalog, @@ -269,7 +269,7 @@ def test_unknown_person_choice_is_not_accepted(catalog, monkeypatch): # -- an unclassified paraphrase is not an answer rejection ----------------------------- def test_failed_model_plan_asks_a_concrete_question(catalog): - from tools.answers.question_plan import build_question_plan + from tools.answers.planning.question_plan import build_question_plan def broken_model(messages): return {"choices": [{"message": {"content": "not json"}}]} @@ -283,7 +283,7 @@ def test_failed_model_plan_asks_a_concrete_question(catalog): def test_relative_wiki_link_in_a_quote_is_not_an_unsupported_citation(): import re - from tools.answers.context_policy import citation_check + from tools.answers.verification.context_policy import citation_check quote = "- [Question Answering](/topics/question) - interný projekt, https://zp.kemt.fei.tuke.sk/x" shown = re.sub(r"\[([^\]\n]+)\]\((?![a-zA-Z][a-zA-Z0-9+.-]*:|www\.)[^)\s]*\)", r"\1", quote) diff --git a/test/test_question_variants.py b/test/planning/test_question_variants.py similarity index 97% rename from test/test_question_variants.py rename to test/planning/test_question_variants.py index a24febb..df5e5ea 100644 --- a/test/test_question_variants.py +++ b/test/planning/test_question_variants.py @@ -5,8 +5,8 @@ expected values were checked directly in the student profiles. """ import pytest -from tools.answers.question_plan import QuestionPlan, WorkRequest, PersonRequest, direct_spec -from tools.answers import delivery_contract as dc +from tools.answers.planning.question_plan import QuestionPlan, WorkRequest, PersonRequest, direct_spec +from tools.answers.verification import delivery_contract as dc from tools.knowledge import roster from tools.knowledge.academic import completion_rows, with_completion_status from tools.knowledge.query import month_period, intent @@ -182,7 +182,7 @@ def test_graph_search_reads_singular_tema_as_a_title_request(): def test_supervisor_this_year_does_not_become_a_work_year(): - from tools.answers.question_plan import build_question_plan + from tools.answers.planning.question_plan import build_question_plan catalog = [{"kind": "DocumentAuthor", "name": "Daniel Hladek"}] plan = build_question_plan("Ktorých študentov má v tomto roku pod sebou aktuálne Daniel Hladek?", catalog).spec assert plan.intent == "supervisor" and plan.years == [] and all(not w.years for w in plan.works) diff --git a/test/test_audit_question_scopes.py b/test/planning/test_request_scopes.py similarity index 96% rename from test/test_audit_question_scopes.py rename to test/planning/test_request_scopes.py index 30dbf2f..a6df5b8 100644 --- a/test/test_audit_question_scopes.py +++ b/test/planning/test_request_scopes.py @@ -1,7 +1,7 @@ """Regressions for request scope; no live model or expected production answer.""" import pytest -from tools.answers.question_plan import build_question_plan, MeetingRequest -from tools.answers.delivery_contract import mechanical_check, ContractError +from tools.answers.planning.question_plan import build_question_plan, MeetingRequest +from tools.answers.verification.delivery_contract import mechanical_check, ContractError from tools.knowledge.sources import profile_units from tools.knowledge.academic import answer_academic from tools.knowledge.planned_answers import answer_facets diff --git a/test/test_answer_clarity.py b/test/presentation/test_answer_clarity.py similarity index 95% rename from test/test_answer_clarity.py rename to test/presentation/test_answer_clarity.py index 87ed590..df3a6fd 100644 --- a/test/test_answer_clarity.py +++ b/test/presentation/test_answer_clarity.py @@ -7,13 +7,13 @@ import pytest from test_quality_block import corpus, prepare, complete from test_evidence_selection import update_eva, selection -from tools.answers.context_policy import answer_context_issues -from tools.answers.content_selection import facet_lines -from tools.answers.graph_context import graph_context -from tools.answers.presentation import comparison_table -from tools.answers.rag_evidence import rag_evidence_context -from tools.answers.render_answer import render_graph_answer -from tools.answers.verified_rag import generate_verified_rag, rag_answer_issues +from tools.answers.verification.context_policy import answer_context_issues +from tools.answers.evidence.content_selection import facet_lines +from tools.answers.evidence.graph_context import graph_context +from tools.answers.presentation.presentation import comparison_table +from tools.answers.evidence.rag_evidence import rag_evidence_context +from tools.answers.presentation.render_answer import render_graph_answer +from tools.answers.verification.verified_rag import generate_verified_rag, rag_answer_issues def test_missing_aspects_share_one_specific_notice_without_empty_sections(corpus): diff --git a/test/test_answer_explanations.py b/test/presentation/test_answer_explanations.py similarity index 98% rename from test/test_answer_explanations.py rename to test/presentation/test_answer_explanations.py index 757ff78..5495236 100644 --- a/test/test_answer_explanations.py +++ b/test/presentation/test_answer_explanations.py @@ -4,9 +4,9 @@ import json import pytest -from tools.answers import synthesis as s, recommendations as rec -from tools.answers.notices import clean_answer_notices,LIMIT_NOTICE -from tools.answers.question_plan import build_question_plan,QuestionPlan,PersonRequest +from tools.answers.generation import synthesis as s, recommendations as rec +from tools.answers.presentation.notices import clean_answer_notices,LIMIT_NOTICE +from tools.answers.planning.question_plan import build_question_plan,QuestionPlan,PersonRequest from tools.knowledge.sources import profile_units from tools.knowledge.academic import answer_academic diff --git a/test/test_answer_presentation.py b/test/presentation/test_answer_presentation.py similarity index 95% rename from test/test_answer_presentation.py rename to test/presentation/test_answer_presentation.py index b5a957b..ca06e14 100644 --- a/test/test_answer_presentation.py +++ b/test/presentation/test_answer_presentation.py @@ -4,11 +4,11 @@ import copy import pytest -from tools.answers.context_policy import answer_context_issues, prose_issues -from tools.answers.graph_context import graph_context -from tools.answers.presentation import content_lines, fact_sentences, goal_text, owner_in_question -from tools.answers.render_answer import render_graph_answer -from tools.answers.verified_rag import generate_verified_rag +from tools.answers.verification.context_policy import answer_context_issues, prose_issues +from tools.answers.evidence.graph_context import graph_context +from tools.answers.presentation.presentation import content_lines, fact_sentences, goal_text, owner_in_question +from tools.answers.presentation.render_answer import render_graph_answer +from tools.answers.verification.verified_rag import generate_verified_rag from test_graph_work_listing import retrieved, listing_answer from test_rag_work_content import payload, description, completion, ASSIGNMENT, QUESTION, URL diff --git a/test/test_combined_answers.py b/test/presentation/test_combined_answers.py similarity index 96% rename from test/test_combined_answers.py rename to test/presentation/test_combined_answers.py index 2fe4f4f..d310a98 100644 --- a/test/test_combined_answers.py +++ b/test/presentation/test_combined_answers.py @@ -19,12 +19,12 @@ def combo(monkeypatch): state = {"part": None, "match": {"name": "Ján Pták", "student": True}} monkeypatch.setattr("tools.crzp.answering.wiki_bridge.wiki_match", lambda q, db_file=None: state["match"]) monkeypatch.setattr(C, "crzp_part", lambda q, person, complete=None, student=True: state["part"]) - # The composition of these tests, not the records of data/ (tools/answers/unified.py has its own tests). - monkeypatch.setattr("tools.answers.unified.catalog", lambda: {"people": {}, "works": {}}) - monkeypatch.setattr("tools.answers.unified.recency", lambda name: "") - monkeypatch.setattr("tools.answers.unified.registry_rows", lambda person: []) + # The composition of these tests, not the records of data/ (tools/answers/presentation/unified.py has its own tests). + monkeypatch.setattr("tools.answers.presentation.unified.catalog", lambda: {"people": {}, "works": {}}) + monkeypatch.setattr("tools.answers.presentation.unified.recency", lambda name: "") + monkeypatch.setattr("tools.answers.presentation.unified.registry_rows", lambda person: []) monkeypatch.setenv("NAME_FORMS_MODEL", "0") - monkeypatch.setattr("tools.answers.names.spelled", lambda name: name) + monkeypatch.setattr("tools.answers.presentation.names.spelled", lambda name: name) monkeypatch.setattr(C, "_one_person", lambda q: None) state["deliver"] = lambda q, **kw: dict(WIKI) return state @@ -32,7 +32,7 @@ def combo(monkeypatch): def bound(result, question): """Like the real wiki answer: bound to the question it was asked.""" - from tools.answers.delivery_contract import fingerprint + from tools.answers.verification.delivery_contract import fingerprint check = result.get("delivery_check") if isinstance(check, dict) and check.get("request_fingerprint") == "x": result = {**result, "delivery_check": {**check, "request_fingerprint": fingerprint(question, "rag")}} @@ -244,7 +244,7 @@ def test_synonym_groups_match_case_forms_quickly(): def test_a_crzp_follow_up_is_bound_to_the_engine_asked(combo, monkeypatch): from tools.crzp.answering import answer as crzp - from tools.answers.delivery_contract import fingerprint + from tools.answers.verification.delivery_contract import fingerprint combo["match"] = None combo["part"] = {"mode": "explicit", "status": "ambiguous", "text": "Ktorú osobu myslíš?\n\n1. A\n2. B", "rows": [], "urls": [], "crzp_token": "crzp-token"} @@ -313,7 +313,7 @@ def test_paging_and_school_replies_do_not_swallow_new_questions(): def test_finalize_drops_source_labels_supervisor_lines_and_checkboxes(): - from tools.answers.finalize import finalize + from tools.answers.presentation.finalize import finalize out = finalize("**P**\n\n- Téma: Názov bakalárskej práce: Metódy prekladu\n\n" "- Bakalárska práca 2020: Meno vedúceho: Ing. Daniel Hládek, PhD.\n\n" "- Bakalárska práca 2025 (2024-10-30): [x] Natrénujte model.\n\n- Vedúci: Matúš Pleva") diff --git a/test/test_comparison_answers.py b/test/presentation/test_comparison_answers.py similarity index 97% rename from test/test_comparison_answers.py rename to test/presentation/test_comparison_answers.py index fd0f76f..14020ed 100644 --- a/test/test_comparison_answers.py +++ b/test/presentation/test_comparison_answers.py @@ -6,17 +6,17 @@ import sqlite3 import pytest -from tools.answers.context_policy import answer_context_issues, text_contains_value -from tools.answers.graph_context import graph_context -from tools.answers.presentation import content_lines, goal_text -from tools.answers.rag_evidence import ( +from tools.answers.verification.context_policy import answer_context_issues, text_contains_value +from tools.answers.evidence.graph_context import graph_context +from tools.answers.presentation.presentation import content_lines, goal_text +from tools.answers.evidence.rag_evidence import ( content_sections, expand_comparison_sources, rag_evidence_context, requested_types, ) -from tools.answers.verified_rag import generate_verified_rag, rag_answer_issues -from tools.answers.render_answer import render_graph_answer +from tools.answers.verification.verified_rag import generate_verified_rag, rag_answer_issues +from tools.answers.presentation.render_answer import render_graph_answer from tools.graphrag import graph_search as gs from tools.graphrag.tests.test_graph_search import FakeSession from tools.rag.llm_context import compact_rag_payload diff --git a/test/test_content_selection_ids.py b/test/presentation/test_content_selection_ids.py similarity index 94% rename from test/test_content_selection_ids.py rename to test/presentation/test_content_selection_ids.py index 03fb321..3df973f 100644 --- a/test/test_content_selection_ids.py +++ b/test/presentation/test_content_selection_ids.py @@ -8,11 +8,11 @@ import pytest from test_rag_work_content import payload, QUESTION, URL from test_quality_block import corpus, prepare, complete -from tools.answers.evidence_selection import resolve_selection, EvidenceSelectionError -from tools.answers.rag_evidence import rag_evidence_context -from tools.answers.verified_rag import generate_verified_rag, rag_answer_issues -from tools.answers.content_selection import fit_candidates -from tools.answers.question_intent import graph_needs_text +from tools.answers.evidence.evidence_selection import resolve_selection, EvidenceSelectionError +from tools.answers.evidence.rag_evidence import rag_evidence_context +from tools.answers.verification.verified_rag import generate_verified_rag, rag_answer_issues +from tools.answers.evidence.content_selection import fit_candidates +from tools.answers.planning.question_intent import graph_needs_text from tools.answers import answer_delivery from tools.rag.rag_utils import build_context_text @@ -161,7 +161,7 @@ def test_budgeted_out_id_cannot_be_resolved_and_limited_overview_has_a_specific_ assert dropped and c["truncated"] and "answer_candidate_budget" in c["truncation_reasons"] with pytest.raises(EvidenceSelectionError, match="unknown_evidence_id"): resolve_selection({**id_answer(c), "evidence_ids": [dropped[0]["evidence_id"]]}, c) - from tools.answers.answer_coverage import answer_coverage, coverage_notices + from tools.answers.evidence.answer_coverage import answer_coverage, coverage_notices a = resolve_selection(id_answer(c), c) coverage = answer_coverage(a, c) @@ -250,7 +250,7 @@ def test_partial_refusal_gets_corrected_without_inventing_the_missing_persons_ev def test_graph_narrative_request_uses_shared_plan_and_content_evidence(monkeypatch): from contextlib import nullcontext - from tools.answers import question_plan + from tools.answers.planning import question_plan from tools.knowledge import query from tools.knowledge.sources import profile_units from tools.knowledge.planned_answers import answer_facets @@ -283,7 +283,7 @@ def test_graph_narrative_request_uses_shared_plan_and_content_evidence(monkeypat def test_a_status_record_naming_tools_answers_which_technologies_were_used(): - from tools.answers.content_selection import facets_for, named_tools + from tools.answers.evidence.content_selection import facets_for, named_tools q = "Aké technológie použil Ján Pták vo svojej diplomovej práci?" assert "methods" in facets_for("- Sú Skills aj MCP server. RAG vie v ZPwiki vyhľadávať.", "progress", q) assert "methods" in facets_for("- začíname pracovať na GraphRAG a Neo4J", "progress", q) @@ -294,8 +294,8 @@ def test_a_status_record_naming_tools_answers_which_technologies_were_used(): def test_a_meeting_question_is_not_narrowed_to_a_guessed_aspect(): - from tools.answers.question_catalog import Route - from tools.answers.question_plan import direct_spec + from tools.answers.planning.question_catalog import Route + from tools.answers.planning.question_plan import direct_spec from tools.retrieval.person_names import resolve_person_names catalog = [{"name": "Jakub Schwarc", "kind": "Person", "source_document": "pages/students/2022/jakub_schwarc/README.md"}] for question, facets in [("Kedy mal Jakub Schwarc posledné stretnutie a čo na ňom riešil?", ["progress"]), @@ -307,8 +307,8 @@ def test_a_meeting_question_is_not_narrowed_to_a_guessed_aspect(): def test_an_aspect_named_in_the_question_wins_over_the_classifier(): - from tools.answers.question_catalog import Route - from tools.answers.question_plan import direct_spec + from tools.answers.planning.question_catalog import Route + from tools.answers.planning.question_plan import direct_spec from tools.retrieval.person_names import resolve_person_names catalog = [{"name": "Jakub Schwarc", "kind": "Person", "source_document": "pages/students/2022/jakub_schwarc/README.md"}] question = "Aké úlohy dostal Jakub Schwarc?" @@ -317,7 +317,7 @@ def test_an_aspect_named_in_the_question_wins_over_the_classifier(): def test_final_pass_writes_full_sources_and_drops_system_notices(): - from tools.answers.finalize import finalize + from tools.answers.presentation.finalize import finalize text = ("**Ján Pták — Diplomová práca 2027**\n\nNázov / téma zo zdroja: Agent\n\nPoužíva RAG. [1]\n\n" "Vedúci je určený podľa autora profilovej stránky študenta v ZP Wiki.\n\n" "Profil obsahuje aj záznamy bez úplného dátumu; nemožno spoľahlivo určiť, či sú novšie. Rok nedopĺňam z roku práce.\n\n" @@ -330,7 +330,7 @@ def test_final_pass_writes_full_sources_and_drops_system_notices(): def test_final_pass_simplifies_technical_bullets_and_collapses_assignment_only_students(): - from tools.answers.finalize import finalize + from tools.answers.presentation.finalize import finalize text = ("**Samuel Džurina**\n\n- Bakalárska práca 2026; priebežný stav; záznam 2025-05-13: Chatbot funguje.\n\n" "**Martin Jancura**\n\nMartin Jancura — téma je v zadaní, téme alebo pláne práce; zaznamenaný výsledok k nej sa nenašiel.\n\n" "- Diplomový projekt; podklad: ## Diplomový projekt 2\n\n" @@ -345,12 +345,12 @@ def test_final_pass_simplifies_technical_bullets_and_collapses_assignment_only_s def test_related_topics_find_inflected_phrases_and_synonyms(): from tools.retrieval.synonyms import base_name, variants_pattern - from tools.answers.context_policy import normalized + from tools.answers.verification.context_policy import normalized assert base_name("rozpoznávaním reči") == base_name("speech recognition") == "rozpoznávanie reči" assert variants_pattern("speech recognition").search(normalized("Funguje automatické rozpoznávanie reči.")) assert base_name("Python") == "Python" def test_vyuziva_asks_for_methods_like_pouziva(): - from tools.answers.question_intent import requested_facets + from tools.answers.planning.question_intent import requested_facets assert requested_facets("Aké technológie využíva Ján Pták vo svojej diplomovej práci?") == ["methods"] diff --git a/test/test_evidence_selection.py b/test/presentation/test_evidence_selection.py similarity index 97% rename from test/test_evidence_selection.py rename to test/presentation/test_evidence_selection.py index 905109c..63015ac 100644 --- a/test/test_evidence_selection.py +++ b/test/presentation/test_evidence_selection.py @@ -6,11 +6,11 @@ import sqlite3 import pytest from test_quality_block import corpus, prepare, complete -from tools.answers.content_selection import administrative_only, evidence_units -from tools.answers.rag_evidence import rag_evidence_context, content_sections -from tools.answers.rag_preparation import prepare_named_content -from tools.answers.verified_rag import generate_verified_rag, rag_answer_issues -from tools.answers.verified_rag import overview_excerpts +from tools.answers.evidence.content_selection import administrative_only, evidence_units +from tools.answers.evidence.rag_evidence import rag_evidence_context, content_sections +from tools.answers.evidence.rag_preparation import prepare_named_content +from tools.answers.verification.verified_rag import generate_verified_rag, rag_answer_issues +from tools.answers.verification.verified_rag import overview_excerpts from tools.rag.llm_context import compact_rag_payload from tools.rag.rag_utils import build_context_text diff --git a/test/test_synthesis.py b/test/presentation/test_synthesis.py similarity index 98% rename from test/test_synthesis.py rename to test/presentation/test_synthesis.py index ea088a8..d279b76 100644 --- a/test/test_synthesis.py +++ b/test/presentation/test_synthesis.py @@ -4,8 +4,8 @@ import json import pytest -from tools.answers import synthesis as s -from tools.answers.question_plan import QuestionPlan +from tools.answers.generation import synthesis as s +from tools.answers.planning.question_plan import QuestionPlan from tools.knowledge.sources import profile_units @@ -277,8 +277,9 @@ def test_coverage_repair_has_one_attempt_and_all_guards_still_apply(): def test_common_delivery_uses_prose_but_never_treats_document_titles_as_people(monkeypatch): from contextlib import nullcontext - from tools.answers import answer_delivery,question_plan - from tools.answers.question_plan import PlannedQuestion + from tools.answers import answer_delivery + from tools.answers.planning import question_plan + from tools.answers.planning.question_plan import PlannedQuestion from tools.knowledge import query result,plan=fixture('assignment','Implementujte systém na získavanie informácií.') from tools.knowledge import store diff --git a/test/test_unified_answers.py b/test/presentation/test_unified_answers.py similarity index 96% rename from test/test_unified_answers.py rename to test/presentation/test_unified_answers.py index 9acbcbe..2a42278 100644 --- a/test/test_unified_answers.py +++ b/test/presentation/test_unified_answers.py @@ -1,8 +1,8 @@ """One answer from both sources: direct first sentence, no source labels, one work once, newest first.""" import pytest -from tools.answers import unified as U -from tools.answers.context_policy import normalized +from tools.answers.presentation import unified as U +from tools.answers.verification.context_policy import normalized PROFILE = "https://zp.test/students/2023/ronald_zalacko" UNITS = [ @@ -35,7 +35,7 @@ def data(monkeypatch): monkeypatch.setattr(U, "catalog", lambda: {"people": people, "works": works}) monkeypatch.setattr(U, "registry_rows", lambda person: []) # not the local register cache monkeypatch.setenv("NAME_FORMS_MODEL", "0") # the rules, no model call - monkeypatch.setattr("tools.answers.names.spelled", lambda name: name) + monkeypatch.setattr("tools.answers.presentation.names.spelled", lambda name: name) monkeypatch.setattr(U, "units", lambda person: [u for u in UNITS if u["person"] == person]) monkeypatch.setattr("tools.knowledge.sources.profile_authors", lambda: {}) monkeypatch.setattr("tools.answers.combined.same_person_work", lambda person, row: False) @@ -110,7 +110,7 @@ def test_the_conversation_token_is_compressed_and_still_read(monkeypatch): def test_name_forms_from_the_model_are_checked_and_kept(monkeypatch, tmp_path): - from tools.answers import names + from tools.answers.presentation import names monkeypatch.setenv("NAME_FORMS_MODEL", "1") monkeypatch.setattr(names, "_file", lambda: tmp_path / "name_forms.json") monkeypatch.setattr(names, "_cache", {}) @@ -119,7 +119,7 @@ def test_name_forms_from_the_model_are_checked_and_kept(monkeypatch, tmp_path): bad = good.model_copy(update={"genitive": "pána Ronalda Zalačka"}) # an extra word assert names.valid("Ronald Zalačko", good) and not names.valid("Ronald Zalačko", bad) calls = [] - monkeypatch.setattr("tools.answers.synthesis._call", lambda *a, **k: calls.append(1) or good) + monkeypatch.setattr("tools.answers.generation.synthesis._call", lambda *a, **k: calls.append(1) or good) monkeypatch.setattr(names, "spelled", lambda name: name) assert names.case("Ronald Zalačko", "genitive") == "Ronalda Zalačka" assert names.case("Ronald Zalačko", "instrumental") == "Ronaldom Zalačkom" and len(calls) == 1 # asked once @@ -127,14 +127,14 @@ def test_name_forms_from_the_model_are_checked_and_kept(monkeypatch, tmp_path): def test_a_name_without_diacritics_takes_the_register_spelling(monkeypatch): - from tools.answers import names + from tools.answers.presentation import names monkeypatch.setattr(names, "_spellings", lambda: {"ronald zalacko": "Ronald Zalačko", "daniel hladek": "Daniel Hládek"}) assert names.spelled("Ronald Zalacko") == "Ronald Zalačko" and names.spelled("Daniel Hladek") == "Daniel Hládek" assert names.spelled("Ján Pták") == "Ján Pták" and names.spelled("Valerii Kutsenko") == "Valerii Kutsenko" def test_a_respelled_or_undeclined_name_is_rejected(): - from tools.answers import names + from tools.answers.presentation import names base = dict(gender="male", dative="Jakubovi Schwarcovi", accusative="Jakuba Schwarca", locative="Jakubovi Schwarcovi") assert names.valid("Jakub Schwarc", names.NameForms(genitive="Jakuba Schwarca", instrumental="Jakubom Schwarcom", **base)) assert not names.valid("Jakub Schwarc", names.NameForms(genitive="Jakuba Schwarca", instrumental="Jakubom Schwarzom", **base)) diff --git a/test/test_embedding_budget.py b/test/retrieval/test_embedding_budget.py similarity index 100% rename from test/test_embedding_budget.py rename to test/retrieval/test_embedding_budget.py diff --git a/test/test_llm_context_budget.py b/test/retrieval/test_llm_context_budget.py similarity index 100% rename from test/test_llm_context_budget.py rename to test/retrieval/test_llm_context_budget.py diff --git a/test/test_rag_answer_coverage.py b/test/retrieval/test_rag_answer_coverage.py similarity index 96% rename from test/test_rag_answer_coverage.py rename to test/retrieval/test_rag_answer_coverage.py index bc0df0c..934137b 100644 --- a/test/test_rag_answer_coverage.py +++ b/test/retrieval/test_rag_answer_coverage.py @@ -5,9 +5,9 @@ import json import pytest -from tools.answers.answer_coverage import answer_coverage -from tools.answers.rag_evidence import rag_evidence_context -from tools.answers.verified_rag import generate_verified_rag, rag_answer_issues, render_rag_answer +from tools.answers.evidence.answer_coverage import answer_coverage +from tools.answers.evidence.rag_evidence import rag_evidence_context +from tools.answers.verification.verified_rag import generate_verified_rag, rag_answer_issues, render_rag_answer from tools.rag.rag_utils import build_context_text URL = "https://example.test/eva" @@ -251,7 +251,7 @@ def test_short_comparison_can_cover_three_people_instead_of_dropping_one(payload def test_overview_renderer_only_selects_literal_units_and_preserves_full_evidence(payload): - from tools.answers.verified_rag import overview_excerpts + from tools.answers.verification.verified_rag import overview_excerpts extra = "Stav:\n\n- Implementované indexovanie dokumentov." payload["sources"][0]["text"] += "\n" + extra @@ -270,7 +270,7 @@ def test_overview_renderer_only_selects_literal_units_and_preserves_full_evidenc def test_long_prose_excerpt_is_selected_without_inventing_a_summary(payload): - from tools.answers.verified_rag import overview_excerpts + from tools.answers.verification.verified_rag import overview_excerpts prose = "Práca skúma vyhľadávanie v slovenských dokumentoch. " * 18 payload["sources"][0]["text"] = ( diff --git a/test/test_rag_delivery.py b/test/retrieval/test_rag_delivery.py similarity index 100% rename from test/test_rag_delivery.py rename to test/retrieval/test_rag_delivery.py diff --git a/test/test_rag_work_content.py b/test/retrieval/test_rag_work_content.py similarity index 98% rename from test/test_rag_work_content.py rename to test/retrieval/test_rag_work_content.py index b0eccae..9ea61c9 100644 --- a/test/test_rag_work_content.py +++ b/test/retrieval/test_rag_work_content.py @@ -5,8 +5,8 @@ import json import pytest -from tools.answers.rag_evidence import rag_evidence_context -from tools.answers.verified_rag import generate_verified_rag, rag_answer_issues +from tools.answers.evidence.rag_evidence import rag_evidence_context +from tools.answers.verification.verified_rag import generate_verified_rag, rag_answer_issues from tools.rag.llm_context import compact_rag_payload from tools.rag.rag_utils import build_context_text diff --git a/test/test_retrieval_contract.py b/test/retrieval/test_retrieval_contract.py similarity index 100% rename from test/test_retrieval_contract.py rename to test/retrieval/test_retrieval_contract.py diff --git a/test/test_verified_rag.py b/test/retrieval/test_verified_rag.py similarity index 98% rename from test/test_verified_rag.py rename to test/retrieval/test_verified_rag.py index 4d27906..d885992 100644 --- a/test/test_verified_rag.py +++ b/test/retrieval/test_verified_rag.py @@ -6,8 +6,8 @@ from fastapi.testclient import TestClient import app.main as main import app.routes as routes -from tools.answers.rag_evidence import rag_evidence_context, rag_prose_issues -from tools.answers.verified_rag import generate_verified_rag, rag_answer_issues +from tools.answers.evidence.rag_evidence import rag_evidence_context, rag_prose_issues +from tools.answers.verification.verified_rag import generate_verified_rag, rag_answer_issues from tools.rag.rag_utils import build_context_text QUESTION = ( @@ -289,7 +289,7 @@ def test_graph_production_delivery_checks_renders_and_propagates_metadata(monkey "sources": [{"source_url": "https://example.test/eva"}], } from contextlib import nullcontext - from tools.answers import question_plan + from tools.answers.planning import question_plan monkeypatch.setattr(question_plan,'planning_catalog',lambda db:[{'name':'Eva Nová','kind':'Person','source_document':'pages/students/2022/eva/README.md'}]) monkeypatch.setattr(delivery,'index_snapshot',lambda *a,**kw:nullcontext()) monkeypatch.setattr(delivery, "search_graph", lambda query, **kwargs: {}) diff --git a/test/test_verified_rag_extended.py b/test/retrieval/test_verified_rag_extended.py similarity index 96% rename from test/test_verified_rag_extended.py rename to test/retrieval/test_verified_rag_extended.py index 0c1b5a6..1b89a49 100644 --- a/test/test_verified_rag_extended.py +++ b/test/retrieval/test_verified_rag_extended.py @@ -3,8 +3,8 @@ import json import pytest from tools.evaluation.evaluate_verified_rag import binding_matches, evaluate_case -from tools.answers.rag_evidence import rag_evidence_context -from tools.answers.verified_rag import rag_answer_issues, generate_verified_rag +from tools.answers.evidence.rag_evidence import rag_evidence_context +from tools.answers.verification.verified_rag import rag_answer_issues, generate_verified_rag from tools.rag.rag_utils import build_context_text @@ -207,7 +207,7 @@ def test_evaluator_rejects_cross_person_join_wrong_tuple_and_false_refusal(): def test_evaluator_accepts_extra_supported_project_but_rejects_wrong_rendered_year(): - from tools.answers.verified_rag import render_rag_answer + from tools.answers.verification.verified_rag import render_rag_answer p = payload( "Sekcia: Diplomová práca 2025\nNázov: Overené modelovanie textu\n" @@ -261,8 +261,8 @@ def test_evaluator_accepts_extra_supported_project_but_rejects_wrong_rendered_ye ], ) def test_literal_source_references_are_allowed_without_replacing_wiki_citation(reference): - from tools.answers.verified_rag import quoted_reference_urls, render_rag_answer - from tools.answers.context_policy import citation_check, allowed_urls + from tools.answers.verification.verified_rag import quoted_reference_urls, render_rag_answer + from tools.answers.verification.context_policy import citation_check, allowed_urls quote = "Dokumentácia: " + reference if not reference.startswith("[guide]") else reference if reference.startswith(("/", ".", "#")): @@ -350,7 +350,7 @@ def test_general_question_repairs_unrequested_claims_and_sends_only_quote_eviden def test_evaluator_accepts_exact_quoted_reference_but_rejects_invented_rendered_link(): - from tools.answers.verified_rag import render_rag_answer + from tools.answers.verification.verified_rag import render_rag_answer p = payload("Knižnica Library: https://library.example/docs") question = "Aká knižnica je uvedená?" diff --git a/test/test_work_scope_selection.py b/test/retrieval/test_work_scope_selection.py similarity index 96% rename from test/test_work_scope_selection.py rename to test/retrieval/test_work_scope_selection.py index 4d0cd2a..ab93355 100644 --- a/test/test_work_scope_selection.py +++ b/test/retrieval/test_work_scope_selection.py @@ -5,10 +5,10 @@ import sqlite3 import pytest -from tools.answers.rag_preparation import prepare_named_content -from tools.answers.rag_evidence import rag_evidence_context, project_number, content_sections -from tools.answers.verified_rag import generate_verified_rag -from tools.answers.content_selection import facets_for +from tools.answers.evidence.rag_preparation import prepare_named_content +from tools.answers.evidence.rag_evidence import rag_evidence_context, project_number, content_sections +from tools.answers.verification.verified_rag import generate_verified_rag +from tools.answers.evidence.content_selection import facets_for from tools.retrieval.work_selector import parse_work_selector from tools.retrieval.question_constraints import requested_years, unsupported_constraint from tools.answers import answer_delivery diff --git a/test/test_git_runner.py b/test/sync/test_git_runner.py similarity index 99% rename from test/test_git_runner.py rename to test/sync/test_git_runner.py index 7aefcd1..e14b92d 100644 --- a/test/test_git_runner.py +++ b/test/sync/test_git_runner.py @@ -10,7 +10,7 @@ import subprocess import pytest import yaml -ROOT = Path(__file__).resolve().parents[1] +ROOT = Path(__file__).resolve().parents[2] RUNNER = ROOT / "tools/git_runner" LAUNCHER = ROOT / "scripts/runner.sh" FORK = "git@git.kemt.fei.tuke.sk:jp170na/zpwiki.git" diff --git a/test/test_index_sync.py b/test/sync/test_index_sync.py similarity index 100% rename from test/test_index_sync.py rename to test/sync/test_index_sync.py diff --git a/test/test_project_layout.py b/test/sync/test_project_layout.py similarity index 98% rename from test/test_project_layout.py rename to test/sync/test_project_layout.py index b33353c..09963fc 100644 --- a/test/test_project_layout.py +++ b/test/sync/test_project_layout.py @@ -115,6 +115,6 @@ def test_freeze_separates_runtime_and_evaluation_code(tmp_path): questions.write_text('{"questions": []}\n') fingerprints = content_fingerprints(questions) assert "tools/knowledge/query.py" in fingerprints["implementation"] - assert "tools/answers/context_policy.py" in fingerprints["implementation"] + assert "tools/answers/verification/context_policy.py" in fingerprints["implementation"] assert "tools/evaluation/archive.py" in fingerprints["evaluation"] assert not any("/tests/" in p or "/evaluation/" in p for p in fingerprints["implementation"]) diff --git a/test/test_publication_health.py b/test/sync/test_publication_health.py similarity index 99% rename from test/test_publication_health.py rename to test/sync/test_publication_health.py index f85bf9b..453c029 100644 --- a/test/test_publication_health.py +++ b/test/sync/test_publication_health.py @@ -224,7 +224,7 @@ def test_connection_readiness_is_distinct_from_graph_readiness(monkeypatch, actu def test_model_probe_requires_authentication_and_returns_sanitized_status(corpus, monkeypatch): - import tools.answers.model_client as model + import tools.answers.generation.model_client as model seen = [] monkeypatch.setattr(model, "probe_generation", lambda: seen.append(1) or {"ready": True, "status": "ready", "reason": None}) diff --git a/test/test_report_files.py b/test/sync/test_report_files.py similarity index 100% rename from test/test_report_files.py rename to test/sync/test_report_files.py diff --git a/test/test_runtime_assets.py b/test/sync/test_runtime_assets.py similarity index 100% rename from test/test_runtime_assets.py rename to test/sync/test_runtime_assets.py diff --git a/test/test_sync_jobs.py b/test/sync/test_sync_jobs.py similarity index 100% rename from test/test_sync_jobs.py rename to test/sync/test_sync_jobs.py diff --git a/test/test_wiki_git.py b/test/sync/test_wiki_git.py similarity index 100% rename from test/test_wiki_git.py rename to test/sync/test_wiki_git.py diff --git a/test/test_answer_failures_limits.py b/test/verification/test_answer_failures_limits.py similarity index 98% rename from test/test_answer_failures_limits.py rename to test/verification/test_answer_failures_limits.py index 7b43f62..3ec6890 100644 --- a/test/test_answer_failures_limits.py +++ b/test/verification/test_answer_failures_limits.py @@ -10,7 +10,7 @@ import app.main as main import app.routes as routes from packages.claude import client from tools.answers import answer_delivery as delivery -from tools.answers.answer_errors import MESSAGES +from tools.answers.presentation.answer_errors import MESSAGES from tools.graphrag import graph_search as gs from tools.graphrag.tests.test_graph_search import FakeSession from test_claude_packages import backend, KEY @@ -21,7 +21,7 @@ URL = "https://example.test/eva" @pytest.fixture(autouse=True) def isolated_planning_catalog(monkeypatch): - from tools.answers import question_plan + from tools.answers.planning import question_plan from tools.knowledge import store from tools.sync import index_state monkeypatch.setattr(store,'load_index',lambda *a,**kw:None) diff --git a/test/test_bod3_closure.py b/test/verification/test_answer_guards.py similarity index 96% rename from test/test_bod3_closure.py rename to test/verification/test_answer_guards.py index 25aabe4..ed4667d 100644 --- a/test/test_bod3_closure.py +++ b/test/verification/test_answer_guards.py @@ -3,15 +3,15 @@ import json import pytest -from tools.answers.context_policy import ( +from tools.answers.verification.context_policy import ( answer_context_issues, citation_check, coverage_issues, prose_issues, text_contains_value, ) -from tools.answers.checked_generation import generate_checked_answer -from tools.answers.render_answer import render_graph_answer +from tools.answers.generation.checked_generation import generate_checked_answer +from tools.answers.presentation.render_answer import render_graph_answer from tools.graphrag.graph_search import extract_query_constraints from tools.graphrag.graphrag import extract_start_year diff --git a/test/test_answer_repair_regressions.py b/test/verification/test_answer_repair_regressions.py similarity index 96% rename from test/test_answer_repair_regressions.py rename to test/verification/test_answer_repair_regressions.py index 56adadb..3e421e4 100644 --- a/test/test_answer_repair_regressions.py +++ b/test/verification/test_answer_repair_regressions.py @@ -5,7 +5,7 @@ from types import SimpleNamespace import numpy as np import pytest -from tools.answers.question_plan import build_question_plan,QuestionPlan,PersonRequest +from tools.answers.planning.question_plan import build_question_plan,QuestionPlan,PersonRequest from tools.retrieval.person_names import resolve_person_names from tools.knowledge.text_retrieval import retrieve_units @@ -92,7 +92,7 @@ def metadata_payload(presentation='list',fields=None): def test_exact_metadata_keeps_distinct_untitled_records_without_a_model(): - from tools.answers.verified_rag import generate_verified_rag + from tools.answers.verification.verified_rag import generate_verified_rag result=generate_verified_rag('Zostav prehľad prác Adriána Ondru.',metadata_payload(),lambda _:pytest.fail('No model for exact complete records')) assert result['status']=='ok' and len(result['claims'])==2 assert len({r['record_id'] for r in result['claims']})==2 @@ -100,7 +100,7 @@ def test_exact_metadata_keeps_distinct_untitled_records_without_a_model(): def test_exact_count_counts_records_not_source_windows_or_people(): - from tools.answers.verified_rag import generate_verified_rag + from tools.answers.verification.verified_rag import generate_verified_rag payload=metadata_payload('count',[]) result=generate_verified_rag('Zostav prehľad prác Adriána Ondru.',payload,lambda _:pytest.fail('No model for exact count')) assert result['count']==2 and 'prác a projektov' in result['answer'] @@ -109,7 +109,7 @@ def test_exact_count_counts_records_not_source_windows_or_people(): @pytest.mark.parametrize('presentation',['list','count']) def test_exact_metadata_is_accepted_by_the_actual_claude_client(monkeypatch,presentation): from packages.claude import client - from tools.answers.verified_rag import generate_verified_rag + from tools.answers.verification.verified_rag import generate_verified_rag question='Zostav prehľad prác Adriána Ondru.' result=generate_verified_rag(question,metadata_payload(presentation),lambda _:pytest.fail('No model')) monkeypatch.setattr(client,'request_json',lambda *a,**kw:{**result,'query':question,'engine':'rag'}) @@ -119,8 +119,8 @@ def test_exact_metadata_is_accepted_by_the_actual_claude_client(monkeypatch,pres def test_complete_scope_flag_cannot_override_context_clipping(): - from tools.answers.rag_metadata import exact_metadata_answer - from tools.answers.rag_evidence import rag_evidence_context + from tools.answers.evidence.rag_metadata import exact_metadata_answer + from tools.answers.evidence.rag_evidence import rag_evidence_context payload=metadata_payload();payload['truncation_reasons']=['llm_context_budget'] assert exact_metadata_answer(payload,rag_evidence_context('Zostav prehľad prác Adriána Ondru.',payload)) is None @@ -172,7 +172,7 @@ def test_graph_work_count_is_not_the_number_of_authors(): def test_declarative_stack_is_a_method_description_without_promoting_its_phase(): - from tools.answers.content_selection import facets_for + from tools.answers.evidence.content_selection import facets_for q='Aké technológie má študent na frontende, backende a čo je doložené o funkčnosti?' assert 'methods' in facets_for('Frontend React, backend Flask, DB Postgres.','other',q,'unknown') assert 'methods' not in facets_for('Frontend bude React, backend bude Flask.','task',q,'planned') diff --git a/test/test_context_policy.py b/test/verification/test_context_policy.py similarity index 98% rename from test/test_context_policy.py rename to test/verification/test_context_policy.py index 5139f4e..8440e75 100644 --- a/test/test_context_policy.py +++ b/test/verification/test_context_policy.py @@ -3,8 +3,8 @@ import json import pytest -from tools.answers.context_policy import citation_check, answer_context_issues, joined_candidates -from tools.answers.checked_generation import generate_checked_answer +from tools.answers.verification.context_policy import citation_check, answer_context_issues, joined_candidates +from tools.answers.generation.checked_generation import generate_checked_answer from tools.evaluation.evaluate_graph_answers import graph_context, grade_answer diff --git a/test/test_delivery_bindings.py b/test/verification/test_delivery_bindings.py similarity index 93% rename from test/test_delivery_bindings.py rename to test/verification/test_delivery_bindings.py index 3ca4d17..27057da 100644 --- a/test/test_delivery_bindings.py +++ b/test/verification/test_delivery_bindings.py @@ -1,10 +1,10 @@ """Source identity survives presentation field selection in both retrievers.""" import copy import pytest -from tools.answers import delivery_contract as contract -from tools.answers.graph_context import delivery_facts -from tools.answers.question_plan import QuestionPlan, PersonRequest, WorkRequest -from tools.answers.verified_rag import generate_verified_rag +from tools.answers.verification import delivery_contract as contract +from tools.answers.evidence.graph_context import delivery_facts +from tools.answers.planning.question_plan import QuestionPlan, PersonRequest, WorkRequest +from tools.answers.verification.verified_rag import generate_verified_rag URL='https://example.test/eva' diff --git a/test/test_delivery_contract.py b/test/verification/test_delivery_contract.py similarity index 97% rename from test/test_delivery_contract.py rename to test/verification/test_delivery_contract.py index 0fdbcd6..4751b26 100644 --- a/test/test_delivery_contract.py +++ b/test/verification/test_delivery_contract.py @@ -2,8 +2,8 @@ import copy import json import pytest -from tools.answers import delivery_contract as c -from tools.answers.question_plan import QuestionPlan,PersonRequest,WorkRequest,Period,MeetingRequest +from tools.answers.verification import delivery_contract as c +from tools.answers.planning.question_plan import QuestionPlan,PersonRequest,WorkRequest,Period,MeetingRequest from tools.knowledge.sources import profile_units @@ -151,7 +151,7 @@ def test_all_requirements_unfulfilled_is_still_rejected(): def test_spent_budget_delivers_checked_facts_with_an_explicit_unverified_notice(): - from tools.answers import model_client as mc + from tools.answers.generation import model_client as mc plan,result,index=fixture();called=[] token=mc.start_deadline(3) try: @@ -212,7 +212,7 @@ def test_rejected_wording_falls_back_to_verbatim_lines_with_their_own_audit(): def test_unaudited_wording_is_never_delivered(): - from tools.answers import model_client as mc + from tools.answers.generation import model_client as mc plan,result,index,swaps,readable,plain=_prose_fixture() token=mc.start_deadline(3) try: @@ -230,7 +230,7 @@ def test_wording_fallback_never_rescues_a_different_request(): def test_audit_evidence_is_grouped_without_losing_attribution(): - from tools.answers.delivery_contract import audit_evidence + from tools.answers.verification.delivery_contract import audit_evidence rows={ 'a':{'id':'a','person':'Eva Nová','work_id':'w1','work_label':'Diplomová práca 2027','work_type':'diplomova', 'work_year':2027,'meeting_id':'m-long-internal-id','phase':'result','text':'Hotový model.', @@ -250,7 +250,7 @@ def test_audit_evidence_is_grouped_without_losing_attribution(): def test_verbatim_quoted_unit_is_sent_once_as_a_reference(): - from tools.answers.delivery_contract import audit_evidence + from tools.answers.verification.delivery_contract import audit_evidence text='- Dotrénované 4 modely, slovakt5-base, slavict5-base, mt5-base, umt5-base.' rows={'a':{'id':'a','person':'Eva Nová','phase':'result','text':text}, 'b':{'id':'b','person':'Eva Nová','phase':'result','text':'- Model s augmentovanými dátami je o dosť lepší než pôvodný.'}} @@ -263,7 +263,7 @@ def test_verbatim_quoted_unit_is_sent_once_as_a_reference(): def test_discovery_audit_receives_the_executed_decomposition(): - from tools.answers import delivery_contract as dc + from tools.answers.verification import delivery_contract as dc plan,result,index=fixture() plan=plan.model_copy(update={'intent':'discovery','question':'Ktorí študenti robili s LLM a čo im fungovalo?'}) seen=[] diff --git a/test/test_quality_block.py b/test/verification/test_quality_block.py similarity index 97% rename from test/test_quality_block.py rename to test/verification/test_quality_block.py index b158f3d..74f5a7f 100644 --- a/test/test_quality_block.py +++ b/test/verification/test_quality_block.py @@ -6,11 +6,11 @@ import sqlite3 import pytest -from tools.answers.content_selection import candidates, facets_for -from tools.answers.rag_evidence import rag_evidence_context -from tools.answers.rag_preparation import prepare_named_content -from tools.answers.verified_rag import generate_verified_rag, rag_answer_issues -from tools.answers.answer_errors import public_failure +from tools.answers.evidence.content_selection import candidates, facets_for +from tools.answers.evidence.rag_evidence import rag_evidence_context +from tools.answers.evidence.rag_preparation import prepare_named_content +from tools.answers.verification.verified_rag import generate_verified_rag, rag_answer_issues +from tools.answers.presentation.answer_errors import public_failure from tools.graphrag import graph_search as gs from tools.graphrag.tests.test_graph_search import FakeSession from tools.rag.llm_context import compact_rag_payload @@ -416,7 +416,7 @@ def test_retrieval_failure_is_not_misreported_as_bad_model_answer(monkeypatch): raise RuntimeError("SECRET backend address") from contextlib import nullcontext - from tools.answers import question_plan + from tools.answers.planning import question_plan monkeypatch.setattr(question_plan,'planning_catalog',lambda db:[{'kind':'Person','name':'Eva Nová','source_document':'eva.md'}]) monkeypatch.setattr(delivery,'index_snapshot',lambda *a,**kw:nullcontext()) monkeypatch.setattr(delivery, "search_graph", unavailable) diff --git a/test/test_source_audit.py b/test/verification/test_source_audit.py similarity index 98% rename from test/test_source_audit.py rename to test/verification/test_source_audit.py index b92ea02..c35445c 100644 --- a/test/test_source_audit.py +++ b/test/verification/test_source_audit.py @@ -6,8 +6,8 @@ import urllib.error import pytest -from tools.answers import reference_links as links -from tools.answers.content_selection import reference_only, evidence_phase, facets_for +from tools.answers.verification import reference_links as links +from tools.answers.evidence.content_selection import reference_only, evidence_phase, facets_for from tools.knowledge.sources import profile_units from tools.knowledge.query import answer_from_index from tools.retrieval.person_names import resolve_person_names diff --git a/tools/answers/answer_delivery.py b/tools/answers/answer_delivery.py index d336164..876c828 100644 --- a/tools/answers/answer_delivery.py +++ b/tools/answers/answer_delivery.py @@ -9,14 +9,14 @@ from tools.rag.common import DB_FILE from tools.rag.rag_utils import build_rag_context from tools.rag.llm_context import compact_rag_payload from tools.graphrag.graph_search import search_graph -from tools.answers.graph_context import graph_context, delivery_facts -from tools.answers.checked_generation import generate_checked_answer -from tools.answers.verified_rag import generate_verified_rag -from tools.answers.rag_evidence import expand_comparison_sources -from tools.answers.rag_preparation import prepare_named_content +from tools.answers.evidence.graph_context import graph_context, delivery_facts +from tools.answers.generation.checked_generation import generate_checked_answer +from tools.answers.verification.verified_rag import generate_verified_rag +from tools.answers.evidence.rag_evidence import expand_comparison_sources +from tools.answers.evidence.rag_preparation import prepare_named_content from tools.sync.index_state import index_snapshot -from tools.answers.model_client import complete_with_configured_model -from tools.answers.answer_errors import public_failure, clarification_result +from tools.answers.generation.model_client import complete_with_configured_model +from tools.answers.presentation.answer_errors import public_failure, clarification_result import os import time @@ -101,7 +101,7 @@ def deliver_answer( context_token: str | None = None, ) -> dict: """Checked answer within one time budget; identical repeats reuse it.""" - from tools.answers.model_client import start_deadline, reset_deadline, answer_budget_seconds + from tools.answers.generation.model_client import start_deadline, reset_deadline, answer_budget_seconds import copy key = None if complete is not None or include_diagnostics else _cache_key( @@ -150,12 +150,12 @@ def _deliver_checked( include_diagnostics: bool = False, context_token: str | None = None, ) -> dict: - from tools.answers.reference_links import checked_repository_links - from tools.answers.conversation import resolve_question, issue_context, ContextError - from tools.answers.question_plan import planning_catalog,QuestionPlan + from tools.answers.verification.reference_links import checked_repository_links + from tools.answers.planning.conversation import resolve_question, issue_context, ContextError + from tools.answers.planning.question_plan import planning_catalog,QuestionPlan from tools.knowledge.store import load_index from tools.sync.index_state import read_version - from tools.answers.delivery_contract import diagnose + from tools.answers.verification.delivery_contract import diagnose catalog=[];index=None;version=None try: @@ -187,17 +187,17 @@ def _deliver_checked( facts=result.pop('_delivery_facts',[]) prose_swaps=result.pop('_prose_swaps',[]) result=checked_repository_links(result) - from tools.answers.notices import clean_answer_notices + from tools.answers.presentation.notices import clean_answer_notices result=clean_answer_notices(result) if plan_data: - from tools.answers.delivery_contract import enforce + from tools.answers.verification.delivery_contract import enforce result=enforce(question,engine,QuestionPlan.model_validate(plan_data),result,index=index,facts=facts, complete=complete,prose_swaps=prose_swaps) else: - from tools.answers.delivery_contract import verbatim + from tools.answers.verification.delivery_contract import verbatim result=diagnose(verbatim(result,prose_swaps) if prose_swaps else result,question,engine) if resolved.query!=question.strip():result['resolved_query']=resolved.query - if plan_data: # what the question asks, for the one combined answer (tools/answers/unified.py); internal + if plan_data: # what the question asks, for the one combined answer (tools/answers/presentation/unified.py); internal result['_plan']={k:plan_data.get(k) for k in ('intent','fields','facets','presentation','answer_mode', 'meeting','people','works','years','period')} conversation=issue_context(resolved.query,result,catalog,index,version) @@ -221,7 +221,7 @@ def _deliver_answer( return public_failure({"reason": "answer_capacity_exceeded", "engine": engine}) try: model = complete or complete_with_configured_model - from tools.answers.question_plan import (build_question_plan, planning_catalog, QuestionPlan, PlanMeaning, + from tools.answers.planning.question_plan import (build_question_plan, planning_catalog, QuestionPlan, PlanMeaning, PlanRejected, PlanModelUnavailable) from tools.knowledge.query import deliver_content, ContentModelUnavailable, ContentAnswerRejected try: @@ -235,7 +235,7 @@ def _deliver_answer( messages, output_schema=PlanMeaning.model_json_schema())) classify = None if complete is None and os.getenv("ANSWER_QUESTION_CATALOG", "1") != "0": - from tools.answers.question_catalog import classify as classify_question + from tools.answers.planning.question_catalog import classify as classify_question classify = classify_question plan = build_question_plan(question, catalog, complete=plan_model,verify_complete=verify_model,index_version=planned_version,meeting=meeting, classify=classify) @@ -283,8 +283,8 @@ def _deliver_answer( include_diagnostics=include_diagnostics, ) if content_result is not None: - from tools.answers.synthesis import synthesize - from tools.answers.recommendations import generate + from tools.answers.generation.synthesis import synthesize + from tools.answers.generation.recommendations import generate from tools.knowledge.academic import with_completion_status completion = content_result.pop('_completion_rows', []) render=generate if plan.spec.intent=='proposal' else synthesize diff --git a/tools/answers/combined.py b/tools/answers/combined.py index 07a07a7..4bf0ae1 100644 --- a/tools/answers/combined.py +++ b/tools/answers/combined.py @@ -28,8 +28,8 @@ import threading import time from concurrent.futures import ThreadPoolExecutor, TimeoutError as FutureTimeout -from tools.answers.context_policy import normalized -from tools.answers.delivery_contract import fingerprint +from tools.answers.verification.context_policy import normalized +from tools.answers.verification.delivery_contract import fingerprint CRZP_SECONDS = float(os.getenv("CRZP_COMBINED_SECONDS", "45")) LIFETIME = 24 * 3600 @@ -162,7 +162,7 @@ COULD = re.compile(r"\b(?:mohol|mohla|mohli|moze|mozu|hodil|hodila)\b") def _one_person(question: str) -> dict | None: """{"name", "input"}: the one ZP Wiki person a question names, with the words naming it.""" - from tools.answers.question_plan import planning_catalog + from tools.answers.planning.question_plan import planning_catalog from tools.rag.common import DB_FILE from tools.retrieval.person_names import resolve_person_names try: @@ -298,7 +298,7 @@ FRAMEWORKS = {"python", "fastapi", "flask", "django", "streamlit", "react", "doc def wiki_terms(person: str) -> list[str]: """The person's most specific topics and tools (reviewed topic groups first, frameworks never): the words to look for in CRZP to find similar works.""" - from tools.answers.content_selection import named_tools + from tools.answers.evidence.content_selection import named_tools from tools.retrieval.synonyms import base_name, group_of counts: dict[str, float] = {} for unit in wiki_units(person): @@ -421,7 +421,7 @@ METHOD_STOP = {"analyza", "navrh", "system", "systemy", "aplikacia", "implementa def crzp_methods(person: str, row: dict, detail: dict | None) -> str: """"Ján Pták vo svojej bakalárskej práci „…“ (2025) využíva: ESP32, MQTT, InfluxDB, Home Assistant." — the work's keywords and the tools its abstract names.""" - from tools.answers.content_selection import named_tools + from tools.answers.evidence.content_selection import named_tools record = detail or row abstract = record.get("abstract") or "" found = [] @@ -645,7 +645,7 @@ def related_part(query) -> dict | None: authors = example.get("authors") or [] from tools.crzp.source.parse import display_name wiki = wiki_people_for(entry["label"]) - from tools.answers.unified import catalog as wiki_catalog, join + from tools.answers.presentation.unified import catalog as wiki_catalog, join text = (f"{crzp.plural(len(entry['rows']))}, napr. „{example['title']}“ " f"({display_name(authors[0]) if authors else 'autor neuvedený'}, {crzp.university(example)}, " f"{example.get('year') or 'rok neuvedený'})") @@ -783,7 +783,7 @@ def merge_people(wiki: list[dict], crzp_items: list[dict]) -> list[dict]: def newest_first(items: list[dict]) -> list[dict]: """People of a list from the one with the newest work or record (stable for equal dates).""" - from tools.answers.unified import recency + from tools.answers.presentation.unified import recency return sorted(items, key=lambda i: recency(i["name"]) if i.get("source") == "wiki" else str(i.get("year") or ""), reverse=True) @@ -967,7 +967,7 @@ def _crzp_work_answer(question: str, engine: str, chosen: dict, complete=None) - result.pop(key, None) if result.get("accepted_for_delivery") is not True: return result - from tools.answers.unified import strip_sources + from tools.answers.presentation.unified import strip_sources body, urls = split_sources(strip_sources(clean_crzp(result["answer"]))) urls = list(dict.fromkeys([*urls, *(result.get("source_urls") or [])])) text = body + ("\n\nZdroje: " + ", ".join(urls) if urls else "") @@ -981,7 +981,7 @@ def _answer(question: str, *, engine: str, limit: int, context_token: str | None from tools.crzp.answering.wiki_bridge import wiki_match, wiki_person previous = unseal(context_token) if previous and previous.get("error"): - from tools.answers.answer_errors import public_failure + from tools.answers.presentation.answer_errors import public_failure failure = public_failure({"reason": previous["error"], "engine": engine}) failure["delivery_check"] = {"layer": "context", "code": "unavailable", "request_fingerprint": fingerprint(question, engine)} @@ -1045,7 +1045,7 @@ def _answer(question: str, *, engine: str, limit: int, context_token: str | None followed.pop("_shown", None), followed.pop("_asked", None), followed.pop("_options", None) shown = followed.pop("_entities", None) or [] if followed.get("accepted_for_delivery") is True: - from tools.answers.unified import strip_sources + from tools.answers.presentation.unified import strip_sources body, urls = split_sources(strip_sources(clean_crzp(followed["answer"]))) urls = list(dict.fromkeys([*urls, *(followed.get("source_urls") or [])]))[:12] result = {**followed, "answer": body + ("\n\nZdroje: " + ", ".join(urls) if urls else ""), @@ -1085,7 +1085,7 @@ def _answer(question: str, *, engine: str, limit: int, context_token: str | None def compose(asked: str, question: str, engine: str, wiki: dict, part: dict | None, person: str | None) -> dict: """One answer from the ZP Wiki result and the CRZP part (without naming the sources in the text).""" - from tools.answers.unified import strip_sources + from tools.answers.presentation.unified import strip_sources result = _compose(asked, question, engine, wiki, part, person) if result.get("accepted_for_delivery") is True and isinstance(result.get("answer"), str): result["answer"] = strip_sources(result["answer"]) @@ -1094,8 +1094,8 @@ def compose(asked: str, question: str, engine: str, wiki: dict, part: dict | Non def _unified(asked, question, engine, wiki, wiki_ok, part, person, wiki_context, plan) -> dict | None: """The answer of a question about one person, a supervisor's students or two people, built from the - records of both sources (tools/answers/unified.py); None leaves the general composition.""" - from tools.answers import unified as U + records of both sources (tools/answers/presentation/unified.py); None leaves the general composition.""" + from tools.answers.presentation import unified as U if wiki.get("reason") in REFUSED or wiki.get("status") == "ambiguous" and person is None: return None low = normalized(question) @@ -1200,7 +1200,7 @@ def _unified(asked, question, engine, wiki, wiki_ok, part, person, wiki_context, def _compose(asked: str, question: str, engine: str, wiki: dict, part: dict | None, person: str | None) -> dict: """One answer from the ZP Wiki result and the CRZP part.""" - from tools.answers.finalize import finalize + from tools.answers.presentation.finalize import finalize low = normalized(question) if wiki.get("reason") in REFUSED or wiki.get("status") == "ambiguous" and ( person or wiki.get("reason") not in WIKI_CLARIFICATION_YIELDS): @@ -1284,7 +1284,7 @@ def _compose(asked: str, question: str, engine: str, wiki: dict, part: dict | No crzp=part.get("crzp_token")) if wiki_ok and person and part["mode"] == "person": # A work the wiki answer already names is not repeated (its link stays in "Zdroje:"). - from tools.answers.unified import catalog as wiki_catalog, _same_title + from tools.answers.presentation.unified import catalog as wiki_catalog, _same_title titles = [w.get("title") for w in wiki_catalog()["works"].get(person, []) if w.get("title")] kept = [b for b in re.split(r"\n\s*\n", crzp_body) if not any(_same_title(t, (re.search(r"„([^“]+)“", b) or [None, ""])[1]) for t in titles)] @@ -1330,7 +1330,7 @@ def _choice(low: str, options: list[dict]) -> dict | None: words = [w for w in re.findall(r"[a-z0-9]+", low) if w not in CHOICE_FILLERS] typed = [o for o in options if o.get("type")] if typed and len(words) <= 4: # options of different thesis types: "bakalársku", "tú diplomovú" - from tools.answers.unified import asked_type + from tools.answers.presentation.unified import asked_type kind = asked_type(low) same = [o for o in typed if o["type"] == kind] if kind and len(same) == 1: @@ -1349,10 +1349,10 @@ def _choice(low: str, options: list[dict]) -> dict | None: def _answer_choice(question: str, chosen: dict, *, engine: str, limit: int, complete=None, deliver=None) -> dict: """The answer to the pending question about the chosen work (the caller binds it to the reply).""" - from tools.answers.finalize import finalize + from tools.answers.presentation.finalize import finalize deliver_answer = deliver if chosen.get("type"): # one of the person's theses: the same question about that thesis - from tools.answers.unified import TYPES + from tools.answers.presentation.unified import TYPES nominative, genitive_, locative = TYPES[chosen["type"]] if re.search(r"\bpráce\b", question): asked = re.sub(r"\bpráce\b", genitive_, question, count=1) diff --git a/tools/answers/evidence/__init__.py b/tools/answers/evidence/__init__.py new file mode 100644 index 0000000..21733e5 --- /dev/null +++ b/tools/answers/evidence/__init__.py @@ -0,0 +1 @@ +"""Selecting the source evidence an answer may use (RAG text, graph facts, excerpts, coverage).""" diff --git a/tools/answers/answer_coverage.py b/tools/answers/evidence/answer_coverage.py similarity index 96% rename from tools/answers/answer_coverage.py rename to tools/answers/evidence/answer_coverage.py index ee304b7..50e739d 100644 --- a/tools/answers/answer_coverage.py +++ b/tools/answers/evidence/answer_coverage.py @@ -6,7 +6,7 @@ exhaustive retrieval, a complete source document or absence of other records. import re -from tools.answers.context_policy import normalized +from tools.answers.verification.context_policy import normalized def response_scope(question: str, *, content: bool = False) -> str: @@ -73,13 +73,13 @@ def answer_coverage(answer: dict, context: dict) -> dict: coverage = "partial" warnings.append("partial_requested_fields") if requirements.get("facets"): - from tools.answers.content_selection import missing_facets + from tools.answers.evidence.content_selection import missing_facets if missing_facets(answer, context): coverage = "partial" warnings.append("partial_requested_aspects") elif requirements.get("content"): - from tools.answers.rag_evidence import missing_content_people + from tools.answers.evidence.rag_evidence import missing_content_people if missing_content_people(answer, context): coverage = "partial" diff --git a/tools/answers/content_selection.py b/tools/answers/evidence/content_selection.py similarity index 97% rename from tools/answers/content_selection.py rename to tools/answers/evidence/content_selection.py index de315a9..f451634 100644 --- a/tools/answers/content_selection.py +++ b/tools/answers/evidence/content_selection.py @@ -3,8 +3,8 @@ from __future__ import annotations import re -from tools.answers.context_policy import normalized -from tools.answers.question_intent import ( +from tools.answers.verification.context_policy import normalized +from tools.answers.planning.question_intent import ( FACET_LABELS, planned_experiments, requested_facets, @@ -59,7 +59,7 @@ def reference_only(text: str) -> bool: value = re.sub(r"^\s*(?:[-*+]|\d+[.)])\s+", "", text).strip() if re.fullmatch(r"\[[^]]+\]\([^\s]+\)", value): return True - from tools.answers.context_policy import text_urls + from tools.answers.verification.context_policy import text_urls links = text_urls(value) if not links: @@ -75,7 +75,7 @@ def reference_only(text: str) -> bool: def split_units(text: str) -> list[str]: - from tools.answers.rag_evidence import descriptive_text + from tools.answers.evidence.rag_evidence import descriptive_text parts = re.split(r"\n\s*\n|(?=^[ \t]*(?:\d+[.)]|[-+*])\s+)", text, flags=re.M) units = [] @@ -97,7 +97,7 @@ def split_units(text: str) -> list[str]: def effective_role(text: str, role: str) -> str: n = normalized(re.sub(r"^\s*(?:\d+[.)]|[-+*])\s+", "", text)) if role in {"other", "progress"}: - from tools.answers.presentation import GOAL_VERBS + from tools.answers.presentation.presentation import GOAL_VERBS first = n.split()[0] if n else "" if ( @@ -212,7 +212,7 @@ def unit_score(text: str, role: str, facet: str = "") -> int: def prioritize_frames(frames: list[str], question: str) -> list[str]: """Order whole source windows before budgeting; do not rewrite their text.""" - from tools.answers.rag_evidence import content_sections, TITLE_LABELS + from tools.answers.evidence.rag_evidence import content_sections, TITLE_LABELS rankings = [] for facet in requested_facets(question): @@ -248,7 +248,7 @@ def prioritize_frames(frames: list[str], question: str) -> list[str]: def evidence_units(context: dict, quotes: list[dict] | None = None) -> list[dict]: - from tools.answers.rag_evidence import content_sections, quote_sections, quote_matches_passage + from tools.answers.evidence.rag_evidence import content_sections, quote_sections, quote_matches_passage rows = [] for passage in context.get("content_passages", []): @@ -353,7 +353,7 @@ def scope_context(context: dict, person: str, label: str | None) -> dict: def candidates(context: dict) -> list[dict]: - from tools.answers.evidence_selection import identify + from tools.answers.evidence.evidence_selection import identify facets = context["requirements"].get("facets", []) selected = [] @@ -462,7 +462,7 @@ def fit_candidates(sent: dict, context: dict, limit: int, encoding: str) -> None def facet_lines(answer: dict, context: dict) -> list[str]: - from tools.answers.presentation import ( + from tools.answers.presentation.presentation import ( goal_text, evidence_subject, missing_aspects, diff --git a/tools/answers/evidence_selection.py b/tools/answers/evidence/evidence_selection.py similarity index 96% rename from tools/answers/evidence_selection.py rename to tools/answers/evidence/evidence_selection.py index 1f0da1f..02cc24a 100644 --- a/tools/answers/evidence_selection.py +++ b/tools/answers/evidence/evidence_selection.py @@ -35,7 +35,7 @@ def identify(row: dict, *, required: bool = False) -> dict: def overview_candidates(context: dict) -> list[dict]: """Keep every main assignment item; do not confuse a backlog with goals.""" - from tools.answers.content_selection import ( + from tools.answers.evidence.content_selection import ( evidence_units, administrative_only, unit_score, @@ -125,7 +125,7 @@ def missing_required_evidence(answer: dict, context: dict) -> list[str]: def overview_units(answer: dict, context: dict) -> list[dict]: """Render all checked assignment items and at most two fallback units per person.""" - from tools.answers.content_selection import evidence_units, scope_groups, matches_scope + from tools.answers.evidence.content_selection import evidence_units, scope_groups, matches_scope rows = evidence_units(context, answer.get("evidence_quotes", [])) selected = [] diff --git a/tools/answers/graph_context.py b/tools/answers/evidence/graph_context.py similarity index 99% rename from tools/answers/graph_context.py rename to tools/answers/evidence/graph_context.py index f6834df..a5e91c0 100644 --- a/tools/answers/graph_context.py +++ b/tools/answers/evidence/graph_context.py @@ -1,6 +1,6 @@ """Production graph-to-answer context adapter; no benchmark or oracle dependencies.""" -from tools.answers.context_policy import joined_candidates +from tools.answers.verification.context_policy import joined_candidates def delivery_facts(context, result): diff --git a/tools/answers/rag_evidence.py b/tools/answers/evidence/rag_evidence.py similarity index 98% rename from tools/answers/rag_evidence.py rename to tools/answers/evidence/rag_evidence.py index 1f292ff..f1e762d 100644 --- a/tools/answers/rag_evidence.py +++ b/tools/answers/evidence/rag_evidence.py @@ -11,8 +11,8 @@ import json import sqlite3 import hashlib from contextlib import closing -from tools.answers.context_policy import normalized, text_contains_value, person_pattern -from tools.answers.question_intent import ( +from tools.answers.verification.context_policy import normalized, text_contains_value, person_pattern +from tools.answers.planning.question_intent import ( requested_facets, content_question, facet_mode, @@ -587,7 +587,7 @@ def expand_comparison_sources(db_file, question: str, payload: dict) -> dict: def rag_evidence_context(question: str, payload: dict) -> dict: - from tools.answers.question_plan import QuestionPlan + from tools.answers.planning.question_plan import QuestionPlan plan=QuestionPlan.model_validate(payload["question_plan"]) if payload.get("question_plan") else None blocks = source_blocks(payload) if payload.get("sources") else [] facts = [] @@ -797,7 +797,7 @@ def rag_evidence_context(question: str, payload: dict) -> dict: "response_mode": "claims" if academic or start_year else "quotes", } if content: - from tools.answers.answer_coverage import response_scope + from tools.answers.evidence.answer_coverage import response_scope requirements["content_style"] = response_scope(question, content=True) requirements["response_mode"] = ( @@ -890,11 +890,11 @@ def rag_evidence_context(question: str, payload: dict) -> dict: if requirements["separate_works"]: requirements["work_scopes"] = context["work_scopes"] if requirements.get("facets"): - from tools.answers.content_selection import candidates + from tools.answers.evidence.content_selection import candidates context["content_candidates"] = candidates(context) elif requirements["content_style"] in {"overview", "assignment"}: - from tools.answers.evidence_selection import overview_candidates + from tools.answers.evidence.evidence_selection import overview_candidates context["content_candidates"] = overview_candidates(context) if requirements["distinguish_progress"]: @@ -920,7 +920,7 @@ def rag_prose_issues(question: str, answer: str, payload: dict) -> list[str]: if not context["requirements"]["academic"]: return [] text = answer - from tools.answers.context_policy import text_urls + from tools.answers.verification.context_policy import text_urls for url in sorted(text_urls(text), key=len, reverse=True): text = text.replace(url, "") diff --git a/tools/answers/rag_metadata.py b/tools/answers/evidence/rag_metadata.py similarity index 95% rename from tools/answers/rag_metadata.py rename to tools/answers/evidence/rag_metadata.py index 2ee530d..c9730b4 100644 --- a/tools/answers/rag_metadata.py +++ b/tools/answers/evidence/rag_metadata.py @@ -1,8 +1,8 @@ """Exact metadata answers from delivered text, never from Neo4j or a gold set.""" import re -from tools.answers.context_policy import normalized,citation_check -from tools.answers.question_plan import QuestionPlan -from tools.answers.render_answer import render_graph_answer +from tools.answers.verification.context_policy import normalized,citation_check +from tools.answers.planning.question_plan import QuestionPlan +from tools.answers.presentation.render_answer import render_graph_answer def exact_metadata_answer(payload,context): diff --git a/tools/answers/rag_preparation.py b/tools/answers/evidence/rag_preparation.py similarity index 95% rename from tools/answers/rag_preparation.py rename to tools/answers/evidence/rag_preparation.py index 3ff498a..f4ba00b 100644 --- a/tools/answers/rag_preparation.py +++ b/tools/answers/evidence/rag_preparation.py @@ -7,9 +7,9 @@ import re import sqlite3 from contextlib import closing -from tools.answers.context_policy import normalized, person_pattern, text_contains_value -from tools.answers.question_intent import content_question -from tools.answers.rag_evidence import ( +from tools.answers.verification.context_policy import normalized, person_pattern, text_contains_value +from tools.answers.planning.question_intent import content_question +from tools.answers.evidence.rag_evidence import ( PROFILE, academic_windows_metadata, requested_types, @@ -31,7 +31,7 @@ def clarify(payload: dict, reason: str, message: str) -> dict: def prepare_named_content(db_file, question: str, payload: dict) -> dict: from tools.retrieval.work_selector import parse_work_selector, label_key - from tools.answers.question_plan import QuestionPlan, build_question_plan + from tools.answers.planning.question_plan import QuestionPlan, build_question_plan plan=QuestionPlan.model_validate(payload['question_plan']) if payload.get('question_plan') else None selector = parse_work_selector(question) metadata_scope=bool(plan and plan.intent=='metadata' and any(p.role=='student' for p in plan.people) @@ -173,7 +173,7 @@ def prepare_named_content(db_file, question: str, payload: dict) -> dict: } for (scope, _key), label in records.items() ) - from tools.answers.content_selection import prioritize_frames + from tools.answers.evidence.content_selection import prioritize_frames frames = prioritize_frames(frames, question) source = next( diff --git a/tools/answers/generation/__init__.py b/tools/answers/generation/__init__.py new file mode 100644 index 0000000..8e94f0e --- /dev/null +++ b/tools/answers/generation/__init__.py @@ -0,0 +1 @@ +"""Text written by the model from supplied evidence, and the model client.""" diff --git a/tools/answers/answer_format.py b/tools/answers/generation/answer_format.py similarity index 100% rename from tools/answers/answer_format.py rename to tools/answers/generation/answer_format.py diff --git a/tools/answers/checked_generation.py b/tools/answers/generation/checked_generation.py similarity index 94% rename from tools/answers/checked_generation.py rename to tools/answers/generation/checked_generation.py index f468f56..cf44313 100644 --- a/tools/answers/checked_generation.py +++ b/tools/answers/generation/checked_generation.py @@ -1,9 +1,9 @@ """One bounded corrective request based solely on retrieval evidence.""" import json -from tools.answers.answer_format import parse_answer, Answer, Claim -from tools.answers.context_policy import answer_context_issues -from tools.answers.render_answer import render_graph_answer +from tools.answers.generation.answer_format import parse_answer, Answer, Claim +from tools.answers.verification.context_policy import answer_context_issues +from tools.answers.presentation.render_answer import render_graph_answer def generate_checked_answer(question: str, context: dict, prompt: str, complete) -> dict: diff --git a/tools/answers/model_client.py b/tools/answers/generation/model_client.py similarity index 100% rename from tools/answers/model_client.py rename to tools/answers/generation/model_client.py diff --git a/tools/answers/recommendations.py b/tools/answers/generation/recommendations.py similarity index 97% rename from tools/answers/recommendations.py rename to tools/answers/generation/recommendations.py index 7980b5f..3eaab0d 100644 --- a/tools/answers/recommendations.py +++ b/tools/answers/generation/recommendations.py @@ -7,10 +7,10 @@ from collections import defaultdict import re from pydantic import Field -from tools.answers import synthesis as s -from tools.answers.context_policy import normalized,text_contains_value,text_urls,citation_check -from tools.answers.notices import unique_notices -from tools.answers.answer_errors import clarification_result +from tools.answers.generation import synthesis as s +from tools.answers.verification.context_policy import normalized,text_contains_value,text_urls,citation_check +from tools.answers.presentation.notices import unique_notices +from tools.answers.presentation.answer_errors import clarification_result from tools.knowledge.evidence import claim_eligible @@ -107,7 +107,7 @@ def collect_evidence(bound,index,units,*,engine,limit): latest_ids.update(r.get('meeting_id') or r['id'] for r in dated if r['date']==stamp) if any(r['person']==name and not r.get('date') for r in markers): meeting_notes.append(name+': záznamy bez úplného dátumu nemožno spoľahlivo zoradiť; vychádzam z posledného záznamu s úplným dátumom.') - from tools.answers.content_selection import administrative_only,reference_only + from tools.answers.evidence.content_selection import administrative_only,reference_only for row in units: if row['person'] not in people or not plan.matches_evidence(row) or not claim_eligible(row):continue if latest_ids is not None and row.get('meeting_id') not in latest_ids:continue diff --git a/tools/answers/synthesis.py b/tools/answers/generation/synthesis.py similarity index 98% rename from tools/answers/synthesis.py rename to tools/answers/generation/synthesis.py index ef02cdd..e56a604 100644 --- a/tools/answers/synthesis.py +++ b/tools/answers/generation/synthesis.py @@ -14,7 +14,7 @@ from typing import Literal from pydantic import BaseModel, ConfigDict, Field -from tools.answers.context_policy import normalized, text_contains_value, text_urls +from tools.answers.verification.context_policy import normalized, text_contains_value, text_urls class Strict(BaseModel): @@ -256,7 +256,7 @@ def _call(complete, prompt, schema_type, payload, *, max_tokens=None): from tools.knowledge.query import model_json messages = _messages(prompt, schema_type.model_json_schema(), payload) - from tools.answers.model_client import complete_with_configured_model + from tools.answers.generation.model_client import complete_with_configured_model if complete is None or complete is complete_with_configured_model: # The configured model receives the schema (compact constrained JSON # where enabled); test doubles and custom callables get the prompt only. @@ -350,7 +350,7 @@ def validate_draft(draft, rows, plan, known_people=()): source_text = source_text.replace(url,' ') source_n=normalized(source_text) if phases<={'result','progress'}: - from tools.answers.presentation import GOAL_VERBS + from tools.answers.presentation.presentation import GOAL_VERBS verbs='|'.join(re.escape(normalized(v)) for v in GOAL_VERBS.values()) intended=r'\b(?:ma|maju|mal|mali)\s+(?:za ulohu\s+)?(?:'+verbs+r')\b' if re.search(intended,n) and not re.search(intended,source_n): @@ -458,7 +458,7 @@ def graph_notices(rows, result): def render(draft, rows, result, plan): """Only reviewed prose plus server-owned identities, phases and record dates.""" - from tools.answers.notices import unique_notices + from tools.answers.presentation.notices import unique_notices urls=list(dict.fromkeys(r['source_url'] for r in rows.values())) def cites(claim): return ' '.join(f'[{urls.index(url)+1}]' for url in dict.fromkeys(rows[k]['source_url'] for k in claim.evidence_ids)) @@ -499,7 +499,7 @@ def render(draft, rows, result, plan): cell_dates=' (dátum záznamu: '+displayed+')' if displayed else '' table_cells[(scope,label,phase)].append((cell_dates+': ' if cell_dates else '')+text) if plan.presentation in {'table','comparison'} and plan.intent!='meeting': - from tools.answers.presentation import comparison_table + from tools.answers.presentation.presentation import comparison_table table=comparison_table(['Oblasť',*(scope[0]+' — '+label for scope,label in scopes)], [(PHASES[phase],[' '.join(table_cells.get((scope,label,phase),[])) or 'V tomto výbere nie je doložené.' for scope,label in scopes]) for phase in PHASES if any(k[2]==phase for k in table_cells)]) @@ -520,7 +520,7 @@ def synthesize(result, plan, *, complete=None, known_people=(), diagnostics=Fals return result # Prose needs a draft plus parallel reviews and leaves time for the final # fulfilment audit. Without that budget the checked evidence answer stays. - from tools.answers.model_client import has_budget + from tools.answers.generation.model_client import has_budget if not has_budget(float(os.getenv('ANSWER_SYNTHESIS_MIN_SECONDS', '45'))): return {**result, **({"synthesis": {"status": "fallback", "reason": "time_budget"}} if diagnostics else {})} stage = 'evidence' @@ -639,7 +639,7 @@ def synthesize(result, plan, *, complete=None, known_people=(), diagnostics=Fals validate_draft(draft, rows, plan, known_people) stage = 'support_review' notes=[*result['presentation_notes'],*graph_notices(rows,result)] - from tools.answers.model_client import parallel_map + from tools.answers.generation.model_client import parallel_map for support_attempt in range(2): try: # The support and the adversarial review judge the same draft @@ -670,7 +670,7 @@ def synthesize(result, plan, *, complete=None, known_people=(), diagnostics=Fals text, urls = render(draft, rows, result, plan) if len(text)>18000: raise SynthesisRejected('output_budget') - from tools.answers.context_policy import citation_check + from tools.answers.verification.context_policy import citation_check if not citation_check({"answer": text, "source_urls": urls}, set(result["source_urls"]))["citations_ok"]: raise SynthesisRejected("rendered_citation") audit = {"status": "accepted", "claims": [c.model_dump() for c in draft.claims], diff --git a/tools/answers/planning/__init__.py b/tools/answers/planning/__init__.py new file mode 100644 index 0000000..d71e2cb --- /dev/null +++ b/tools/answers/planning/__init__.py @@ -0,0 +1 @@ +"""Understanding the question: the typed plan, the question catalog, aspects and conversation references.""" diff --git a/tools/answers/catalog_examples.json b/tools/answers/planning/catalog_examples.json similarity index 100% rename from tools/answers/catalog_examples.json rename to tools/answers/planning/catalog_examples.json diff --git a/tools/answers/catalog_optimize.py b/tools/answers/planning/catalog_optimize.py similarity index 94% rename from tools/answers/catalog_optimize.py rename to tools/answers/planning/catalog_optimize.py index 5b5e525..296cae0 100644 --- a/tools/answers/catalog_optimize.py +++ b/tools/answers/planning/catalog_optimize.py @@ -1,6 +1,6 @@ """Offline DSPy optimization of the question catalog (dev dependency: dspy). - python -m tools.answers.catalog_optimize [--threads 2] [--provisional] + python -m tools.answers.planning.catalog_optimize [--threads 2] [--provisional] Reads the labeled questions (catalog_examples.json), splits them into train and dev sets deterministically, compiles a few-shot program with DSPy @@ -16,8 +16,8 @@ import json import time from pathlib import Path -from tools.answers.context_policy import normalized -from tools.answers.question_catalog import (CatalogDecision, INSTRUCTIONS, EXAMPLES_FILE, PROGRAM_FILE, +from tools.answers.verification.context_policy import normalized +from tools.answers.planning.question_catalog import (CatalogDecision, INSTRUCTIONS, EXAMPLES_FILE, PROGRAM_FILE, TYPE_DESCRIPTIONS, checked, classify, _cache) @@ -71,7 +71,7 @@ def provisional(train): def optimize(train, dev, threads): import dspy - from tools.answers.model_client import model_configuration + from tools.answers.generation.model_client import model_configuration config = model_configuration() api_base = config["endpoint"].rsplit("/chat/completions", 1)[0] lm = dspy.LM("openai/" + config["model"], api_base=api_base, api_key=config["key"], temperature=0, @@ -133,7 +133,7 @@ def evaluate(program, dev): def main(): from dotenv import load_dotenv - load_dotenv(Path(__file__).resolve().parents[2] / ".env", override=False) + load_dotenv(Path(__file__).resolve().parents[3] / ".env", override=False) parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("--threads", type=int, default=2) parser.add_argument("--provisional", action="store_true") diff --git a/tools/answers/conversation.py b/tools/answers/planning/conversation.py similarity index 98% rename from tools/answers/conversation.py rename to tools/answers/planning/conversation.py index b0094f0..674fae7 100644 --- a/tools/answers/conversation.py +++ b/tools/answers/planning/conversation.py @@ -14,9 +14,9 @@ import os import re import time -from tools.answers.context_policy import normalized -from tools.answers.question_intent import normalize_question -from tools.answers.question_plan import MeetingRequest, direct_spec +from tools.answers.verification.context_policy import normalized +from tools.answers.planning.question_intent import normalize_question +from tools.answers.planning.question_plan import MeetingRequest, direct_spec from tools.retrieval.person_names import resolve_person_names MAX_TOKEN = 16000 @@ -277,7 +277,7 @@ def _chosen_person(query, pending, catalog): def _inherit_constraints(query, context, catalog): """Carry previous explicit constraints, allowing explicit new replacements.""" - from tools.answers.rag_evidence import WORK_LABELS + from tools.answers.evidence.rag_evidence import WORK_LABELS old=direct_spec(context['question'],resolve_person_names(context['question'],catalog)) new=direct_spec(query,resolve_person_names(query,catalog)) if len(old.people)!=1:return query diff --git a/tools/answers/question_catalog.json b/tools/answers/planning/question_catalog.json similarity index 100% rename from tools/answers/question_catalog.json rename to tools/answers/planning/question_catalog.json diff --git a/tools/answers/question_catalog.py b/tools/answers/planning/question_catalog.py similarity index 97% rename from tools/answers/question_catalog.py rename to tools/answers/planning/question_catalog.py index d62ec14..c867372 100644 --- a/tools/answers/question_catalog.py +++ b/tools/answers/planning/question_catalog.py @@ -2,7 +2,7 @@ code builds and executes the plan. The instructions and few-shot demonstrations are optimized offline with DSPy -(``python -m tools.answers.catalog_optimize``) on labeled questions in +(``python -m tools.answers.planning.catalog_optimize``) on labeled questions in ``catalog_examples.json`` and stored in ``question_catalog.json``. At run time no DSPy is needed: the stored program is sent through the shared model client (deadline, fair gate). Parameters are checked against the question: a person, @@ -22,7 +22,7 @@ from typing import Literal from pydantic import BaseModel, ConfigDict, Field -from tools.answers.context_policy import normalized +from tools.answers.verification.context_policy import normalized PROGRAM_FILE = Path(__file__).with_name("question_catalog.json") EXAMPLES_FILE = Path(__file__).with_name("catalog_examples.json") @@ -132,7 +132,7 @@ def load_program(path: Path = PROGRAM_FILE) -> dict: def messages_for(question: str, program: dict) -> list[dict]: - from tools.answers.synthesis import FORMAT_LINE + from tools.answers.generation.synthesis import FORMAT_LINE schema = json.dumps(CatalogDecision.model_json_schema(), ensure_ascii=False) messages = [{"role": "system", "content": FORMAT_LINE + "\n" + program.get("instructions", INSTRUCTIONS) + "\nOutput: a JSON object of this schema: " + schema}] @@ -150,7 +150,7 @@ _cache_lock = threading.Lock() def classify(question: str, complete=None, *, program: dict | None = None) -> CatalogDecision | None: """The catalog decision, or None (model unavailable, invalid output).""" - from tools.answers.model_client import complete_with_configured_model, call_floor + from tools.answers.generation.model_client import complete_with_configured_model, call_floor key = normalized(question).strip() with _cache_lock: if key in _cache: diff --git a/tools/answers/question_intent.py b/tools/answers/planning/question_intent.py similarity index 99% rename from tools/answers/question_intent.py rename to tools/answers/planning/question_intent.py index 92acd7a..8a37e5c 100644 --- a/tools/answers/question_intent.py +++ b/tools/answers/planning/question_intent.py @@ -1,7 +1,7 @@ """Explicit answer aspects; these select evidence, never supply facts.""" import re -from tools.answers.context_policy import normalized +from tools.answers.verification.context_policy import normalized FACET_PATTERNS = { "assignment": r"\b(?:zadani\w*|ciel\w*)\b|\bco\s+(?:ma|maju|mal[aoiy]?)\b[^?;!.]*\b(?:vytvorit|vypracovat|implementovat|navrhnut|zostavit)\b", diff --git a/tools/answers/question_plan.py b/tools/answers/planning/question_plan.py similarity index 98% rename from tools/answers/question_plan.py rename to tools/answers/planning/question_plan.py index 4bea3b9..2e1f879 100644 --- a/tools/answers/question_plan.py +++ b/tools/answers/planning/question_plan.py @@ -13,9 +13,9 @@ from typing import Literal from pydantic import BaseModel, ConfigDict, Field, model_validator -from tools.answers.context_policy import normalized -from tools.answers.question_intent import requested_facets, content_question, unresolved_followup, discovery_question, person_topic -from tools.answers.rag_evidence import requested_types, TYPE_PATTERN +from tools.answers.verification.context_policy import normalized +from tools.answers.planning.question_intent import requested_facets, content_question, unresolved_followup, discovery_question, person_topic +from tools.answers.evidence.rag_evidence import requested_types, TYPE_PATTERN from tools.retrieval.person_names import resolve_person_names, sqlite_people from tools.retrieval.question_constraints import unsupported_constraint, requested_years, constraint_message from tools.retrieval.work_selector import parse_work_selector, WorkSelector @@ -213,7 +213,7 @@ def direct_spec(question, resolution, *, meeting=None, route=None, relative_year or re.search(r'\b'+name+r'\s+konzult\w*\b',n)) role='consultant' if consultant else 'supervisor' people.append(PersonRequest(name=m['name'],role=role,source_document=m.get('source_document'))) - from tools.answers.context_policy import text_contains_value + from tools.answers.verification.context_policy import text_contains_value independent=re.split(r'[?;!]+\s*',q) owners=[{p.name for p in people if text_contains_value(c,p.name,person=True)} for c in independent] if len(people)>1 and sum(bool(o) for o in owners)>1 and all(len(o)<=1 for o in owners): @@ -242,7 +242,7 @@ def direct_spec(question, resolution, *, meeting=None, route=None, relative_year if not kind: kind='diploma_thesis' if re.search(r'\bdiplomovk\w*',own_text) else 'bachelor_thesis' if re.search(r'\bbakalark\w*',own_text) else None if not p and len({m.group(0) for m in TYPE_PATTERN.finditer(types_text)})==1: - from tools.answers.rag_evidence import work_type + from tools.answers.evidence.rag_evidence import work_type kind=work_type(types_text) works.append(WorkRequest(person=p.name if p and p.role=='student' else None,work_type=kind,years=own_years, labels=list(own_selector.labels),excluded_labels=list(own_selector.excluded_labels),numbers=list(own_selector.numbers), @@ -456,7 +456,7 @@ WIKI_WORDS=re.compile(r'\b(?:student\w*|prac\w*|tem\w*|veduc\w*|vedie|viedol|pro def build_question_plan(question, catalog, *, complete=None, verify_complete=None, index_version=None, meeting=None, classify=None): - from tools.answers.question_intent import normalize_question + from tools.answers.planning.question_intent import normalize_question # "v tomto roku" becomes "v roku 2026" below; remember that it was relative. relative_year=bool(re.search(r'\b(?:tento rok|tomto roku|tohto roku|tohtorocn\w*)\b',normalized(question))) question=normalize_question(question) @@ -466,7 +466,7 @@ def build_question_plan(question, catalog, *, complete=None, verify_complete=Non if classify is not None and resolution.get('status')=='ok' and not {'request_out_of_scope','meeting_count_limit'}&set(spec.unsupported): # The catalog chooses the question type; the rules above remain the # fallback whenever the model is unavailable or its type is unclear. - from tools.answers.question_catalog import route_for, OUT_OF_SCOPE_MESSAGE + from tools.answers.planning.question_catalog import route_for, OUT_OF_SCOPE_MESSAGE decision=classify(resolution.get('resolved_query') or question) if (decision is not None and decision.type=='out_of_scope' and spec.intent=='metadata' and not spec.people and not WIKI_WORDS.search(normalized(question))): @@ -513,7 +513,7 @@ def build_question_plan(question, catalog, *, complete=None, verify_complete=Non if ambiguous_bindings and complete is None: return bound.model_copy(update={'reason':'ambiguous_work_binding','clarification':'Ku každej osobe uveď prácu a príslušný rok; priradenie týchto podmienok nie je jednoznačne určené.'}) if needs_help and complete: - from tools.answers.synthesis import FORMAT_LINE + from tools.answers.generation.synthesis import FORMAT_LINE messages=[{'role':'system','content':FORMAT_LINE+'\nInterpret this student-wiki question, not the source data. Return only a complete JSON question plan matching this schema: '+json.dumps(QuestionPlan.model_json_schema())+ ('. If work bindings are ambiguous, assign each supplied work year/label and type to its correct person from the question; preserve every supplied literal and all other work fields. ' if ambiguous_bindings else '. Preserve every work request exactly. ')+ 'Preserve the supplied baseline question, people with their roles, years, period, conditions, scope and unsupported fields exactly. You may refine intent, facets and presentation. Do not answer or produce SQL/Cypher. If the meaning is unclear, use intent=unsupported.'}, {'role':'user','content':json.dumps({'question':spec.question,'baseline':spec.model_dump()},ensure_ascii=False)}] diff --git a/tools/answers/presentation/__init__.py b/tools/answers/presentation/__init__.py new file mode 100644 index 0000000..3837041 --- /dev/null +++ b/tools/answers/presentation/__init__.py @@ -0,0 +1 @@ +"""How an answer reads: templates, rendering, final wording, one answer from both sources, names.""" diff --git a/tools/answers/answer_errors.py b/tools/answers/presentation/answer_errors.py similarity index 100% rename from tools/answers/answer_errors.py rename to tools/answers/presentation/answer_errors.py diff --git a/tools/answers/finalize.py b/tools/answers/presentation/finalize.py similarity index 100% rename from tools/answers/finalize.py rename to tools/answers/presentation/finalize.py diff --git a/tools/answers/names.py b/tools/answers/presentation/names.py similarity index 97% rename from tools/answers/names.py rename to tools/answers/presentation/names.py index eb007dc..9462632 100644 --- a/tools/answers/names.py +++ b/tools/answers/presentation/names.py @@ -8,7 +8,7 @@ Thanh, Mohorian). Each name is declined once by the configured model, the forms are checked (same number of words, every word keeps its beginning, a plausible ending) and kept in data/name_forms.json, so a name costs one short model call ever. Until the model has answered - (or without a model) the rules of tools/answers/unified.py are used. + (or without a model) the rules of tools/answers/presentation/unified.py are used. """ from __future__ import annotations @@ -117,7 +117,7 @@ def valid(name: str, value: NameForms) -> bool: def _ask(name: str) -> None: - from tools.answers.synthesis import _call + from tools.answers.generation.synthesis import _call try: value = _call(None, PROMPT, NameForms, {"name": name}, max_tokens=300) except Exception: @@ -194,7 +194,7 @@ def case(name: str, which: str) -> str: value = forms(shown) if value and value.get(which): return value[which] - from tools.answers import unified + from tools.answers.presentation import unified return unified.rule_genitive(shown) if which == "genitive" else shown @@ -202,5 +202,5 @@ def female(name: str) -> bool: value = forms(spelled(name)) if value: return value["gender"] == "female" - from tools.answers import unified + from tools.answers.presentation import unified return unified.rule_female(name) diff --git a/tools/answers/notices.py b/tools/answers/presentation/notices.py similarity index 95% rename from tools/answers/notices.py rename to tools/answers/presentation/notices.py index f432b80..d08f731 100644 --- a/tools/answers/notices.py +++ b/tools/answers/presentation/notices.py @@ -1,5 +1,5 @@ """Deduplicate server-owned notices without removing factual qualifications.""" -from tools.answers.context_policy import normalized +from tools.answers.verification.context_policy import normalized LIMIT_NOTICE='Zobrazený je obmedzený výber podkladov. Otázku môžeš zúžiť na osobu, prácu, obdobie alebo konkrétnu oblasť.' LIMIT_PREFIXES=('prechod grafom dosiahol limit vyberu','zobrazene su priklady z obmedzeneho vyberu', diff --git a/tools/answers/presentation.py b/tools/answers/presentation/presentation.py similarity index 98% rename from tools/answers/presentation.py rename to tools/answers/presentation/presentation.py index 7fa06ae..93ec170 100644 --- a/tools/answers/presentation.py +++ b/tools/answers/presentation/presentation.py @@ -8,8 +8,8 @@ from __future__ import annotations import re -from tools.answers.context_policy import normalized, person_token_pattern, text_urls -from tools.answers.rag_evidence import WORK_LABELS +from tools.answers.verification.context_policy import normalized, person_token_pattern, text_urls +from tools.answers.evidence.rag_evidence import WORK_LABELS ACCUSATIVE = { "bachelor_thesis": "bakalársku prácu", @@ -293,7 +293,7 @@ def no_answer_text(context: dict) -> str: def missing_aspects(facets: list[str], question: str = "") -> str: """Name only the missing requested fields, without empty helper sections.""" - from tools.answers.question_intent import planned_experiments, actual_methods_requested + from tools.answers.planning.question_intent import planned_experiments, actual_methods_requested labels = { "assignment": "zadaní a cieľoch", diff --git a/tools/answers/render_answer.py b/tools/answers/presentation/render_answer.py similarity index 98% rename from tools/answers/render_answer.py rename to tools/answers/presentation/render_answer.py index 9bc6fa5..b864e31 100644 --- a/tools/answers/render_answer.py +++ b/tools/answers/presentation/render_answer.py @@ -4,7 +4,7 @@ from copy import deepcopy import re from tools.graphrag.graphrag import WORK_TYPE_LABELS -from tools.answers.presentation import fact_sentences, no_answer_text, clean_answer +from tools.answers.presentation.presentation import fact_sentences, no_answer_text, clean_answer def render_graph_answer(answer: dict, context: dict) -> dict: diff --git a/tools/answers/unified.py b/tools/answers/presentation/unified.py similarity index 99% rename from tools/answers/unified.py rename to tools/answers/presentation/unified.py index a30ff00..407e4c4 100644 --- a/tools/answers/unified.py +++ b/tools/answers/presentation/unified.py @@ -22,7 +22,7 @@ import re import threading from pathlib import Path -from tools.answers.context_policy import normalized +from tools.answers.verification.context_policy import normalized TYPES = { # work type -> (nominative, genitive, locative) "bachelor_thesis": ("bakalárska práca", "bakalárskej práce", "bakalárskej práci"), @@ -67,7 +67,7 @@ _catalog: dict = {} # ------------------------------------------------------------------ names and words def female(name: str) -> bool: - from tools.answers import names + from tools.answers.presentation import names return names.female(name) @@ -82,13 +82,13 @@ def ending(name: str) -> str: def genitive(name: str) -> str: - """"Ronalda Zalačka", "Andriiho Pervashova": the checked forms of tools/answers/names.py.""" - from tools.answers import names + """"Ronalda Zalačka", "Andriiho Pervashova": the checked forms of tools/answers/presentation/names.py.""" + from tools.answers.presentation import names return names.case(name, "genitive") def spelled(name: str) -> str: - from tools.answers import names + from tools.answers.presentation import names return names.spelled(name) diff --git a/tools/answers/verification/__init__.py b/tools/answers/verification/__init__.py new file mode 100644 index 0000000..544bbaf --- /dev/null +++ b/tools/answers/verification/__init__.py @@ -0,0 +1 @@ +"""Checks before an answer is delivered: contract, guards, verified RAG, repository links.""" diff --git a/tools/answers/context_policy.py b/tools/answers/verification/context_policy.py similarity index 99% rename from tools/answers/context_policy.py rename to tools/answers/verification/context_policy.py index 044a915..0988227 100644 --- a/tools/answers/context_policy.py +++ b/tools/answers/verification/context_policy.py @@ -146,7 +146,7 @@ def prose_issues(answer: dict, context: dict | None = None) -> list[str]: """Conservative numeric consistency check; final prose is rendered from claims.""" text = str(answer.get("answer", "")) if context is not None and answer.get("status") == "no_answer": - from tools.answers.presentation import no_answer_text + from tools.answers.presentation.presentation import no_answer_text expected = no_answer_text(context) # These years describe the failed query, never a positive factual claim. diff --git a/tools/answers/delivery_contract.py b/tools/answers/verification/delivery_contract.py similarity index 98% rename from tools/answers/delivery_contract.py rename to tools/answers/verification/delivery_contract.py index 1c99563..30f02bb 100644 --- a/tools/answers/delivery_contract.py +++ b/tools/answers/verification/delivery_contract.py @@ -11,9 +11,9 @@ import re from typing import Literal from pydantic import Field -from tools.answers import synthesis as s -from tools.answers.context_policy import normalized, text_contains_value, text_urls, citation_check -from tools.answers.answer_errors import public_failure +from tools.answers.generation import synthesis as s +from tools.answers.verification.context_policy import normalized, text_contains_value, text_urls, citation_check +from tools.answers.presentation.answer_errors import public_failure from tools.knowledge.evidence import PROVENANCE_FIELDS @@ -240,7 +240,7 @@ def semantic_check(query,plan,result,*,complete=None): if plan.intent=='discovery': # A list of people with requested details: left alone, the model # writes one requirement per listed person (three times the output). - from tools.answers.question_intent import discovery_topic + from tools.answers.planning.question_intent import discovery_topic from tools.knowledge.discovery import follow_up_parts details=follow_up_parts(plan.question) main=discovery_topic(plan.question) @@ -357,7 +357,7 @@ def enforce(query,engine,plan,result,*,index=None,facts=(),complete=None,prose_s # role lines or profile authorship, like metadata; the mechanical check # above already binds every row to its person, work and source. if plan.intent not in {'metadata','supervisor','advisors'} and result.get('evidence'): - from tools.answers.model_client import has_budget, DeadlineExceeded + from tools.answers.generation.model_client import has_budget, DeadlineExceeded audit_seconds=float(os.getenv('ANSWER_AUDIT_MIN_SECONDS','8')) if not has_budget(audit_seconds): state='unverified' diff --git a/tools/answers/reference_links.py b/tools/answers/verification/reference_links.py similarity index 97% rename from tools/answers/reference_links.py rename to tools/answers/verification/reference_links.py index 289266e..3eb4388 100644 --- a/tools/answers/reference_links.py +++ b/tools/answers/verification/reference_links.py @@ -16,7 +16,7 @@ import urllib.error import urllib.parse import urllib.request -from tools.answers.context_policy import text_urls +from tools.answers.verification.context_policy import text_urls class NoRedirect(urllib.request.HTTPRedirectHandler): @@ -114,7 +114,7 @@ def checked_repository_links(result, *, check=None): if not bad: return result if bad & set(sources): - from tools.answers.answer_errors import public_failure + from tools.answers.presentation.answer_errors import public_failure return public_failure({**result, "reason": "reference_unavailable"}) variants = {variant for url in bad for variant in (url, escape(url, quote=False))} diff --git a/tools/answers/verified_rag.py b/tools/answers/verification/verified_rag.py similarity index 98% rename from tools/answers/verified_rag.py rename to tools/answers/verification/verified_rag.py index 5534c76..5e2d39e 100644 --- a/tools/answers/verified_rag.py +++ b/tools/answers/verification/verified_rag.py @@ -9,21 +9,21 @@ from typing import Literal from pydantic import BaseModel, ConfigDict, Field -from tools.answers.context_policy import ( +from tools.answers.verification.context_policy import ( answer_context_issues, citation_check, allowed_urls, normalized, text_urls, ) -from tools.answers.rag_evidence import ( +from tools.answers.evidence.rag_evidence import ( descriptive_text, rag_evidence_context, quote_sections, quote_matches_passage, ) -from tools.answers.answer_coverage import answer_coverage, coverage_notices -from tools.answers.presentation import ( +from tools.answers.evidence.answer_coverage import answer_coverage, coverage_notices +from tools.answers.presentation.presentation import ( content_lines, fact_sentences, no_answer_text, @@ -32,7 +32,7 @@ from tools.answers.presentation import ( evidence_subject, comparison_table, ) -from tools.answers.content_selection import ( +from tools.answers.evidence.content_selection import ( facet_lines, evidence_units, missing_facets, @@ -41,7 +41,7 @@ from tools.answers.content_selection import ( fit_candidates, has_qualification, ) -from tools.answers.evidence_selection import ( +from tools.answers.evidence.evidence_selection import ( resolve_selection, EvidenceSelectionError, missing_required_evidence, @@ -698,7 +698,7 @@ def render_rag_answer(answer: dict, context: dict) -> str: and len(groups) > 1 and re.search(r"\bporovnaj\w*\b", normalized(context.get("question", ""))) ): - from tools.answers.presentation import goal_text + from tools.answers.presentation.presentation import goal_text table = comparison_table( [ @@ -764,7 +764,7 @@ def render_rag_answer(answer: dict, context: dict) -> str: if answer.get("count") is not None: lines.append(f'Počet: {answer["count"]}.') if req.get("content") and not req.get("facets"): - from tools.answers.rag_evidence import missing_content_people + from tools.answers.evidence.rag_evidence import missing_content_people for person in missing_content_people(answer, context): lines.extend( @@ -818,7 +818,7 @@ def _generate_from_context(question, payload, complete, context): "truncation_reasons": [], "index_version": context.get("index_version"), } - from tools.answers.rag_metadata import exact_metadata_answer + from tools.answers.evidence.rag_metadata import exact_metadata_answer exact=exact_metadata_answer(payload,context) if exact is not None:return exact if ( diff --git a/tools/crzp/answering/answer.py b/tools/crzp/answering/answer.py index 9537cb3..f7439e6 100644 --- a/tools/crzp/answering/answer.py +++ b/tools/crzp/answering/answer.py @@ -18,7 +18,7 @@ import threading import time from collections import Counter, OrderedDict -from tools.answers.delivery_contract import fingerprint +from tools.answers.verification.delivery_contract import fingerprint from tools.crzp import fetch from tools.crzp.answering import context from tools.crzp.answering.names import name_variants @@ -479,7 +479,7 @@ CHECK_PROMPT = ("Over, či je každé tvrdenie zhrnutia podložené abstraktom a def _ask(system: str, payload: dict, complete=None, max_tokens: int = 400) -> str | None: - from tools.answers.model_client import complete_with_configured_model + from tools.answers.generation.model_client import complete_with_configured_model try: response = (complete or complete_with_configured_model)( [{"role": "system", "content": system}, {"role": "user", "content": json.dumps(payload, ensure_ascii=False)}], @@ -641,7 +641,7 @@ ROLE_INSTRUMENTAL = {"author": ("Autorom", "Autormi", "Autorkou"), "supervisor": def _relation_sentences(query: CrzpQuery, target: str, rows: list[dict]) -> str: """"Oponentmi habilitačnej práce Daniela Hládka „…“ (2024) boli Roman Jarina, … a Miloš Oravec." One sentence for one work, a short list for a person's few works.""" - from tools.answers.unified import TYPES, CRZP_TYPES, female, genitive, join + from tools.answers.presentation.unified import TYPES, CRZP_TYPES, female, genitive, join person = query.people[0] if query.people else None owner = f" {genitive(display_name(person.name))}" if person and person.role in ("author", "any") else "" diff --git a/tools/crzp/answering/understand.py b/tools/crzp/answering/understand.py index a70e49a..0f51937 100644 --- a/tools/crzp/answering/understand.py +++ b/tools/crzp/answering/understand.py @@ -342,7 +342,7 @@ Názov práce nie je meno osoby. Nepridávaj nič, čo v otázke nie je.""" def _model_fields(question: str, complete=None) -> dict | None: - from tools.answers.model_client import complete_with_configured_model + from tools.answers.generation.model_client import complete_with_configured_model try: response = (complete or complete_with_configured_model)( [{"role": "system", "content": PROMPT}, {"role": "user", "content": question}], max_tokens=300) diff --git a/tools/crzp/answering/wiki_bridge.py b/tools/crzp/answering/wiki_bridge.py index 94c9298..70b4827 100644 --- a/tools/crzp/answering/wiki_bridge.py +++ b/tools/crzp/answering/wiki_bridge.py @@ -14,7 +14,7 @@ def wiki_person(question: str, db_file=None) -> str | None: def wiki_match(question: str, db_file=None) -> dict | None: """{"name", "student"}: the one ZP Wiki person the question names; student = has a profile page.""" - from tools.answers.question_plan import planning_catalog + from tools.answers.planning.question_plan import planning_catalog from tools.rag.common import DB_FILE from tools.retrieval.person_names import resolve_person_names try: diff --git a/tools/graphrag/graph_search.py b/tools/graphrag/graph_search.py index f0217c8..bb73536 100644 --- a/tools/graphrag/graph_search.py +++ b/tools/graphrag/graph_search.py @@ -1788,7 +1788,7 @@ def search_graph_with_session( unsupported = unsupported_constraint(clean_query) spec=None if question_plan is not None: - from tools.answers.question_plan import QuestionPlan + from tools.answers.planning.question_plan import QuestionPlan spec=question_plan if isinstance(question_plan,QuestionPlan) else QuestionPlan.model_validate(question_plan) # The shared planner implements work-year intervals. The legacy raw # search guard must not reject that validated operator before execution. @@ -2074,7 +2074,7 @@ def search_graph_with_session( if question_plan is not None: thesis_rows=[row for row in thesis_rows if spec.matches_work(row.get('person'),row.get('heading'),row.get('thesis_type'),row.get('year'))] work_rows=[row for row in work_rows if spec.matches_work(row.get('person'),row.get('heading'),row.get('work_type'),row.get('year'))] - from tools.answers.question_plan import ambiguous_work_choice + from tools.answers.planning.question_plan import ambiguous_work_choice message=ambiguous_work_choice(spec,[{'person':r.get('person'),'work_label':r.get('heading')} for r in thesis_rows+work_rows]) if message: return {**result_fields(status='ambiguous',sources=[],reason='ambiguous_work',complete=False), diff --git a/tools/graphrag/tests/test_evaluation_v5.py b/tools/graphrag/tests/test_evaluation_v5.py index 9d05a39..eba332f 100644 --- a/tools/graphrag/tests/test_evaluation_v5.py +++ b/tools/graphrag/tests/test_evaluation_v5.py @@ -8,7 +8,7 @@ from tools.graphrag.evaluation.source_oracle import academic_type from tools.graphrag.evaluation.source_validation import validate_returned_facts, claim_issues from tools.graphrag.evaluation.graphrag_evaluator import evaluate_result from tools.graphrag.evaluation.reproducibility import content_fingerprints -from tools.answers.answer_format import parse_answer +from tools.answers.generation.answer_format import parse_answer @pytest.mark.parametrize( diff --git a/tools/graphrag/tests/test_graph_publication.py b/tools/graphrag/tests/test_graph_publication.py index 48b0481..4715a43 100644 --- a/tools/graphrag/tests/test_graph_publication.py +++ b/tools/graphrag/tests/test_graph_publication.py @@ -165,7 +165,7 @@ def test_delivery_limit_uses_actual_cypher_and_keeps_verified_total( ): from tools.answers import answer_delivery as delivery from contextlib import nullcontext - from tools.answers import question_plan + from tools.answers.planning import question_plan monkeypatch.setattr(delivery,'index_snapshot',lambda *a,**kw:nullcontext()) monkeypatch.setattr(question_plan,'planning_catalog',lambda db:[]) @@ -209,7 +209,7 @@ def test_delivery_limit_uses_actual_cypher_and_keeps_verified_total( def test_small_limit_keeps_actual_tag_proof_with_the_same_person(graph, monkeypatch): from tools.answers import answer_delivery as delivery from contextlib import nullcontext - from tools.answers import question_plan + from tools.answers.planning import question_plan monkeypatch.setattr(delivery,'index_snapshot',lambda *a,**kw:nullcontext()) monkeypatch.setattr(question_plan,'planning_catalog',lambda db:[]) diff --git a/tools/knowledge/academic.py b/tools/knowledge/academic.py index ae210a9..2817539 100644 --- a/tools/knowledge/academic.py +++ b/tools/knowledge/academic.py @@ -10,7 +10,7 @@ from __future__ import annotations from collections import defaultdict import re -from tools.answers.context_policy import normalized +from tools.answers.verification.context_policy import normalized from tools.knowledge.sources import advisor_name @@ -129,7 +129,7 @@ def completion_event(unit): return None scope = "studies" if study else "work" if work else "unspecified" if scope == "work": - from tools.answers.rag_evidence import academic_scope + from tools.answers.evidence.rag_evidence import academic_scope mentioned = academic_scope(unit["text"]) if mentioned and unit.get("work_type") and mentioned[0] != unit["work_type"]: @@ -264,7 +264,7 @@ def answer_academic(question, index, *, engine, limit=5, units=None, mode=None, status="ambiguous", reason="ambiguous_advisor_filter", ) - from tools.answers.rag_evidence import requested_types + from tools.answers.evidence.rag_evidence import requested_types types = requested_types(resolved, [m["name"] for m in students]) # Ordinary wording of the same work-type constraint must not silently @@ -287,7 +287,7 @@ def answer_academic(question, index, *, engine, limit=5, units=None, mode=None, types = {m["name"]: next(iter(informal)) for m in students} global_types = set(types.values()) if not students: - from tools.answers.rag_evidence import work_type + from tools.answers.evidence.rag_evidence import work_type kind = work_type(resolved) if kind: @@ -497,11 +497,11 @@ def answer_academic(question, index, *, engine, limit=5, units=None, mode=None, and r["kind"] not in {"meeting", "work_record", "reference", "supervisor", "consultant"} ] - from tools.answers.content_selection import unit_score + from tools.answers.evidence.content_selection import unit_score notes = [r for r in notes if not r["text"].rstrip().endswith(":")] if plan and plan.spec.facets and plan.spec.answer_mode!='comparison': - from tools.answers.content_selection import facets_for + from tools.answers.evidence.content_selection import facets_for notes=[r for r in notes if set(plan.spec.facets)&set(facets_for(r['text'], {'assignment':'assignment','planned':'task','result':'progress','progress':'progress'}.get(r['phase'],'other'), plan.spec.question,r['phase']))] @@ -524,8 +524,8 @@ def answer_academic(question, index, *, engine, limit=5, units=None, mode=None, selected.extend(r for r in notes if r not in selected) notes = selected if plan and plan.spec.facets: - from tools.answers.content_selection import facets_for - from tools.answers.question_intent import FACET_LABELS + from tools.answers.evidence.content_selection import facets_for + from tools.answers.planning.question_intent import FACET_LABELS found={f for r in notes for f in facets_for(r['text'], {'assignment':'assignment','planned':'task','result':'progress','progress':'progress'}.get(r['phase'],'other'), plan.spec.question,r['phase'])} @@ -688,7 +688,7 @@ def completion_rows(spec, index): A question about the state of a work must not omit that it ended. Only a literal source statement of the same profile and work is used. """ - from tools.answers.context_policy import normalized as _norm + from tools.answers.verification.context_policy import normalized as _norm if spec.intent not in {"facets", "progress"} or not STATUS_QUESTION.search(_norm(spec.question)): return [] if spec.period and spec.period.field != "work_year": diff --git a/tools/knowledge/activities.py b/tools/knowledge/activities.py index 85fa8b6..53e65ed 100644 --- a/tools/knowledge/activities.py +++ b/tools/knowledge/activities.py @@ -32,7 +32,7 @@ from typing import Literal from pydantic import BaseModel, ConfigDict, Field, ValidationError -from tools.answers.context_policy import normalized +from tools.answers.verification.context_policy import normalized from tools.knowledge.evidence import claim_eligible ACTIVITY_SCHEMA = 1 @@ -333,7 +333,7 @@ def _lenient_item(item) -> ExtractedItem | None: def extract_batch(batch: list[dict], complete) -> dict[str, list[dict]]: - from tools.answers.synthesis import FORMAT_LINE + from tools.answers.generation.synthesis import FORMAT_LINE aliases = {f"U{i}": unit for i, unit in enumerate(batch, 1)} payload = {"units": [{"id": alias, "phase": unit.get("phase"), "work": unit.get("work_label"), "text": unit["text"][:1500]} for alias, unit in aliases.items()]} @@ -437,7 +437,7 @@ def _embed(texts: list[str]): def confirm_pairs(pairs: list[tuple[str, str]], complete, *, workers=2, cache_path: Path | None = None) -> list[tuple[str, str]]: """Model decisions "same concept?" for name pairs; decisions are cached.""" from concurrent.futures import ThreadPoolExecutor - from tools.answers.synthesis import FORMAT_LINE + from tools.answers.generation.synthesis import FORMAT_LINE known = {} if cache_path is not None and cache_path.exists(): for line in cache_path.read_text(encoding="utf-8").splitlines(): @@ -825,7 +825,7 @@ class ActivityGraph: key = (normalized(asked or ""), canonical or "", tuple(sorted(candidates))) if key in self.selected: return self.selected[key] - from tools.answers.synthesis import FORMAT_LINE + from tools.answers.generation.synthesis import FORMAT_LINE ids = {f"C{i}": gid for i, gid in enumerate(candidates, 1)} payload = {"asked_topic": asked, "asked_topic_english": canonical, "candidates": [{"id": cid, "name": self.concepts[g]["label"], @@ -833,7 +833,7 @@ class ActivityGraph: messages = [{"role": "system", "content": FORMAT_LINE + "\n" + SELECT_PROMPT}, {"role": "user", "content": json.dumps(payload, ensure_ascii=False)}] try: - from tools.answers.model_client import complete_with_configured_model + from tools.answers.generation.model_client import complete_with_configured_model if complete is complete_with_configured_model: response = complete(messages, max_tokens=60 + 14 * len(ids)) else: @@ -909,7 +909,7 @@ def topic_of_question(question: str) -> str | None: """Fallback topic when no catalog parameter is available: the main clause of the question minus its interrogative, verbs, follow-ups and generic words.""" from tools.knowledge.query import _terms - from tools.answers.question_intent import discovery_topic + from tools.answers.planning.question_intent import discovery_topic from tools.knowledge.discovery import follow_up_parts main = discovery_topic(question) for detail in follow_up_parts(question): diff --git a/tools/knowledge/build.py b/tools/knowledge/build.py index 6bfb586..f970f56 100644 --- a/tools/knowledge/build.py +++ b/tools/knowledge/build.py @@ -339,7 +339,7 @@ def embedding_index(units: list[dict], data_dir: Path) -> dict: def configured_extractor(): from functools import partial - from tools.answers.model_client import complete_with_configured_model + from tools.answers.generation.model_client import complete_with_configured_model provider = os.getenv("ANSWER_PROVIDER", "openai_compatible") legacy = bool(os.getenv("OPENWEBUI_API_KEY")) diff --git a/tools/knowledge/concepts.py b/tools/knowledge/concepts.py index 213698b..da7d175 100644 --- a/tools/knowledge/concepts.py +++ b/tools/knowledge/concepts.py @@ -1,6 +1,6 @@ """Curated equivalents, never arbitrary related tasks or inferred relations.""" import re -from tools.answers.context_policy import normalized +from tools.answers.verification.context_policy import normalized def concept_key(text: str) -> str: diff --git a/tools/knowledge/discovery.py b/tools/knowledge/discovery.py index 7986c50..0ab896a 100644 --- a/tools/knowledge/discovery.py +++ b/tools/knowledge/discovery.py @@ -11,7 +11,7 @@ import re from pydantic import BaseModel, ConfigDict, Field, field_validator from tools.knowledge.evidence import claim_eligible -from tools.answers.content_selection import administrative_only +from tools.answers.evidence.content_selection import administrative_only class Part(BaseModel): @@ -158,7 +158,7 @@ _MASCULINE_A = {'nikola', 'nikita', 'luka', 'ilja', 'sasha', 'sasa', 'misha', 'k def grammatical_gender(name): """Verb agreement for Slovak wording; a hint only, the audit still checks.""" - from tools.answers.context_policy import normalized + from tools.answers.verification.context_policy import normalized tokens = name.casefold().split() if not tokens: return 'unknown' @@ -309,9 +309,9 @@ def expand_and_select(question, seeds, pool, complete, *, limit=5, plan=None, kn decision sees the whole scope). Such a student is added only by a positive decision of this step with evidence from the same scope. """ - from tools.answers.synthesis import _call, SynthesisRejected - from tools.answers.question_intent import discovery_topic - from tools.answers.model_client import (parallel_map, has_budget, reserved_budget, DeadlineExceeded, + from tools.answers.generation.synthesis import _call, SynthesisRejected + from tools.answers.planning.question_intent import discovery_topic + from tools.answers.generation.model_client import (parallel_map, has_budget, reserved_budget, DeadlineExceeded, call_floor, model_busy, remaining_seconds) from tools.knowledge.query import _terms, ContentAnswerRejected, ContentModelUnavailable @@ -545,8 +545,8 @@ _SECOND_PERSON = re.compile(r"\b(?:ty|tvoj\w*|\w+(?:aš|áš|eš|éš|íš|ieš| def _checked_wording(row,text,plan,known_people): """The sentence, if it passes the same local guards as synthesized prose.""" - from tools.answers.synthesis import Draft, ProseClaim, SynthesisRejected, validate_draft, ACHIEVED - from tools.answers.context_policy import normalized + from tools.answers.generation.synthesis import Draft, ProseClaim, SynthesisRejected, validate_draft, ACHIEVED + from tools.answers.verification.context_policy import normalized wording=normalized(text) source=normalized(row['text']) if any(match[:5] not in source for match in ACHIEVED.findall(wording)): @@ -618,8 +618,8 @@ def rephrase(rows,complete,plan,known_people): sentences). Every sentence passes the local guards and later the final audit; otherwise the verbatim line is shown. Failures only drop wording. """ - from tools.answers.synthesis import _call - from tools.answers.model_client import parallel_map, call_floor + from tools.answers.generation.synthesis import _call + from tools.answers.generation.model_client import parallel_map, call_floor units={f'U{i}':row for i,row in enumerate(rows,1)} items=[{'id':key,'phase':row['phase'],'student_gender':grammatical_gender(row['person']),'text':row['text']} for key,row in units.items()] diff --git a/tools/knowledge/evidence.py b/tools/knowledge/evidence.py index 84db06e..6226d41 100644 --- a/tools/knowledge/evidence.py +++ b/tools/knowledge/evidence.py @@ -6,7 +6,7 @@ import re from typing import Literal from pydantic import BaseModel, ConfigDict, Field, model_validator -from tools.answers.context_policy import normalized +from tools.answers.verification.context_policy import normalized from tools.retrieval.person_names import name_token_variants, normalize EXTRACTION_SCHEMA = 2 diff --git a/tools/knowledge/extraction.py b/tools/knowledge/extraction.py index 5daf0e7..03a9067 100644 --- a/tools/knowledge/extraction.py +++ b/tools/knowledge/extraction.py @@ -5,7 +5,7 @@ import json import re from typing import Literal from pydantic import BaseModel, ConfigDict, Field, ValidationError -from tools.answers.context_policy import normalized +from tools.answers.verification.context_policy import normalized from tools.knowledge.sources import identifier from tools.knowledge.evidence import EXTRACTION_POLICY, claim_eligible, relation_has_local_support diff --git a/tools/knowledge/graph_answers.py b/tools/knowledge/graph_answers.py index 9f0d5e1..212b8ec 100644 --- a/tools/knowledge/graph_answers.py +++ b/tools/knowledge/graph_answers.py @@ -1,8 +1,8 @@ """Render witnessed graph paths; an ABOUT edge never means 'used' or 'finished'.""" from collections import defaultdict -from tools.answers.answer_errors import clarification_result -from tools.answers.context_policy import citation_check, text_urls +from tools.answers.presentation.answer_errors import clarification_result +from tools.answers.verification.context_policy import citation_check, text_urls from tools.knowledge.concepts import concept_key PHASES={'result':'zaznamenaný výsledok','progress':'priebežný stav', diff --git a/tools/knowledge/local_graph.py b/tools/knowledge/local_graph.py index 4e70c26..d10d2f0 100644 --- a/tools/knowledge/local_graph.py +++ b/tools/knowledge/local_graph.py @@ -10,7 +10,7 @@ from tools.knowledge import store from tools.knowledge.concepts import concept_key, substantive_concept from tools.knowledge.evidence import claim_eligible, relation_has_local_support from tools.graphrag.graph_db import create_neo4j_driver, get_neo4j_settings -from tools.answers.context_policy import normalized +from tools.answers.verification.context_policy import normalized TIMEOUT = 8 SEED_LIMIT = 32 @@ -122,8 +122,8 @@ def validated_row(record, by_id): def seed_ids(question, index, spec): """Classical retrieval proposes entry points; Neo4j must prove every path.""" from tools.knowledge.query import _terms, activity_supported, concept_families - from tools.answers.content_selection import administrative_only - from tools.answers.question_intent import discovery_topic + from tools.answers.evidence.content_selection import administrative_only + from tools.answers.planning.question_intent import discovery_topic if spec.intent=='discovery':question=discovery_topic(question) terms = _terms(question); families = concept_families(question) candidates = [u for u in index['units'] if u.get('work_id') and claim_eligible(u) diff --git a/tools/knowledge/planned_answers.py b/tools/knowledge/planned_answers.py index 29d9257..b386def 100644 --- a/tools/knowledge/planned_answers.py +++ b/tools/knowledge/planned_answers.py @@ -2,10 +2,10 @@ from collections import defaultdict import re -from tools.answers.answer_errors import clarification_result -from tools.answers.context_policy import normalized -from tools.answers.question_intent import FACET_LABELS -from tools.answers.content_selection import facets_for, unit_score +from tools.answers.presentation.answer_errors import clarification_result +from tools.answers.verification.context_policy import normalized +from tools.answers.planning.question_intent import FACET_LABELS +from tools.answers.evidence.content_selection import facets_for, unit_score from tools.knowledge.evidence import claim_eligible @@ -18,7 +18,7 @@ TOOL_NOUNS = {'server','model','modely','modelu','dataset','datasety','databaza' def _tool_concept(concept): """"MCP server", "Fast120 (Qwen3.5)", "AYA collection dataset" — not "prístup na HPC" or a URL.""" - from tools.answers.content_selection import named_tools + from tools.answers.evidence.content_selection import named_tools if re.search(r'https?:|/|\.[a-z]{2,4}\b',concept) or len(concept.split())>4:return False tools={normalized(t) for t in named_tools(concept)}-NOT_TOOLS words=[w for w in normalized(concept).split()] @@ -34,7 +34,7 @@ READING = re.compile(r'\b(?:prestudova\w*|precita\w*|nastudova\w*|studuj\w*|zist def methods_sentence(person, label, rows, candidates): """"Ján Pták vo svojej diplomovej práci „Agent…“ využíva: RAG, MCP server, …" from the tools and methods the cited records name (concepts of those records, named tools, method phrases).""" - from tools.answers.content_selection import named_tools + from tools.answers.evidence.content_selection import named_tools found=[];starting=set();used=set();going=set() for row in candidates: text=re.sub(r'https?://\S+','',re.sub(r'^\s*(?:[-*+]\s+|\d+[.)]\s+)','',row['text'])) @@ -89,7 +89,7 @@ def answer_facets(bound, index, units, *, engine, limit): actual=row.get(period.field) if not actual or not period.start<=actual<=period.end:continue groups[(row['person'],row['work_label'])].append(row) - from tools.answers.question_plan import ambiguous_work_choice + from tools.answers.planning.question_plan import ambiguous_work_choice message=ambiguous_work_choice(plan,[{'person':p,'work_label':label} for p,label in groups]) if message:return clarify('ambiguous_work',message) for person in people: @@ -106,7 +106,7 @@ def answer_facets(bound, index, units, *, engine, limit): keys=[part[i] for i in range(max((len(v) for v in by_person.values()),default=0)) for part in by_person.values() if i str | None: r"\b(?:obdob\w*|medzi|od roku|do roku)\b", text ): return "period" - from tools.answers.question_intent import discovery_question + from tools.answers.planning.question_intent import discovery_question if discovery_question(question): return "discovery" return None @@ -342,7 +342,7 @@ def answer_from_index( text = "\n".join(notices) + ("\n\n" if notices else "") + answer if urls: text += "\n\nZdroje: " + ", ".join(urls) - from tools.answers.context_policy import citation_check, text_urls + from tools.answers.verification.context_policy import citation_check, text_urls allowed = set(urls) for row in evidence: @@ -460,7 +460,7 @@ def answer_from_index( if selection.labels or selection.numbers: if not selection.matches(row.get("work_label") or ""): return False - from tools.answers.rag_evidence import requested_types + from tools.answers.evidence.rag_evidence import requested_types kinds = requested_types(resolved, [row["person"]]) if kinds.get(row["person"]) and kinds[row["person"]] != row.get("work_type"): @@ -496,7 +496,7 @@ def answer_from_index( seen_ids = {r["id"] for r in candidates} candidates += [r for r in index["units"] if r["kind"] == "supervisor" and r["id"] not in seen_ids and claim_eligible(r) and scoped(r) and not reference_only(r["text"])] - from tools.answers.context_policy import text_contains_value + from tools.answers.verification.context_policy import text_contains_value names = {p.name for p in plan.spec.people if p.role=="supervisor"} if plan else people & supervisor_names if len(names) != 1: @@ -670,7 +670,7 @@ def answer_from_index( and not administrative_only(r["text"]) ] elif mode == "discovery": - from tools.answers.question_intent import discovery_topic + from tools.answers.planning.question_intent import discovery_topic absent = re.search(r"\bne(?:pouziva|vyuziva|pouzi|vyuzi|robi|pracova|skusa)\w*\s+(.{2,40}?)(?:[?.!,]|$)", normalized(question)) if absent and not (plan and any(c.kind == "exclusion" for c in plan.spec.conditions)): @@ -734,7 +734,7 @@ def answer_from_index( "nie je dôkazom nepoužitia.") excluded_terms = [] # already applied by the graph if complete: - from tools.answers.model_client import has_budget, model_busy + from tools.answers.generation.model_client import has_budget, model_busy from tools.knowledge.discovery import rephrase, REPHRASE_SECONDS, REPHRASE_UNITS first = {} for row in filtered: @@ -963,8 +963,8 @@ def answer_from_index( group.sort(key=lambda r: (r.get("date") or "", r["line"]), reverse=True) chosen = group[:5] if mode == "discovery" else group[:8] if mode == "progress": - from tools.answers.content_selection import unit_score - from tools.answers.question_intent import requested_facets, FACET_LABELS + from tools.answers.evidence.content_selection import unit_score + from tools.answers.planning.question_intent import requested_facets, FACET_LABELS def priority(r): return ( @@ -1049,7 +1049,7 @@ def answer_from_index( ) quote = re.sub(r"^\s*(?:[-*+]|\d+[.)])\s+", "", row["text"]) if row["phase"] in {"assignment", "planned"}: - from tools.answers.presentation import goal_text + from tools.answers.presentation.presentation import goal_text quote = goal_text(quote)[0] lines.append(f"- {prefix}: {quote}") @@ -1309,7 +1309,7 @@ def _deliver_content(question: str, *, engine: str, limit: int, db_file, complet index = load_index(db_file.parent, current_version) if index is None: if mode: - from tools.answers.answer_errors import public_failure + from tools.answers.presentation.answer_errors import public_failure return public_failure({"reason": "content_index_unavailable", "engine": engine}) return None @@ -1367,7 +1367,7 @@ def _deliver_content(question: str, *, engine: str, limit: int, db_file, complet from tools.knowledge.graph_answers import render_similarity return traced(render_similarity(question,index,plan,local,limit=limit,complete=complete)) if mode=='proposal' and plan: - from tools.answers.recommendations import collect_evidence + from tools.answers.generation.recommendations import collect_evidence result=collect_evidence(plan,index,units,engine=engine,limit=limit) if local is not None: from tools.knowledge.graph_answers import graph_details @@ -1462,7 +1462,7 @@ def _deliver_content(question: str, *, engine: str, limit: int, db_file, complet def needs_intent_model(question): - from tools.answers.question_intent import content_question + from tools.answers.planning.question_intent import content_question text = normalized(question) if len(text.split()) < 5: diff --git a/tools/knowledge/roster.py b/tools/knowledge/roster.py index d7888dc..af75941 100644 --- a/tools/knowledge/roster.py +++ b/tools/knowledge/roster.py @@ -9,9 +9,9 @@ from __future__ import annotations from collections import defaultdict import re -from tools.answers.context_policy import normalized +from tools.answers.verification.context_policy import normalized from tools.knowledge.evidence import claim_eligible -from tools.answers.content_selection import administrative_only +from tools.answers.evidence.content_selection import administrative_only MAX_WORKS = 40 _RANK = {"topic": 0, "assignment": 1} diff --git a/tools/knowledge/sources.py b/tools/knowledge/sources.py index 5e2c2ad..0ea4444 100644 --- a/tools/knowledge/sources.py +++ b/tools/knowledge/sources.py @@ -13,9 +13,9 @@ import re from tools.rag.common import clean_heading_text from tools.rag.search_core import make_source_url -from tools.answers.context_policy import normalized -from tools.answers.rag_evidence import academic_scope -from tools.answers.content_selection import effective_role, evidence_phase, reference_only +from tools.answers.verification.context_policy import normalized +from tools.answers.evidence.rag_evidence import academic_scope +from tools.answers.evidence.content_selection import effective_role, evidence_phase, reference_only from tools.knowledge.evidence import actor_binding, temporal_fields, EvidenceAssertion, EXTRACTION_SCHEMA, claim_eligible PROFILE = re.compile(r"(?:pages/)?students/\d{4}/[^/]+/README\.md$") diff --git a/tools/knowledge/store.py b/tools/knowledge/store.py index 2210c78..e7d6faa 100644 --- a/tools/knowledge/store.py +++ b/tools/knowledge/store.py @@ -6,7 +6,7 @@ import json from pathlib import Path from tools.knowledge.sources import identifier from tools.graphrag.graph_db import create_neo4j_driver, get_neo4j_settings -from tools.answers.context_policy import normalized +from tools.answers.verification.context_policy import normalized from tools.knowledge.concepts import concept_key SCOPE = "zpwiki-content-v1" diff --git a/tools/knowledge/text_retrieval.py b/tools/knowledge/text_retrieval.py index bb27c3d..3803159 100644 --- a/tools/knowledge/text_retrieval.py +++ b/tools/knowledge/text_retrieval.py @@ -10,7 +10,7 @@ import sqlite3 import threading import zlib -from tools.answers.context_policy import normalized +from tools.answers.verification.context_policy import normalized _lock = threading.RLock() @@ -41,7 +41,7 @@ def _unit_lemmas(index, data_dir): def retrieve_units(question, index, spec, *, limit=5, data_dir=None): from tools.knowledge.query import _terms from tools.knowledge.evidence import claim_eligible - from tools.answers.question_intent import discovery_topic + from tools.answers.planning.question_intent import discovery_topic search_question=discovery_topic(question) if spec.intent=='discovery' else question people={p.name for p in spec.people if p.role=='student'} similar=spec.intent=='similar' diff --git a/tools/rag/rag_utils.py b/tools/rag/rag_utils.py index cdb2534..75c6499 100644 --- a/tools/rag/rag_utils.py +++ b/tools/rag/rag_utils.py @@ -763,7 +763,7 @@ def build_rag_context( # Expansions are candidates too: they must not restore another work/year # that was excluded before the BM25/vector candidate budgets. if db_path.exists(): - from tools.answers.question_plan import build_question_plan, QuestionPlan + from tools.answers.planning.question_plan import build_question_plan, QuestionPlan from tools.rag.search_scope import SearchScope spec = (question_plan if isinstance(question_plan, QuestionPlan) else QuestionPlan.model_validate(question_plan)) if question_plan is not None else build_question_plan(query, catalog).spec diff --git a/tools/rag/search_scope.py b/tools/rag/search_scope.py index 65024c5..8abe62d 100644 --- a/tools/rag/search_scope.py +++ b/tools/rag/search_scope.py @@ -4,9 +4,9 @@ from __future__ import annotations from dataclasses import dataclass import json -from tools.answers.question_plan import QuestionPlan, build_question_plan -from tools.answers.rag_evidence import academic_windows_metadata -from tools.answers.context_policy import normalized +from tools.answers.planning.question_plan import QuestionPlan, build_question_plan +from tools.answers.evidence.rag_evidence import academic_windows_metadata +from tools.answers.verification.context_policy import normalized from tools.retrieval.person_names import sqlite_people from tools.retrieval.retrieval_contract import result_fields diff --git a/tools/rag/tests/test_hybrid_candidates.py b/tools/rag/tests/test_hybrid_candidates.py index 44bf5d7..4ea9142 100644 --- a/tools/rag/tests/test_hybrid_candidates.py +++ b/tools/rag/tests/test_hybrid_candidates.py @@ -11,7 +11,7 @@ try: # evaluation code lives locally in local/evaluation, outside the repositor except ImportError: retrieve_all_modes = None from tools.rag.search_scope import SearchScope -from tools.answers.question_plan import build_question_plan +from tools.answers.planning.question_plan import build_question_plan EVA = 'pages/students/2022/eva_nova/README.md' ADAM = 'pages/students/2022/adam_stary/README.md' @@ -147,8 +147,8 @@ def test_query_grammar_is_not_an_unknown_person(corpus,q): ('Kto sa venoval rozpoznávaniu pomenovaných entít?', 'Anotoval pomenované entity v korpuse.'), ]) def test_related_tasks_are_rejected_by_the_final_rag_guard(question, quote): - from tools.answers.rag_evidence import rag_evidence_context - from tools.answers.verified_rag import rag_answer_issues + from tools.answers.evidence.rag_evidence import rag_evidence_context + from tools.answers.verification.verified_rag import rag_answer_issues from tools.rag.rag_utils import build_context_text sources = [{'source_id': 'S1', 'title': 'Príklad', 'document_path': 'pages/topics/example/README.md', 'source_url': 'https://example.test/source', 'text': quote}] diff --git a/tools/retrieval/lemmatize.py b/tools/retrieval/lemmatize.py index 6e36e25..e402c80 100644 --- a/tools/retrieval/lemmatize.py +++ b/tools/retrieval/lemmatize.py @@ -22,7 +22,7 @@ from contextlib import closing from functools import lru_cache from pathlib import Path -from tools.answers.context_policy import normalized +from tools.answers.verification.context_policy import normalized LEMMA_VERSION = "stanza-sk-1" _lock = threading.Lock() diff --git a/tools/retrieval/synonyms.py b/tools/retrieval/synonyms.py index 71b3bf2..1005f8b 100644 --- a/tools/retrieval/synonyms.py +++ b/tools/retrieval/synonyms.py @@ -10,7 +10,7 @@ from __future__ import annotations import re from functools import lru_cache -from tools.answers.context_policy import normalized +from tools.answers.verification.context_policy import normalized GROUPS = [ ["rozpoznávanie reči", "speech recognition", "ASR", "automatické rozpoznávanie reči", "prepis reči", "speech to text"], diff --git a/tools/runtime/answer_health.py b/tools/runtime/answer_health.py index 7e95ba1..083a16a 100644 --- a/tools/runtime/answer_health.py +++ b/tools/runtime/answer_health.py @@ -8,7 +8,7 @@ from pathlib import Path from neo4j import Query -from tools.answers.model_client import generation_status +from tools.answers.generation.model_client import generation_status from tools.graphrag.graph_db import create_neo4j_driver, get_neo4j_settings from tools.knowledge.publication import read_state, state_matches_graph from tools.knowledge.store import SCOPE