Dec
This commit is contained in:
commit
e92f6f1a8b
4
.gitignore
vendored
Normal file
4
.gitignore
vendored
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
.env
|
||||||
|
data/chroma/
|
||||||
|
cache/
|
||||||
|
__pycache__/
|
||||||
3
.vscode/settings.json
vendored
Normal file
3
.vscode/settings.json
vendored
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
{
|
||||||
|
"python.terminal.useEnvFile": true
|
||||||
|
}
|
||||||
@ -0,0 +1,9 @@
|
|||||||
|
networkx>=3.2
|
||||||
|
requests>=2.31
|
||||||
|
pypdf>=4.0
|
||||||
|
python-docx>=1.1
|
||||||
|
gradio>=4.0
|
||||||
|
chromadb>=0.5
|
||||||
|
sentence-transformers>=3.0
|
||||||
|
neo4j>=5.0
|
||||||
|
deepeval>=2.0
|
||||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
documents/11678.ba079f.pdf
Normal file
BIN
documents/11678.ba079f.pdf
Normal file
Binary file not shown.
BIN
documents/17683.4d634b.pdf
Normal file
BIN
documents/17683.4d634b.pdf
Normal file
Binary file not shown.
BIN
documents/29705.d2943f.pdf
Normal file
BIN
documents/29705.d2943f.pdf
Normal file
Binary file not shown.
BIN
documents/31348.c5d248.pdf
Normal file
BIN
documents/31348.c5d248.pdf
Normal file
Binary file not shown.
BIN
documents/32637.868230.pdf
Normal file
BIN
documents/32637.868230.pdf
Normal file
Binary file not shown.
BIN
documents/35338.27f1c7.pdf
Normal file
BIN
documents/35338.27f1c7.pdf
Normal file
Binary file not shown.
BIN
documents/35579.191e57.xlsx
Normal file
BIN
documents/35579.191e57.xlsx
Normal file
Binary file not shown.
BIN
documents/35808.3830ec.docx
Normal file
BIN
documents/35808.3830ec.docx
Normal file
Binary file not shown.
BIN
documents/35809.153b9f.docx
Normal file
BIN
documents/35809.153b9f.docx
Normal file
Binary file not shown.
BIN
documents/35810.897bd9.docx
Normal file
BIN
documents/35810.897bd9.docx
Normal file
Binary file not shown.
BIN
documents/35815.10b47a.pdf
Normal file
BIN
documents/35815.10b47a.pdf
Normal file
Binary file not shown.
7196
documents/37521.08ad6b.pdf
Normal file
7196
documents/37521.08ad6b.pdf
Normal file
File diff suppressed because it is too large
Load Diff
BIN
documents/37569.252606.pdf
Normal file
BIN
documents/37569.252606.pdf
Normal file
Binary file not shown.
BIN
documents/37725.77184f.pdf
Normal file
BIN
documents/37725.77184f.pdf
Normal file
Binary file not shown.
BIN
documents/37726.df6e96.pdf
Normal file
BIN
documents/37726.df6e96.pdf
Normal file
Binary file not shown.
BIN
documents/Buletin_Ped-Asistent.pdf
Normal file
BIN
documents/Buletin_Ped-Asistent.pdf
Normal file
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
documents/Dyslexia-prevencia.pdf
Normal file
BIN
documents/Dyslexia-prevencia.pdf
Normal file
Binary file not shown.
BIN
documents/EV_1st.pdf
Normal file
BIN
documents/EV_1st.pdf
Normal file
Binary file not shown.
BIN
documents/EV_2st.pdf
Normal file
BIN
documents/EV_2st.pdf
Normal file
Binary file not shown.
BIN
documents/FRJ_2st.pdf
Normal file
BIN
documents/FRJ_2st.pdf
Normal file
Binary file not shown.
BIN
documents/HUD_1st.pdf
Normal file
BIN
documents/HUD_1st.pdf
Normal file
Binary file not shown.
BIN
documents/HUD_2st.pdf
Normal file
BIN
documents/HUD_2st.pdf
Normal file
Binary file not shown.
BIN
documents/MDJ_1st.pdf
Normal file
BIN
documents/MDJ_1st.pdf
Normal file
Binary file not shown.
BIN
documents/NBV1_1st.pdf
Normal file
BIN
documents/NBV1_1st.pdf
Normal file
Binary file not shown.
BIN
documents/NBV1_2st.pdf
Normal file
BIN
documents/NBV1_2st.pdf
Normal file
Binary file not shown.
BIN
documents/NBV2_1st.pdf
Normal file
BIN
documents/NBV2_1st.pdf
Normal file
Binary file not shown.
BIN
documents/NBV2_2st.pdf
Normal file
BIN
documents/NBV2_2st.pdf
Normal file
Binary file not shown.
BIN
documents/NBV3_1st.pdf
Normal file
BIN
documents/NBV3_1st.pdf
Normal file
Binary file not shown.
BIN
documents/NBV3_2st.pdf
Normal file
BIN
documents/NBV3_2st.pdf
Normal file
Binary file not shown.
BIN
documents/NBV4_1st.pdf
Normal file
BIN
documents/NBV4_1st.pdf
Normal file
Binary file not shown.
BIN
documents/NBV4_2st.pdf
Normal file
BIN
documents/NBV4_2st.pdf
Normal file
Binary file not shown.
BIN
documents/NBV5_1st.pdf
Normal file
BIN
documents/NBV5_1st.pdf
Normal file
Binary file not shown.
BIN
documents/NBV5_2st.pdf
Normal file
BIN
documents/NBV5_2st.pdf
Normal file
Binary file not shown.
BIN
documents/NEJ_2st.pdf
Normal file
BIN
documents/NEJ_2st.pdf
Normal file
Binary file not shown.
BIN
documents/Odporúčané učebné priestory a ich vybavenie.pdf
Normal file
BIN
documents/Odporúčané učebné priestory a ich vybavenie.pdf
Normal file
Binary file not shown.
BIN
documents/Odporúčané vybavenie učebných priestorov.pdf
Normal file
BIN
documents/Odporúčané vybavenie učebných priestorov.pdf
Normal file
Binary file not shown.
BIN
documents/PRIMÁRNE VZDELÁVANIE – 1. STUPEŇ ZÁKLADNEJ ŠKOLY.pdf
Normal file
BIN
documents/PRIMÁRNE VZDELÁVANIE – 1. STUPEŇ ZÁKLADNEJ ŠKOLY.pdf
Normal file
Binary file not shown.
BIN
documents/PU_1st.pdf
Normal file
BIN
documents/PU_1st.pdf
Normal file
Binary file not shown.
BIN
documents/PV_1st.pdf
Normal file
BIN
documents/PV_1st.pdf
Normal file
Binary file not shown.
BIN
documents/Pedagogicky_asistent_(1).pdf
Normal file
BIN
documents/Pedagogicky_asistent_(1).pdf
Normal file
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
documents/RIJ_1st.pdf
Normal file
BIN
documents/RIJ_1st.pdf
Normal file
Binary file not shown.
BIN
documents/RIJ_2st.pdf
Normal file
BIN
documents/RIJ_2st.pdf
Normal file
Binary file not shown.
BIN
documents/ROJ_1st.pdf
Normal file
BIN
documents/ROJ_1st.pdf
Normal file
Binary file not shown.
BIN
documents/ROJ_2st.pdf
Normal file
BIN
documents/ROJ_2st.pdf
Normal file
Binary file not shown.
BIN
documents/RUJ_2st.pdf
Normal file
BIN
documents/RUJ_2st.pdf
Normal file
Binary file not shown.
BIN
documents/RÁMCOVÝ UČEBNÝ PLÁN 2.pdf
Normal file
BIN
documents/RÁMCOVÝ UČEBNÝ PLÁN 2.pdf
Normal file
Binary file not shown.
BIN
documents/RÁMCOVÝ UČEBNÝ PLÁN 3.pdf
Normal file
BIN
documents/RÁMCOVÝ UČEBNÝ PLÁN 3.pdf
Normal file
Binary file not shown.
BIN
documents/RÁMCOVÝ UČEBNÝ PLÁN.pdf
Normal file
BIN
documents/RÁMCOVÝ UČEBNÝ PLÁN.pdf
Normal file
Binary file not shown.
BIN
documents/SPJ_2st.pdf
Normal file
BIN
documents/SPJ_2st.pdf
Normal file
Binary file not shown.
BIN
documents/Skolska_integracia_1_2_21_1.pdf
Normal file
BIN
documents/Skolska_integracia_1_2_21_1.pdf
Normal file
Binary file not shown.
BIN
documents/TECH_2st.pdf
Normal file
BIN
documents/TECH_2st.pdf
Normal file
Binary file not shown.
BIN
documents/TJ_2st.pdf
Normal file
BIN
documents/TJ_2st.pdf
Normal file
Binary file not shown.
BIN
documents/UKRJ_1st.pdf
Normal file
BIN
documents/UKRJ_1st.pdf
Normal file
Binary file not shown.
BIN
documents/UKRJ_2st.pdf
Normal file
BIN
documents/UKRJ_2st.pdf
Normal file
Binary file not shown.
BIN
documents/UO-1._cyklus.pdf
Normal file
BIN
documents/UO-1._cyklus.pdf
Normal file
Binary file not shown.
BIN
documents/VYT_1st.pdf
Normal file
BIN
documents/VYT_1st.pdf
Normal file
Binary file not shown.
BIN
documents/VYT_2st.pdf
Normal file
BIN
documents/VYT_2st.pdf
Normal file
Binary file not shown.
BIN
documents/prirucka_asistenta_ucitela.pdf
Normal file
BIN
documents/prirucka_asistenta_ucitela.pdf
Normal file
Binary file not shown.
BIN
documents/{1FDFF8FF-4073-42B1-89C7-40882BB4924C}.pdf
Normal file
BIN
documents/{1FDFF8FF-4073-42B1-89C7-40882BB4924C}.pdf
Normal file
Binary file not shown.
142
evaluate.py
Normal file
142
evaluate.py
Normal file
@ -0,0 +1,142 @@
|
|||||||
|
"""Evaluate GraphRAG responses with DeepEval."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from main import ask_question, get_or_build_graph
|
||||||
|
|
||||||
|
|
||||||
|
DEFAULT_DATASET = Path(__file__).with_name("evaluation_dataset.json")
|
||||||
|
|
||||||
|
|
||||||
|
def load_questions(path: Path) -> list[dict[str, str]]:
|
||||||
|
with path.open("r", encoding="utf-8") as file:
|
||||||
|
data = json.load(file)
|
||||||
|
if not isinstance(data, list):
|
||||||
|
raise ValueError("Evaluation dataset must be a JSON array")
|
||||||
|
return [item for item in data if isinstance(item, dict)]
|
||||||
|
|
||||||
|
|
||||||
|
def configure_deepeval_llm() -> None:
|
||||||
|
"""Map the project's OpenAI-compatible settings to DeepEval's defaults."""
|
||||||
|
api_key = os.getenv("UNIVERSITY_API_KEY")
|
||||||
|
if api_key:
|
||||||
|
os.environ.setdefault("OPENAI_API_KEY", api_key)
|
||||||
|
|
||||||
|
base_url = os.getenv("UNIVERSITY_BASE_URL")
|
||||||
|
if base_url:
|
||||||
|
os.environ.setdefault(
|
||||||
|
"OPENAI_BASE_URL",
|
||||||
|
base_url.removesuffix("/chat/completions").rstrip("/"),
|
||||||
|
)
|
||||||
|
os.environ.setdefault("OPENAI_MODEL_NAME", os.getenv("UNIVERSITY_MODEL", "model2"))
|
||||||
|
os.environ.setdefault(
|
||||||
|
"DEEPEVAL_PER_ATTEMPT_TIMEOUT_SECONDS_OVERRIDE",
|
||||||
|
os.getenv("DEEPEVAL_TIMEOUT", "180"),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def evaluate_case(test_case: Any, metrics: list[Any]) -> dict[str, Any]:
|
||||||
|
results: dict[str, Any] = {}
|
||||||
|
for metric in metrics:
|
||||||
|
metric.measure(test_case)
|
||||||
|
name = metric.__class__.__name__
|
||||||
|
results[name] = {
|
||||||
|
"score": metric.score,
|
||||||
|
"reason": metric.reason,
|
||||||
|
"success": metric.is_successful(),
|
||||||
|
}
|
||||||
|
return results
|
||||||
|
|
||||||
|
|
||||||
|
def run_evaluation(dataset_path: Path, output_path: Path, rebuild: bool = False):
|
||||||
|
configure_deepeval_llm()
|
||||||
|
from deepeval.metrics import (
|
||||||
|
AnswerRelevancyMetric,
|
||||||
|
ContextualRelevancyMetric,
|
||||||
|
FaithfulnessMetric,
|
||||||
|
)
|
||||||
|
from deepeval.test_case import LLMTestCase
|
||||||
|
|
||||||
|
graph = get_or_build_graph(force_rebuild=rebuild)
|
||||||
|
rows = load_questions(dataset_path)
|
||||||
|
test_cases = []
|
||||||
|
for item in rows:
|
||||||
|
question = str(item.get("question", "")).strip()
|
||||||
|
if not question:
|
||||||
|
continue
|
||||||
|
response = ask_question(graph, question)
|
||||||
|
contexts = [
|
||||||
|
line.strip()
|
||||||
|
for line in (response.evidence or "").splitlines()
|
||||||
|
if line.strip()
|
||||||
|
]
|
||||||
|
actual_output = str(response.answer or "").strip()
|
||||||
|
if not actual_output:
|
||||||
|
raise RuntimeError(
|
||||||
|
f"GraphRAG returned an empty answer for evaluation question: {question!r}"
|
||||||
|
)
|
||||||
|
case_kwargs = {
|
||||||
|
"input": question,
|
||||||
|
"actual_output": actual_output,
|
||||||
|
"retrieval_context": contexts,
|
||||||
|
}
|
||||||
|
ground_truth = str(item.get("ground_truth", "")).strip()
|
||||||
|
if ground_truth:
|
||||||
|
case_kwargs["expected_output"] = ground_truth
|
||||||
|
test_cases.append(LLMTestCase(**case_kwargs))
|
||||||
|
|
||||||
|
if not test_cases:
|
||||||
|
raise ValueError("Evaluation dataset contains no valid questions")
|
||||||
|
|
||||||
|
metrics = [
|
||||||
|
FaithfulnessMetric(threshold=0.5, async_mode=False),
|
||||||
|
AnswerRelevancyMetric(threshold=0.5, async_mode=False),
|
||||||
|
ContextualRelevancyMetric(threshold=0.5, async_mode=False),
|
||||||
|
]
|
||||||
|
evaluations = []
|
||||||
|
for test_case in test_cases:
|
||||||
|
if not test_case.retrieval_context:
|
||||||
|
print(
|
||||||
|
f"Warning: no graph context was retrieved for {test_case.input!r}; "
|
||||||
|
"faithfulness and contextual relevancy may be low."
|
||||||
|
)
|
||||||
|
evaluations.append(
|
||||||
|
{
|
||||||
|
"input": test_case.input,
|
||||||
|
"actual_output": test_case.actual_output,
|
||||||
|
"retrieval_context": test_case.retrieval_context,
|
||||||
|
"expected_output": getattr(test_case, "expected_output", None),
|
||||||
|
"metrics": evaluate_case(test_case, metrics),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
output = {
|
||||||
|
"framework": "deepeval",
|
||||||
|
"metrics": [metric.__class__.__name__ for metric in metrics],
|
||||||
|
"evaluations": evaluations,
|
||||||
|
}
|
||||||
|
output_path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
output_path.write_text(
|
||||||
|
json.dumps(output, ensure_ascii=False, indent=2),
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
|
print(f"Saved DeepEval evaluation to {output_path}")
|
||||||
|
return output
|
||||||
|
|
||||||
|
|
||||||
|
def parse_args() -> argparse.Namespace:
|
||||||
|
parser = argparse.ArgumentParser(description="Evaluate GraphRAG answers with DeepEval")
|
||||||
|
parser.add_argument("--dataset", type=Path, default=DEFAULT_DATASET)
|
||||||
|
parser.add_argument("--output", type=Path, default=Path("evaluation_results.json"))
|
||||||
|
parser.add_argument("--rebuild", action="store_true")
|
||||||
|
return parser.parse_args()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
args = parse_args()
|
||||||
|
run_evaluation(args.dataset, args.output, args.rebuild)
|
||||||
6
evaluation_dataset.json
Normal file
6
evaluation_dataset.json
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
[
|
||||||
|
{
|
||||||
|
"question": "Ake deila sa preberaju na literatúre?",
|
||||||
|
"ground_truth": ""
|
||||||
|
}
|
||||||
|
]
|
||||||
131
evaluation_results.json
Normal file
131
evaluation_results.json
Normal file
@ -0,0 +1,131 @@
|
|||||||
|
[
|
||||||
|
{
|
||||||
|
"user_input":"Ake diela sa preberaju na literature?",
|
||||||
|
"retrieved_contexts":[
|
||||||
|
"Vonkajšia Kompozícia Literárneho Diela --is_a--> Kompozícia Literárneho Diela",
|
||||||
|
"Vnútorná Kompozícia Literárneho Diela --is_a--> Kompozícia Literárneho Diela",
|
||||||
|
"Ukrainian Literature In Slovakia --subfield_of--> Ukrainian Language And Literature",
|
||||||
|
"Ukrainian Language And Literature --applies_to--> Lower Secondary Education",
|
||||||
|
"Ukrainian Language And Literature --teaches--> Vocabulary Management",
|
||||||
|
"Ukrainian Language And Literature --teaches--> Morphological Analysis",
|
||||||
|
"Ukrainian Language And Literature --teaches--> Syntactic Analysis",
|
||||||
|
"Ukrainian Language And Literature --teaches--> Text Analysis",
|
||||||
|
"Ukrainian Language And Literature --teaches--> Oral Communication",
|
||||||
|
"Ukrainian Language And Literature --teaches--> Writing Production",
|
||||||
|
"Ukrainian Language And Literature --teaches--> Reading Comprehension",
|
||||||
|
"Ukrainian Language And Literature --teaches--> Punctuation",
|
||||||
|
"Ukrainian Language And Literature --teaches--> Narrative Composition",
|
||||||
|
"Slovak Language And Literature --teaches--> Bullying",
|
||||||
|
"Slovak Language And Literature --part_of--> Primary Education",
|
||||||
|
"Slovak Language And Literature --applies_to--> Hungarian-Language Schools",
|
||||||
|
"Slovak Language And Literature --teaches--> Communication Skills",
|
||||||
|
"Slovak Language And Literature --teaches--> Grammar",
|
||||||
|
"Slovak Language And Literature --teaches--> Vocabulary",
|
||||||
|
"Slovak Language And Literature --implements--> Slovak As A Second Language",
|
||||||
|
"Slovak Language And Literature --teaches--> Slovak Grammar",
|
||||||
|
"Slovak Language And Literature --teaches--> Vocabulary Themes",
|
||||||
|
"Slovak Language And Literature --applies_to--> Lower Secondary Education",
|
||||||
|
"Slovak Language And Literature --teaches--> Storytelling",
|
||||||
|
"Slovak Language And Literature --teaches--> Description",
|
||||||
|
"Slovak Language And Literature --teaches--> Reproduction",
|
||||||
|
"Slovak Language And Literature --teaches--> Vocabulary Acquisition",
|
||||||
|
"Slovak Language And Literature --teaches--> Orthography Of I\/Y And Í\/Ý",
|
||||||
|
"Slovak Language And Literature --teaches--> Adjective Agreement",
|
||||||
|
"Slovak Language And Literature --teaches--> Work With Dictionaries",
|
||||||
|
"Slovak Language And Literature --teaches--> Oral Communication",
|
||||||
|
"Slovak Language And Literature --teaches--> Written Communication",
|
||||||
|
"Slovak Language And Literature --teaches--> Reading Comprehension",
|
||||||
|
"Slovak Language And Literature --teaches--> Literature Reproduction",
|
||||||
|
"Slovak Language And Literature --contains--> Reading Literacy",
|
||||||
|
"Slovak Language And Literature --uses--> Literary Text",
|
||||||
|
"Slovak Language And Literature --uses--> Creative Drama",
|
||||||
|
"Slovak Language And Literature --teaches--> Empathy Formation",
|
||||||
|
"Slovak Language And Literature --teaches--> Reading Portfolio",
|
||||||
|
"Slovak Language And Literature --applies_to--> Theater Performance",
|
||||||
|
"Slovak Language And Literature --applies_to--> Film Performance",
|
||||||
|
"Slovak Language And Literature --requires--> Library Navigation",
|
||||||
|
"Sformulovanie Hodnotenia Diela --requires--> Kritické Myslenie",
|
||||||
|
"Rusyn Language And Literature --part_of--> Lower Secondary Education",
|
||||||
|
"Rusyn Language And Literature --teaches--> Communication And Composition",
|
||||||
|
"Romany Language And Literature --applies_to--> Lower Secondary Education",
|
||||||
|
"Romany Language And Literature --contains--> Listening Comprehension",
|
||||||
|
"Romany Language And Literature --contains--> Reading Comprehension",
|
||||||
|
"Romany Language And Literature --contains--> Oral Interaction",
|
||||||
|
"Romany Language And Literature --contains--> Oral Expression",
|
||||||
|
"Romany Language And Literature --contains--> Written Expression",
|
||||||
|
"Romany Language And Literature --contains--> Vocabulary",
|
||||||
|
"Romany Language And Literature --contains--> Morphology",
|
||||||
|
"Romany Language And Literature --teaches--> Romany Language",
|
||||||
|
"Romany Language And Literature --teaches--> Romany Tradition",
|
||||||
|
"Romany Language And Literature --teaches--> Weather",
|
||||||
|
"Romany Language And Literature --teaches--> Seasons",
|
||||||
|
"Romany Language And Literature --teaches--> Animals",
|
||||||
|
"Romany Language And Literature --teaches--> Plants",
|
||||||
|
"Romany Language And Literature --teaches--> Sports",
|
||||||
|
"Romany Language And Literature --teaches--> Transport",
|
||||||
|
"Romany Language And Literature --teaches--> Clothing",
|
||||||
|
"Romany Language And Literature --teaches--> Food",
|
||||||
|
"Romany Language And Literature --teaches--> Crafts",
|
||||||
|
"Romany Language And Literature --teaches--> Professions",
|
||||||
|
"Romany Language And Literature --teaches--> Family",
|
||||||
|
"Romany Language And Literature --teaches--> School",
|
||||||
|
"Romany Language And Literature --teaches--> Time",
|
||||||
|
"Romany Language And Literature --teaches--> Numbers",
|
||||||
|
"Romani Language And Literature --part_of--> Primary Education",
|
||||||
|
"Romani Language And Literature --applies_to--> 4Th Grade",
|
||||||
|
"Romani Language And Literature --contains--> Morphology",
|
||||||
|
"Romani Language And Literature --teaches--> Syntax",
|
||||||
|
"Romani Language And Literature --teaches--> Lexicon",
|
||||||
|
"Romani Language And Literature --teaches--> Pronunciation",
|
||||||
|
"Romani Language And Literature --teaches--> Listening Comprehension",
|
||||||
|
"Romani Language And Literature --contains--> Reading Comprehension",
|
||||||
|
"Romani Language And Literature --contains--> Oral Interaction",
|
||||||
|
"Romani Language And Literature --teaches--> Oral Production",
|
||||||
|
"Romani Language And Literature --teaches--> Written Production",
|
||||||
|
"Romani Language And Literature --applies_to--> Lower Secondary Education",
|
||||||
|
"Romani Language And Literature --part_of--> 9Th Grade",
|
||||||
|
"Romani Language And Literature --teaches--> Nouns",
|
||||||
|
"Romani Language And Literature --teaches--> Adjectives",
|
||||||
|
"Romani Language And Literature --teaches--> Pronouns",
|
||||||
|
"Romani Language And Literature --teaches--> Numerals",
|
||||||
|
"Romani Language And Literature --teaches--> Verbs",
|
||||||
|
"Romani Language And Literature --teaches--> Adverbs",
|
||||||
|
"Romani Language And Literature --teaches--> Prepositions",
|
||||||
|
"Romani Language And Literature --teaches--> Conjunctions",
|
||||||
|
"Romani Language And Literature --teaches--> Particles",
|
||||||
|
"Romani Language And Literature --teaches--> Orthography",
|
||||||
|
"Romani Language And Literature --teaches--> Self And Family Information",
|
||||||
|
"Romani Language And Literature --teaches--> Interests And Daily Activities",
|
||||||
|
"Romani Language And Literature --teaches--> Expression Of Feelings",
|
||||||
|
"Romani Language And Literature --teaches--> Body Parts And Health",
|
||||||
|
"Romani Language And Literature --teaches--> Family Activities",
|
||||||
|
"Romani Language And Literature --teaches--> Roma Customs And Traditions",
|
||||||
|
"Romani Language And Literature --teaches--> Home And Apartment",
|
||||||
|
"Romani Language And Literature --teaches--> Furniture",
|
||||||
|
"Romani Language And Literature --teaches--> City Buildings",
|
||||||
|
"Romani Language And Literature --teaches--> Trades And Professions",
|
||||||
|
"Romani Language And Literature --teaches--> Celebrations And Holidays",
|
||||||
|
"Romani Language And Literature --teaches--> School Subjects",
|
||||||
|
"Romani Language And Literature --contains--> Oral Expression",
|
||||||
|
"Romani Language And Literature --contains--> Written Expression",
|
||||||
|
"Romani Language And Literature --contains--> Vocabulary",
|
||||||
|
"Romani Language And Literature --teaches--> Romani Culture",
|
||||||
|
"Romani Language And Literature --teaches--> Daily Life",
|
||||||
|
"Romani Language And Literature --teaches--> Family",
|
||||||
|
"Romani Language And Literature --teaches--> Travel",
|
||||||
|
"Romani Language And Literature --teaches--> Food",
|
||||||
|
"Romani Language And Literature --teaches--> Clothing",
|
||||||
|
"Romani Language And Literature --teaches--> Weather",
|
||||||
|
"Romani Language And Literature --teaches--> Animals",
|
||||||
|
"Romani Language And Literature --teaches--> Romani Crafts",
|
||||||
|
"Romani Language And Literature --teaches--> Romani Professions",
|
||||||
|
"Romani Language And Literature --teaches--> School",
|
||||||
|
"Romani Language And Literature --teaches--> Leisure Activities",
|
||||||
|
"Kompozícia Literárneho Diela --part_of--> Literárna Teória",
|
||||||
|
"Interpretovať Umelecké Diela --uses--> Vizuálna Symbolika",
|
||||||
|
"Children'S Literature --uses--> Slovak Language Environment"
|
||||||
|
],
|
||||||
|
"response":"Na základe poskytnutých grafových údajov možno pre učiteľa určiť nasledujúce kategórie diel a textov, ktoré sú súčasťou výučby literatúry (najmä v rámci predmetu Slovenský jazyk a literatúra):\n\n* **Literárny text (Literary Text):** Predmet Slovenský jazyk a literatúra priamo využíva literárne texty.\n* **Detská literatúra (Children'S Literature):** Táto kategória je prepojená so slovenským jazykovým prostredím.\n* **Umelecké diela (Artistic Works):** Študenti sa učia tieto diela interpretovať, pričom sa využíva vizuálna symbolika.\n\nOkrem samotných diel sa v rámci literárnej teórie preberá aj **kompozícia literárneho diela** (rozlišuje sa na vnútornú a vonkajšiu kompozíciu) a študenti sa učia **reprodukciu literatúry**.\n\n*Poznámka: Z dostupných grafových údajov nie sú uvedené konkrétne názvy kníh ani mená autorov, ale len vyššie spomenuté kategórie a teoretické koncepty.*",
|
||||||
|
"faithfulness":null
|
||||||
|
}
|
||||||
|
]
|
||||||
156
gradio_app.py
Normal file
156
gradio_app.py
Normal file
@ -0,0 +1,156 @@
|
|||||||
|
"""Teacher-facing Gradio demo preserving graph evidence and visualization."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import gradio as gr
|
||||||
|
|
||||||
|
from main import get_or_build_graph
|
||||||
|
from react_agent import react_agent
|
||||||
|
from tools import answer_general_question, check_teaching_suitability
|
||||||
|
|
||||||
|
|
||||||
|
GRAPH = get_or_build_graph()
|
||||||
|
|
||||||
|
|
||||||
|
def prepare_lesson(subject: str, grade: str, topic: str, duration: str, language: str):
|
||||||
|
subject = subject.strip() or "not specified"
|
||||||
|
grade = grade.strip() or "not specified"
|
||||||
|
topic = topic.strip() or "not specified"
|
||||||
|
duration = duration.strip() or "45"
|
||||||
|
language = language.strip() or "Slovak"
|
||||||
|
request = f"""Prepare a well-structured {duration}-minute lesson in {language}.
|
||||||
|
Subject: {subject}
|
||||||
|
Grade: {grade}
|
||||||
|
Topic: {topic}
|
||||||
|
|
||||||
|
Some fields may be unspecified. Make sensible, clearly stated assumptions for
|
||||||
|
missing fields and keep the lesson adaptable. If the topic is unspecified,
|
||||||
|
choose a suitable topic only when the graph evidence supports it; otherwise
|
||||||
|
propose a clearly labelled topic assumption rather than presenting it as a
|
||||||
|
confirmed curriculum fact.
|
||||||
|
|
||||||
|
Return a complete lesson plan with:
|
||||||
|
1. Assumptions and intended learners
|
||||||
|
2. Learning objectives
|
||||||
|
3. Materials and preparation
|
||||||
|
4. Step-by-step activities with approximate timings
|
||||||
|
5. Differentiation and inclusion
|
||||||
|
6. Assessment
|
||||||
|
7. Homework or extension
|
||||||
|
Use only the retrieved graph evidence for curriculum-specific claims."""
|
||||||
|
try:
|
||||||
|
response = react_agent(request, [], GRAPH, language)
|
||||||
|
except (RuntimeError, TimeoutError) as error:
|
||||||
|
return f"Unable to generate the lesson: {error}", "No answer was returned by the LLM service."
|
||||||
|
return response.answer, response.evidence or "No graph evidence retrieved."
|
||||||
|
|
||||||
|
|
||||||
|
def check_suitability(subject: str, grade: str, topic: str, conditions: str, language: str):
|
||||||
|
try:
|
||||||
|
result = check_teaching_suitability(subject, grade, topic, conditions, GRAPH, language)
|
||||||
|
except (RuntimeError, TimeoutError) as error:
|
||||||
|
return f"Unable to assess suitability: {error}", "No answer was returned by the LLM service."
|
||||||
|
return result["answer"], result["evidence"] or "No graph evidence retrieved."
|
||||||
|
|
||||||
|
|
||||||
|
def answer_question(question: str, language: str = "Slovak"):
|
||||||
|
question = question.strip()
|
||||||
|
if not question:
|
||||||
|
return "Please enter a question.", ""
|
||||||
|
try:
|
||||||
|
result = answer_general_question(question, GRAPH, language)
|
||||||
|
except (RuntimeError, TimeoutError) as error:
|
||||||
|
return f"Unable to answer the question: {error}", "No answer was returned by the LLM service."
|
||||||
|
return result["answer"], result["evidence"] or "No graph evidence retrieved."
|
||||||
|
|
||||||
|
|
||||||
|
def create_demo():
|
||||||
|
with gr.Blocks(title="GraphRAG Teacher Assistant") as demo:
|
||||||
|
gr.Markdown("# GraphRAG teacher assistant\nAnswers questions and prepares lessons using linked graph evidence.")
|
||||||
|
|
||||||
|
with gr.Tab("General Q&A"):
|
||||||
|
gr.Markdown(
|
||||||
|
"Ask a general question about curriculum, teaching topics, educational needs, "
|
||||||
|
"or documents. Answers are kept separate from lesson planning."
|
||||||
|
)
|
||||||
|
question = gr.Textbox(
|
||||||
|
label="Question",
|
||||||
|
placeholder="For example: What is the role of a pedagogical assistant in primary schools?",
|
||||||
|
lines=3,
|
||||||
|
)
|
||||||
|
general_language = gr.Dropdown(
|
||||||
|
choices=["Slovak", "English"],
|
||||||
|
value="Slovak",
|
||||||
|
label="Answer language",
|
||||||
|
)
|
||||||
|
ask_button = gr.Button("Ask", variant="primary")
|
||||||
|
general_answer = gr.Markdown(label="Answer")
|
||||||
|
general_evidence = gr.Textbox(label="Graph evidence", lines=8)
|
||||||
|
ask_button.click(
|
||||||
|
answer_question,
|
||||||
|
[question, general_language],
|
||||||
|
[general_answer, general_evidence],
|
||||||
|
)
|
||||||
|
|
||||||
|
with gr.Tab("Lesson preparation"):
|
||||||
|
with gr.Row():
|
||||||
|
subject = gr.Textbox(
|
||||||
|
label="Subject (optional)",
|
||||||
|
placeholder="Leave blank to let the assistant make an assumption",
|
||||||
|
)
|
||||||
|
grade = gr.Textbox(
|
||||||
|
label="Grade (optional)",
|
||||||
|
placeholder="Leave blank for an adaptable lesson",
|
||||||
|
)
|
||||||
|
topic = gr.Textbox(
|
||||||
|
label="Topic (optional)",
|
||||||
|
placeholder="Leave blank to request a suitable topic assumption",
|
||||||
|
)
|
||||||
|
with gr.Row():
|
||||||
|
duration = gr.Textbox(value="45", label="Duration (minutes, optional)")
|
||||||
|
language = gr.Dropdown(
|
||||||
|
choices=["Slovak", "English"],
|
||||||
|
value="Slovak",
|
||||||
|
label="Answer language",
|
||||||
|
)
|
||||||
|
button = gr.Button("Prepare lesson", variant="primary")
|
||||||
|
answer = gr.Markdown(label="Lesson plan")
|
||||||
|
evidence = gr.Textbox(label="Graph evidence", lines=8)
|
||||||
|
button.click(prepare_lesson, [subject, grade, topic, duration, language], [answer, evidence])
|
||||||
|
|
||||||
|
with gr.Tab("Teaching suitability and compliance"):
|
||||||
|
gr.Markdown(
|
||||||
|
"This advisory feature indicates whether available curriculum evidence supports a topic "
|
||||||
|
"or teaching condition. It is not a legal opinion."
|
||||||
|
)
|
||||||
|
suitability_subject = gr.Textbox(label="Subject")
|
||||||
|
suitability_grade = gr.Textbox(label="Grade")
|
||||||
|
suitability_topic = gr.Textbox(label="Topic")
|
||||||
|
suitability_conditions = gr.Textbox(
|
||||||
|
label="Specific conditions",
|
||||||
|
placeholder="For example: mixed ability class, ADHD, 30-minute class, outdoor teaching, no internet",
|
||||||
|
lines=4,
|
||||||
|
)
|
||||||
|
suitability_language = gr.Dropdown(
|
||||||
|
choices=["Slovak", "English"],
|
||||||
|
value="Slovak",
|
||||||
|
label="Answer language",
|
||||||
|
)
|
||||||
|
suitability_button = gr.Button("Check suitability", variant="primary")
|
||||||
|
suitability_answer = gr.Markdown(label="Suitability assessment")
|
||||||
|
suitability_evidence = gr.Textbox(label="Graph evidence", lines=8)
|
||||||
|
suitability_button.click(
|
||||||
|
check_suitability,
|
||||||
|
[
|
||||||
|
suitability_subject,
|
||||||
|
suitability_grade,
|
||||||
|
suitability_topic,
|
||||||
|
suitability_conditions,
|
||||||
|
suitability_language,
|
||||||
|
],
|
||||||
|
[suitability_answer, suitability_evidence],
|
||||||
|
)
|
||||||
|
return demo
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
create_demo().launch()
|
||||||
87069
graph/kg.graphml
87069
graph/kg.graphml
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
485
graph_builder.py
485
graph_builder.py
@ -1,411 +1,156 @@
|
|||||||
|
"""Graph construction with LLM extraction, concept clustering and optional Neo4j sync."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
import networkx as nx
|
|
||||||
import re
|
import re
|
||||||
import hashlib
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
import networkx as nx
|
||||||
|
|
||||||
from ingest import load_documents
|
from ingest import load_documents
|
||||||
from llm import llm_call
|
from llm import llm_call
|
||||||
|
|
||||||
# Cleans response to avoid errors
|
RELATIONS = {
|
||||||
def clean_llm_response(text: str) -> str:
|
"is_a", "part_of", "uses", "teaches", "requires", "depends_on",
|
||||||
"""
|
"implements", "applies_to", "subfield_of", "contains", "defined_by",
|
||||||
Removes markdown, extra text, and extracts JSON safely.
|
"related_to",
|
||||||
"""
|
}
|
||||||
|
|
||||||
if not text:
|
|
||||||
raise ValueError("LLM returned empty response")
|
|
||||||
|
|
||||||
text = text.strip()
|
|
||||||
|
|
||||||
# Remove ```json or ``` wrappers
|
|
||||||
text = re.sub(r"^```json", "", text)
|
|
||||||
text = re.sub(r"^```", "", text)
|
|
||||||
text = re.sub(r"```$", "", text)
|
|
||||||
|
|
||||||
text = text.strip()
|
|
||||||
|
|
||||||
# Try to extract JSON object if model adds extra text
|
|
||||||
match = re.search(r"\{.*\}", text, re.DOTALL)
|
|
||||||
if match:
|
|
||||||
return match.group(0)
|
|
||||||
|
|
||||||
return text
|
|
||||||
|
|
||||||
# Gets cached extraction for a chunk, or extracts and caches it
|
|
||||||
def get_cached_extraction(chunk, cache_dir="cache"):
|
|
||||||
|
|
||||||
os.makedirs(cache_dir, exist_ok=True)
|
|
||||||
|
|
||||||
# Create unique hash for chunk
|
|
||||||
chunk_hash = hashlib.md5(
|
|
||||||
chunk.encode("utf-8")
|
|
||||||
).hexdigest()
|
|
||||||
|
|
||||||
cache_path = os.path.join(
|
|
||||||
cache_dir,
|
|
||||||
f"{chunk_hash}.json"
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
# Cache Load (if exists)
|
def _normalise(value: str) -> str:
|
||||||
if os.path.exists(cache_path):
|
return " ".join(value.strip().split()).title()
|
||||||
|
|
||||||
print(f"[CACHE HIT] {chunk_hash}")
|
|
||||||
|
|
||||||
with open(cache_path, "r", encoding="utf-8") as f:
|
|
||||||
return json.load(f)
|
|
||||||
|
|
||||||
|
|
||||||
# Extract json and store in cache
|
def _json_response(text: str) -> dict[str, Any]:
|
||||||
print(f"[CACHE MISS] {chunk_hash}")
|
cleaned = re.sub(r"^```(?:json)?\s*|```\s*$", "", text.strip(), flags=re.MULTILINE).strip()
|
||||||
|
decoder = json.JSONDecoder()
|
||||||
extraction = extract_entities_and_relations(chunk)
|
|
||||||
|
|
||||||
|
|
||||||
# Save cache
|
|
||||||
with open(cache_path, "w", encoding="utf-8") as f:
|
|
||||||
json.dump(
|
|
||||||
extraction,
|
|
||||||
f,
|
|
||||||
indent=2,
|
|
||||||
ensure_ascii=False
|
|
||||||
)
|
|
||||||
|
|
||||||
return extraction
|
|
||||||
|
|
||||||
# Calls LLM to get entities and realtions (.json) and saves them to cache
|
|
||||||
def extract_entities_and_relations(text):
|
|
||||||
|
|
||||||
text = text[:8000] # prevent context overflow
|
|
||||||
|
|
||||||
prompt = f"""
|
|
||||||
You are an educational knowledge graph extraction system.
|
|
||||||
|
|
||||||
Your task:
|
|
||||||
|
|
||||||
Extract educational entities and relations.
|
|
||||||
|
|
||||||
Rules:
|
|
||||||
- Return ONLY EXACT JSON
|
|
||||||
- Use ONLY meaningful educational concepts
|
|
||||||
- NO markdown
|
|
||||||
- NO explanations
|
|
||||||
- NO extra text
|
|
||||||
- Use these relations ONLY:
|
|
||||||
[ "is_a",
|
|
||||||
"part_of",
|
|
||||||
"uses",
|
|
||||||
"teaches",
|
|
||||||
"requires",
|
|
||||||
"depends_on",
|
|
||||||
"implements",
|
|
||||||
"applies_to",
|
|
||||||
"subfield_of",
|
|
||||||
"contains",
|
|
||||||
"defined_by"]
|
|
||||||
- Entity names must be normalized:
|
|
||||||
GOOD:
|
|
||||||
- "Machine Learning"
|
|
||||||
- "Artificial Intelligence"
|
|
||||||
BAD:
|
|
||||||
- "machine learning"
|
|
||||||
- "ML"
|
|
||||||
- "AI systems"
|
|
||||||
- Prefer fewer HIGH QUALITY relations over many weak relations
|
|
||||||
- Every entity should participate in at least one relation
|
|
||||||
|
|
||||||
OUTPUT FORMAT EXACTLY:
|
|
||||||
{{
|
|
||||||
"entities": [
|
|
||||||
{{"name": "...", "type": "..."}}
|
|
||||||
],
|
|
||||||
"relations": [
|
|
||||||
{{
|
|
||||||
"source": "...",
|
|
||||||
"target": "...",
|
|
||||||
"relation": "..."
|
|
||||||
}}
|
|
||||||
]
|
|
||||||
}}
|
|
||||||
|
|
||||||
TEXT:
|
|
||||||
{text}
|
|
||||||
"""
|
|
||||||
|
|
||||||
response = llm_call([
|
|
||||||
{"role": "user", "content": prompt}
|
|
||||||
])
|
|
||||||
|
|
||||||
cleaned = clean_llm_response(response)
|
|
||||||
|
|
||||||
|
for match in re.finditer(r"\{", cleaned):
|
||||||
try:
|
try:
|
||||||
data = json.loads(cleaned)
|
value, _ = decoder.raw_decode(cleaned, match.start())
|
||||||
|
|
||||||
except json.JSONDecodeError:
|
except json.JSONDecodeError:
|
||||||
print("\nINVALID JSON")
|
|
||||||
print(cleaned)
|
|
||||||
raise
|
|
||||||
|
|
||||||
# Checks if llm output is valid
|
|
||||||
entities = data.get("entities", [])
|
|
||||||
relations = data.get("relations", [])
|
|
||||||
|
|
||||||
# Normalize entity names
|
|
||||||
normalized_entities = {}
|
|
||||||
|
|
||||||
for ent in entities:
|
|
||||||
|
|
||||||
name = ent["name"].strip()
|
|
||||||
|
|
||||||
# title case normalization
|
|
||||||
name = " ".join(word.capitalize() for word in name.split())
|
|
||||||
|
|
||||||
normalized_entities[name] = {
|
|
||||||
"name": name,
|
|
||||||
"type": ent.get("type", "concept")
|
|
||||||
}
|
|
||||||
|
|
||||||
entity_names = set(normalized_entities.keys())
|
|
||||||
|
|
||||||
valid_relations = []
|
|
||||||
|
|
||||||
for rel in relations:
|
|
||||||
|
|
||||||
source = rel["source"].strip()
|
|
||||||
target = rel["target"].strip()
|
|
||||||
relation = rel["relation"].strip()
|
|
||||||
|
|
||||||
source = " ".join(word.capitalize() for word in source.split())
|
|
||||||
target = " ".join(word.capitalize() for word in target.split())
|
|
||||||
|
|
||||||
# Skip self-loops
|
|
||||||
if source == target:
|
|
||||||
continue
|
continue
|
||||||
|
if isinstance(value, dict) and ("entities" in value or "relations" in value):
|
||||||
|
return value
|
||||||
|
|
||||||
# Ensure both entities exist
|
raise ValueError("The LLM did not return a JSON object")
|
||||||
if source not in entity_names:
|
|
||||||
|
|
||||||
|
def extract_entities_and_relations(text: str) -> dict[str, list[dict[str, str]]]:
|
||||||
|
prompt = f"""Extract a high-quality educational knowledge graph from this text.
|
||||||
|
Return only JSON with entities and relations. Resolve aliases to canonical names,
|
||||||
|
include subjects, skills, named entities and prerequisites, and avoid generic words.
|
||||||
|
Allowed relations: {sorted(RELATIONS)}
|
||||||
|
Schema: {{"entities":[{{"name":"...","type":"concept"}}],
|
||||||
|
"relations":[{{"source":"...","target":"...","relation":"requires"}}]}}
|
||||||
|
Text:
|
||||||
|
{text[:8000]}"""
|
||||||
|
data = _json_response(llm_call([{"role": "user", "content": prompt}]))
|
||||||
|
entities: dict[str, dict[str, str]] = {}
|
||||||
|
for item in data.get("entities", []):
|
||||||
|
if isinstance(item, dict) and item.get("name"):
|
||||||
|
name = _normalise(str(item["name"]))
|
||||||
|
entities[name] = {"name": name, "type": str(item.get("type", "concept"))}
|
||||||
|
relations = []
|
||||||
|
for item in data.get("relations", []):
|
||||||
|
if not isinstance(item, dict):
|
||||||
continue
|
continue
|
||||||
|
source, target = _normalise(str(item.get("source", ""))), _normalise(str(item.get("target", "")))
|
||||||
|
relation = str(item.get("relation", "related_to")).lower().strip()
|
||||||
|
if source != target and source in entities and target in entities and relation in RELATIONS:
|
||||||
|
relations.append({"source": source, "target": target, "relation": relation})
|
||||||
|
connected = {x for r in relations for x in (r["source"], r["target"])}
|
||||||
|
return {"entities": [e for name, e in entities.items() if name in connected], "relations": relations}
|
||||||
|
|
||||||
if target not in entity_names:
|
|
||||||
continue
|
|
||||||
|
|
||||||
valid_relations.append({
|
def get_cached_extraction(chunk: str, cache_dir: str = "cache") -> dict[str, list[dict[str, str]]]:
|
||||||
"source": source,
|
Path(cache_dir).mkdir(exist_ok=True)
|
||||||
"target": target,
|
path = Path(cache_dir) / f"{hashlib.sha256(chunk.encode()).hexdigest()}.json"
|
||||||
"relation": relation
|
if path.exists():
|
||||||
})
|
return json.loads(path.read_text(encoding="utf-8"))
|
||||||
|
result = extract_entities_and_relations(chunk)
|
||||||
|
path.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||||
|
return result
|
||||||
|
|
||||||
# Remove isolated entities
|
|
||||||
connected = set()
|
|
||||||
|
|
||||||
for rel in valid_relations:
|
|
||||||
connected.add(rel["source"])
|
|
||||||
connected.add(rel["target"])
|
|
||||||
|
|
||||||
final_entities = [
|
|
||||||
ent for ent in normalized_entities.values()
|
|
||||||
if ent["name"] in connected
|
|
||||||
]
|
|
||||||
|
|
||||||
return {
|
|
||||||
"entities": final_entities,
|
|
||||||
"relations": valid_relations
|
|
||||||
}
|
|
||||||
|
|
||||||
# Chunks document into chunks (with overlap)
|
|
||||||
def chunk_text(text, chunk_size=8000, overlap=300):
|
|
||||||
|
|
||||||
|
def chunk_text(text: str, chunk_size: int = 8000, overlap: int = 300) -> list[str]:
|
||||||
text = text.replace("\r", " ")
|
text = text.replace("\r", " ")
|
||||||
|
chunks, current = [], ""
|
||||||
paragraphs = text.split("\n")
|
for paragraph in text.split("\n"):
|
||||||
|
paragraph = paragraph.strip()
|
||||||
chunks = []
|
if len(paragraph) < 40:
|
||||||
current = ""
|
|
||||||
|
|
||||||
for para in paragraphs:
|
|
||||||
|
|
||||||
para = para.strip()
|
|
||||||
|
|
||||||
# Skip useless tiny paragraphs
|
|
||||||
if len(para) < 40:
|
|
||||||
continue
|
continue
|
||||||
|
if len(current) + len(paragraph) <= chunk_size:
|
||||||
if len(current) + len(para) < chunk_size:
|
current += paragraph + "\n"
|
||||||
|
|
||||||
current += para + "\n"
|
|
||||||
|
|
||||||
else:
|
else:
|
||||||
|
|
||||||
chunks.append(current)
|
chunks.append(current)
|
||||||
|
current = current[-overlap:] + "\n" + paragraph + "\n"
|
||||||
# overlap keeps context continuity
|
|
||||||
current = current[-overlap:] + "\n" + para + "\n"
|
|
||||||
|
|
||||||
if current:
|
if current:
|
||||||
chunks.append(current)
|
chunks.append(current)
|
||||||
|
|
||||||
return chunks
|
return chunks
|
||||||
|
|
||||||
# Builds graph from documents (must be in documents folder [.pdf, .txt, .docx])
|
|
||||||
def build_graph_from_documents(folder="documents"):
|
|
||||||
|
|
||||||
G = nx.DiGraph()
|
|
||||||
|
|
||||||
docs = load_documents(folder)
|
|
||||||
|
|
||||||
for doc in docs:
|
|
||||||
|
|
||||||
print(f"\n[INFO] Processing document: {doc['filename']}")
|
|
||||||
|
|
||||||
# Document is split into chunks
|
|
||||||
chunks = chunk_text(doc["content"])
|
|
||||||
|
|
||||||
print(f"[INFO] Total chunks: {len(chunks)}")
|
|
||||||
|
|
||||||
# Process chunk by chunk
|
|
||||||
for idx, chunk in enumerate(chunks):
|
|
||||||
|
|
||||||
print(f"[INFO] Processing chunk {idx + 1}/{len(chunks)}")
|
|
||||||
|
|
||||||
|
def cluster_concepts(graph: nx.Graph, resolution: float = 1.0) -> list[set[str]]:
|
||||||
|
"""Cluster named entities using graph community structure and label nodes."""
|
||||||
|
undirected = graph.to_undirected()
|
||||||
|
if not undirected.nodes:
|
||||||
|
return []
|
||||||
try:
|
try:
|
||||||
|
communities = list(nx.community.louvain_communities(undirected, resolution=resolution, seed=42))
|
||||||
|
except (AttributeError, nx.NetworkXError):
|
||||||
|
communities = list(nx.community.greedy_modularity_communities(undirected))
|
||||||
|
for index, community in enumerate(communities, start=1):
|
||||||
|
for node in community:
|
||||||
|
graph.nodes[node]["cluster"] = f"concept_{index}"
|
||||||
|
return communities
|
||||||
|
|
||||||
|
|
||||||
|
def build_graph_from_documents(folder: str = "documents") -> nx.DiGraph:
|
||||||
|
graph = nx.DiGraph()
|
||||||
|
for document in load_documents(folder):
|
||||||
|
for chunk in chunk_text(document["content"]):
|
||||||
extraction = get_cached_extraction(chunk)
|
extraction = get_cached_extraction(chunk)
|
||||||
|
for entity in extraction["entities"]:
|
||||||
|
graph.add_node(entity["name"], type=entity["type"], source_doc=document["filename"])
|
||||||
|
for relation in extraction["relations"]:
|
||||||
|
graph.add_edge(relation["source"], relation["target"],
|
||||||
|
relation=relation["relation"], source_doc=document["filename"])
|
||||||
|
cluster_concepts(graph)
|
||||||
|
return graph
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
|
|
||||||
print(f"[WARN] Extraction failed on chunk {idx + 1}")
|
def save_graph(graph: nx.DiGraph, path: str = "graph/kg.graphml") -> None:
|
||||||
print(e)
|
Path(path).parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
nx.write_graphml(graph, path)
|
||||||
|
|
||||||
continue
|
|
||||||
|
|
||||||
# Add entities (nodes) to graph
|
def load_graph(path: str = "graph/kg.graphml") -> nx.DiGraph:
|
||||||
for ent in extraction["entities"]:
|
|
||||||
|
|
||||||
G.add_node(
|
|
||||||
ent["name"],
|
|
||||||
type=ent["type"],
|
|
||||||
source_doc=doc["filename"]
|
|
||||||
)
|
|
||||||
|
|
||||||
# Adds entity realtions (links nodes)
|
|
||||||
for rel in extraction["relations"]:
|
|
||||||
|
|
||||||
G.add_edge(
|
|
||||||
rel["source"],
|
|
||||||
rel["target"],
|
|
||||||
relation=rel["relation"],
|
|
||||||
source_doc=doc["filename"]
|
|
||||||
)
|
|
||||||
|
|
||||||
return G
|
|
||||||
|
|
||||||
# Saves graph to file
|
|
||||||
def save_graph(G, path="graph/kg.graphml"):
|
|
||||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
|
||||||
nx.write_graphml(G, path)
|
|
||||||
print(f"Graph saved to {path}")
|
|
||||||
|
|
||||||
# Loads graph from file
|
|
||||||
def load_graph(path="graph/kg.graphml"):
|
|
||||||
return nx.read_graphml(path)
|
return nx.read_graphml(path)
|
||||||
|
|
||||||
# Adds document to graph
|
|
||||||
def add_document(filepath, G):
|
|
||||||
|
|
||||||
docs = load_documents(folder=filepath)
|
def sync_graph_to_neo4j(graph: nx.DiGraph) -> int:
|
||||||
|
"""Sync to Neo4j when NEO4J_URI/USER/PASSWORD are configured; return edge count."""
|
||||||
if not docs:
|
from neo4j import GraphDatabase
|
||||||
print(f"[WARN] No documents found in: {filepath}")
|
|
||||||
return
|
|
||||||
|
|
||||||
doc = docs[0]
|
|
||||||
|
|
||||||
print(f"\n[INFO] Adding document: {doc['filename']}")
|
|
||||||
|
|
||||||
# Document is split into chunks
|
|
||||||
chunks = chunk_text(doc["content"])
|
|
||||||
|
|
||||||
print(f"[INFO] Total chunks: {len(chunks)}")
|
|
||||||
|
|
||||||
# Process chunk by chunk
|
|
||||||
for idx, chunk in enumerate(chunks):
|
|
||||||
|
|
||||||
print(f"[INFO] Processing chunk {idx + 1}/{len(chunks)}")
|
|
||||||
|
|
||||||
|
uri = os.environ["NEO4J_URI"]
|
||||||
|
user = os.environ.get("NEO4J_USER", "neo4j")
|
||||||
|
password = os.environ["NEO4J_PASSWORD"]
|
||||||
|
database = os.environ.get("NEO4J_DATABASE", "neo4j")
|
||||||
|
driver = GraphDatabase.driver(uri, auth=(user, password))
|
||||||
try:
|
try:
|
||||||
|
with driver.session(database=database) as session:
|
||||||
extraction = get_cached_extraction(chunk)
|
for node, data in graph.nodes(data=True):
|
||||||
|
session.run("MERGE (n:Concept {name:$name}) SET n.type=$type, n.cluster=$cluster",
|
||||||
except Exception as e:
|
name=node, type=data.get("type", "concept"), cluster=data.get("cluster"))
|
||||||
|
for source, target, data in graph.edges(data=True):
|
||||||
print(f"[WARN] Extraction failed on chunk {idx + 1}")
|
session.run("""MATCH (a:Concept {name:$source}), (b:Concept {name:$target})
|
||||||
print(e)
|
MERGE (a)-[r:RELATED {relation:$relation}]->(b)
|
||||||
|
SET r.source_doc=$source_doc""",
|
||||||
continue
|
source=source, target=target, relation=data.get("relation", "related_to"),
|
||||||
|
source_doc=data.get("source_doc"))
|
||||||
# Add entities (nodes) to graph
|
finally:
|
||||||
for ent in extraction["entities"]:
|
driver.close()
|
||||||
|
return graph.number_of_edges()
|
||||||
G.add_node(
|
|
||||||
ent["name"],
|
|
||||||
type=ent["type"],
|
|
||||||
source_doc=doc["filename"]
|
|
||||||
)
|
|
||||||
|
|
||||||
# Adds entity realtions (links nodes)
|
|
||||||
for rel in extraction["relations"]:
|
|
||||||
|
|
||||||
G.add_edge(
|
|
||||||
rel["source"],
|
|
||||||
rel["target"],
|
|
||||||
relation=rel["relation"],
|
|
||||||
source_doc=doc["filename"]
|
|
||||||
)
|
|
||||||
|
|
||||||
print(f"[INFO] Finished adding {doc['filename']}")
|
|
||||||
|
|
||||||
# Removes document from graph
|
|
||||||
def remove_document(filename, G):
|
|
||||||
|
|
||||||
edges_to_remove = []
|
|
||||||
|
|
||||||
for u, v, data in G.edges(data=True):
|
|
||||||
|
|
||||||
if data.get("source_doc") == filename:
|
|
||||||
edges_to_remove.append((u, v))
|
|
||||||
|
|
||||||
G.remove_edges_from(edges_to_remove)
|
|
||||||
|
|
||||||
# Remove orphan nodes
|
|
||||||
isolated_nodes = list(nx.isolates(G))
|
|
||||||
|
|
||||||
G.remove_nodes_from(isolated_nodes)
|
|
||||||
|
|
||||||
print(f"[INFO] Removed document: {filename}")
|
|
||||||
|
|
||||||
'''
|
|
||||||
#test
|
|
||||||
if __name__ == "__main__":
|
|
||||||
|
|
||||||
docs = load_documents()
|
|
||||||
|
|
||||||
extraction = extract_entities_and_relations(
|
|
||||||
docs[0]["content"]
|
|
||||||
)
|
|
||||||
|
|
||||||
print(extraction)
|
|
||||||
'''
|
|
||||||
|
|
||||||
#test
|
|
||||||
if __name__ == "__main__":
|
|
||||||
|
|
||||||
#G2 = load_graph()
|
|
||||||
|
|
||||||
#print(G2.nodes(data=True))
|
|
||||||
G = build_graph_from_documents()
|
|
||||||
|
|
||||||
save_graph(G)
|
|
||||||
#print(G.nodes(data=True))
|
|
||||||
|
|
||||||
#print(G.edges(data=True))
|
|
||||||
|
|
||||||
|
|||||||
51
ingest.py
51
ingest.py
@ -2,42 +2,17 @@ from pathlib import Path
|
|||||||
from pypdf import PdfReader
|
from pypdf import PdfReader
|
||||||
from docx import Document
|
from docx import Document
|
||||||
|
|
||||||
def load_documents(folder="documents"):
|
|
||||||
docs = []
|
|
||||||
|
|
||||||
for file in Path(folder).glob("*"):
|
def load_documents(folder: str = "documents") -> list[dict[str, str]]:
|
||||||
if file.suffix == ".txt":
|
documents = []
|
||||||
text = file.read_text(encoding="utf-8")
|
for path in Path(folder).glob("*"):
|
||||||
|
if path.suffix.lower() == ".txt":
|
||||||
docs.append({
|
content = path.read_text(encoding="utf-8")
|
||||||
"filename": file.name,
|
elif path.suffix.lower() == ".pdf":
|
||||||
"content": text
|
content = "\n".join(page.extract_text() or "" for page in PdfReader(path).pages)
|
||||||
})
|
elif path.suffix.lower() == ".docx":
|
||||||
|
content = "\n".join(paragraph.text for paragraph in Document(path).paragraphs)
|
||||||
elif file.suffix == ".pdf":
|
else:
|
||||||
reader = PdfReader(file)
|
continue
|
||||||
text = ""
|
documents.append({"filename": path.name, "content": content})
|
||||||
for page in reader.pages:
|
return documents
|
||||||
text += page.extract_text()
|
|
||||||
|
|
||||||
docs.append({
|
|
||||||
"filename": file.name,
|
|
||||||
"content": text
|
|
||||||
})
|
|
||||||
|
|
||||||
elif file.suffix == ".docx":
|
|
||||||
doc = Document(file)
|
|
||||||
text = "\n".join([paragraph.text for paragraph in doc.paragraphs])
|
|
||||||
|
|
||||||
docs.append({
|
|
||||||
"filename": file.name,
|
|
||||||
"content": text
|
|
||||||
})
|
|
||||||
|
|
||||||
return docs
|
|
||||||
|
|
||||||
#test
|
|
||||||
if __name__ == "__main__":
|
|
||||||
docs = load_documents()
|
|
||||||
|
|
||||||
print(docs)
|
|
||||||
|
|||||||
79
llm.py
79
llm.py
@ -1,35 +1,64 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
from dataclasses import dataclass
|
|
||||||
|
import os
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
from typing import Dict, List
|
from typing import Dict, List
|
||||||
|
|
||||||
import requests
|
import requests
|
||||||
|
from dotenv import load_dotenv
|
||||||
|
|
||||||
|
load_dotenv(dotenv_path=Path(__file__).with_name(".env"))
|
||||||
|
|
||||||
|
UNIVERSITY_BASE_URL = os.getenv("UNIVERSITY_BASE_URL", "https://ui.tukekemt.xyz/api/v1/chat/completions")
|
||||||
|
UNIVERSITY_MODEL = os.getenv("UNIVERSITY_MODEL", "model2")
|
||||||
|
UNIVERSITY_TIMEOUT = int(os.getenv("UNIVERSITY_TIMEOUT", "600"))
|
||||||
|
UNIVERSITY_RETRIES = int(os.getenv("UNIVERSITY_RETRIES", "3"))
|
||||||
|
UNIVERSITY_MAX_TOKENS = int(os.getenv("UNIVERSITY_MAX_TOKENS", "8192"))
|
||||||
|
RETRYABLE_STATUS_CODES = {429, 500, 502, 503, 504}
|
||||||
|
|
||||||
# TUKE LLM Connection
|
|
||||||
UNIVERSITY_BASE_URL = "https://ui.tukekemt.xyz/api/v1/chat/completions"
|
|
||||||
UNIVERSITY_API_KEY = "sk-06098ff9afb946c2b9d197cb400cd752"
|
|
||||||
UNIVERSITY_MODEL = "model2"
|
|
||||||
|
|
||||||
# LLM call
|
|
||||||
def llm_call(messages: List[Dict[str, str]]) -> str:
|
def llm_call(messages: List[Dict[str, str]]) -> str:
|
||||||
"""Send a list of {role, content} dicts to the university LLM and return the reply text."""
|
"""Call the project's existing university LLM using local environment configuration."""
|
||||||
resp = requests.post(
|
api_key = os.getenv("UNIVERSITY_API_KEY")
|
||||||
|
if not api_key:
|
||||||
|
raise RuntimeError("UNIVERSITY_API_KEY is not configured")
|
||||||
|
|
||||||
|
for attempt in range(UNIVERSITY_RETRIES + 1):
|
||||||
|
try:
|
||||||
|
response = requests.post(
|
||||||
UNIVERSITY_BASE_URL,
|
UNIVERSITY_BASE_URL,
|
||||||
json={"model": UNIVERSITY_MODEL, "messages": messages, "stream": False},
|
json={
|
||||||
headers={
|
"model": UNIVERSITY_MODEL,
|
||||||
"Authorization": f"Bearer {UNIVERSITY_API_KEY}",
|
"messages": messages,
|
||||||
"Content-Type": "application/json",
|
"stream": False,
|
||||||
|
"max_tokens": UNIVERSITY_MAX_TOKENS,
|
||||||
},
|
},
|
||||||
timeout=600,
|
headers={"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"},
|
||||||
|
timeout=UNIVERSITY_TIMEOUT,
|
||||||
)
|
)
|
||||||
resp.raise_for_status()
|
if response.status_code in RETRYABLE_STATUS_CODES and attempt < UNIVERSITY_RETRIES:
|
||||||
return resp.json()["choices"][0]["message"]["content"]
|
time.sleep(2 ** attempt)
|
||||||
|
continue
|
||||||
|
response.raise_for_status()
|
||||||
|
payload = response.json()
|
||||||
|
content = payload["choices"][0]["message"].get("content")
|
||||||
|
if not isinstance(content, str) or not content.strip():
|
||||||
|
if attempt < UNIVERSITY_RETRIES:
|
||||||
|
time.sleep(2 ** attempt)
|
||||||
|
continue
|
||||||
|
raise RuntimeError(
|
||||||
|
"The LLM returned no final answer content after retries; "
|
||||||
|
"the provider may have exhausted its reasoning budget"
|
||||||
|
)
|
||||||
|
return content
|
||||||
|
except requests.exceptions.Timeout as error:
|
||||||
|
if attempt >= UNIVERSITY_RETRIES:
|
||||||
|
raise RuntimeError("The LLM service timed out") from error
|
||||||
|
time.sleep(2 ** attempt)
|
||||||
|
except requests.exceptions.ConnectionError as error:
|
||||||
|
if attempt >= UNIVERSITY_RETRIES:
|
||||||
|
raise RuntimeError("The LLM service could not be reached") from error
|
||||||
|
time.sleep(2 ** attempt)
|
||||||
|
|
||||||
#test
|
raise RuntimeError("LLM request failed")
|
||||||
if __name__ == "__main__":
|
|
||||||
response = llm_call([
|
|
||||||
{
|
|
||||||
"role": "user",
|
|
||||||
"content": "Say hello"
|
|
||||||
}
|
|
||||||
])
|
|
||||||
|
|
||||||
print(response)
|
|
||||||
|
|||||||
94
main.py
94
main.py
@ -1,88 +1,26 @@
|
|||||||
from graph_builder import (
|
import os
|
||||||
build_graph_from_documents,
|
from pathlib import Path
|
||||||
save_graph,
|
|
||||||
load_graph
|
from graph_builder import build_graph_from_documents, load_graph, save_graph, sync_graph_to_neo4j
|
||||||
)
|
|
||||||
from react_agent import react_agent
|
from react_agent import react_agent
|
||||||
from visualization import visualize_graph
|
|
||||||
|
|
||||||
GRAPH_PATH = "graph/kg.graphml"
|
GRAPH_PATH = "graph/kg.graphml"
|
||||||
|
|
||||||
# Create graph or load existing one
|
|
||||||
def get_or_build_graph(force_rebuild=False):
|
|
||||||
|
|
||||||
if not force_rebuild:
|
def get_or_build_graph(force_rebuild: bool = False):
|
||||||
try:
|
if not force_rebuild and Path(GRAPH_PATH).exists():
|
||||||
print("\n[INFO] Loading existing graph...")
|
return load_graph(GRAPH_PATH)
|
||||||
G = load_graph(GRAPH_PATH)
|
graph = build_graph_from_documents()
|
||||||
|
save_graph(graph, GRAPH_PATH)
|
||||||
print(f"[INFO] Loaded graph: {len(G.nodes())} nodes, {len(G.edges())} edges")
|
if os.getenv("NEO4J_URI") and os.getenv("NEO4J_PASSWORD"):
|
||||||
return G
|
sync_graph_to_neo4j(graph)
|
||||||
|
return graph
|
||||||
except Exception as e:
|
|
||||||
print(f"[WARN] Could not load graph: {e}")
|
|
||||||
print("[INFO] Rebuilding graph...")
|
|
||||||
|
|
||||||
print("\n[INFO] Building graph from documents...")
|
|
||||||
G = build_graph_from_documents()
|
|
||||||
|
|
||||||
print(f"[INFO] Built graph: {len(G.nodes())} nodes, {len(G.edges())} edges")
|
|
||||||
|
|
||||||
print("\n[INFO] Saving graph...")
|
|
||||||
save_graph(G, GRAPH_PATH)
|
|
||||||
return G
|
|
||||||
|
|
||||||
# Testing questions (query)
|
|
||||||
def ask_question(G, question):
|
|
||||||
|
|
||||||
print("\n" + "=" * 60)
|
|
||||||
print(f"QUESTION: {question}")
|
|
||||||
print("=" * 60)
|
|
||||||
|
|
||||||
history = []
|
|
||||||
|
|
||||||
result = react_agent(
|
|
||||||
user_message=question,
|
|
||||||
history=history,
|
|
||||||
G=G
|
|
||||||
)
|
|
||||||
|
|
||||||
print("\n--- FINAL ANSWER ---")
|
|
||||||
print(result.answer)
|
|
||||||
|
|
||||||
print("\n--- EVIDENCE (GRAPH) ---")
|
|
||||||
print(result.evidence)
|
|
||||||
|
|
||||||
return result
|
|
||||||
|
|
||||||
|
|
||||||
# Visualisation
|
def ask_question(graph, question: str):
|
||||||
def show_graph(G):
|
return react_agent(question, [], graph)
|
||||||
|
|
||||||
print("\n[INFO] Generating visualization...")
|
|
||||||
|
|
||||||
visualize_graph(G)
|
|
||||||
|
|
||||||
print("[INFO] Graph saved as kg.html")
|
|
||||||
|
|
||||||
# Run main
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
graph = get_or_build_graph()
|
||||||
# Create graph or load existing one
|
print(ask_question(graph, "Čo sa učí na predmete Slovenský jazyk a literatúra?"))
|
||||||
G = get_or_build_graph(force_rebuild=False)
|
|
||||||
|
|
||||||
# Run visualisation.py (optional and for testing)
|
|
||||||
#show_graph(G)
|
|
||||||
|
|
||||||
# Testing questions (query)
|
|
||||||
test_questions = [
|
|
||||||
#"What is taught in Informatics?",
|
|
||||||
#"What is used in machine learning?",
|
|
||||||
#"What Literary Texts are taught in Slovak Language And Slovak Literature?",
|
|
||||||
"Čo sa učí na predmete Slovenský jazyk a literatúra?"
|
|
||||||
]
|
|
||||||
|
|
||||||
for q in test_questions:
|
|
||||||
ask_question(G, q)
|
|
||||||
|
|
||||||
print("\n[INFO] PIPELINE COMPLETED")
|
|
||||||
|
|||||||
27
models.py
27
models.py
@ -1,30 +1,11 @@
|
|||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from typing import Optional, List
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class GraphRAGResponse:
|
class GraphRAGResponse:
|
||||||
|
|
||||||
question: str
|
question: str
|
||||||
|
|
||||||
answer: str
|
answer: str
|
||||||
|
evidence: str = ""
|
||||||
|
|
||||||
evidence: Optional[str] = None
|
def __str__(self) -> str:
|
||||||
|
return f"GraphRAGResponse(question={self.question!r}, answer={self.answer!r}, evidence={self.evidence!r})"
|
||||||
entities_used: Optional[List[str]] = None
|
|
||||||
|
|
||||||
relations_used: Optional[List[str]] = None
|
|
||||||
|
|
||||||
source_documents: Optional[List[str]] = None
|
|
||||||
|
|
||||||
def __str__(self):
|
|
||||||
|
|
||||||
return (
|
|
||||||
"\nGraphRAGResponse(\n"
|
|
||||||
f" question = {self.question!r}\n"
|
|
||||||
f" answer = {self.answer!r}\n"
|
|
||||||
f" evidence = {self.evidence!r}\n"
|
|
||||||
f" entities_used = {self.entities_used!r}\n"
|
|
||||||
f" relations_used = {self.relations_used!r}\n"
|
|
||||||
f" source_documents = {self.source_documents!r}\n"
|
|
||||||
")"
|
|
||||||
)
|
|
||||||
|
|||||||
@ -1,82 +1,13 @@
|
|||||||
from tools import TOOL_MAP
|
|
||||||
from llm import llm_call
|
|
||||||
import re
|
|
||||||
from typing import List, Dict
|
|
||||||
from models import GraphRAGResponse
|
from models import GraphRAGResponse
|
||||||
|
from tools import TOOL_MAP
|
||||||
|
|
||||||
SYSTEM_PROMPT = """
|
|
||||||
You are an educational GraphRAG assistant for schools.
|
|
||||||
|
|
||||||
You MUST use tools when answering knowledge questions.
|
def react_agent(user_message: str, history=None, G=None, language: str = "Slovak") -> GraphRAGResponse:
|
||||||
|
"""Retrieve graph evidence first, then answer strictly from it."""
|
||||||
Available tool:
|
del history
|
||||||
- query_knowledge_graph
|
result = TOOL_MAP["query_knowledge_graph"](user_message.strip(), G, language)
|
||||||
|
|
||||||
Format:
|
|
||||||
Action: query_knowledge_graph
|
|
||||||
Action Input: <question>
|
|
||||||
|
|
||||||
OR:
|
|
||||||
|
|
||||||
Final Answer: <answer>
|
|
||||||
"""
|
|
||||||
|
|
||||||
def parse_action(text: str):
|
|
||||||
action = re.search(r"Action:\s*(\w+)", text)
|
|
||||||
input_ = re.search(r"Action Input:\s*(.+)", text)
|
|
||||||
|
|
||||||
if action and input_:
|
|
||||||
return action.group(1), input_.group(1)
|
|
||||||
|
|
||||||
return None
|
|
||||||
|
|
||||||
def parse_final(text: str):
|
|
||||||
m = re.search(r"Final Answer:\s*(.+)", text, re.DOTALL)
|
|
||||||
return m.group(1).strip() if m else None
|
|
||||||
|
|
||||||
def react_agent(user_message: str, history: List[Dict], G=None, max_steps: int = 5):
|
|
||||||
|
|
||||||
messages = (
|
|
||||||
[{"role": "system", "content": SYSTEM_PROMPT}]
|
|
||||||
+ history
|
|
||||||
+ [{"role": "user", "content": user_message}]
|
|
||||||
)
|
|
||||||
|
|
||||||
last = ""
|
|
||||||
|
|
||||||
for _ in range(max_steps):
|
|
||||||
|
|
||||||
reply = llm_call(messages)
|
|
||||||
last = reply
|
|
||||||
|
|
||||||
final = parse_final(reply)
|
|
||||||
if final:
|
|
||||||
return GraphRAGResponse(
|
return GraphRAGResponse(
|
||||||
question=user_message,
|
user_message,
|
||||||
answer=final,
|
result["answer"],
|
||||||
evidence=""
|
result["evidence"],
|
||||||
)
|
|
||||||
|
|
||||||
action = parse_action(reply)
|
|
||||||
|
|
||||||
if action:
|
|
||||||
|
|
||||||
tool_name, tool_input = action
|
|
||||||
|
|
||||||
if tool_name == "query_knowledge_graph":
|
|
||||||
result = TOOL_MAP[tool_name](tool_input, G)
|
|
||||||
|
|
||||||
messages.append({"role": "assistant", "content": reply})
|
|
||||||
messages.append({"role": "user", "content": f"Observation: {result}"})
|
|
||||||
|
|
||||||
return GraphRAGResponse(
|
|
||||||
question=user_message,
|
|
||||||
answer=result["answer"],
|
|
||||||
evidence=result["evidence"]
|
|
||||||
)
|
|
||||||
|
|
||||||
return GraphRAGResponse(
|
|
||||||
question=user_message,
|
|
||||||
answer=last,
|
|
||||||
evidence=""
|
|
||||||
)
|
)
|
||||||
217
retrieval.py
217
retrieval.py
@ -1,37 +1,208 @@
|
|||||||
def retrieve_subgraph(G, query):
|
from __future__ import annotations
|
||||||
query = query.lower()
|
|
||||||
|
|
||||||
context = []
|
import re
|
||||||
|
import unicodedata
|
||||||
|
from difflib import SequenceMatcher
|
||||||
|
from math import log
|
||||||
|
import weakref
|
||||||
|
import networkx as nx
|
||||||
|
|
||||||
for node in G.nodes(data=True):
|
|
||||||
|
|
||||||
node_name = node[0].lower()
|
SYNONYMS = {
|
||||||
|
"slovensky": {
|
||||||
|
"slovak",
|
||||||
|
"slovenska",
|
||||||
|
"slovenskom",
|
||||||
|
"slovensky jazyk",
|
||||||
|
"slovencina",
|
||||||
|
"slovak language",
|
||||||
|
"slovak language and literature",
|
||||||
|
},
|
||||||
|
"jazyku": {"jazyk", "jazykovy"},
|
||||||
|
"uciva": {"učiť", "ucenie", "vzdelavanie", "predmet", "temy"},
|
||||||
|
"vzdelava": {"uciva", "ucenie", "temy"},
|
||||||
|
"literatura": {"literarne", "literarny", "literarne dielo", "sjl"},
|
||||||
|
}
|
||||||
|
STOP_WORDS = {
|
||||||
|
"co", "sa", "na", "aku", "ake", "ako", "pre", "je", "ci",
|
||||||
|
"v", "do", "pri", "o", "a",
|
||||||
|
"a", "an", "the", "what", "does", "about", "prepare", "lesson",
|
||||||
|
"in", "for", "grade", "subject", "include", "objectives", "activities",
|
||||||
|
"differentiation", "assessment", "homework", "minute", "minutes",
|
||||||
|
}
|
||||||
|
_INDEX_CACHE: weakref.WeakKeyDictionary = weakref.WeakKeyDictionary()
|
||||||
|
|
||||||
|
|
||||||
|
def _normalise_text(value: str) -> str:
|
||||||
|
value = unicodedata.normalize("NFKD", value.lower())
|
||||||
|
value = "".join(char for char in value if not unicodedata.combining(char))
|
||||||
|
value = re.sub(r"[^a-z0-9]+", " ", value)
|
||||||
|
return " ".join(value.split())
|
||||||
|
|
||||||
|
|
||||||
|
def _expanded_terms(query: str) -> set[str]:
|
||||||
|
words = {
|
||||||
|
word for word in _normalise_text(query).split()
|
||||||
if (
|
if (
|
||||||
query in node_name
|
word not in STOP_WORDS
|
||||||
or node_name in query
|
and not word.isdigit()
|
||||||
|
and not re.fullmatch(r"\d+(?:st|nd|rd|th)", word)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
expanded = set(words)
|
||||||
|
for word in words:
|
||||||
|
expanded.update(SYNONYMS.get(word, set()))
|
||||||
|
for synonym_set in SYNONYMS.values():
|
||||||
|
if word in synonym_set:
|
||||||
|
expanded.update(synonym_set)
|
||||||
|
return expanded
|
||||||
|
|
||||||
|
|
||||||
|
def _graph_index(graph: nx.Graph) -> dict:
|
||||||
|
cached = _INDEX_CACHE.get(graph)
|
||||||
|
if cached is not None:
|
||||||
|
return cached
|
||||||
|
|
||||||
|
node_records = []
|
||||||
|
inverted: dict[str, set[str]] = {}
|
||||||
|
for node in graph.nodes:
|
||||||
|
words = _normalise_text(str(node)).split()
|
||||||
|
text = " ".join(words)
|
||||||
|
node_records.append((node, words, text))
|
||||||
|
for word in set(words):
|
||||||
|
inverted.setdefault(word, set()).add(node)
|
||||||
|
cached = {
|
||||||
|
"node_records": node_records,
|
||||||
|
"inverted": inverted,
|
||||||
|
"node_count": len(node_records),
|
||||||
|
}
|
||||||
|
_INDEX_CACHE[graph] = cached
|
||||||
|
return cached
|
||||||
|
|
||||||
|
|
||||||
|
def retrieve_subgraph(graph: nx.Graph, query: str, limit: int = 60) -> str:
|
||||||
|
terms = _expanded_terms(query)
|
||||||
|
normalised_query = _normalise_text(query)
|
||||||
|
index = _graph_index(graph)
|
||||||
|
node_records = index["node_records"]
|
||||||
|
inverted = index["inverted"]
|
||||||
|
document_frequency = {
|
||||||
|
term: len(inverted.get(term, set()))
|
||||||
|
for term in terms
|
||||||
|
}
|
||||||
|
ranked = []
|
||||||
|
exact_candidates = set().union(*(inverted.get(term, set()) for term in terms))
|
||||||
|
candidates = (
|
||||||
|
{record[0] for record in node_records}
|
||||||
|
if not exact_candidates
|
||||||
|
else exact_candidates
|
||||||
|
)
|
||||||
|
for node, node_words, node_text in node_records:
|
||||||
|
if node not in candidates:
|
||||||
|
continue
|
||||||
|
exact_terms = {
|
||||||
|
term for term in terms
|
||||||
|
if term in node_words or (len(term.split()) > 1 and term in node_text)
|
||||||
|
}
|
||||||
|
exact_score = sum(
|
||||||
|
(log((index["node_count"] + 1) / (document_frequency[term] + 1)) + 1)
|
||||||
|
for term in exact_terms
|
||||||
|
)
|
||||||
|
fuzzy_score = SequenceMatcher(None, normalised_query, node_text).ratio()
|
||||||
|
token_score = max(
|
||||||
|
(
|
||||||
|
SequenceMatcher(None, term, node_term).ratio()
|
||||||
|
if len(term) >= 4 and len(node_term) >= 4
|
||||||
|
else 0
|
||||||
|
for term in terms
|
||||||
|
for node_term in node_text.split()
|
||||||
|
),
|
||||||
|
default=0,
|
||||||
|
)
|
||||||
|
score = exact_score * 2 + fuzzy_score + token_score
|
||||||
|
partial_match = any(
|
||||||
|
len(term) >= 5 and term in node_text
|
||||||
|
for term in terms
|
||||||
|
)
|
||||||
|
if exact_score or partial_match or (
|
||||||
|
fuzzy_score >= 0.42 and token_score >= 0.78
|
||||||
):
|
):
|
||||||
|
ranked.append((score, node))
|
||||||
|
|
||||||
for neighbor in G.neighbors(node[0]):
|
# If exact terms exist but only produce weak candidates, retain a small
|
||||||
|
# fuzzy pass so typos and inflections are not discarded.
|
||||||
|
if not ranked and exact_candidates:
|
||||||
|
for node, node_words, node_text in node_records:
|
||||||
|
fuzzy_score = SequenceMatcher(None, normalised_query, node_text).ratio()
|
||||||
|
if fuzzy_score >= 0.42:
|
||||||
|
ranked.append((fuzzy_score, node))
|
||||||
|
|
||||||
edge = G[node[0]][neighbor]
|
context_lines: list[str] = []
|
||||||
|
seen_edges: set[tuple[str, str, str, str]] = set()
|
||||||
|
seed_nodes = [node for _, node in sorted(ranked, reverse=True)[:15]]
|
||||||
|
|
||||||
context.append(
|
def add_edge(source: str, target: str, data: dict) -> None:
|
||||||
f"{node[0]} --{edge.get('relation','related_to')}--> {neighbor}"
|
relation = str(data.get("relation", "related_to"))
|
||||||
|
source_doc = str(
|
||||||
|
data.get("source_doc")
|
||||||
|
or graph.nodes[source].get("source_doc")
|
||||||
|
or graph.nodes[target].get("source_doc")
|
||||||
|
or "unknown source"
|
||||||
|
)
|
||||||
|
edge_key = (source, target, relation, source_doc)
|
||||||
|
if edge_key not in seen_edges:
|
||||||
|
seen_edges.add(edge_key)
|
||||||
|
context_lines.append(
|
||||||
|
f"{source} --{relation}--> {target} [source: {source_doc}]"
|
||||||
)
|
)
|
||||||
|
|
||||||
return "\n".join(context)
|
# Direct node/edge matches are collected first.
|
||||||
|
undirected = graph.to_undirected()
|
||||||
|
for source, target, data in graph.edges(data=True):
|
||||||
|
source_text = _normalise_text(str(source))
|
||||||
|
target_text = _normalise_text(str(target))
|
||||||
|
edge_text = f"{source_text} {target_text} {_normalise_text(str(data.get('relation', '')))}"
|
||||||
|
if any(term in edge_text for term in terms):
|
||||||
|
add_edge(str(source), str(target), data)
|
||||||
|
if len(context_lines) >= limit:
|
||||||
|
return "\n".join(context_lines)
|
||||||
|
|
||||||
#test
|
# Expand from the strongest seeds in both directions. This recovers facts
|
||||||
from graph_builder import load_graph
|
# several hops away and avoids hiding a match behind a broad hub node.
|
||||||
|
for seed in seed_nodes:
|
||||||
|
frontier = {seed}
|
||||||
|
visited = set()
|
||||||
|
for _depth in range(3):
|
||||||
|
next_frontier = set()
|
||||||
|
for node in frontier:
|
||||||
|
if node in visited:
|
||||||
|
continue
|
||||||
|
visited.add(node)
|
||||||
|
neighbours = set(undirected.neighbors(node))
|
||||||
|
for neighbor in neighbours:
|
||||||
|
if graph.has_edge(node, neighbor):
|
||||||
|
add_edge(str(node), str(neighbor), graph[node][neighbor])
|
||||||
|
if graph.has_edge(neighbor, node):
|
||||||
|
add_edge(str(neighbor), str(node), graph[neighbor][node])
|
||||||
|
next_frontier.add(neighbor)
|
||||||
|
if len(context_lines) >= limit:
|
||||||
|
break
|
||||||
|
if len(context_lines) >= limit:
|
||||||
|
break
|
||||||
|
frontier = next_frontier
|
||||||
|
if len(context_lines) >= limit:
|
||||||
|
break
|
||||||
|
if len(context_lines) >= limit:
|
||||||
|
break
|
||||||
|
|
||||||
if __name__ == "__main__":
|
# Include the nodes themselves as a final fallback. For isolates this is
|
||||||
|
# still graph evidence; for other nodes it supplements sparse edge data.
|
||||||
|
for _, node in sorted(ranked, reverse=True)[:15]:
|
||||||
|
source_doc = graph.nodes[node].get("source_doc") or "unknown source"
|
||||||
|
line = f"{node} (type: {graph.nodes[node].get('type', 'concept')}) [source: {source_doc}]"
|
||||||
|
if line not in context_lines:
|
||||||
|
context_lines.append(line)
|
||||||
|
if len(context_lines) >= limit:
|
||||||
|
break
|
||||||
|
|
||||||
G = load_graph()
|
return "\n".join(dict.fromkeys(context_lines))
|
||||||
|
|
||||||
result = retrieve_subgraph(
|
|
||||||
G,
|
|
||||||
"Python"
|
|
||||||
)
|
|
||||||
|
|
||||||
print(result)
|
|
||||||
|
|||||||
8
start.ps1
Normal file
8
start.ps1
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
$ErrorActionPreference = "Stop"
|
||||||
|
Set-Location $PSScriptRoot
|
||||||
|
|
||||||
|
if (-not (Test-Path ".env")) {
|
||||||
|
Write-Error "Missing .env. Add UNIVERSITY_API_KEY, NEO4J_URI, NEO4J_USER and NEO4J_PASSWORD first."
|
||||||
|
}
|
||||||
|
|
||||||
|
python start.py @args
|
||||||
77
start.py
Normal file
77
start.py
Normal file
@ -0,0 +1,77 @@
|
|||||||
|
"""One-command startup for the GraphRAG teacher application."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from dotenv import load_dotenv
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parent
|
||||||
|
os.chdir(ROOT)
|
||||||
|
load_dotenv(ROOT / ".env")
|
||||||
|
|
||||||
|
from graph_builder import build_graph_from_documents, load_graph, save_graph, sync_graph_to_neo4j
|
||||||
|
from vector_store import ChromaVectorStore
|
||||||
|
|
||||||
|
|
||||||
|
def build_or_load_graph(rebuild: bool):
|
||||||
|
graph_path = ROOT / "graph" / "kg.graphml"
|
||||||
|
if not rebuild and graph_path.exists():
|
||||||
|
graph = load_graph(str(graph_path))
|
||||||
|
print(f"[OK] Loaded graph: {graph.number_of_nodes()} nodes, {graph.number_of_edges()} edges")
|
||||||
|
return graph
|
||||||
|
print("[INFO] Building graph from documents...")
|
||||||
|
graph = build_graph_from_documents(str(ROOT / "documents"))
|
||||||
|
save_graph(graph, str(graph_path))
|
||||||
|
print(f"[OK] Built graph: {graph.number_of_nodes()} nodes, {graph.number_of_edges()} edges")
|
||||||
|
return graph
|
||||||
|
|
||||||
|
|
||||||
|
def sync_neo4j(graph, skip: bool) -> None:
|
||||||
|
if skip:
|
||||||
|
print("[INFO] Neo4j synchronization skipped")
|
||||||
|
return
|
||||||
|
if not os.getenv("NEO4J_URI") or not os.getenv("NEO4J_PASSWORD"):
|
||||||
|
raise RuntimeError("NEO4J_URI and NEO4J_PASSWORD must be configured in .env")
|
||||||
|
edge_count = sync_graph_to_neo4j(graph)
|
||||||
|
print(f"[OK] Synchronized Neo4j: {edge_count} relationships")
|
||||||
|
|
||||||
|
|
||||||
|
def index_chroma(force: bool, skip: bool) -> None:
|
||||||
|
if skip:
|
||||||
|
print("[INFO] ChromaDB indexing skipped")
|
||||||
|
return
|
||||||
|
store = ChromaVectorStore(str(ROOT / "data" / "chroma"))
|
||||||
|
if store.collection.count() and not force:
|
||||||
|
print(f"[OK] ChromaDB ready: {store.collection.count()} indexed chunks")
|
||||||
|
return
|
||||||
|
count = store.index_documents(str(ROOT / "documents"))
|
||||||
|
print(f"[OK] ChromaDB indexed: {count} chunks")
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
parser = argparse.ArgumentParser(description="Start the GraphRAG teacher application")
|
||||||
|
parser.add_argument("--rebuild", action="store_true", help="Re-extract documents and rebuild the graph")
|
||||||
|
parser.add_argument("--reindex", action="store_true", help="Re-index all documents in ChromaDB")
|
||||||
|
parser.add_argument("--skip-neo4j", action="store_true", help="Do not synchronize Neo4j")
|
||||||
|
parser.add_argument("--skip-chroma", action="store_true", help="Do not initialize or index ChromaDB")
|
||||||
|
parser.add_argument("--no-ui", action="store_true", help="Prepare services without launching Gradio")
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
graph = build_or_load_graph(args.rebuild)
|
||||||
|
sync_neo4j(graph, args.skip_neo4j)
|
||||||
|
index_chroma(args.reindex, args.skip_chroma)
|
||||||
|
|
||||||
|
if args.no_ui:
|
||||||
|
print("[OK] Project services are ready")
|
||||||
|
return
|
||||||
|
|
||||||
|
print("[INFO] Starting Gradio at http://127.0.0.1:7860")
|
||||||
|
from gradio_app import create_demo
|
||||||
|
|
||||||
|
create_demo().launch()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
34
test_graph_builder.py
Normal file
34
test_graph_builder.py
Normal file
@ -0,0 +1,34 @@
|
|||||||
|
import unittest
|
||||||
|
|
||||||
|
from graph_builder import _json_response
|
||||||
|
|
||||||
|
|
||||||
|
class JsonResponseTests(unittest.TestCase):
|
||||||
|
def test_parses_object_with_trailing_text(self):
|
||||||
|
text = '{"entities":[{"name":"Python","type":"language"}],"relations":[]}\nExtra text'
|
||||||
|
|
||||||
|
result = _json_response(text)
|
||||||
|
|
||||||
|
self.assertEqual(result["entities"][0]["name"], "Python")
|
||||||
|
|
||||||
|
def test_parses_object_from_markdown_fence(self):
|
||||||
|
text = '```json\n{"entities":[],"relations":[]}\n```'
|
||||||
|
|
||||||
|
result = _json_response(text)
|
||||||
|
|
||||||
|
self.assertEqual(result, {"entities": [], "relations": []})
|
||||||
|
|
||||||
|
def test_selects_object_with_graph_schema(self):
|
||||||
|
text = 'Status {"status":"ok"}\nResult: {"entities":[],"relations":[]}'
|
||||||
|
|
||||||
|
result = _json_response(text)
|
||||||
|
|
||||||
|
self.assertEqual(result, {"entities": [], "relations": []})
|
||||||
|
|
||||||
|
def test_rejects_response_without_schema(self):
|
||||||
|
with self.assertRaises(ValueError):
|
||||||
|
_json_response('{"status":"ok"}')
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
49
test_llm.py
Normal file
49
test_llm.py
Normal file
@ -0,0 +1,49 @@
|
|||||||
|
import unittest
|
||||||
|
from unittest.mock import Mock, patch
|
||||||
|
|
||||||
|
import requests
|
||||||
|
|
||||||
|
import llm
|
||||||
|
|
||||||
|
|
||||||
|
class LlmCallTests(unittest.TestCase):
|
||||||
|
@patch.dict("os.environ", {"UNIVERSITY_API_KEY": "test-key"})
|
||||||
|
@patch("llm.time.sleep")
|
||||||
|
@patch("llm.requests.post")
|
||||||
|
def test_retries_read_timeout_then_succeeds(self, post, sleep):
|
||||||
|
success = Mock()
|
||||||
|
success.status_code = 200
|
||||||
|
success.json.return_value = {
|
||||||
|
"choices": [{"message": {"content": "ok"}}]
|
||||||
|
}
|
||||||
|
post.side_effect = [
|
||||||
|
requests.exceptions.ReadTimeout("timed out"),
|
||||||
|
success,
|
||||||
|
]
|
||||||
|
|
||||||
|
result = llm.llm_call([{"role": "user", "content": "test"}])
|
||||||
|
|
||||||
|
self.assertEqual(result, "ok")
|
||||||
|
self.assertEqual(post.call_count, 2)
|
||||||
|
sleep.assert_called_once_with(1)
|
||||||
|
|
||||||
|
@patch.dict("os.environ", {"UNIVERSITY_API_KEY": "test-key"})
|
||||||
|
@patch("llm.time.sleep")
|
||||||
|
@patch("llm.requests.post")
|
||||||
|
def test_retries_retryable_http_status(self, post, sleep):
|
||||||
|
unavailable = Mock(status_code=503)
|
||||||
|
success = Mock(status_code=200)
|
||||||
|
success.json.return_value = {
|
||||||
|
"choices": [{"message": {"content": "recovered"}}]
|
||||||
|
}
|
||||||
|
post.side_effect = [unavailable, success]
|
||||||
|
|
||||||
|
result = llm.llm_call([{"role": "user", "content": "test"}])
|
||||||
|
|
||||||
|
self.assertEqual(result, "recovered")
|
||||||
|
self.assertEqual(post.call_count, 2)
|
||||||
|
sleep.assert_called_once_with(1)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
221
test_retrieval.py
Normal file
221
test_retrieval.py
Normal file
@ -0,0 +1,221 @@
|
|||||||
|
import unittest
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
import networkx as nx
|
||||||
|
|
||||||
|
import gradio_app
|
||||||
|
from react_agent import react_agent
|
||||||
|
from retrieval import retrieve_subgraph
|
||||||
|
from tools import check_teaching_suitability
|
||||||
|
|
||||||
|
|
||||||
|
class RetrievalAndAgentTests(unittest.TestCase):
|
||||||
|
def test_retrieval_returns_matching_edge(self):
|
||||||
|
graph = nx.DiGraph()
|
||||||
|
graph.add_node("Literature", type="concept")
|
||||||
|
graph.add_node("Reading", type="skill")
|
||||||
|
graph.add_edge("Literature", "Reading", relation="requires")
|
||||||
|
|
||||||
|
evidence = retrieve_subgraph(graph, "What does literature require?")
|
||||||
|
|
||||||
|
self.assertIn("Literature --requires--> Reading", evidence)
|
||||||
|
|
||||||
|
def test_retrieval_includes_source_document_metadata(self):
|
||||||
|
graph = nx.DiGraph()
|
||||||
|
graph.add_node("Literature", type="concept", source_doc="SJL_1_1st.pdf")
|
||||||
|
graph.add_node("Reading", type="skill", source_doc="SJL_1_1st.pdf")
|
||||||
|
graph.add_edge(
|
||||||
|
"Literature",
|
||||||
|
"Reading",
|
||||||
|
relation="requires",
|
||||||
|
source_doc="SJL_1_1st.pdf",
|
||||||
|
)
|
||||||
|
|
||||||
|
evidence = retrieve_subgraph(graph, "Literature reading")
|
||||||
|
|
||||||
|
self.assertIn("[source: SJL_1_1st.pdf]", evidence)
|
||||||
|
|
||||||
|
@patch("tools.llm_call", return_value="Partial curriculum support")
|
||||||
|
def test_suitability_check_returns_status_and_evidence(self, llm_call):
|
||||||
|
graph = nx.DiGraph()
|
||||||
|
graph.add_node("Literature", type="concept", source_doc="SJL_1_1st.pdf")
|
||||||
|
graph.add_node("Reading", type="skill", source_doc="SJL_1_1st.pdf")
|
||||||
|
graph.add_edge(
|
||||||
|
"Literature",
|
||||||
|
"Reading",
|
||||||
|
relation="requires",
|
||||||
|
source_doc="SJL_1_1st.pdf",
|
||||||
|
)
|
||||||
|
|
||||||
|
result = check_teaching_suitability(
|
||||||
|
"Slovak language",
|
||||||
|
"5",
|
||||||
|
"Literature",
|
||||||
|
"Class includes pupils with dyslexia",
|
||||||
|
graph,
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertEqual(result["answer"], "Partial curriculum support")
|
||||||
|
self.assertIn("[source: SJL_1_1st.pdf]", result["evidence"])
|
||||||
|
llm_call.assert_called_once()
|
||||||
|
|
||||||
|
@patch("tools.llm_call", return_value="Graph-backed lesson")
|
||||||
|
def test_agent_always_returns_retrieved_evidence(self, llm_call):
|
||||||
|
graph = nx.DiGraph()
|
||||||
|
graph.add_node("Literature", type="concept")
|
||||||
|
graph.add_node("Reading", type="skill")
|
||||||
|
graph.add_edge("Literature", "Reading", relation="requires")
|
||||||
|
|
||||||
|
response = react_agent("Prepare literature lesson", [], graph)
|
||||||
|
|
||||||
|
self.assertEqual(response.answer, "Graph-backed lesson")
|
||||||
|
self.assertIn("Literature --requires--> Reading", response.evidence)
|
||||||
|
llm_call.assert_called_once()
|
||||||
|
|
||||||
|
@patch("tools.llm_call", return_value="No matching graph evidence")
|
||||||
|
def test_agent_has_empty_evidence_when_retrieval_is_empty(self, llm_call):
|
||||||
|
graph = nx.DiGraph()
|
||||||
|
|
||||||
|
response = react_agent("Prepare calculus lesson", [], graph)
|
||||||
|
|
||||||
|
self.assertEqual(response.evidence, "")
|
||||||
|
|
||||||
|
def test_prepare_lesson_does_not_render_interactive_graph(self):
|
||||||
|
graph = nx.DiGraph()
|
||||||
|
graph.add_node("Literature", type="concept")
|
||||||
|
graph.add_node("Reading", type="skill")
|
||||||
|
graph.add_edge("Literature", "Reading", relation="requires")
|
||||||
|
|
||||||
|
with patch("gradio_app.GRAPH", graph), patch("gradio_app.react_agent") as react:
|
||||||
|
from models import GraphRAGResponse
|
||||||
|
|
||||||
|
react.return_value = GraphRAGResponse(
|
||||||
|
"lesson",
|
||||||
|
"Lesson answer",
|
||||||
|
"Literature --requires--> Reading",
|
||||||
|
)
|
||||||
|
answer, evidence = gradio_app.prepare_lesson(
|
||||||
|
"Literature", "5", "Reading", "45", "Slovak"
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertEqual(answer, "Lesson answer")
|
||||||
|
self.assertEqual(evidence, "Literature --requires--> Reading")
|
||||||
|
|
||||||
|
@patch("gradio_app.answer_general_question")
|
||||||
|
def test_general_question_returns_standard_answer_and_evidence(self, answer_general_question):
|
||||||
|
answer_general_question.return_value = {
|
||||||
|
"answer": "A pedagogical assistant supports the teacher.",
|
||||||
|
"evidence": "Teacher --related_to--> Pedagogical Assistant",
|
||||||
|
}
|
||||||
|
|
||||||
|
with patch("gradio_app.GRAPH", nx.DiGraph()):
|
||||||
|
answer, evidence = gradio_app.answer_question(
|
||||||
|
"What does a pedagogical assistant do?"
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertEqual(answer, "A pedagogical assistant supports the teacher.")
|
||||||
|
self.assertEqual(evidence, "Teacher --related_to--> Pedagogical Assistant")
|
||||||
|
|
||||||
|
def test_general_question_rejects_empty_input(self):
|
||||||
|
answer, evidence = gradio_app.answer_question(" ")
|
||||||
|
|
||||||
|
self.assertEqual(answer, "Please enter a question.")
|
||||||
|
self.assertEqual(evidence, "")
|
||||||
|
|
||||||
|
@patch("gradio_app.react_agent")
|
||||||
|
def test_prepare_lesson_supports_omitted_fields(self, react):
|
||||||
|
from models import GraphRAGResponse
|
||||||
|
|
||||||
|
react.return_value = GraphRAGResponse(
|
||||||
|
"lesson",
|
||||||
|
"Assumption-based lesson",
|
||||||
|
"Literature --teaches--> Reading",
|
||||||
|
)
|
||||||
|
|
||||||
|
with patch("gradio_app.GRAPH", nx.DiGraph()):
|
||||||
|
answer, evidence = gradio_app.prepare_lesson("", "", "", "", "")
|
||||||
|
|
||||||
|
request = react.call_args.args[0]
|
||||||
|
self.assertIn("Subject: not specified", request)
|
||||||
|
self.assertIn("Grade: not specified", request)
|
||||||
|
self.assertIn("Topic: not specified", request)
|
||||||
|
self.assertIn("45-minute", request)
|
||||||
|
self.assertIn("in Slovak", request)
|
||||||
|
self.assertEqual(answer, "Assumption-based lesson")
|
||||||
|
self.assertEqual(evidence, "Literature --teaches--> Reading")
|
||||||
|
|
||||||
|
def test_retrieval_matches_typo_or_paraphrase(self):
|
||||||
|
graph = nx.DiGraph()
|
||||||
|
graph.add_node("Slovensky Jazyk A Literatura", type="subject")
|
||||||
|
graph.add_node("Grammar", type="concept")
|
||||||
|
graph.add_edge(
|
||||||
|
"Slovensky Jazyk A Literatura",
|
||||||
|
"Grammar",
|
||||||
|
relation="teaches",
|
||||||
|
source_doc="SJL_1_1st.pdf",
|
||||||
|
)
|
||||||
|
|
||||||
|
evidence = retrieve_subgraph(
|
||||||
|
graph,
|
||||||
|
"Co sa vzucuje na slovenskom jazyku",
|
||||||
|
limit=20,
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertIn("Slovensky Jazyk A Literatura --teaches--> Grammar", evidence)
|
||||||
|
|
||||||
|
def test_retrieval_keeps_rare_topic_from_broad_subject_node(self):
|
||||||
|
graph = nx.DiGraph()
|
||||||
|
graph.add_node("Slovensky Jazyk A Literatura", type="subject")
|
||||||
|
for index in range(45):
|
||||||
|
graph.add_edge(
|
||||||
|
"Slovensky Jazyk A Literatura",
|
||||||
|
f"Common Curriculum Concept {index}",
|
||||||
|
relation="teaches",
|
||||||
|
)
|
||||||
|
graph.add_node("Klasicizmus", type="concept")
|
||||||
|
graph.add_edge("Hudobny Styl", "Klasicizmus", relation="related_to")
|
||||||
|
|
||||||
|
evidence = retrieve_subgraph(
|
||||||
|
graph,
|
||||||
|
"Prepare a lesson about Klasicizmus for grade 5. "
|
||||||
|
"Subject: Slovensky jazyk a literatura.",
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertIn("Hudobny Styl --related_to--> Klasicizmus", evidence)
|
||||||
|
|
||||||
|
def test_retrieval_expands_multiple_hops_from_seed_node(self):
|
||||||
|
graph = nx.DiGraph()
|
||||||
|
graph.add_edge("Literature", "Middle Ages", relation="covers")
|
||||||
|
graph.add_edge("Middle Ages", "Court Poetry", relation="includes")
|
||||||
|
graph.add_edge("Court Poetry", "Minnesang", relation="teaches")
|
||||||
|
|
||||||
|
evidence = retrieve_subgraph(
|
||||||
|
graph,
|
||||||
|
"What should we teach about Minnesang?",
|
||||||
|
limit=20,
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertIn("Court Poetry --teaches--> Minnesang", evidence)
|
||||||
|
self.assertIn("Middle Ages", evidence)
|
||||||
|
|
||||||
|
def test_retrieval_matches_requested_edge_relation(self):
|
||||||
|
graph = nx.DiGraph()
|
||||||
|
graph.add_edge(
|
||||||
|
"Programming",
|
||||||
|
"Algorithms",
|
||||||
|
relation="requires",
|
||||||
|
source_doc="INF_1st.pdf",
|
||||||
|
)
|
||||||
|
|
||||||
|
evidence = retrieve_subgraph(
|
||||||
|
graph,
|
||||||
|
"Which concepts does programming require?",
|
||||||
|
limit=20,
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertIn("Programming --requires--> Algorithms", evidence)
|
||||||
|
self.assertIn("[source: INF_1st.pdf]", evidence)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
142
tools.py
142
tools.py
@ -1,50 +1,118 @@
|
|||||||
from retrieval import retrieve_subgraph
|
from retrieval import retrieve_subgraph
|
||||||
from llm import llm_call
|
from llm import llm_call
|
||||||
|
|
||||||
def query_knowledge_graph(question: str, G):
|
|
||||||
|
|
||||||
graph_context = retrieve_subgraph(G, question)
|
|
||||||
|
|
||||||
prompt = f"""
|
|
||||||
You are an educational assistant.
|
|
||||||
|
|
||||||
Use ONLY the graph knowledge below to answer.
|
|
||||||
|
|
||||||
Graph Knowledge:
|
|
||||||
{graph_context}
|
|
||||||
|
|
||||||
|
def query_knowledge_graph(question: str, graph, language: str = "Slovak"):
|
||||||
|
evidence = retrieve_subgraph(graph, question).strip()
|
||||||
|
if not evidence:
|
||||||
|
prompt = f"""You are an educational assistant.
|
||||||
|
Respond only in {language}.
|
||||||
|
No directly matching graph evidence was retrieved, but that does not prove the
|
||||||
|
topic is absent from the graph. State that the retrieved context was insufficient,
|
||||||
|
name the exact topic or document that needs verification, and do not claim it is
|
||||||
|
absent or invent curriculum details.
|
||||||
Question:
|
Question:
|
||||||
{question}
|
|
||||||
|
|
||||||
Rules:
|
|
||||||
- If graph is empty, say "No information in knowledge graph"
|
|
||||||
- Be concise and educational
|
|
||||||
"""
|
"""
|
||||||
|
prompt += question
|
||||||
|
else:
|
||||||
|
prompt = f"""You are an educational assistant. Respond only in {language}.
|
||||||
|
Answer using only this graph evidence.
|
||||||
|
Create a practical, age-appropriate answer for a teacher.
|
||||||
|
Interpret minor spelling mistakes and paraphrases as the likely meaning of the question.
|
||||||
|
If an exact topic name is missing, distinguish confirmed concepts from inferred suggestions and do not claim unsupported facts.
|
||||||
|
Treat every relation and source line as retrieved graph context, not as an external fact.
|
||||||
|
If the evidence is related but does not directly answer the question, say that the
|
||||||
|
evidence is partial and identify the missing point instead of filling it from general knowledge.
|
||||||
|
Evidence:
|
||||||
|
{evidence}
|
||||||
|
Question: {question}"""
|
||||||
|
return {"answer": llm_call([{"role": "user", "content": prompt}]), "evidence": evidence}
|
||||||
|
|
||||||
response = llm_call([
|
|
||||||
{"role": "user", "content": prompt}
|
|
||||||
])
|
|
||||||
|
|
||||||
return {
|
def answer_general_question(question: str, graph, language: str = "Slovak"):
|
||||||
"answer": response,
|
evidence = retrieve_subgraph(graph, question).strip()
|
||||||
"evidence": graph_context
|
if not evidence:
|
||||||
}
|
prompt = f"""You are a helpful educational assistant for teachers.
|
||||||
|
Respond only in {language}.
|
||||||
|
No directly matching evidence was retrieved from the knowledge graph.
|
||||||
|
Do not say that the topic is definitely absent from the graph.
|
||||||
|
Answer briefly and clearly without inventing curriculum facts.
|
||||||
|
Explain what cannot be confirmed and suggest an exact source or concept to verify.
|
||||||
|
Question: {question}"""
|
||||||
|
else:
|
||||||
|
prompt = f"""You are a helpful educational assistant for teachers.
|
||||||
|
Respond only in {language}.
|
||||||
|
Answer the question directly in clear, standard prose.
|
||||||
|
Do not turn the answer into a lesson plan unless the question explicitly asks for one.
|
||||||
|
Use only the retrieved knowledge graph evidence below. Do not use outside knowledge.
|
||||||
|
Interpret spelling mistakes and paraphrases naturally.
|
||||||
|
Distinguish confirmed facts from suggestions or inferences.
|
||||||
|
If the evidence only partially answers the question, state that clearly and identify
|
||||||
|
the missing information rather than guessing.
|
||||||
|
Use this structure when it helps:
|
||||||
|
1. Direct answer
|
||||||
|
2. Supporting graph facts
|
||||||
|
3. Limits or verification needed
|
||||||
|
|
||||||
|
Evidence:
|
||||||
|
{evidence}
|
||||||
|
|
||||||
|
Question: {question}"""
|
||||||
|
return {"answer": llm_call([{"role": "user", "content": prompt}]), "evidence": evidence}
|
||||||
|
|
||||||
|
|
||||||
|
def check_teaching_suitability(
|
||||||
|
subject: str,
|
||||||
|
grade: str,
|
||||||
|
topic: str,
|
||||||
|
conditions: str,
|
||||||
|
graph,
|
||||||
|
language: str = "Slovak",
|
||||||
|
):
|
||||||
|
question = (
|
||||||
|
f"Teaching suitability check for subject {subject}, grade {grade}, topic {topic}. "
|
||||||
|
f"Specific conditions and constraints: {conditions}. "
|
||||||
|
"Assess whether the topic and conditions are consistent with the Slovak curriculum and applicable educational rules."
|
||||||
|
)
|
||||||
|
evidence = retrieve_subgraph(graph, question).strip()
|
||||||
|
if not evidence:
|
||||||
|
prompt = f"""You are a pedagogical advisory assistant.
|
||||||
|
Respond only in {language}.
|
||||||
|
No supporting graph evidence was retrieved.
|
||||||
|
Do not claim that the topic is legally or curriculum-compliant.
|
||||||
|
Clearly state that there is insufficient evidence and identify which official documents or professional experts should verify it.
|
||||||
|
Question: {question}
|
||||||
|
Return a structured answer with:
|
||||||
|
1. Status: insufficient evidence
|
||||||
|
2. What can be determined
|
||||||
|
3. What cannot be determined
|
||||||
|
4. Required verification
|
||||||
|
5. Safety and inclusion considerations
|
||||||
|
"""
|
||||||
|
else:
|
||||||
|
prompt = f"""You are a pedagogical advisory assistant.
|
||||||
|
Respond only in {language}.
|
||||||
|
Use only the graph evidence below to assess curriculum and educational appropriateness.
|
||||||
|
Do not present an unsupported conclusion as a legal determination.
|
||||||
|
If the evidence does not directly cover a law or the required grade/topic, say that verification is needed.
|
||||||
|
Distinguish curriculum alignment from legal compliance.
|
||||||
|
Add a short disclaimer that the teacher should confirm the result against the current official school documents and local school rules.
|
||||||
|
Evidence:
|
||||||
|
{evidence}
|
||||||
|
Request: {question}
|
||||||
|
Return a structured answer with:
|
||||||
|
1. Status: supported / partial support / insufficient evidence
|
||||||
|
2. Curriculum alignment
|
||||||
|
3. Conditions and feasibility
|
||||||
|
4. Legal or official-source verification needed
|
||||||
|
5. Inclusion, safety and accessibility considerations
|
||||||
|
6. Recommended next step
|
||||||
|
"""
|
||||||
|
return {"answer": llm_call([{"role": "user", "content": prompt}]), "evidence": evidence}
|
||||||
|
|
||||||
|
|
||||||
TOOL_MAP = {
|
TOOL_MAP = {
|
||||||
"query_knowledge_graph": query_knowledge_graph,
|
"query_knowledge_graph": query_knowledge_graph,
|
||||||
|
"answer_general_question": answer_general_question,
|
||||||
|
"check_teaching_suitability": check_teaching_suitability,
|
||||||
}
|
}
|
||||||
|
|
||||||
#test
|
|
||||||
from graph_builder import load_graph
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
|
|
||||||
G = load_graph()
|
|
||||||
|
|
||||||
result = query_knowledge_graph(
|
|
||||||
"What is used in machine learning?",
|
|
||||||
G
|
|
||||||
)
|
|
||||||
|
|
||||||
print(result)
|
|
||||||
32
vector_store.py
Normal file
32
vector_store.py
Normal file
@ -0,0 +1,32 @@
|
|||||||
|
"""ChromaDB retrieval using multilingual-e5-large with the required query/passage prefixes."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from ingest import load_documents
|
||||||
|
|
||||||
|
|
||||||
|
class ChromaVectorStore:
|
||||||
|
def __init__(self, path: str = "data/chroma", model_name: str = "intfloat/multilingual-e5-large"):
|
||||||
|
import chromadb
|
||||||
|
from sentence_transformers import SentenceTransformer
|
||||||
|
|
||||||
|
self.client = chromadb.PersistentClient(path=path)
|
||||||
|
self.collection = self.client.get_or_create_collection("lesson_documents")
|
||||||
|
self.model = SentenceTransformer(model_name)
|
||||||
|
|
||||||
|
def index_documents(self, folder: str = "documents") -> int:
|
||||||
|
docs = load_documents(folder)
|
||||||
|
ids, texts, metadatas = [], [], []
|
||||||
|
for document in docs:
|
||||||
|
text = document["content"]
|
||||||
|
for index in range(0, len(text), 6000):
|
||||||
|
chunk = text[index:index + 6000].strip()
|
||||||
|
if chunk:
|
||||||
|
ids.append(f"{document['filename']}:{index}")
|
||||||
|
texts.append(f"passage: {chunk}")
|
||||||
|
metadatas.append({"source": document["filename"]})
|
||||||
|
if texts:
|
||||||
|
embeddings = self.model.encode(texts, normalize_embeddings=True).tolist()
|
||||||
|
self.collection.upsert(ids=ids, documents=texts, embeddings=embeddings, metadatas=metadatas)
|
||||||
|
return len(texts)
|
||||||
@ -1,31 +0,0 @@
|
|||||||
from pyvis.network import Network
|
|
||||||
from graph_builder import load_graph
|
|
||||||
|
|
||||||
def visualize_graph(G):
|
|
||||||
net = Network(
|
|
||||||
directed=True,
|
|
||||||
notebook=False
|
|
||||||
)
|
|
||||||
|
|
||||||
for node in G.nodes():
|
|
||||||
net.add_node(node)
|
|
||||||
|
|
||||||
for u, v, data in G.edges(data=True):
|
|
||||||
net.add_edge(
|
|
||||||
u,
|
|
||||||
v,
|
|
||||||
label=data.get("relation", "")
|
|
||||||
)
|
|
||||||
|
|
||||||
output_path = "kg.html"
|
|
||||||
|
|
||||||
net.write_html(output_path)
|
|
||||||
|
|
||||||
print(f"Graph saved to {output_path}")
|
|
||||||
|
|
||||||
#test
|
|
||||||
if __name__ == "__main__":
|
|
||||||
|
|
||||||
G = load_graph()
|
|
||||||
|
|
||||||
visualize_graph(G)
|
|
||||||
Loading…
Reference in New Issue
Block a user