-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi_server.py
More file actions
1907 lines (1540 loc) · 47.4 KB
/
Copy pathapi_server.py
File metadata and controls
1907 lines (1540 loc) · 47.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from fastapi.middleware.cors import CORSMiddleware
from pathlib import Path
import json
import time
import threading
import os
import re
import unicodedata
from datetime import datetime
from typing import Dict, Optional
import shutil
from fastapi import FastAPI, UploadFile, File, Header, HTTPException
from pydantic import BaseModel, Field
from fastapi.responses import FileResponse
from fastapi.staticfiles import StaticFiles
from dotenv import load_dotenv
from llm_core.local_model import LocalLLM, GenerationCancelled
from audit.audit_logger import AuditLogger
from audit.telemetry_logger import TelemetryLogger
from security.prompt_guard import PromptGuard
from rag.document_loader import DocumentLoader
from rag.chunker import TextChunker
from rag.chroma_retriever import ChromaRetriever
from common.text_cleaner import clean_llm_output
from common.accessibility_formatter import to_accessible_speech
from services.routing_language_service import RoutingLanguageService
from services.direct_knowledge_service import DirectKnowledgeService
from services.direct_answer_composer import compose_direct_answer
load_dotenv(override=True)
APP_VERSION = "0.1.0"
DOCS_DIR = Path("data/documents")
CONTENT_GAP_FILE = Path(__file__).resolve().parent / "logs" / "content_gap.jsonl"
EDUCATION_DOCS_DIR = (
Path(__file__).resolve().parent.parent
/ "01_KODA_Education_Platform"
/ "kodaai"
/ "data"
/ "output"
/ "license"
)
DOCS_DIR.mkdir(exist_ok=True)
ALLOWED_DOCUMENT_EXTENSIONS = {
".txt",
".pdf",
".docx",
".json",
}
app = FastAPI(
title="KODA Local AI API",
version=APP_VERSION,
description="Local-first experimental RAG-powered Turkish LLM runtime.",
docs_url=None,
redoc_url=None,
openapi_url=None,
)
WEB_DIR = Path(__file__).resolve().parent / "web"
app.mount(
"/static",
StaticFiles(directory=WEB_DIR),
name="static",
)
app.add_middleware(
CORSMiddleware,
allow_origins=["http://127.0.0.1:5500"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/", include_in_schema=False)
def local_ai_ui():
return FileResponse(WEB_DIR / "index.html")
@app.middleware("http")
async def telemetry_exception_middleware(request, call_next):
started_at = time.perf_counter()
try:
return await call_next(request)
except Exception as exc:
if request.url.path == "/ask":
telemetry.log_request(
request_id=telemetry.new_request_id(),
route="ERROR",
duration_ms=(time.perf_counter() - started_at) * 1000,
source_count=0,
used_context=False,
success=False,
blocked=False,
subject=None,
accessibility_layer="NONE",
error=type(exc).__name__,
)
raise
class AskRequest(BaseModel):
question: str
user_role: str = "research"
session_id: str | None = None
client_request_id: str | None = None
class StopTelemetryRequest(BaseModel):
request_id: str
session_id: str | None = None
stop_after_ms: float | None = None
class SourceItem(BaseModel):
file_name: str
content_type: str | None = None
subject: str | None = None
chunk_id: int | str
similarity: float
class AskResponse(BaseModel):
answer: str
answer_speech: str | None = None
used_context: bool
sources: list[SourceItem] = Field(default_factory=list)
process_steps: list[str] = Field(default_factory=list)
blocked: bool = False
reason: str | None = None
class TutorExplainRequest(BaseModel):
lesson_code: str
question_id: str
user_message: str
question: str
options: Dict[str, str]
correct_answer: str
passage: Optional[str] = None
explanation_hint: Optional[str] = None
user_answer: Optional[str] = None
user_role: str = "student"
class TutorExplainResponse(BaseModel):
answer: str
lesson_code: str
question_id: str
used_passage: bool
blocked: bool = False
reason: str | None = None
audit = AuditLogger()
telemetry = TelemetryLogger()
guard = PromptGuard()
routing_language = RoutingLanguageService()
direct_knowledge = DirectKnowledgeService()
_active_generations_lock = threading.Lock()
_active_generations = {}
def begin_generation(session_id: str | None):
if not session_id:
return threading.Event()
with _active_generations_lock:
previous = _active_generations.get(session_id)
if previous is not None:
previous.set()
current = threading.Event()
_active_generations[session_id] = current
return current
def cancel_generation(session_id: str | None):
if not session_id:
return False
with _active_generations_lock:
current = _active_generations.get(session_id)
if current is None:
return False
current.set()
return True
def finish_generation(
session_id: str | None,
cancel_event
):
if not session_id:
return
with _active_generations_lock:
current = _active_generations.get(session_id)
if current is cancel_event:
_active_generations.pop(session_id, None)
loader = DocumentLoader(docs_dir=str(DOCS_DIR))
documents = loader.load_documents()
for education_subdir in ("reading", "quiz", "exam"):
education_loader = DocumentLoader(
docs_dir=str(EDUCATION_DOCS_DIR / education_subdir)
)
documents += education_loader.load_documents()
chunker = TextChunker(chunk_size=600, overlap=100)
chunks = chunker.chunk_documents(documents)
retriever = ChromaRetriever([])
llm = LocalLLM(
model_name="gemma3:4b",
mode="offline"
)
SUBJECT_KEYWORDS = {
"cografya": (
"coğrafya",
"doğu anadolu",
"batı anadolu",
"iç anadolu",
"marmara",
"ege bölgesi",
"akdeniz bölgesi",
"karadeniz bölgesi",
"güneydoğu anadolu",
"iklim",
"masif",
"jeoloji",
"jeolojik",
"jeomorfoloji",
"jeomorfolojik",
"kayaç",
"tektonik",
"yeryüzü şekilleri",
"nüfus",
"yerleşme",
"göç",
),
"tarih": (
"tarih",
"osmanlı",
"selçuklu",
"atatürk",
"kurtuluş savaşı",
"milli mücadele",
"inkılap",
"birinci dünya savaşı",
"ikinci dünya savaşı",
"ii. dünya savaşı",
"i. dünya savaşı",
"i dünya savaşı",
"ii dünya savaşı",
),
"matematik": (
"matematik",
"denklem",
"kesir",
"yüzde",
"oran",
"orantı",
"üslü",
"köklü",
"geometri",
"fonksiyon",
"eşitsizlik",
"olasılık",
"ifade",
"işlem",
"denklem",
"eşitlik",
"eşitsizlik",
),
"turkce": (
"türkçe",
"paragraf",
"sözcük",
"cümle",
"fiilimsi",
"anlatım bozukluğu",
"noktalama",
"yazım",
),
"vatandaslik": (
"vatandaşlık",
"anayasa",
"tbmm",
"hukuk",
"yargı",
"yasama",
"yürütme",
"seçim",
"siyasi parti",
),
}
def log_content_gap(
*,
question: str,
subject: str | None,
topic_guess: str | None,
retrieval_score: float,
matched_sources: int,
request_id: str | None = None,
session_id: str | None = None,
) -> bool:
"""
Append one curriculum content-gap event to logs/content_gap.jsonl.
This logger is deliberately fail-safe: telemetry/logging must never
break the user's /ask request path.
"""
if not subject or subject not in SUBJECT_KEYWORDS:
return False
record = {
"timestamp": datetime.now().astimezone().isoformat(timespec="seconds"),
"event": "CONTENT_GAP",
"question": question,
"subject": subject,
"topic_guess": topic_guess or "",
"curriculum_scope": True,
"retrieval_score": round(float(retrieval_score), 3),
"matched_sources": int(matched_sources),
"status": "PENDING_REVIEW",
"request_id": request_id,
"session_id": session_id,
}
try:
CONTENT_GAP_FILE.parent.mkdir(parents=True, exist_ok=True)
with CONTENT_GAP_FILE.open(
"a",
encoding="utf-8",
) as handle:
handle.write(
json.dumps(
record,
ensure_ascii=False,
)
+ "\n"
)
return True
except Exception:
# Content-gap logging is observational only.
# Never interrupt the answer pipeline because the log could not be written.
return False
def detect_subject(question: str) -> str | None:
# Turkish-aware, ASCII-stable normalization.
# PowerShell/clipboard encoding differences must not affect routing.
normalized = question.casefold().replace(chr(775), "")
normalized = normalized.translate(
str.maketrans({
ord(chr(231)): "c", # c-cedilla
ord(chr(287)): "g", # g-breve
ord(chr(305)): "i", # dotless i
ord(chr(246)): "o", # o-diaeresis
ord(chr(351)): "s", # s-cedilla
ord(chr(252)): "u", # u-diaeresis
})
)
# 1. Explicit mathematical symbols
math_symbols = (
"=", "+", "-", "*", "<", ">", "%",
chr(215),
chr(247),
chr(8804),
chr(8805),
chr(8730),
chr(178),
chr(179),
)
if any(symbol in question for symbol in math_symbols):
return "matematik"
if re.search(r"\b\d+\s*/\s*\d+\b", question):
return "matematik"
# 2. High-confidence curriculum expressions.
# Patterns are deliberately ASCII after normalization.
strong_patterns = {
"turkce": (
"gercek anlam",
"mecaz anlam",
"es anlam",
"zit anlam",
"yakin anlam",
"terim anlam",
"paragraf",
"sozcuk",
"kelime",
"baglam",
"ana dusunce",
"ana fikir",
"yardimci dusunce",
"cikarim",
),
"matematik": (
"rasyonel sayi",
"rasyonel",
"dogal sayi",
"tam sayi",
"sayi kumeleri",
"rakam",
"basamak",
"bolu",
),
"tarih": (
"orhun",
"gokturk",
"islamiyet oncesi turk",
"islamiyet oncesindeki devlet",
"ilk turk devlet",
"eski turk",
"kurultay",
"kut anlayisi",
"hukumdar",
),
"cografya": (
"iklim",
"cografya",
"yer sekilleri",
"yeryuzu sekilleri",
"denizlerin iklime",
"karasal iklim",
),
}
scores = {}
for subject, patterns in strong_patterns.items():
score = sum(
3 for pattern in patterns
if pattern in normalized
)
if score:
scores[subject] = scores.get(subject, 0) + score
# Generic number concepts, but not every occurrence of "sayi".
if re.search(
r"\b("
r"sayi\s+nedir"
r"|sayi\s+ile"
r"|bir\s+sayi\b"
r"|sayilar\b"
r"|sayilarin\b"
r"|sayinin\b"
r")",
normalized,
):
scores["matematik"] = scores.get("matematik", 0) + 3
# 3. Existing SUBJECT_KEYWORDS remain useful as secondary evidence.
for subject, keywords in SUBJECT_KEYWORDS.items():
score = 0
for keyword in keywords:
k = keyword.casefold().replace(chr(775), "")
k = k.translate(
str.maketrans({
ord(chr(231)): "c",
ord(chr(287)): "g",
ord(chr(305)): "i",
ord(chr(246)): "o",
ord(chr(351)): "s",
ord(chr(252)): "u",
})
)
# Too generic for mathematics.
if subject == "matematik" and k == "ifade":
continue
if k in normalized:
score += 1
if score:
scores[subject] = scores.get(subject, 0) + score
if not scores:
return None
ranked = sorted(
scores.items(),
key=lambda item: (-item[1], item[0])
)
best_subject, best_score = ranked[0]
if len(ranked) > 1 and ranked[1][1] == best_score:
return None
return best_subject
def _normalize_answerability_text(text: str) -> list[str]:
text = text.casefold()
turkish_map = str.maketrans({
"\u0131": "i",
"\u011f": "g",
"\u00fc": "u",
"\u015f": "s",
"\u00f6": "o",
"\u00e7": "c",
})
text = text.translate(turkish_map)
text = unicodedata.normalize("NFKD", text)
text = "".join(
char for char in text
if not unicodedata.combining(char)
)
return re.findall(r"[a-z0-9]+", text)
def is_context_answerable(question: str, context: str) -> tuple[bool, float]:
if not context.strip():
return False, 0.0
stop_words = {
"ve", "veya", "ile", "bir", "bu", "su",
"nedir", "nelerdir", "neler", "hangileri", "hangileridir", "say", "acikla", "anlat",
"hakkinda", "icin", "olan", "olarak",
"mi", "midir", "dir",
"nin", "nın", "nun", "nün",
"ni", "nı", "nu", "nü", "deki", "daki", "teki", "taki",
}
question_words = [
word
for word in _normalize_answerability_text(question)
if len(word) > 2 and word not in stop_words
]
if not question_words:
return True, 1.0
context_words = set(_normalize_answerability_text(context))
def supported(word: str) -> bool:
if word in context_words:
return True
if len(word) >= 5:
prefix = word[:5]
return any(
len(candidate) >= 5 and candidate.startswith(prefix)
for candidate in context_words
)
return False
matched = sum(1 for word in question_words if supported(word))
coverage = matched / len(question_words)
return coverage >= 0.50, round(coverage, 3)
def has_required_answer_evidence(question: str, context: str) -> tuple[bool, str]:
"""
Soru yalnızca konu benzerliği değil, belirli bir bilgi türü istiyorsa
bağlamın o bilgi türünü gerçekten içerip içermediğini kontrol eder.
"""
q_words = _normalize_answerability_text(question)
c_words = _normalize_answerability_text(context)
q_text = " ".join(q_words)
c_text = " ".join(c_words)
# ORHUN TARGETED EVIDENCE GUARD
if "orhun" in q_text:
if "dili" in q_text:
language_markers = (
"gokturkce",
"kokturkce",
"eski turkce",
"orhun turkcesi",
)
if not any(
marker in c_text
for marker in language_markers
):
return (
False,
"orhun_language_missing_explicit_evidence",
)
if "yansit" in q_text:
reflection_markers = (
"yansitir",
"yansitmistir",
"yansitan",
"yansitmakta",
)
if not any(
marker in c_text
for marker in reflection_markers
):
return (
False,
"orhun_reflection_missing_explicit_evidence",
)
# Görev / yetki / işlev soruları
duty_intent = any(
token in q_text
for token in (
"gorev",
"gorevleri",
"yetki",
"yetkileri",
"islev",
"islevi",
"ne ise yarar",
)
)
if duty_intent:
duty_evidence_patterns = (
r"\bgorevi\b",
r"\bgorevleri\b",
r"\bgorevidir\b",
r"\bgorevleridir\b",
r"\byetkisi\b",
r"\byetkileri\b",
r"\bsorumludur\b",
r"\byukumludur\b",
r"\binceler\b",
r"\barastirir\b",
r"\bdenetler\b",
r"\bdegerlendirir\b",
r"\bsonuclandirir\b",
r"\btavsiyede\s+bulunur\b",
r"\bkarar\s+verir\b",
r"\byerine\s+getirir\b",
r"\bbasvuru(?:yu|lari|lar)?\s+(?:inceler|degerlendirir|sonuclandirir)\b",
)
if not any(
re.search(pattern, c_text)
for pattern in duty_evidence_patterns
):
return False, "DUTY_EVIDENCE_MISSING"
# --------------------------------------------------
# DUTY SUBJECT LINK GUARD
#
# "X'in gorevleri nelerdir?" sorusunda baglam,
# gorev/yetki bilgisini ayni ana ozneye baglamali.
#
# Ornek:
# "Belediye encumeninin gorevleri..." ifadesi
# "Belediyenin gorevleri..." sorusuna tek basina
# yeterli evidence sayilmaz.
# --------------------------------------------------
duty_stop_words = {
"gorev",
"gorevleri",
"yetki",
"yetkileri",
"islev",
"islevi",
"nelerdir",
"nedir",
"ne",
"ise",
"yarar",
}
subject_tokens = [
token
for token in q_words
if (
len(token) > 2
and token not in duty_stop_words
)
]
if subject_tokens:
subject_linked = False
raw_sentences = re.split(
r"(?<=[.!?])\s+|\n+",
context,
)
for raw_sentence in raw_sentences:
sentence_words = (
_normalize_answerability_text(
raw_sentence
)
)
if not sentence_words:
continue
sentence_text = " ".join(
sentence_words
)
has_duty_marker = any(
re.search(
pattern,
sentence_text,
)
for pattern in duty_evidence_patterns
)
if not has_duty_marker:
continue
subject_hit = any(
(
token in sentence_words
or (
len(token) >= 5
and any(
word.startswith(token[:5])
for word in sentence_words
)
)
)
for token in subject_tokens
)
if not subject_hit:
continue
if any(
marker in sentence_text
for marker in (
"belediye encumeni",
"belediye meclisi",
"belediye baskani",
)
):
continue
# Bir kurumun organini tanimlayan cumle,
# kurumun kendi gorevlerini aciklayan evidence
# olarak kullanilamaz.
#
# Ornek:
# "Belediyenin danisma ve yurutme gorevleri
# bulunan organidir."
#
# Bu, belediyenin gorevlerini degil bir belediye
# organinin niteligini anlatir.
if (
"organidir" in sentence_text
or "organdir" in sentence_text
):
continue
subject_linked = True
break
if not subject_linked:
return False, "DUTY_SUBJECT_EVIDENCE_MISSING"
# --------------------------------------------------
# DEFINITION EVIDENCE GATE
# --------------------------------------------------
strong_definition_intent = (
"ne demektir" in q_text
or "ne anlama gelir" in q_text
or "anlami nedir" in q_text
)
semantic_nedir_intent = (
q_text.endswith(" nedir")
and any(
token in q_words
for token in (
"anlam",
"anlamli",
"sozcuk",
"dusunce",
"kavram",
"terim",
)
)
)
definition_intent = (
strong_definition_intent
or semantic_nedir_intent
)
if definition_intent:
definition_stop_words = {
"ne",
"nedir",
"demektir",
"anlama",
"gelir",
"anlami",
"paragrafta",
"paragraf",
"bir",
"bu",
}
concept_tokens = [
token
for token in q_words
if (
len(token) > 2
and token
not in definition_stop_words
)
]
raw_sentences = re.split(
r"(?<=[.!?])\s+|\n+",
context,
)
definition_patterns = (
r"\bdenir\b",
r"\bifade\s+eder\b",
r"\banlamina\s+gelir\b",
r"\banlamindadir\b",
r"\bolarak\s+tanimlanir\b",
r"\btanimlanir\b",
r"\bkabul\s+edilir\b",
)
definition_found = False
for raw_sentence in raw_sentences:
sentence_words = (
_normalize_answerability_text(
raw_sentence
)
)
if not sentence_words:
continue
sentence_text = " ".join(
sentence_words
)
def token_supported(token: str) -> bool:
if token in sentence_words:
return True
if len(token) >= 5:
prefix = token[:5]
return any(
len(candidate) >= 5
and candidate.startswith(prefix)
for candidate in sentence_words
)
return False
concept_hits = sum(
1
for token in concept_tokens
if token_supported(token)
)
if not concept_tokens:
continue
required_hits = (
len(concept_tokens)
if len(concept_tokens) <= 3
else max(
2,
int(
len(concept_tokens)
* 0.75
),
)
)
if concept_hits < required_hits:
continue
if any(
re.search(
pattern,
sentence_text,
)
for pattern
in definition_patterns
):
definition_found = True
break
if not definition_found:
return (
False,
"DEFINITION_EVIDENCE_MISSING",
)
# Zaman soruları
time_intent = any(
token in q_text
for token in (
"ne zaman",
"hangi yil",
"hangi tarihte",
"kac yil",
)
)
if time_intent:
if not re.search(r"\b(1[0-9]{3}|20[0-9]{2})\b", c_text):
return False, "TIME_EVIDENCE_MISSING"
# Neden / sebep soruları
reason_intent = any(
token in q_text
for token in (
"neden",
"nicin",
"sebebi",
"sebep",
)
)
if reason_intent:
reason_markers = (
"cunku",
"nedeni",
"sebebi",
"sonuc",
"dolayi",
"amac",
)
if not any(marker in c_text for marker in reason_markers):
return False, "REASON_EVIDENCE_MISSING"
return True, "OK"
def rebuild_retriever(reset_collection: bool = True):
global documents, chunks, retriever
loader = DocumentLoader(docs_dir=str(DOCS_DIR))
documents = loader.load_documents()
for education_subdir in ("reading", "quiz", "exam"):
education_loader = DocumentLoader(
docs_dir=str(EDUCATION_DOCS_DIR / education_subdir)
)
documents += education_loader.load_documents()
chunker = TextChunker(chunk_size=600, overlap=100)
chunks = chunker.chunk_documents(documents)
retriever = ChromaRetriever(