nová štruktúra
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
a9fbd1c81e
commit
4ef7686a82
@ -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.
|
||||
|
||||
@ -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()
|
||||
|
||||
|
||||
|
||||
@ -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)))
|
||||
|
||||
@ -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)
|
||||
|
||||
@ -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
|
||||
@ -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:
|
||||
@ -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
|
||||
@ -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')
|
||||
@ -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é",
|
||||
@ -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)
|
||||
|
||||
@ -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')
|
||||
|
||||
|
||||
@ -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))
|
||||
@ -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)
|
||||
@ -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
|
||||
@ -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))
|
||||
|
||||
|
||||
@ -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']
|
||||
@ -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)
|
||||
@ -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")
|
||||
@ -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)
|
||||
@ -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'
|
||||
@ -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",
|
||||
@ -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
|
||||
@ -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)
|
||||
@ -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)
|
||||
@ -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
|
||||
@ -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):
|
||||
@ -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
|
||||
|
||||
@ -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
|
||||
|
||||
@ -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")
|
||||
@ -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
|
||||
@ -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"]
|
||||
@ -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
|
||||
|
||||
@ -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
|
||||
@ -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))
|
||||
@ -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"] = (
|
||||
@ -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
|
||||
|
||||
@ -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: {})
|
||||
@ -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á?"
|
||||
@ -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
|
||||
@ -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"
|
||||
@ -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"])
|
||||
@ -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})
|
||||
@ -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)
|
||||
@ -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
|
||||
|
||||
@ -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')
|
||||
@ -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
|
||||
|
||||
|
||||
@ -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'
|
||||
@ -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=[]
|
||||
@ -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)
|
||||
@ -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
|
||||
@ -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
|
||||
|
||||
@ -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)
|
||||
|
||||
1
tools/answers/evidence/__init__.py
Normal file
1
tools/answers/evidence/__init__.py
Normal file
@ -0,0 +1 @@
|
||||
"""Selecting the source evidence an answer may use (RAG text, graph facts, excerpts, coverage)."""
|
||||
@ -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"
|
||||
@ -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,
|
||||
@ -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 = []
|
||||
@ -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):
|
||||
@ -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, "")
|
||||
@ -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):
|
||||
@ -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(
|
||||
1
tools/answers/generation/__init__.py
Normal file
1
tools/answers/generation/__init__.py
Normal file
@ -0,0 +1 @@
|
||||
"""Text written by the model from supplied evidence, and the model client."""
|
||||
@ -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:
|
||||
@ -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
|
||||
@ -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],
|
||||
1
tools/answers/planning/__init__.py
Normal file
1
tools/answers/planning/__init__.py
Normal file
@ -0,0 +1 @@
|
||||
"""Understanding the question: the typed plan, the question catalog, aspects and conversation references."""
|
||||
@ -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")
|
||||
@ -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
|
||||
@ -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:
|
||||
@ -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",
|
||||
@ -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)}]
|
||||
1
tools/answers/presentation/__init__.py
Normal file
1
tools/answers/presentation/__init__.py
Normal file
@ -0,0 +1 @@
|
||||
"""How an answer reads: templates, rendering, final wording, one answer from both sources, names."""
|
||||
@ -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)
|
||||
@ -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',
|
||||
@ -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",
|
||||
@ -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:
|
||||
@ -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)
|
||||
|
||||
|
||||
1
tools/answers/verification/__init__.py
Normal file
1
tools/answers/verification/__init__.py
Normal file
@ -0,0 +1 @@
|
||||
"""Checks before an answer is delivered: contract, guards, verified RAG, repository links."""
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user