From db671f15bac57799a7c2917b5e80b9be950385cf Mon Sep 17 00:00:00 2001 From: jp170na Date: Thu, 19 Nov 2026 06:07:04 +0100 Subject: [PATCH] =?UTF-8?q?men=C3=A1=20a=20pam=C3=A4=C5=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- README.md | 18 +- conftest.py | 3 + test/presentation/test_combined_answers.py | 101 +++++++ test/presentation/test_conversation_store.py | 151 ++++++++++ test/presentation/test_unified_answers.py | 5 + tools/answers/combined.py | 298 +++++++++++++++++-- tools/answers/context_store.py | 149 ++++++++++ tools/answers/pages.py | 4 +- tools/crzp/answering/answer.py | 76 ++++- tools/crzp/answering/names.py | 71 +++++ tools/crzp/answering/understand.py | 1 + tools/crzp/tests/test_crzp.py | 47 +++ 12 files changed, 890 insertions(+), 34 deletions(-) create mode 100644 test/presentation/test_conversation_store.py create mode 100644 tools/answers/context_store.py diff --git a/README.md b/README.md index ef10a13..f563ec5 100644 --- a/README.md +++ b/README.md @@ -57,8 +57,20 @@ s osobami a témami ZP Wiki (`PROBABLY_SAME`, `SAME_TOPIC`). - Jedna odpoveď: zoznam ľudí je jeden očíslovaný zoznam (najprv ZP Wiki, potom CRZP, s označením zdroja), zdroje sú v jednom riadku na konci. - Dlhý zoznam ukáže 6 položiek a opýta sa „Chceš vidieť ďalšie?“; odpoveď „áno“ ukáže ďalšie. -- Doplňujúce otázky cez podpísaný token: „a z akých škôl sú?“, „a čo robil prvý z nich?“, - výber práce („2“, „tak 1“, „bakalársku“), výber menovca a „a o čom je?“. +- Doplňujúce otázky cez krátky podpísaný token (`zc3..`, asi 40 znakov): „a z akých + škôl sú?“, „a čo robil prvý z nich?“, výber práce („2“, „tak 1“, „bakalársku“), výber menovca, + „a o čom je?“. Kontext krokov konverzácie je na serveri (`tools/answers/context_store.py`, + `data/conversation_pages.sqlite`), preto odkaz môže siahnuť aj na staršiu otázku („a čo robil + druhý z nich?“ o niekoľko otázok neskôr, „vráť sa k otázke o GraphRAG, …“). Nepoužitá konverzácia + sa zmaže po `ANSWER_CONTEXT_DAYS` (7) dňoch, nad `ANSWER_CONTEXT_MAX_MB` (50) najmenej používané; + `ANSWER_CONTEXT_STORE=0` vráti dlhý token `zc2`. +- Keď odpovedá len CRZP (osoba mimo ZP Wiki, obhájené práce pracoviska, „v CRZP“) alebo ZP Wiki + nemá čo dať, odpoveď počká na CRZP do `CRZP_WAIT_SECONDS` (80 s od začiatku otázky, pod limitom + MCP klienta 90 s); inak povie, že hľadanie ešte prebieha (`crzp_pending`), a zopakovaná otázka + dostane výsledok z toho istého hľadania. +- Meno osoby z otázky sa v CRZP hľadá v základnom tvare od modelu, potom v pravidlovom tvare + („Samuela Furdy“ → „Samuel Furda“), s celým menom prezývky („Samo“ → „Samuel“) a nakoniec + len podľa priezviska s kontrolou krstného mena. - Súvisiace témy: téma, kto ju robil v ZP Wiki a koľko prác je v CRZP (vážené podľa toho, ako špecifický je pojem); podobné práce: najšpecifickejšie spoločné pojmy v základnom tvare. - Čas každej odpovede (kroky, počet a typ volaní modelu, bez textu otázky) sa zapisuje do @@ -97,7 +109,7 @@ 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/` – odpoveď: `answer_delivery.py` (ZP Wiki), `combined.py` (ZP Wiki + CRZP), `pages.py`, `timing.py`; +- `tools/answers/` – odpoveď: `answer_delivery.py` (ZP Wiki), `combined.py` (ZP Wiki + CRZP), `context_store.py`, `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. diff --git a/conftest.py b/conftest.py index ee5d4d8..11a095c 100644 --- a/conftest.py +++ b/conftest.py @@ -14,6 +14,9 @@ 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/presentation/names.py enable it +# Conversation steps and paged lists of tests go to a temporary file, not to data/. +import tempfile +os.environ.setdefault("ANSWER_CONTEXT_FILE", os.path.join(tempfile.mkdtemp(prefix="zp-context-"), "conversation_pages.sqlite")) # 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. diff --git a/test/presentation/test_combined_answers.py b/test/presentation/test_combined_answers.py index d310a98..3bc1662 100644 --- a/test/presentation/test_combined_answers.py +++ b/test/presentation/test_combined_answers.py @@ -331,3 +331,104 @@ def test_a_short_follow_up_about_another_person_repeats_the_previous_question(mo assert C.ellipsis("a Jan Ptak?", {"question": "Kto je vedúci práce Jakuba Schwarca?"}) == "Kto je vedúci práce Ján Pták?" assert C.ellipsis("a čo výsledky?", {"question": "Kto je vedúci práce Jakuba Schwarca?"}) is None assert C.ellipsis("Kto je Jan Ptak?", {"question": "Kto je vedúci práce Jakuba Schwarca?"}) is None + + +NO_WIKI = {"status": "no_answer", "reason": "unknown_person", "accepted_for_delivery": True, "claims": [], + "index_version": {"version": "v"}, "complete": True, "truncated": False, "truncation_reasons": [], + "answer": "Osobu „Samuela Furdy“ som v ZP Wiki nenašiel. Skontroluj meno alebo uveď celé meno študenta či vedúceho.", + "source_urls": [], "delivery_check": {"layer": "retrieval", "code": "evidence_not_found", "request_fingerprint": "x"}} +CRZP_ANSWER = {"mode": "explicit", "status": "ok", "text": "Vedúcim bakalárskej práce Samuela Furdy „Detekcia“ (2025) bol Peter Novák.", + "rows": [], "urls": ["https://opac.test/9"], "crzp_token": None, "entities": []} + + +def slow_crzp(seconds, part=None, mode="explicit", calls=None, release=None): + """A CRZP part that tells its plan at once and answers after `seconds` (or when `release` is set).""" + def run(q, person, complete=None, student=True): + if calls is not None: + calls.append(q) + probe = C._probe.get() + if probe is not None: + probe["mode"] = mode + if release is not None: + release.wait(seconds) + else: + time.sleep(seconds) + return part + return run + + +def test_a_question_only_crzp_can_answer_waits_for_a_slow_crzp(combo, monkeypatch): + monkeypatch.setattr(C, "CRZP_SECONDS", 0.2) + monkeypatch.setattr(C, "CRZP_WAIT_SECONDS", 5) + monkeypatch.setattr(C, "crzp_part", slow_crzp(0.8, dict(CRZP_ANSWER))) + combo["match"], combo["deliver"] = None, lambda q, **kw: dict(NO_WIKI) + result = ask(combo, "Kto bol vedúci práce Samuela Furdy?") + assert result["status"] == "ok" and "Peter Novák" in result["answer"] and "nenašiel" not in result["answer"] + + +def test_a_crzp_slower_than_the_wait_says_the_search_is_still_running(combo, monkeypatch): + monkeypatch.setattr(C, "CRZP_SECONDS", 0.1) + monkeypatch.setattr(C, "CRZP_WAIT_SECONDS", 0.4) + monkeypatch.setattr(C, "crzp_part", slow_crzp(1.5, dict(CRZP_ANSWER))) + combo["match"], combo["deliver"] = None, lambda q, **kw: dict(NO_WIKI) + question = "Kto bol vedúci práce Samuela Furdy?" + started = time.monotonic() + result = ask(combo, question) + assert time.monotonic() - started < 1.2 + assert result["status"] == "no_answer" and result["reason"] == "crzp_pending" and result["accepted_for_delivery"] is True + assert result["answer"] == C.CRZP_PENDING and "nenašiel" not in result["answer"] + import packages.claude.client as client + client.validate_metadata(result) + assert client.validated_delivery_check(result, question, "rag") + + +def test_the_repeated_question_waits_for_the_running_search_instead_of_a_new_one(combo, monkeypatch): + import threading + calls, release = [], threading.Event() + monkeypatch.setattr(C, "CRZP_SECONDS", 0.1) + monkeypatch.setattr(C, "CRZP_WAIT_SECONDS", 0.3) + monkeypatch.setattr(C, "crzp_part", slow_crzp(10, dict(CRZP_ANSWER), calls=calls, release=release)) + combo["match"], combo["deliver"] = None, lambda q, **kw: dict(NO_WIKI) + question = "Kto bol vedúci práce Samuela Furdy?" + assert ask(combo, question)["reason"] == "crzp_pending" + monkeypatch.setattr(C, "CRZP_WAIT_SECONDS", 5) + threading.Timer(0.3, release.set).start() + again = ask(combo, question) + assert again["status"] == "ok" and "Peter Novák" in again["answer"] and len(calls) == 1 + + +def test_a_wiki_answer_does_not_wait_when_crzp_only_adds_to_it(combo, monkeypatch): + monkeypatch.setattr(C, "CRZP_SECONDS", 0.2) + monkeypatch.setattr(C, "CRZP_WAIT_SECONDS", 5) + monkeypatch.setattr(C, "crzp_part", slow_crzp(3, None, mode="person")) + started = time.monotonic() + result = ask(combo, "Kto vedie Jána Ptáka?") + assert result["status"] == "ok" and time.monotonic() - started < 1.5 + + +def test_crzp_as_the_main_source_is_waited_for_even_beside_a_wiki_answer(combo, monkeypatch): + monkeypatch.setattr(C, "CRZP_SECONDS", 0.2) + monkeypatch.setattr(C, "CRZP_WAIT_SECONDS", 5) + part = {**CRZP_ANSWER, "text": "Na KEMT FEI Technickej univerzity v Košiciach v roku 2021 obhájili 34 diplomových prác."} + monkeypatch.setattr(C, "crzp_part", slow_crzp(0.6, part)) + combo["match"] = None + result = ask(combo, "Koľko diplomových prác obhájili na KEMT v roku 2021?") + assert result["status"] == "ok" and "34 diplomových prác" in result["answer"] + + +def test_a_person_unknown_to_both_sources_says_both_were_searched(combo, monkeypatch): + monkeypatch.setattr(C, "crzp_part", slow_crzp(0, None)) + combo["match"], combo["deliver"] = None, lambda q, **kw: dict(NO_WIKI) + result = ask(combo, "Kto bol vedúci práce Samuela Furdy?") + assert result["status"] == "no_answer" and "ani v registri záverečných prác." in result["answer"] + + +def test_an_unavailable_crzp_is_never_reported_as_searched(combo, monkeypatch): + def unavailable(q, person, complete=None, student=True): + probe = C._probe.get() + probe["mode"], probe["failed"] = "explicit", True # what _crzp_part records on CrzpUnavailable + return None + monkeypatch.setattr(C, "crzp_part", unavailable) + combo["match"], combo["deliver"] = None, lambda q, **kw: dict(NO_WIKI) + result = ask(combo, "Kto bol vedúci práce Samuela Furdy?") + assert result["status"] == "no_answer" and "registri" not in result["answer"] diff --git a/test/presentation/test_conversation_store.py b/test/presentation/test_conversation_store.py new file mode 100644 index 0000000..0dceff9 --- /dev/null +++ b/test/presentation/test_conversation_store.py @@ -0,0 +1,151 @@ +"""Conversation steps on the server under a short token (tools/answers/context_store.py, combined.seal).""" +import sqlite3 +import time + +import pytest + +from tools.answers import combined as C +from tools.answers import context_store as S +from test_combined_answers import LIST, WIKI, ask, combo # noqa: F401 (the fixture) + + +@pytest.fixture(autouse=True) +def own_store(monkeypatch, tmp_path): + monkeypatch.setenv("ANSWER_CONTEXT_FILE", str(tmp_path / "conversation_pages.sqlite")) + monkeypatch.setenv("ANSWER_CONTEXT_STORE", "1") + monkeypatch.setenv("SEARCH_API_KEY", "store-test-key") + return tmp_path / "conversation_pages.sqlite" + + +def token(result): + return result["conversation_context"]["token"] + + +def test_the_token_is_short_signed_and_the_context_stays_on_the_server(): + sealed = C.seal({"wiki": "w" * 20000, "entities": [{"n": 1, "name": "Ján Pták"}], "question": "Kto?"}) + assert sealed.startswith("zc3.") and len(sealed) <= 40 + value = C.unseal(sealed) + assert value["wiki"] == "w" * 20000 and value["entities"][0]["name"] == "Ján Pták" and value["_step"] + assert C.unseal(sealed[:-2] + ("aa" if not sealed.endswith("aa") else "bb")) == {"error": "invalid_context"} + assert C.unseal(C.step_token("A" * 16)) == {"error": "expired_context"} # genuine signature, no such step + assert C.token_step("zc3.short.sig") is None + + +def test_steps_form_a_chain_and_an_edited_message_starts_a_branch(combo): + first = ask(combo, "Kto vedie Jána Ptáka?") + second = ask(combo, "a čo robil?", token(first)) + third = ask(combo, "a kedy?", token(second)) + chain = S.chain(C.token_step(token(third))) + assert [step["payload"]["question"] for step in chain][-1] == "Kto vedie Jána Ptáka?" and len(chain) == 3 + branch = ask(combo, "a aké výsledky?", token(first)) # the user edited the second message + assert len(S.chain(C.token_step(token(branch)))) == 2 and len(S.chain(C.token_step(token(third)))) == 3 + + +def test_unused_conversations_expire_and_every_use_extends_them(combo, monkeypatch, own_store): + first = ask(combo, "Kto vedie Jána Ptáka?") + step = C.token_step(token(first)) + with sqlite3.connect(own_store) as db: + db.execute("UPDATE conversations SET last_used = ?", (time.time() - 8 * 86400,)) + assert ask(combo, "a čo robil?", token(first))["reason"] == "expired_context" + fresh = ask(combo, "Kto vedie Jána Ptáka?") + with sqlite3.connect(own_store) as db: + db.execute("UPDATE conversations SET last_used = ?", (time.time() - 6 * 86400,)) + assert ask(combo, "a čo robil?", token(fresh))["status"] == "ok" # read within 7 days: extended + with sqlite3.connect(own_store) as db: + used = db.execute("SELECT MAX(last_used) FROM conversations").fetchone()[0] + assert used > time.time() - 60 + assert db.execute("SELECT COUNT(*) FROM steps WHERE id = ?", (step,)).fetchone()[0] == 0 # deleted + + +def test_above_the_size_cap_the_least_recently_used_conversations_go(monkeypatch, own_store): + monkeypatch.setenv("ANSWER_CONTEXT_MAX_MB", "1") + old = C.seal({"wiki": "x" * 300_000, "question": "stará"}) + for i in range(6): + C.seal({"wiki": "y" * 300_000, "question": f"nová {i}"}) + assert C.unseal(old) == {"error": "expired_context"} and C.unseal(C.seal({"question": "posledná"}))["question"] + with sqlite3.connect(own_store) as db: + pages, free, size = (db.execute(f"PRAGMA {p}").fetchone()[0] for p in ("page_count", "freelist_count", "page_size")) + assert (pages - free) * size <= 1.2 * 1024 * 1024 + + +def test_the_store_can_be_switched_off(monkeypatch, combo): + monkeypatch.setenv("ANSWER_CONTEXT_STORE", "0") + first = ask(combo, "Kto vedie Jána Ptáka?") + assert token(first).startswith("zc2.") and ask(combo, "a čo robil?", token(first))["status"] == "ok" + + +def test_people_of_an_older_answer_are_found_when_the_latest_lists_none(combo): + combo["match"] = None + combo["deliver"] = lambda q, **kw: dict(LIST) + listed = ask(combo, "Kto pracoval s Neo4j?") + combo["deliver"] = lambda q, **kw: dict(WIKI) + combo["match"] = {"name": "Ján Pták", "student": True} + between = ask(combo, "Kto vedie Jána Ptáka?", token(listed)) + seen = [] + combo["deliver"] = lambda q, **kw: (seen.append(q), dict(WIKI))[1] + combo["match"] = {"name": "Maksym Zatirka", "student": True} + ask(combo, "a čo robil druhý z nich?", token(between)) + assert seen == ["a čo robil Maksym Zatirka?"] + + +def test_a_return_to_an_older_question_answers_in_its_context(combo): + combo["match"] = None + combo["deliver"] = lambda q, **kw: dict(LIST) + listed = ask(combo, "Kto pracoval s Neo4j?") + combo["deliver"] = lambda q, **kw: dict(WIKI) + combo["match"] = {"name": "Ján Pták", "student": True} + between = ask(combo, "Kto vedie Jána Ptáka?", token(listed)) + combo["match"] = None + schools = ask(combo, "Vráť sa k otázke o Neo4j, z akých škôl sú?", token(between)) + assert "2. Maksym Zatirka — Technická univerzita v Košiciach" in schools["answer"] + import packages.claude.client as client + assert client.validated_delivery_check(schools, "Vráť sa k otázke o Neo4j, z akých škôl sú?", "rag") + + +def test_two_older_questions_matching_alike_are_offered(combo): + combo["match"] = None + combo["deliver"] = lambda q, **kw: dict(LIST) + one = ask(combo, "Kto pracoval s Neo4j v roku 2025?") + two = ask(combo, "Kto pracoval s Neo4j v roku 2026?", token(one)) + asked = ask(combo, "vráť sa k otázke o Neo4j", token(two)) + assert asked["status"] == "ambiguous" and "1. „Kto pracoval s Neo4j v roku 2026?“" in asked["answer"] + seen = [] + combo["deliver"] = lambda q, **kw: (seen.append(q), dict(LIST))[1] + chosen = ask(combo, "2", token(asked)) + assert chosen["status"] == "ok" and seen == ["Kto pracoval s Neo4j v roku 2025?"] + + +def test_an_expired_wiki_context_of_an_older_step_is_left_out_not_shown_as_an_error(combo): + first = ask(combo, "Kto vedie Jána Ptáka?") + calls = [] + + def deliver(q, **kw): + calls.append(kw.get("context_token")) + if kw.get("context_token"): + return {"status": "error", "reason": "expired_context", "accepted_for_delivery": False, "answer": "x", + "claims": [], "source_urls": [], "index_version": None, "complete": False, "truncated": False, + "truncation_reasons": []} + return dict(WIKI) + combo["deliver"] = deliver + stepped = C.seal({"wiki": "wiki-token-of-yesterday", "question": "Kto vedie Jána Ptáka?", "entities": []}) + result = ask(combo, "a kto je jeho vedúci?", stepped) + assert result["status"] == "ok" and calls == ["wiki-token-of-yesterday", None] + assert first["status"] == "ok" + + +def test_only_a_clear_return_cue_reaches_back(): + from tools.answers.verification.context_policy import normalized + for message in ("Vráť sa k otázke o blockchaine, z akých škôl boli?", "Späť k Hládkovi", "vráť sa k predošlej otázke", + "pri otázke o blockchaine, kto bol prvý?", "a pri tej predošlej otázke o RAG kto bol druhý?"): + assert C.BACK.search(normalized(message)), message + for message in ("Odpovedz na otázku o RAG", "Aká je odpoveď na otázku, kto viedol Ptáka?", "Kto vedie Jána Ptáka?"): + assert not C.BACK.search(normalized(message)), message + + +def test_a_bare_return_to_the_previous_question_asks_the_one_before_the_latest(combo): + seen = [] + combo["deliver"] = lambda q, **kw: (seen.append(q), dict(WIKI))[1] + first = ask(combo, "Kto vedie Jána Ptáka?") + second = ask(combo, "Aké technológie použil Ján Pták?", token(first)) + again = ask(combo, "vráť sa k predošlej otázke", token(second)) + assert again["status"] == "ok" and seen[-1] == "Kto vedie Jána Ptáka?" diff --git a/test/presentation/test_unified_answers.py b/test/presentation/test_unified_answers.py index 2a42278..bf0f1c1 100644 --- a/test/presentation/test_unified_answers.py +++ b/test/presentation/test_unified_answers.py @@ -105,8 +105,13 @@ def test_inline_register_links_move_to_the_sources_line(): def test_the_conversation_token_is_compressed_and_still_read(monkeypatch): from tools.answers import combined as C monkeypatch.setenv("SEARCH_API_KEY", "k") + monkeypatch.setenv("ANSWER_CONTEXT_STORE", "0") # the long signed token without the server store token = C.seal({"wiki": "w" * 20000, "entities": []}) assert token.startswith("zc2.") and len(token) < 16000 and C.unseal(token)["wiki"] == "w" * 20000 + monkeypatch.setenv("ANSWER_CONTEXT_STORE", "1") # default: a short step token; the old token is still read + short = C.seal({"wiki": "w" * 20000, "entities": []}) + assert short.startswith("zc3.") and len(short) < 50 and C.unseal(short)["wiki"] == "w" * 20000 + assert C.unseal(token)["wiki"] == "w" * 20000 def test_name_forms_from_the_model_are_checked_and_kept(monkeypatch, tmp_path): diff --git a/tools/answers/combined.py b/tools/answers/combined.py index 4bf0ae1..7cad8db 100644 --- a/tools/answers/combined.py +++ b/tools/answers/combined.py @@ -12,13 +12,16 @@ Meetings, tasks, progress and results stay ZP Wiki only. The answer is one text: a list of people is one numbered list (ZP Wiki people first, then CRZP works, each marked with its source), the first PAGE items are shown and the rest is offered ("Chceš vidieť ďalších?"); all sources are in one -line at the end. A signed token carries the wiki's own token, the shown people -(for "a z akých škôl sú?", "a čo robil prvý z nich?") and the id of the not -yet shown items (tools/answers/pages.py). +line at the end. The context of the next message (the wiki's own token, the +shown people for "a z akých škôl sú?" and "a čo robil prvý z nich?", the id of +the not yet shown items of tools/answers/pages.py) is one conversation step on +the server (tools/answers/context_store.py); Claude gets a short signed token +of that step, and a message may refer to an older step of the conversation. """ from __future__ import annotations import base64 +import contextvars import hashlib import hmac import json @@ -32,9 +35,21 @@ 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")) +# CRZP is the only source that can answer (a person ZP Wiki does not know, defended works of a +# department, "v CRZP") or ZP Wiki has nothing: the answer waits for CRZP this long from the start +# of the question, under the 90 s limit of the MCP client (packages/claude/client.py), and then +# says the search is still running instead of showing a weak wiki answer or "nenašiel". +CRZP_WAIT_SECONDS = float(os.getenv("CRZP_WAIT_SECONDS", "80")) +CRZP_PENDING = ("Hľadanie v registri záverečných prác (CRZP) ešte prebieha. Zopakuj otázku o chvíľu, " + "výsledok už bude pripravený.") +_probe: contextvars.ContextVar[dict | None] = contextvars.ContextVar("crzp_probe", default=None) +_inflight: dict = {} # a CRZP part still running for the same question: (future, probe) +_inflight_lock = threading.Lock() LIFETIME = 24 * 3600 PREFIX = "zc1." # plain JSON body (still read) -PREFIX2 = "zc2." # zlib-compressed JSON body +PREFIX2 = "zc2." # zlib-compressed JSON body (still read; issued with ANSWER_CONTEXT_STORE=0) +PREFIX3 = "zc3." # the id of a step kept on the server (tools/answers/context_store.py) and its signature +_parent: contextvars.ContextVar[str | None] = contextvars.ContextVar("answer_parent_step", default=None) TUKE = "Technická univerzita v Košiciach" WIKI_SCHOOL = "Technická univerzita v Košiciach (KEMT FEI)" # What only the wiki records: CRZP is not asked. @@ -93,12 +108,40 @@ def _b64(value: bytes) -> str: return base64.urlsafe_b64encode(value).decode().rstrip("=") +def _signature(key: bytes, step: str) -> str: + return _b64(hmac.digest(key, (PREFIX3 + step).encode(), "sha256"))[:16] + + +def step_token(step: str | None) -> str | None: + """The short token of a stored step ("zc3..").""" + key = _key() + return PREFIX3 + step + "." + _signature(key, step) if key and step else None + + +def token_step(token: str | None) -> str | None: + """The step id of a genuine short token, else None.""" + key = _key() + if not isinstance(token, str) or not token.startswith(PREFIX3) or key is None: + return None + parts = token[len(PREFIX3):].split(".") + if len(parts) != 2 or not re.fullmatch(r"[A-Za-z0-9_-]{16}", parts[0]): + return None + return parts[0] if hmac.compare_digest(parts[1], _signature(key, parts[0])) else None + + def seal(payload: dict) -> str | None: - """A signed, compressed token (the wiki's and CRZP's own tokens inside make it long).""" + """The token of the answer's context: a short step token (the context kept on the server after the + step the message continued), or, with ANSWER_CONTEXT_STORE=0 or a failed store, the signed and + compressed context itself (the wiki's and CRZP's own tokens inside make it long).""" import zlib + from tools.answers import context_store key = _key() if key is None: return None + if context_store.enabled(): + token = step_token(context_store.save(payload, _parent.get())) + if token: + return token raw = json.dumps({**payload, "expires": int(time.time()) + LIFETIME}, ensure_ascii=False, separators=(",", ":")) body = _b64(zlib.compress(raw.encode(), 9)) token = PREFIX2 + body + "." + _b64(hmac.digest(key, body.encode(), "sha256")) @@ -106,8 +149,16 @@ def seal(payload: dict) -> str | None: def unseal(token: str | None) -> dict | None: - """The combined context, or None for a token that is not ours (a plain wiki token).""" + """The combined context (a stored step also gives its id as "_step"), or None for a token that + is not ours (a plain wiki token).""" import zlib + if isinstance(token, str) and token.startswith(PREFIX3) and _key() is not None: + from tools.answers import context_store + step = token_step(token) + if step is None: + return {"error": "invalid_context"} + value = context_store.load(step) + return {**value, "_step": step} if value is not None else {"error": "expired_context"} if not isinstance(token, str) or not token.startswith((PREFIX, PREFIX2)) or _key() is None: return None try: @@ -352,7 +403,7 @@ def crzp_plan(question: str, person: str | None, complete=None, student: bool = role = "author" if role == "author" else "any" # "Kto vedie Jána Ptáka?": his own works elif role not in ("supervisor", "opponent"): role = "supervisor" # a supervisor's works are those he or she led - query.people = [Person(name=person, role=role, typed=person)] + query.people = [Person(name=person, role=role, typed=person, canonical=True)] query.school, query.unit, query.from_model, query.title = "tuke", None, True, None query.topics, query.alternatives = [], [] return "person", query @@ -463,6 +514,9 @@ def _crzp_part(question: str, person: str | None, *, complete=None, student: boo from tools.crzp.source.client import CrzpUnavailable try: planned = crzp_plan(question, person, complete, student) + probe = _probe.get() + if probe is not None: # the waiting answer learns whether CRZP is the main source (see needs_crzp) + probe["mode"] = planned[0] if planned else None if planned is None: return None mode, query = planned @@ -523,6 +577,9 @@ def _crzp_part(question: str, person: str | None, *, complete=None, student: boo "works": [{"source": "crzp", "label": _work(r), "type": r.get("work_type"), "key": crzp.work_key(r)} for r in rows[:3]]} except CrzpUnavailable: + probe = _probe.get() + if probe is not None: + probe["failed"] = True # not "nothing found": CRZP did not answer return None @@ -887,6 +944,127 @@ def _reference(question: str, entities: list[dict]) -> tuple[re.Match, dict] | N return (match, chosen) if chosen else None +# "vráť sa k otázke o blockchaine", "späť k Hládkovi", "pri tej predošlej otázke o RAG": an older step. +BACK = re.compile(r"\b(?:vrat\w*\s+sa|vratme\s+sa|spat|naspat)\s+(?:k|ku|na)\b" + r"|\b(?:k|ku|pri)\s+(?:(?:tej|tu)\s+)?(?:predosl|predchadzajuc|minul|skorsej|starsej|povodn)\w*\s+otazk\w*" + r"|\b(?:k|ku|pri)\s+(?:tej|tu)\s+otazk\w*|\b(?:k|ku|pri)\s+otazke\s+o\b") +PREVIOUS_ONE = re.compile(r"\b(?:predosl|predchadzajuc|minul)\w*") +BACK_WORDS = {"vrat", "vratme", "vratit", "sa", "spat", "naspat", "k", "ku", "na", "pri", "tej", "tu", "tom", "o", "a", + "aj", "este", "raz", "znova", "prosim", "otazke", "otazku", "otazky", "otazka", "predoslej", "predchadzajucej", + "minulej", "skorsej", "starsej", "povodnej", "prvej", "druhej", "tomu", "ktora", "bola", "ktoru", "som", "sme", + "dal", "dala", "dali", "pytal", "pytala", "kde", "tam"} +MAX_BACK = 6 # older steps "a čo robil druhý z nich?" may point to (the newest one with such people wins) + + +def _stems(text: str) -> set[str]: + return {w[:max(4, len(w) - 2)] for w in re.findall(r"[a-z0-9]+", normalized(text)) + if len(w) >= 3 and w not in BACK_WORDS} + + +def _split_return(message: str) -> tuple[str, str]: + """"Vráť sa k otázke o blockchaine, z akých škôl boli?" -> (the return, the question asked there).""" + parts = re.split(r"\s*[,;:–—]\s*", message.strip(), maxsplit=1) + at = next((i for i, part in enumerate(parts) if BACK.search(normalized(part))), 0) + rest = " ".join(part for i, part in enumerate(parts) if i != at).strip() + return parts[at], rest if re.search(r"[^\W\d_]{2}", rest) else "" + + +def _keep_context(result: dict, previous: dict) -> dict: + """A clarification that leaves the conversation where it was.""" + return _with_token(result, wiki_context={"token": previous.get("wiki")}, entities=previous.get("entities") or [], + question=previous.get("question", ""), crzp=previous.get("crzp"), + primary=previous.get("primary", "wiki"), page=previous.get("page")) + + +def _back_reference(question: str, previous: dict, *, engine: str, limit: int, complete, deliver) -> dict | None: + """A message returning to an older question of the conversation: the step whose question shares + the most words with the return part (the newest one of equal ones); two different questions + matching equally are offered as a choice.""" + from tools.answers import context_store + reference, _ = _split_return(question) + wanted = _stems(reference) + if not wanted: # "vráť sa k predošlej otázke": the question before the latest one + if not PREVIOUS_ONE.search(normalized(reference)): + return None + older = context_store.chain(previous["_step"], limit=2) + if len(older) < 2: + return None + return _return_to(question, older[1]["id"], engine=engine, limit=limit, complete=complete, deliver=deliver) + match = lambda a, b: a.startswith(b) or b.startswith(a) + scored = [] + for position, step in enumerate(context_store.chain(previous["_step"])): + payload = step["payload"] + known = _stems(payload.get("question") or "") | {s for e in payload.get("entities") or [] for s in _stems(e.get("name", ""))} + score = sum(any(match(w, k) for k in known) for w in wanted) + if score: + scored.append((score, position, step)) + if not scored: + text = "V tejto konverzácii som nenašiel otázku, ku ktorej sa chceš vrátiť. Napíš ju prosím celú." + result = _ok(question, engine, text, [], {}) + result.update(status="ambiguous", reason="clarification_required", + delivery_check={"layer": "planning", "code": "clarification_required", + "request_fingerprint": fingerprint(question, engine)}) + return _keep_context(result, previous) + best = max(score for score, _, _ in scored) + distinct = {} + for score, position, step in sorted(scored, key=lambda item: item[1]): # newest first + asked = normalized(step["payload"].get("question") or "") + if score == best and asked not in distinct: + distinct[asked] = step + if len(distinct) == 1: + return _return_to(question, next(iter(distinct.values()))["id"], engine=engine, limit=limit, + complete=complete, deliver=deliver) + options = [{"source": "step", "step": step["id"], "label": f"„{step['payload'].get('question')}“"} + for step in list(distinct.values())[:4]] + text = ("Ku ktorej otázke sa chceš vrátiť?\n\n" + "\n".join(f"{i}. {o['label']}" for i, o in enumerate(options, 1)) + + "\n\nOdpovedz číslom.") + result = _ok(question, engine, text, [], {}) + result.update(status="ambiguous", reason="clarification_required", + delivery_check={"layer": "planning", "code": "clarification_required", + "request_fingerprint": fingerprint(question, engine)}) + return _with_token(result, options=options, question=question, entities=previous.get("entities") or []) + + +def _return_to(message: str, step: str, *, engine: str, limit: int, complete, deliver) -> dict: + """The message answered in the context of an older step; a bare return ("vráť sa k otázke o + blockchaine") asks that older question again, in the context it was asked in.""" + from tools.answers import context_store + _, rest = _split_return(message) + if rest: + result = _answer(rest, engine=engine, limit=limit, context_token=step_token(step), complete=complete, + deliver=deliver) + return {**result, "_asked_as": [rest, *result.pop("_asked_as", [])]} + steps = context_store.chain(step, limit=2) + asked = steps[0]["payload"].get("question") if steps else None + if not asked: + from tools.answers.presentation.answer_errors import public_failure + failure = public_failure({"reason": "expired_context", "engine": engine}) + failure["delivery_check"] = {"layer": "context", "code": "unavailable", + "request_fingerprint": fingerprint(message, engine)} + return failure + parent = steps[1]["id"] if len(steps) > 1 else None + result = _answer(asked, engine=engine, limit=limit, context_token=step_token(parent), complete=complete, + deliver=deliver) + return {**result, "_asked_as": [asked, *result.pop("_asked_as", [])]} + + +def _with_people(question: str, low: str, previous: dict) -> dict: + """The latest step, unless the message points at listed people ("druhý z nich", "a z akých škôl + sú?") the latest answer has not listed: then the newest of the last MAX_BACK steps that has them.""" + from tools.crzp.answering.wiki_bridge import wiki_person + entities = previous.get("entities") or [] + words = re.findall(r"[a-z0-9]+", low) + schools = bool(SCHOOLS.search(low) and not THESIS.search(low) and len(words) <= 8 and not wiki_person(question)) + if not (REFERENCE.search(question) or schools) or _reference(question, entities) or schools and entities: + return previous + from tools.answers import context_store + for step in context_store.chain(previous["_step"], limit=MAX_BACK + 1)[1:]: + older = step["payload"].get("entities") or [] + if older and (schools or _reference(question, older)): + return {**step["payload"], "_step": step["id"]} + return previous + + def _stamp(result: dict, question: str, engine: str) -> dict: """An answer prepared for a question this layer rewrote ("prvý z nich" -> the name, "2" -> the pending question about the chosen work) is bound to the message the user sent. Any other @@ -909,8 +1087,12 @@ def answer(question: str, *, engine: str, limit: int = 5, context_token: str | N if enabled() and not _warmed.is_set(): # tag rarity for related topics, counted once in the background _warmed.set() _pool().submit(tag_frequencies) - return _stamp(_answer(question, engine=engine, limit=limit, context_token=context_token, complete=complete, - deliver=deliver), question, engine) + parent = _parent.set(token_step(context_token)) # every step of this answer continues the sent one + try: + return _stamp(_answer(question, engine=engine, limit=limit, context_token=context_token, complete=complete, + deliver=deliver), question, engine) + finally: + _parent.reset(parent) def _ask_choice(question: str, engine: str, previous: dict) -> dict: @@ -956,7 +1138,7 @@ def _crzp_work_answer(question: str, engine: str, chosen: dict, complete=None) - from tools.crzp.answering import answer as crzp from tools.crzp.answering.understand import Person, understand query = understand(question, complete=complete) - query.people = [Person(name=chosen["name"], role="author", typed=chosen["name"])] + query.people = [Person(name=chosen["name"], role="author", typed=chosen["name"], canonical=True)] query.sids, query.title, query.topics, query.alternatives = [chosen["sid"]], None, [], [] query.school = query.unit = None query.from_model = True @@ -994,6 +1176,9 @@ def _answer(question: str, *, engine: str, limit: int, context_token: str | None return _next_page(question, engine, previous) if previous and previous.get("options"): # "Ktorú prácu myslíš?" was asked chosen = _choice(low, previous["options"]) + if chosen is not None and chosen.get("source") == "step": # "Ktorú otázku myslíš?" (a return to an older one) + return _return_to(previous["question"], chosen["step"], engine=engine, limit=limit, complete=complete, + deliver=deliver) if chosen is not None: result = _answer_choice(previous["question"], chosen, engine=engine, limit=limit, complete=complete, deliver=deliver_answer) @@ -1016,6 +1201,12 @@ def _answer(question: str, *, engine: str, limit: int, context_token: str | None return _with_token(_ok(question, engine, "Všetko nájdené už je v predchádzajúcej odpovedi.", [], {}), entities=previous["entities"], question=question, crzp=previous.get("crzp"), primary=previous.get("primary", "wiki")) + if previous and previous.get("_step") and BACK.search(low): # "vráť sa k otázke o blockchaine, …" + returned = _back_reference(question, previous, engine=engine, limit=limit, complete=complete, deliver=deliver) + if returned is not None: + return returned + if previous and previous.get("_step"): # "a čo robil druhý z nich?" about the people of an older answer + previous = _with_people(question, low, previous) entities = (previous or {}).get("entities") or [] # "a z akých škôl sú?" asks about the people shown; "Ktoré školy majú práce o RAG?" is a new question. if entities and SCHOOLS.search(low) and not wiki_person(question) and not THESIS.search(low) and len(words) <= 8: @@ -1059,7 +1250,6 @@ def _answer(question: str, *, engine: str, limit: int, context_token: str | None started = time.monotonic() pool = _pool() from tools.answers import timing - import contextvars def timed(name, function, *args, **kwargs): began = time.monotonic() @@ -1071,18 +1261,88 @@ def _answer(question: str, *, engine: str, limit: int, context_token: str | None wiki_future = pool.submit(contextvars.copy_context().run, timed, "wiki", deliver_answer, question, engine=engine, limit=limit, **({"context_token": wiki_token} if wiki_token else {})) - crzp_future = pool.submit(contextvars.copy_context().run, timed, "crzp", crzp_part, question, person, - complete=complete, student=student) if enabled() else None + crzp_future, probe = _crzp_future(pool, timed, question, person, complete, student) if enabled() else (None, {}) wiki = wiki_future.result() - try: - part = crzp_future.result(timeout=max(1.0, CRZP_SECONDS - (time.monotonic() - started))) if crzp_future else None - except FutureTimeout: - part = None # CRZP too slow this time: the wiki answer is not held back (its search stays cached) - except Exception: - part = None + if wiki_token and wiki.get("reason") in ("stale_context", "expired_context"): + # the wiki's own context of an older step is too old (24 hours) or the wiki data changed: the + # question goes to the wiki without it (people, works and the CRZP question of the step stay) + wiki = deliver_answer(question, engine=engine, limit=limit) + part = None + if crzp_future is not None: + try: + part = crzp_future.result(timeout=max(1.0, CRZP_SECONDS - (time.monotonic() - started))) + except FutureTimeout: # CRZP is slow: only an answer that needs CRZP waits longer + if needs_crzp(wiki, probe, person): + try: + part = crzp_future.result(timeout=max(0.0, CRZP_WAIT_SECONDS - (time.monotonic() - started))) + except FutureTimeout: + timing.note("crzp_pending", True) # the search goes on and is cached for the repeated question + return _crzp_pending(question, engine, wiki) + except Exception: + part = None + except Exception: + part = None + if (part is None and crzp_future is not None and crzp_future.done() and crzp_future.exception() is None + and probe.get("mode") == "explicit" and not probe.get("failed")): + wiki = searched_both(wiki) # CRZP was searched for the person too and has nothing return compose(asked, question, engine, wiki, part, person) +def _crzp_future(pool, timed, question, person, complete, student): + """The CRZP part of this question, or the one still running for the same question (a question + repeated after "Hľadanie … ešte prebieha" waits for that search instead of starting it again).""" + key = (normalized(question), person, student, id(complete), crzp_part) + with _inflight_lock: + running = _inflight.get(key) + if running is not None and not running[0].done(): + return running + probe: dict = {} + + def run(): + _probe.set(probe) + return crzp_part(question, person, complete=complete, student=student) + future = pool.submit(contextvars.copy_context().run, timed, "crzp", run) + _inflight[key] = (future, probe) + future.add_done_callback(lambda done: _forget(key, done)) + return future, probe + + +def _forget(key, future) -> None: + with _inflight_lock: + if _inflight.get(key, (None,))[0] is future: + del _inflight[key] + + +def needs_crzp(wiki: dict, probe: dict, person: str | None) -> bool: + """Whether the answer waits for a slow CRZP: CRZP is the main source of this question + (crzp_plan mode "explicit") or ZP Wiki has nothing to give (no answer, an error).""" + mode = probe.get("mode", "unplanned") # "unplanned": CRZP is still reading the question + if mode is None or wiki.get("reason") in REFUSED: + return False # CRZP adds nothing to this question, or it is out of scope + if wiki.get("status") == "ambiguous": # the wiki asks first, unless CRZP answers the question as a whole + return person is None and wiki.get("reason") in WIKI_CLARIFICATION_YIELDS and mode in ("explicit", "unplanned") + wiki_ok = wiki.get("accepted_for_delivery") is True and wiki.get("status") == "ok" + return mode == "explicit" or not wiki_ok + + +def _crzp_pending(question: str, engine: str, wiki: dict) -> dict: + """CRZP did not finish in time: say so (never "nenašiel"); the repeated question gets the result.""" + result = _ok(question, engine, CRZP_PENDING, [], {"index_version": wiki.get("index_version")}) + result.update(status="no_answer", reason="crzp_pending", complete=False, + delivery_check={"layer": "retrieval", "code": "unavailable", + "request_fingerprint": fingerprint(question, engine)}) + return _with_token(result, wiki_context=wiki.get("conversation_context"), question=question) + + +def searched_both(wiki: dict) -> dict: + """"Osobu X som v ZP Wiki nenašiel" when CRZP was searched for X as well and has no work of X.""" + text = wiki.get("answer") + if wiki.get("reason") != "unknown_person" or not isinstance(text, str): + return wiki + return {**wiki, "answer": text.replace("som v ZP Wiki nenašiel", + "som nenašiel v ZP Wiki ani v registri záverečných prác")} + + 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.presentation.unified import strip_sources diff --git a/tools/answers/context_store.py b/tools/answers/context_store.py new file mode 100644 index 0000000..b8b06fd --- /dev/null +++ b/tools/answers/context_store.py @@ -0,0 +1,149 @@ +"""Conversation steps of /rag and /graphrag, kept on the server under a short token. + +Every combined answer is one step: what the next message may continue (the +question as answered, the shown people and works, the offered choices, the id +of the not yet shown items, the wiki's and CRZP's own context tokens, which +source answered). Claude gets only "zc3.." (about 40 +characters, so it cannot be cut or mistyped like the long signed tokens) and +sends it back with the next message. + +A step points to the step it continued (parent), so a conversation is a chain +that can be read back (find the older step a message refers to). Steps are +never changed: a message edited in Claude continues an older step and starts +its own branch. + +Storage stays small and private: a local SQLite file in data/ (gitignored, the +same file as the paged lists, WAL mode for parallel answers); no answer texts, +only the context above. A conversation not used for ANSWER_CONTEXT_DAYS (7) +is deleted, every use extends it; above ANSWER_CONTEXT_MAX_MB (50) the least +recently used conversations are deleted. ANSWER_CONTEXT_STORE=0 turns the +store off (the long signed zc2 token is used again). +""" +from __future__ import annotations + +import json +import os +import secrets +import sqlite3 +import threading +import time +from contextlib import contextmanager +from pathlib import Path + +MAX_CHAIN = 30 # steps read back from one step (a safety cap, not a conversation limit) +_lock = threading.Lock() + + +def enabled() -> bool: + return os.getenv("ANSWER_CONTEXT_STORE", "1") != "0" + + +def _days() -> float: + try: + return max(0.01, float(os.getenv("ANSWER_CONTEXT_DAYS", "7"))) + except ValueError: + return 7.0 + + +def _max_bytes() -> int: + try: + return int(max(1.0, float(os.getenv("ANSWER_CONTEXT_MAX_MB", "50"))) * 1024 * 1024) + except ValueError: + return 50 * 1024 * 1024 + + +def store_file() -> Path: + """data/conversation_pages.sqlite (ANSWER_CONTEXT_FILE elsewhere, e.g. for tests); also the paged lists.""" + if os.getenv("ANSWER_CONTEXT_FILE"): + return Path(os.environ["ANSWER_CONTEXT_FILE"]) + from tools.rag.common import DB_FILE + return DB_FILE.parent / "conversation_pages.sqlite" + + +@contextmanager +def _db(): + """One short transaction (WAL: answers read while another one writes); the connection is closed.""" + connection = sqlite3.connect(store_file(), timeout=10) + try: + connection.execute("PRAGMA journal_mode=WAL") + connection.execute("CREATE TABLE IF NOT EXISTS conversations (conv TEXT PRIMARY KEY, last_used REAL NOT NULL)") + connection.execute("CREATE TABLE IF NOT EXISTS steps (id TEXT PRIMARY KEY, conv TEXT NOT NULL, parent TEXT, " + "created REAL NOT NULL, payload TEXT NOT NULL)") + connection.execute("CREATE INDEX IF NOT EXISTS steps_conv ON steps (conv)") + connection.execute("CREATE INDEX IF NOT EXISTS conversations_used ON conversations (last_used)") + with connection: + yield connection + finally: + connection.close() + + +def _used_bytes(connection: sqlite3.Connection) -> int: + pages = connection.execute("PRAGMA page_count").fetchone()[0] + free = connection.execute("PRAGMA freelist_count").fetchone()[0] + return (pages - free) * connection.execute("PRAGMA page_size").fetchone()[0] + + +def _clean(connection: sqlite3.Connection, now: float) -> None: + """Delete expired conversations; above the size cap the least recently used ones.""" + old = now - _days() * 86400 + connection.execute("DELETE FROM steps WHERE conv IN (SELECT conv FROM conversations WHERE last_used < ?)", (old,)) + connection.execute("DELETE FROM conversations WHERE last_used < ?", (old,)) + for _ in range(5): + if _used_bytes(connection) <= _max_bytes(): + break + count = connection.execute("SELECT COUNT(*) FROM conversations").fetchone()[0] + if count <= 1: + break + oldest = "SELECT conv FROM conversations ORDER BY last_used LIMIT ?" + limit = max(1, count // 10) + connection.execute(f"DELETE FROM steps WHERE conv IN ({oldest})", (limit,)) + connection.execute(f"DELETE FROM conversations WHERE conv IN ({oldest})", (limit,)) + + +def save(payload: dict, parent: str | None = None) -> str | None: + """Store one step after `parent` (the step the message continued); its id, or None.""" + step = secrets.token_urlsafe(12) # 16 characters, 96 random bits + now = time.time() + try: + body = json.dumps(payload, ensure_ascii=False, separators=(",", ":")) + with _lock, _db() as connection: + row = connection.execute("SELECT conv FROM steps WHERE id = ?", (parent,)).fetchone() if parent else None + conv = row[0] if row else secrets.token_urlsafe(12) + connection.execute("INSERT INTO steps VALUES (?, ?, ?, ?, ?)", (step, conv, parent if row else None, now, body)) + connection.execute("INSERT INTO conversations VALUES (?, ?) ON CONFLICT(conv) DO UPDATE SET last_used = ?", + (conv, now, now)) + _clean(connection, now) + return step + except (sqlite3.Error, OSError, TypeError, ValueError): + return None + + +def chain(step: str | None, limit: int = MAX_CHAIN) -> list[dict]: + """The step and the steps before it, newest first ({"id", "payload"}); [] for an unknown or + expired step. Reading a conversation extends its lifetime.""" + if not isinstance(step, str) or not step: + return [] + now = time.time() + try: + with _lock, _db() as connection: + first = connection.execute("SELECT s.conv FROM steps s JOIN conversations c ON c.conv = s.conv " + "WHERE s.id = ? AND c.last_used >= ?", (step, now - _days() * 86400)).fetchone() + if not first: + return [] + connection.execute("UPDATE conversations SET last_used = ? WHERE conv = ?", (now, first[0])) + steps, current = [], step + while current and len(steps) < limit: + row = connection.execute("SELECT parent, payload FROM steps WHERE id = ?", (current,)).fetchone() + if not row: + break + steps.append({"id": current, "payload": json.loads(row[1])}) + current = row[0] + return steps + except (sqlite3.Error, OSError, ValueError): + return [] + + +def load(step: str | None) -> dict | None: + """One step's payload (extends the conversation's lifetime), or None.""" + steps = chain(step, limit=1) + return steps[0]["payload"] if steps else None diff --git a/tools/answers/pages.py b/tools/answers/pages.py index 29b6aab..57c01f2 100644 --- a/tools/answers/pages.py +++ b/tools/answers/pages.py @@ -20,8 +20,8 @@ _lock = threading.Lock() def _file() -> Path: - from tools.rag.common import DB_FILE - return DB_FILE.parent / "conversation_pages.sqlite" + from tools.answers.context_store import store_file + return store_file() def _connect() -> sqlite3.Connection: diff --git a/tools/crzp/answering/answer.py b/tools/crzp/answering/answer.py index f7439e6..526e18f 100644 --- a/tools/crzp/answering/answer.py +++ b/tools/crzp/answering/answer.py @@ -21,7 +21,7 @@ from collections import Counter, OrderedDict from tools.answers.verification.delivery_contract import fingerprint from tools.crzp import fetch from tools.crzp.answering import context -from tools.crzp.answering.names import name_variants +from tools.crzp.answering.names import name_candidates, name_variants from tools.crzp.answering.terms import is_reviewed from tools.crzp.answering.understand import SCHOOLS, CrzpQuery, in_question, stem_match, understand from tools.crzp.answering.units import UNITS, in_unit, unit_label @@ -106,9 +106,7 @@ def search_groups(query: CrzpQuery) -> list[list[str]]: ends = suffixes(query) each = lambda terms: [t + end for t in terms for end in ends] if query.people: - names = [query.people[0].name] if query.from_model else name_variants(query.people[0].name) - title = " " + query.title if query.title else "" - return ([[f"{n} {query.topics[0]}{title}"] for n in names if query.topics] + [[n + title] for n in names]) + return [[text] for text in person_searches(query)] if query.title: return [[query.title]] if not query.topics: @@ -135,6 +133,35 @@ def search_groups(query: CrzpQuery) -> list[list[str]]: return unique +def person_searches(query: CrzpQuery) -> dict[str, dict]: + """Search texts of a person question in order: {text: {"names": the asked names its rows are + checked with, "candidate": another form tried only when no search found the person yet, + "surname": surname alone (one relevance-ordered read, the first name checked in the rows)}}. + - a name ZP Wiki or CRZP gives (canonical) is searched as it is; + - the model's base form first, then other forms of the typed name (names.name_candidates: + "Samuela Furdy" -> "Samuel Furda", "Samo" -> "Samuel"), then the surname alone; + - without the model, the rule forms (names.name_variants).""" + person = query.people[0] + title = " " + query.title if query.title else "" + topic = f" {query.topics[0]}" if query.topics else "" + if not query.from_model: + names = [(n, [person.name], False, False) for n in name_variants(person.name)] + elif person.canonical: + names = [(person.name, [person.name], False, False)] + else: + full, surnames = name_candidates(person.name, person.typed or person.name) + names = [(full[0], [person.name], False, False)] + [(n, [n], True, False) for n in full[1:]] + names += [(s, [person.name, *full[1:]], True, True) for s in surnames] + searches = {} + first = names[:1] if query.from_model else names + for name, asked, candidate, surname in first: # the person with the topic first ("Ján Pták IoT") + if topic and not surname: + searches.setdefault(f"{name}{topic}{title}", {"names": asked, "candidate": candidate, "surname": False}) + for name, asked, candidate, surname in names: + searches.setdefault(f"{name}{title}", {"names": asked, "candidate": candidate, "surname": surname}) + return searches + + def _exact(name: str, crzp_name: str) -> bool: """Same words including diacritics, up to inflection ("Jána" is "Ján", not "Jan").""" words = re.findall(r"[^\W\d_]+", crzp_name) @@ -318,21 +345,38 @@ def reader(query: CrzpQuery): return lambda text: fetch.search(text, links=query.intent != "count", **window) +def _asking(query: CrzpQuery, name: str) -> CrzpQuery: + """The query with another form of the asked person's name (rows are checked with it).""" + if name == query.people[0].name: + return query + asked = query.model_copy(deep=True) + asked.people[0].name = name + return asked + + def find(query: CrzpQuery) -> tuple[dict | None, list[dict]]: """First search group whose rows satisfy all conditions; (merged result, rows). A model-proposed alternative term is searched only if CRZP uses it in a work - already found for the topic, or if nothing was found yet.""" + already found for the topic, or if nothing was found yet. Another form of an + asked person's name (person_searches) is searched only while no search found + the person in any role.""" last, seen = None, [] + met = None # (result, asked name) of the latest search whose rows name the asked person query.searched = [] read = reader(query) + people = person_searches(query) if query.people else {} for group in search_groups(query): + info = people.get(group[0]) if people else None + if info and info["candidate"] and met: + continue # the person is found under an earlier form results, verified_rows, unverified = [], 0, [] for text in group: term = _unverified(query, text) if term and seen and not _used_with_topic(term, seen) and any(keep(r, query) for r in seen): continue # "rozložená kniha" for blockchain: CRZP does not use it, no search # (tried when nothing found so far meets the conditions, e.g. "na iných školách") - results.append(read(text)) + surname_only = bool(info and info["surname"]) + results.append(fetch.search(text, links=True, **filters(query)) if surname_only else read(text)) query.searched.append(text) seen += results[-1]["rows"] if term: @@ -342,7 +386,16 @@ def find(query: CrzpQuery) -> tuple[dict | None, list[dict]]: if not results: continue found = _merge(results) - rows = prefer_exact([r for r in found["rows"] if keep(r, query)], query) + asked = query + for name in (info["names"] if info else [None]): + asked = _asking(query, name) if name else query + rows = prefer_exact([r for r in found["rows"] if keep(r, asked)], asked) + if rows: + break + if info: + name = next((n for n in info["names"] if any(people_in_role(r, n, "any") for r in found["rows"])), None) + if name: + met = (found, name) if by_facets(query) and not found["complete"]: if len(rows) == len(found["rows"]): found["facet_only"] = True # CRZP itself counted it; every read row meets the conditions @@ -354,19 +407,22 @@ def find(query: CrzpQuery) -> tuple[dict | None, list[dict]]: query.unverified_only = unverified # the topic itself found nothing: say so in the answer if rows: if query.people: # show the name as CRZP writes it ("hladek" -> "Daniel Hládek") when it is one person + query.people[0].name = asked.people[0].name names = Counter(n for r in rows for n in people_in_role(r, query.people[0].name, query.people[0].role)) if len(names) == 1 or not query.from_model: query.people[0].name = display_name(names.most_common(1)[0][0]) return last if last and query.people and query.people[0].role == "author": # "práce X" may mean the works X supervised or reviewed: X is no author in the read rows. - relaxed = query.model_copy(deep=True) + base, name = met or (last[0], query.people[0].name) + relaxed = _asking(query, name).model_copy(deep=True) relaxed.people[0].role = "any" - rows = prefer_exact([r for r in last[0]["rows"] if keep(r, relaxed)], relaxed) + rows = prefer_exact([r for r in base["rows"] if keep(r, relaxed)], relaxed) if rows: query.people[0].role = "any" + query.people[0].name = name query.relaxed_author = True - return last[0], rows + return base, rows return last or (None, []) diff --git a/tools/crzp/answering/names.py b/tools/crzp/answering/names.py index 366ced7..7a5073a 100644 --- a/tools/crzp/answering/names.py +++ b/tools/crzp/answering/names.py @@ -47,6 +47,77 @@ def surname_variants(name: str) -> list[str]: return word_forms(words[-1])[:MAX_CANDIDATES] if words else [] +# Common Slovak nicknames (folded nominative) -> the first names CRZP records write. +NICKNAMES = { + "samo": ["Samuel"], "jano": ["Ján"], "janko": ["Ján"], "jozo": ["Jozef"], "jozko": ["Jozef"], + "peto": ["Peter"], "mato": ["Matej", "Martin"], "miro": ["Miroslav"], "miso": ["Michal"], "tomi": ["Tomáš"], + "majo": ["Marián", "Mário"], "palo": ["Pavol"], "fero": ["František"], "duro": ["Juraj"], "juro": ["Juraj"], + "dano": ["Daniel"], "danko": ["Daniel"], "rado": ["Radoslav", "Radovan"], "stano": ["Stanislav"], + "vlado": ["Vladimír"], "laco": ["Ladislav"], "riso": ["Richard"], "robo": ["Róbert"], "kubo": ["Jakub"], + "filo": ["Filip"], "ondro": ["Ondrej"], "adko": ["Adam"], "lubo": ["Ľubomír", "Ľuboš"], "maros": ["Maroš"], + "zuzka": ["Zuzana"], "katka": ["Katarína"], "janka": ["Jana"], "evka": ["Eva"], "majka": ["Mária"], + "danka": ["Daniela"], "lucka": ["Lucia"], "miska": ["Michaela"], "baska": ["Barbora"], "tana": ["Tatiana"], + "sasa": ["Alexandra", "Alexander"], "nika": ["Nikola", "Veronika"], "peta": ["Petra"], +} +# Case endings a nickname takes after its stem ("Sama", "Samovi", "Samom"; "Zuzky", "Zuzkou"). +_NICK_ENDINGS = {"", "o", "a", "u", "y", "e", "i", "ou", "om", "ovi"} +MAX_FULL_NAMES = 4 # full-name searches of one asked person +MAX_SURNAME_ONLY = 2 # surname-only searches (first name checked in the rows) as the last resort + + +def nickname_names(word: str) -> list[str]: + """"Samo"/"Sama" -> ["Samuel"], "Zuzky" -> ["Zuzana"]; [] for a word that is no nickname.""" + folded = fold(word) + names = [] + for nick, full in NICKNAMES.items(): + stem = nick[:-1] + if folded == nick or folded.startswith(stem) and folded[len(stem):] in _NICK_ENDINGS: + names += full + return list(dict.fromkeys(names)) + + +def _capital(name: str) -> str: + """"samuel furda" -> "Samuel Furda" (the question may be typed in lower case).""" + return " ".join(w[:1].upper() + w[1:] for w in name.split()) + + +def name_candidates(model_name: str | None, typed: str) -> tuple[list[str], list[str]]: + """Search candidates of an asked person whose name is written in the question: + (full names, most likely first; surnames alone, the last resort). + + The model's base form comes first ("Samuel Feranc"), then the rule base forms of the + typed words ("Samuela Furdy" -> "Samuel Furda", also when the model wrote "Samuel Furd"), + then the full first names of a nickname ("Samo Furda" -> "Samuel Furda").""" + words = typed.split() + full = [_capital(model_name)] if model_name else [] + if len(words) < 2: # one word: the model's form, then the surname candidates + return _unique(full)[:1], _unique([_capital(s) for s in word_forms(typed)])[:MAX_SURNAME_ONLY] + model_words = model_name.split() if model_name and len(model_name.split()) >= 2 else [] + # The rule forms assume an inflected name; a name the model kept as typed is already the nominative. + inflected = not model_words or fold(typed) != fold(model_name) + rule_surname = _capital(surname_variants(typed)[0]) + rule_first = _capital(word_forms(words[0])[0]) + middle = _capital(" ".join(words[1:-1])) + join = lambda first, last: " ".join(p for p in (first, middle, last) if p) + surname = _capital(model_words[-1]) if model_words else rule_surname + # A nickname: the model writes the nominative ("Samo"); without the model the typed form may be inflected ("Sama"). + nicknames = NICKNAMES.get(fold(model_words[0]), []) if model_words else nickname_names(words[0]) + surnames = [surname, *([rule_surname] if inflected else [])] + candidates = [*full, *([join(rule_first, rule_surname)] if inflected else []), + *[join(n, s) for n in nicknames for s in _unique(surnames)]] + return (_unique(candidates)[:MAX_FULL_NAMES], + [s for s in _unique(surnames) if len(fold(s)) >= 3][:MAX_SURNAME_ONLY]) + + +def _unique(names: list[str]) -> list[str]: + seen, result = set(), [] + for name in names: + if name and fold(name) not in seen: + seen.add(fold(name)) + result.append(name) + return result + + def name_variants(name: str) -> list[str]: """Search texts for an inflected name, most likely first: the likeliest first name with each surname candidate, then each surname candidate alone (the diff --git a/tools/crzp/answering/understand.py b/tools/crzp/answering/understand.py index 0f51937..506d3af 100644 --- a/tools/crzp/answering/understand.py +++ b/tools/crzp/answering/understand.py @@ -89,6 +89,7 @@ class Person(BaseModel): name: str = Field(min_length=2, max_length=80) role: Role = "any" typed: str | None = None # the name as written in the question (decides whether diacritics matter) + canonical: bool = False # a name ZP Wiki or CRZP itself gives (searched as it is, no other forms) class CrzpQuery(BaseModel): diff --git a/tools/crzp/tests/test_crzp.py b/tools/crzp/tests/test_crzp.py index 7d4c106..da1d9b6 100644 --- a/tools/crzp/tests/test_crzp.py +++ b/tools/crzp/tests/test_crzp.py @@ -745,3 +745,50 @@ def test_rule_mode_uses_the_tag_crzp_records_carry(tmp_path, monkeypatch): def test_a_code_without_learned_evidence_stays_a_number(): assert units.unit_label({"school": "Technická univerzita v Košiciach", "school_unit": "1040 104003"}) == "FEI, pracovisko 104003" + + +def test_name_candidates_add_base_forms_and_nicknames(): + from tools.crzp.answering.names import name_candidates, nickname_names + assert name_candidates("Samuel Furd", "Samuela Furdy") == (["Samuel Furd", "Samuel Furda"], ["Furd", "Furda"]) + assert name_candidates("Samo Furda", "Samo Furda") == (["Samo Furda", "Samuel Furda"], ["Furda"]) + assert name_candidates("samuel furda", "samuel furda")[0] == ["Samuel Furda"] # typed in lower case + assert name_candidates("Daniel Hládek", "Daniela Hládka")[0] == ["Daniel Hládek"] # nothing to add + assert nickname_names("Sama") == ["Samuel"] and nickname_names("Samuel") == [] and nickname_names("Zuzky") == ["Zuzana"] + + +def _person_model(name, intent="keywords"): + reply = {"intent": intent, "people": [{"name": name, "role": "author"}], "title": None, "topics": [], + "alternatives": [], "target_role": None} + return lambda messages, **kw: {"choices": [{"message": {"content": json.dumps(reply)}}]} + + +def test_a_wrong_model_base_form_is_corrected_by_the_rule_form(crzp): + crzp["result"] = found([]) + crzp["by_text"] = {"Samuel Furda": found([row("Detekcia hrozieb", author="Furda, Samuel")])} + result = A._answer("Aké kľúčové slová má práca Samuela Furdy?", complete=_person_model("Samuel Furd")) + assert result["status"] == "ok" and "Detekcia hrozieb" in result["answer"] + assert [t for t, _ in crzp["searches"]] == ["Samuel Furd", "Samuel Furda"] # the surname alone is not needed + + +def test_a_nickname_finds_the_full_first_name(crzp): + crzp["result"] = found([]) + crzp["by_text"] = {"Samuel Furda": found([row("Detekcia hrozieb", author="Furda, Samuel")])} + result = A._answer("Aké kľúčové slová má práca Samo Furda?", complete=_person_model("Samo Furda")) + assert result["status"] == "ok" and "Detekcia hrozieb" in result["answer"] + assert [t for t, _ in crzp["searches"]] == ["Samo Furda", "Samuel Furda"] + + +def test_no_other_name_form_is_searched_once_the_person_is_found(crzp): + crzp["result"] = found([row("Iná", author="Furda, Samuel", kind="Zverejnená diplomová práca")]) + result = A._answer("Aké kľúčové slová má bakalárska práca Samuela Furdy?", complete=_person_model("Samuel Furd")) + searched = [t for t, _ in crzp["searches"]] + assert "Samuel Furda" not in searched[1:] and len(searched) <= 2 + + +def test_the_surname_alone_is_the_last_resort_and_the_first_name_is_checked(crzp): + crzp["result"] = found([]) + crzp["by_text"] = {"Furda": found([row("Detekcia hrozieb", author="Furda, Samuel"), + row("Cudzia práca", author="Furda, Peter")])} + result = A._answer("Aké kľúčové slová má práca Samka Furdu?", complete=_person_model("Samko Furda")) + searched = [t for t, _ in crzp["searches"]] + assert searched[-1] == "Furda" and "Detekcia hrozieb" in result["answer"] and "Cudzia práca" not in result["answer"]