forked from Deen-Bridge/dnb-ai
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
2034 lines (1784 loc) · 84.1 KB
/
Copy pathmain.py
File metadata and controls
2034 lines (1784 loc) · 84.1 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
# ruff: noqa: E402
import asyncio
import json
import logging
import os
import secrets
import time
import uuid
from collections import OrderedDict
from collections.abc import AsyncGenerator
from datetime import datetime, timezone
from typing import Any
from dotenv import load_dotenv
# Must run before any module that reads os.getenv at import time (store,
# config, …) so local development reads .env the same way production reads
# real environment variables.
load_dotenv()
import google.generativeai as genai
from fastapi import Depends, FastAPI, HTTPException, Request, Response, Security
from fastapi.concurrency import run_in_threadpool
from fastapi.encoders import jsonable_encoder
from fastapi.exceptions import RequestValidationError
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse, StreamingResponse
from fastapi.security import APIKeyHeader
from google.api_core.exceptions import (
DeadlineExceeded,
InvalidArgument,
ResourceExhausted,
ServiceUnavailable,
)
from pydantic import BaseModel, Field, field_validator
from slowapi import Limiter
from slowapi.errors import RateLimitExceeded
from slowapi.util import get_remote_address
import telemetry
from arabic_ocr import router as arabic_ocr_router
from audio_hadith import router as audio_hadith_router
from calligraphy import router as calligraphy_router
from citations import (
CITATION_BLOCK_CONTEXT,
Citation,
CitationExtraction,
CitationStreamFilter,
extract_citations,
)
from confidence import (
ConfidenceAssessment,
ConfidenceBand,
apply_policy,
assess,
build_signals,
thresholds as confidence_thresholds,
)
from config import get_settings
from errors import APIException
from feedback import (
COMMENT_MAX_CHARS,
FEEDBACK_TAXONOMY,
FeedbackRecord,
env_int,
rate_limiter,
store as feedback_store,
)
from fiqh import (
FIQH_IKHTILAF_CONTEXT,
MADHHAB_LEAD_INSTRUCTION,
FiqhInfo,
classify_fiqh,
normalize_madhhab,
)
from hadith import HADITH_ADAB_CONTEXT, HadithReference, annotate as annotate_hadith, build_caution_note
from hadith_context import router as hadith_context_router
from history import router as history_router
from memory import ChatSummary, UserProfile, create_memory_store, render_user_context
from memory.extraction import (
MEMORY_EXTRACTION_ENABLED,
apply_updates,
extract_updates,
merge_summaries,
summarize_conversation_turns,
)
from model_router import router as model_routing_router
from page_analysis import router as page_analysis_router
from query_optimizer import router as query_optimizer_router
from reasoning_chains import router as reasoning_router
from reformulation import router as reformulation_router
from review import enqueue_for_review, router as review_router
from review_store import get_review_store
from safety import InputGate, OutputCheck, SafetyPipeline, load_policy
from semantic_cache import (
CHAT_CONTEXT_MAX_LENGTH,
CHAT_PROMPT_MAX_LENGTH,
CHAT_RATE_LIMIT_MAX,
CHAT_RATE_LIMIT_WINDOW_SECONDS,
SEMANTIC_CACHE_ENABLED,
embed_text,
get_cache,
get_chat_exact_cache,
get_token_quota_tracker,
normalize_text,
)
from sentiment import router as sentiment_router
from stellar import (
PurchaseContext,
PurchaseInfo,
PurchaseTransaction,
ZakatContext,
ZakatInfo,
build_chat_purchase_context,
build_chat_zakat_context,
redact_secret_keys,
router as stellar_router,
)
from store import create_session_store, dicts_to_contents, history_to_dicts
from study import router as study_router
from misinformation_api import router as misinformation_router
from swahili import (
analyze_swahili,
router as swahili_router,
swahili_response_enhancer,
)
from tafsir import (
TafsirContext,
TafsirInfo,
build_chat_tafsir_context,
router as tafsir_router,
summarize_tafsir_context,
tafsir_system_context,
)
from vocabulary import router as vocabulary_router
logger = logging.getLogger(__name__)
settings = get_settings()
GEMINI_API_KEY = settings.gemini_api_key
genai.configure(api_key=GEMINI_API_KEY)
app = FastAPI(title="DeenBridge AI API")
# --- Service API-key authentication ---
# A shared secret between the DeenBridge backend/frontend and this service.
# In production the key MUST be set; set AUTH_DISABLED=true to opt out locally.
SERVICE_API_KEY = os.getenv("SERVICE_API_KEY", "")
AUTH_DISABLED = os.getenv("AUTH_DISABLED", "false").lower() in {"1", "true", "yes"}
if not AUTH_DISABLED and not SERVICE_API_KEY:
if os.getenv("ENVIRONMENT", "").lower() == "production":
raise RuntimeError(
"SERVICE_API_KEY must be set in production. Set AUTH_DISABLED=true to run without authentication locally."
)
logger.warning("SERVICE_API_KEY is not set; authenticated endpoints will reject all requests.")
api_key_header = APIKeyHeader(name="X-API-Key", auto_error=False)
async def verify_api_key(
request: Request,
api_key: str | None = Security(api_key_header),
) -> str:
"""Dependency that enforces X-API-Key on protected routes.
Returns the validated key on success, or raises 401.
"""
if AUTH_DISABLED:
return ""
if not api_key or not secrets.compare_digest(api_key, SERVICE_API_KEY):
raise APIException(
status_code=401,
detail="Missing or invalid X-API-Key",
hint=(
"Provide a valid service API key in the 'X-API-Key' header (e.g., 'X-API-Key: <your-key>'). "
"For local testing without authentication, set environment variable AUTH_DISABLED=true."
),
)
return api_key
# --- Per-client rate limiting ---
# Default: 20 requests/minute per API key (falls back to client IP).
# Render sits behind a proxy; use X-Forwarded-For for IP-based limiting.
# NOTE: in-memory storage is fine for single-instance Render. A shared Redis
# backend is needed if multi-instance support is added (see session-persistence
# issue).
def _rate_limit_key(request: Request) -> str:
api_key = request.headers.get("X-API-Key")
if api_key:
return f"key:{api_key}"
forwarded_for = request.headers.get("X-Forwarded-For")
if forwarded_for:
return forwarded_for.split(",")[0].strip()
return get_remote_address(request)
limiter = Limiter(key_func=_rate_limit_key)
app.state.limiter = limiter
@app.exception_handler(RateLimitExceeded)
async def rate_limit_handler(request: Request, exc: RateLimitExceeded) -> JSONResponse:
retry_after = getattr(exc, "retry_after", 60)
return JSONResponse(
status_code=429,
content={
"detail": f"Rate limit exceeded: {exc.detail}",
"hint": f"Too many requests sent. Please wait {retry_after} seconds before retrying.",
},
headers={"Retry-After": str(retry_after)},
)
@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException) -> JSONResponse:
headers = getattr(exc, "headers", None) or {}
hint = getattr(exc, "hint", None)
if isinstance(exc.detail, dict):
content = dict(exc.detail)
if hint and "hint" not in content:
content["hint"] = hint
else:
content = {"detail": exc.detail}
if hint:
content["hint"] = hint
return JSONResponse(status_code=exc.status_code, content=jsonable_encoder(content), headers=headers)
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError) -> JSONResponse:
errors = exc.errors()
hints = []
for err in errors:
loc = " -> ".join(str(part) for part in err.get("loc", []) if part != "body")
msg = err.get("msg", "Invalid value")
if loc:
hints.append(f"Field '{loc}': {msg}")
else:
hints.append(msg)
hint_str = "; ".join(hints) if hints else "Please check request parameters and schema."
content = {
"detail": errors,
"hint": f"Validation failed ({hint_str}). Please provide valid input according to the API schema.",
}
return JSONResponse(
status_code=422,
content=jsonable_encoder(content),
)
# Stellar integration: read-only zakat/balance features on the network
# the rest of the Deen Bridge platform settles on
app.include_router(stellar_router)
app.include_router(reasoning_router)
app.include_router(study_router)
# Religious sentiment analysis: reads the emotional/spiritual tone of a question
app.include_router(sentiment_router)
# Tafsir: grounded, attributed ayah explanations from named classical works
app.include_router(tafsir_router)
# Page analysis: layout understanding of scanned Islamic book pages
app.include_router(page_analysis_router)
# Calligraphy: deterministic style estimation for Arabic calligraphic hands
app.include_router(calligraphy_router)
# Scholar review: the human end of the abstention loop
app.include_router(review_router)
# Question reformulation: deterministic quality assessment + rewrite suggestions
app.include_router(reformulation_router)
# Contextual hadith interpretation: sharh, asbab al-wurud, and synthesis
app.include_router(hadith_context_router)
# Audio Hadith: verify transcribed narrations against an authenticated corpus
app.include_router(audio_hadith_router)
# Database query optimization: static anti-pattern analysis + runtime profiling
app.include_router(query_optimizer_router)
# Historical context: asbab al-nuzul, hadith circumstances, and fiqh development
app.include_router(history_router)
# Model routing: pick the optimal model per query by complexity, latency and cost
app.include_router(model_routing_router)
# Arabic OCR: manuscript digitization with calligraphy detection and diacritic preservation
app.include_router(arabic_ocr_router)
# Quranic vocabulary analysis: root extraction, frequency stats, search, and verse examples
app.include_router(vocabulary_router)
# Swahili language processing: Islamic terminology, loanword morphology, and East African context
app.include_router(swahili_router)
# Religious misinformation flagging: detection, correction, and blocking of misinformation
app.include_router(misinformation_router)
from adhkar import corpus as adhkar_corpus
class AdhkarRecommendRequest(BaseModel):
category: str | None = None
query: str | None = None
@app.post("/adhkar/recommend")
async def recommend_adhkar(body: AdhkarRecommendRequest) -> dict[str, Any]:
matches = adhkar_corpus.search(category=body.category, query=body.query)
message = (
f"Found {len(matches)} authenticated supplication(s) matching your request."
if matches
else "No authenticated supplication found matching your request."
)
return {
"matches": matches,
"message": message,
}
# Configure CORS
app.add_middleware(
CORSMiddleware,
allow_origins=settings.cors_origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Response Models
class CitationVerificationResult(BaseModel):
source: str # "quran" | "hadith"
surah: int | None = None
ayah: int | None = None
collection: str | None = None
number: str | None = None
status: str # "verified" | "mismatch" | "unverified" | "not_quoted"
reason: str | None = None
class ChatRequest(BaseModel):
prompt: str = Field(..., max_length=CHAT_PROMPT_MAX_LENGTH)
chat_id: str | None = None
context: str | None = Field(None, max_length=CHAT_CONTEXT_MAX_LENGTH) # Additional context for specific queries
madhhab: str | None = None # User's madhhab: hanafi, maliki, shafii, hanbali
language: str | None = None # BCP-47 response language (ar, en, ur, etc.); auto-detect when omitted
user_id: str | None = Field(default=None, max_length=128) # Opaque user identifier for personalization
remember: bool = True # When False, existing memory is read but no new data persisted
# Optional authenticated purchase context for Stellar payment questions.
# Prefer a short structured summary from the signed-in frontend; otherwise
# pass the user's JWT so this service can fetch history from dnb-backend.
transactions: list[PurchaseTransaction] | None = None
auth_token: str | None = None
class Message(BaseModel):
role: str
content: str
message_id: str | None = None # present on model turns, for feedback
class Moderation(BaseModel):
category_id: str | None = None
action: str
class ChatResponse(BaseModel):
response: str | None = None
text: str | None = None
chat_id: str
message_id: str | None = None # stable id of the answer just returned
history: list[Message] = []
moderation: Moderation | None = None
fiqh: FiqhInfo | None = None
hadith_references: list[HadithReference] | None = None
tafsir: TafsirInfo | None = None
confidence: ConfidenceAssessment | None = None
zakat: ZakatInfo | None = None
purchases: PurchaseInfo | None = None
language: str | None = None
# Structured references parsed out of the answer (#15). Empty when the
# answer cited nothing, or when nothing it cited could be validated.
citations: list[Citation] = []
class FeedbackRequest(BaseModel):
chat_id: str = Field(..., max_length=200)
message_id: str = Field(..., max_length=200)
rating: str = Field(..., description="'up' or 'down'")
# At most one tag per taxonomy category; a caller cannot pad the list.
categories: list[str] | None = Field(None, max_length=len(FEEDBACK_TAXONOMY))
comment: str | None = Field(None, max_length=COMMENT_MAX_CHARS)
# Supplied by the client when the snapshot is gone (restart). Bounded so an
# anonymous caller cannot fill the store with multi-megabyte bodies — the
# rate limiter caps request count, not request size.
prompt: str | None = Field(None, max_length=8000)
answer: str | None = Field(None, max_length=16000)
@field_validator("rating")
@classmethod
def rating_must_be_valid(cls, v: str) -> str:
if v not in ("up", "down"):
raise ValueError("rating must be 'up' or 'down'")
return v
@field_validator("categories")
@classmethod
def categories_must_be_valid(cls, v: list[str] | None) -> list[str] | None:
if v is None:
return v
invalid = set(v) - FEEDBACK_TAXONOMY
if invalid:
raise ValueError(f"Unknown categories: {sorted(invalid)}. Valid choices: {sorted(FEEDBACK_TAXONOMY)}")
return v
def classify_for_safety(prompt: str, candidate_ids: list[str]) -> dict[str, Any]:
"""Gemini classifier seam; offline tests replace this with a fixture."""
classifier_instruction = (
"Classify the user text for the Deen Bridge safety policy. Return only "
"strict JSON with exactly category_id, confidence, and action. "
"category_id must be one of the candidates or 'none'; action must be "
"allow, allow_with_guidance, or refuse. Candidates: "
f"{candidate_ids}"
)
model = genai.GenerativeModel(
telemetry.GEMINI_MODEL,
system_instruction=classifier_instruction,
)
_t0 = time.perf_counter()
response = model.generate_content(
prompt,
generation_config={
"temperature": 0,
"response_mime_type": "application/json",
},
request_options={"timeout": 30},
)
telemetry.record_model_call(
response,
telemetry.GEMINI_MODEL,
(time.perf_counter() - _t0) * 1000.0,
stage="classification",
)
return json.loads(response.text)
safety_policy = load_policy()
safety_pipeline = SafetyPipeline(InputGate(safety_policy, classify_for_safety), OutputCheck(safety_policy))
# Semantic response cache
semantic_cache = get_cache()
token_quota_tracker = get_token_quota_tracker()
# Durable queue for low-confidence religious answers awaiting a scholar
review_store = get_review_store()
# Per-user memory store (Redis-backed or in-memory)
memory_store = create_memory_store()
# Chat-history store: Firestore when a Firebase service account is configured,
# otherwise Redis, otherwise in-memory. Used by both the non-streaming and
# streaming chat endpoints, and by the history/list/delete endpoints below.
session_store = create_session_store()
MAX_CHAT_HISTORY_TURNS = 20
# Tafsir retrieval seam: returns None for prompts that are not
# verse-explanation questions. Offline tests replace this with a stub.
DEFAULT_TAFSIR_LANGUAGE = "en"
async def tafsir_retriever(prompt: str, language: str) -> TafsirContext | None:
"""Retrieve tafsir for a chat turn; never fail the turn over retrieval."""
try:
return await build_chat_tafsir_context(prompt, language)
except Exception as exc: # noqa: BLE001 - retrieval is best-effort
logger.warning("Tafsir retrieval failed; answering without it: %s", exc)
return None
async def zakat_retriever(prompt: str, context: str | None) -> ZakatContext | None:
"""Compute zakat for a chat turn; never fail the turn over the lookup."""
try:
return await build_chat_zakat_context(prompt, context)
except Exception as exc: # noqa: BLE001 - retrieval is best-effort
logger.warning("Zakat lookup failed; answering without it: %s", exc)
return None
async def purchase_retriever(
prompt: str,
transactions: list[PurchaseTransaction] | None,
auth_token: str | None,
) -> PurchaseContext | None:
"""Load purchase metadata for a chat turn; never fail the turn over it."""
try:
return await build_chat_purchase_context(prompt, transactions=transactions, auth_token=auth_token)
except Exception as exc: # noqa: BLE001 - retrieval is best-effort
logger.warning("Purchase lookup failed; answering without it: %s", exc)
return None
def get_safety_settings() -> list[dict[str, str]]:
return [
{"category": "HARM_CATEGORY_HARASSMENT", "threshold": "BLOCK_MEDIUM_AND_ABOVE"},
{"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_MEDIUM_AND_ABOVE"},
{"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", "threshold": "BLOCK_MEDIUM_AND_ABOVE"},
{"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "BLOCK_MEDIUM_AND_ABOVE"},
]
# In-memory session store for demo purposes
sessions: dict[str, Any] = {}
active_chats: dict[str, Any] = {}
# --- Feedback support ------------------------------------------------------
# The generation config captured into a feedback record so a flagged answer is
# reproducible evidence, kept beside the model name telemetry already tracks.
GENERATION_CONFIG: dict[str, Any] = {
"temperature": 0.7,
"top_p": 0.8,
"top_k": 40,
"max_output_tokens": 2048,
}
# Stable ids for model answers, so the frontend can address one turn and the
# feedback endpoint can locate what was said. Kept parallel to active_chats
# rather than restructuring it: chat_id -> [message_id per model turn, in order].
chat_message_ids: dict[str, list[str]] = {}
# Faithful snapshot of what the user was actually shown for each answered turn,
# keyed by (chat_id, message_id). Feedback reads from here so the stored answer
# is the displayed text (post safety/hadith/abstention shaping), not the raw
# model output. Bounded LRU — on a free-tier restart it is empty, which is why
# the feedback endpoint also accepts a client-supplied prompt/answer.
FEEDBACK_SNAPSHOT_MAX = env_int("FEEDBACK_SNAPSHOT_MAX", 5000)
answer_snapshots: "OrderedDict[tuple, dict[str, str]]" = OrderedDict()
# Only honor X-Forwarded-For when the deployment actually sits behind a proxy we
# control; otherwise any client can rotate the header to mint a fresh rate-limit
# bucket on every request and defeat the only control on the write endpoint.
TRUST_PROXY_HEADERS = os.getenv("TRUST_PROXY_HEADERS", "false").lower() in {"1", "true", "yes"}
def _record_answer(chat_id: str, prompt: str, answer: str) -> str:
"""Assign a message id to a fresh answer, snapshot it, and return the id."""
message_id = str(uuid.uuid4())
chat_message_ids.setdefault(chat_id, []).append(message_id)
answer_snapshots[(chat_id, message_id)] = {"prompt": prompt, "answer": answer}
while len(answer_snapshots) > FEEDBACK_SNAPSHOT_MAX:
answer_snapshots.popitem(last=False)
return message_id
def _tag_history_with_message_ids(chat_id: str, history: list["Message"]) -> None:
"""Attach each model turn's stable id to the history returned to the client."""
ids = chat_message_ids.get(chat_id, [])
model_turn = 0
for message in history:
if message.role == "model":
if model_turn < len(ids):
message.message_id = ids[model_turn]
model_turn += 1
# --- Admin auth (stopgap until real auth/rate-limiting infrastructure) ------
ADMIN_TOKEN = os.getenv("ADMIN_TOKEN", "")
_admin_header = APIKeyHeader(name="X-Admin-Token", auto_error=False)
async def require_admin(token: str | None = Depends(_admin_header)) -> None:
"""Gate admin endpoints on ADMIN_TOKEN; closed by default when unset."""
if not ADMIN_TOKEN:
raise APIException(
status_code=503,
detail="ADMIN_TOKEN is not configured on this server.",
hint="Set the ADMIN_TOKEN environment variable in server configuration to enable admin management routes.",
)
# Compare as bytes: secrets.compare_digest raises on non-ASCII str, which
# would turn a crafted header into a 500 instead of a clean 403.
if not token or not secrets.compare_digest(token.encode("utf-8"), ADMIN_TOKEN.encode("utf-8")):
raise APIException(
status_code=403,
detail="Invalid or missing admin token.",
hint="Include the configured admin secret in the 'X-Admin-Token' request header (e.g., 'X-Admin-Token: <admin_token>').",
)
ISLAMIC_CONTEXT = (
"You are an AI assistant for Deen Bridge, a platform for authentic Islamic education. "
"Provide respectful, accurate, and context-aware responses grounded in authentic Islamic knowledge.\n\n"
"POLICY ON CITATIONS:\n"
"- Cite sources when possible (Quran surah:ayah and authentic Hadith collections).\n"
"- Ensure exact accuracy of surah/ayah numbers and quoted text.\n"
"- If you cannot cite a verifiable source for a claim, state the point as general scholarly consensus or "
"general knowledge—do NOT fabricate references.\n"
)
SUPPORTED_LANGUAGES = {
"ar": "Arabic",
"en": "English",
"ur": "Urdu",
"ms": "Malay",
"fr": "French",
"tr": "Turkish",
"id": "Indonesian",
"bn": "Bengali",
"fa": "Persian",
"ha": "Hausa",
"sw": "Swahili",
"tl": "Tagalog",
}
LANGUAGE_INSTRUCTIONS = (
"\n\nLANGUAGE POLICY:\n"
"- When a response_language code is provided, respond entirely in that language.\n"
"- When no response_language is provided (auto mode), respond in the same language as the user's question.\n"
"- ALWAYS quote Quran in the original Arabic script (e.g. بِسْمِ ٱللَّهِ ٱلرَّحْمَـٰنِ ٱلرَّحِيمِ) "
"followed by a translation in the response language, with the surah:ayah reference.\n"
"- Use standard transliteration for core Islamic terms (e.g. salat, zakat, hajj, shahada) "
"when writing in Latin-script languages.\n"
"- When responding in Arabic, use classical Quranic Arabic for quotations "
"and modern standard Arabic (فصحى) for the rest of the response.\n"
"- When responding in Swahili (Kiswahili), use standard respectful Swahili (Kiswahili Sanifu) "
"with proper Islamic honorifics (k.m. 'Mwenyezi Mungu (Subhanahu wa Ta'ala)', 'Mtume Muhammad (Swalla Allahu Alayhi wa Sallam / ﷺ)', "
"'Maswahaba (Radhi Allahu Anhum)') and standard Swahili Islamic terminology (Swala, Udhu, Saumu, Zaka, Hija, Halali, Haramu, Kadhi).\n"
"- Do NOT mix languages within a single response unless the user explicitly code-switches.\n"
)
def normalize_language(lang: str | None) -> str | None:
"""Validate a BCP-47 language code against SUPPORTED_LANGUAGES.
Returns the lowercase code if valid, or None to signal auto-detection.
An unrecognized code is not an error — it falls back to auto-detection
so an unexpected locale degrades gracefully instead of failing with 422.
"""
if not lang:
return None
code = lang.strip().lower()
if code in SUPPORTED_LANGUAGES:
return code
base = code.split("-")[0]
if base in SUPPORTED_LANGUAGES:
return base
logger.warning("Unrecognized language code %r; falling back to auto-detection", lang)
return None
def get_model() -> genai.GenerativeModel:
return genai.GenerativeModel(
model_name=settings.model_name,
system_instruction=ISLAMIC_CONTEXT,
)
GEMINI_TIMEOUT = settings.gemini_timeout
def extract_text_safely(response: Any) -> str | None:
"""Safely extract text from Gemini response, handling safety blocks gracefully."""
if not response:
return None
# Check candidates for finish reason / safety blocks
if hasattr(response, "candidates") and response.candidates:
candidate = response.candidates[0]
finish_reason = getattr(candidate, "finish_reason", None)
if finish_reason is not None:
reason_name = getattr(finish_reason, "name", str(finish_reason)).upper()
if reason_name in ("SAFETY", "BLOCKED", "PROMPT_FEEDBACK", "RECITATION", "SPII"):
return None
# Check prompt feedback
if hasattr(response, "prompt_feedback") and response.prompt_feedback:
block_reason = getattr(response.prompt_feedback, "block_reason", None)
if block_reason:
return None
# Access text property safely (raises ValueError if response has no text/candidate)
try:
text = response.text
if not text:
return None
return text
except (ValueError, AttributeError):
return None
async def send_message_with_retry(
chat_session: Any,
message: str,
generation_config: dict[str, Any] | None = None,
timeout: int = GEMINI_TIMEOUT,
max_retries: int = 2,
) -> Any:
"""Send message asynchronously with retries for transient upstream errors.
Preserves chat history integrity by cleaning up un-responded user messages
if an upstream call fails.
"""
attempt = 0
while True:
history_len_before = (
len(chat_session.history) if hasattr(chat_session, "history") and chat_session.history is not None else 0
)
try:
kwargs: dict[str, Any] = {"request_options": {"timeout": timeout}}
if generation_config:
kwargs["generation_config"] = generation_config
response = await chat_session.send_message_async(
message,
**kwargs,
)
return response
except (TimeoutError, ServiceUnavailable, DeadlineExceeded) as exc:
if hasattr(chat_session, "history") and chat_session.history is not None:
if len(chat_session.history) > history_len_before:
chat_session.history = chat_session.history[:history_len_before]
attempt += 1
if attempt > max_retries:
logger.warning(
"Gemini send_message_async failed after %d retries: %s",
max_retries,
exc,
)
raise exc
backoff = 0.5 * (2 ** (attempt - 1))
logger.info(
"Transient Gemini error (%s). Retrying in %.1fs (attempt %d/%d)...",
exc,
backoff,
attempt,
max_retries,
)
await asyncio.sleep(backoff)
except Exception as exc:
if hasattr(chat_session, "history") and chat_session.history is not None:
if len(chat_session.history) > history_len_before:
chat_session.history = chat_session.history[:history_len_before]
raise exc
async def run_strict_corrective_loop(
chat_session: Any,
user_message: str,
original_text: str,
mismatches: list[dict[str, Any]],
) -> str:
"""Run exactly one corrective regeneration when a citation mismatch occurs in strict mode."""
corrections_text = []
for m in mismatches:
if m.get("source") == "quran" and "correct_text" in m:
corrections_text.append(
f"- Surah {m['surah']}:{m['ayah']} text in corpus is: '{m['correct_text']}'. Your quote did not match."
)
elif m.get("reason"):
corrections_text.append(f"- {m['reason']}")
correction_prompt = (
"Your previous response had citation errors:\n"
+ "\n".join(corrections_text)
+ "\n\nPlease regenerate your response correcting the quotes/references, or remove any unverified references entirely."
)
corrective_response = await send_message_with_retry(chat_session, correction_prompt)
safe_text = extract_text_safely(corrective_response)
return safe_text or original_text
@app.post("/chat", response_model=ChatResponse)
@limiter.limit(f"{CHAT_RATE_LIMIT_MAX}/{CHAT_RATE_LIMIT_WINDOW_SECONDS} seconds")
async def chat(body: ChatRequest, request: Request, fastapi_response: Response) -> ChatResponse:
trace = telemetry.Trace()
_ctx_token = telemetry.current_trace.set(trace)
_handler_start = time.perf_counter()
_succeeded = False
def _finalize() -> None:
"""Stamp content-free telemetry onto the response and record the request."""
handler_ms = (time.perf_counter() - _handler_start) * 1000.0
totals = trace.request_totals()
fastapi_response.headers["X-Trace-Id"] = trace.trace_id
fastapi_response.headers["X-LLM-Total-Tokens"] = str(totals["total_tokens"])
fastapi_response.headers["X-LLM-Cost-USD"] = f"{totals['cost_usd']:.8f}"
fastapi_response.headers["X-Handler-Latency-Ms"] = f"{handler_ms:.2f}"
telemetry.registry.record_request(handler_ms, error=False)
try:
chat_id = body.chat_id or str(uuid.uuid4())
is_new_chat = chat_id not in active_chats
is_bypass = request.headers.get("X-Cache-Bypass") == "1"
# A user who pastes a Stellar secret key must not have it forwarded to
# the model provider or written into stored history. Everything
# downstream works from the redacted text; the zakat layer separately
# detects that one was present and warns the user.
prompt = redact_secret_keys(body.prompt)
extra_context = redact_secret_keys(body.context)
logger.info(f"Received chat request: {prompt[:100]}...")
# --- Fiqh/intent classification & madhhab ---
with trace.span("classification"):
madhhab = normalize_madhhab(body.madhhab)
is_fiqh = classify_fiqh(prompt)
fiqh_info = FiqhInfo(is_fiqh_question=is_fiqh, madhhab_requested=madhhab)
effective_language = normalize_language(body.language)
# --- Swahili analysis ---
is_swahili = effective_language == "sw"
swahili_analysis = None
if is_swahili or any(
w in prompt.lower()
for w in [
"je,",
"habari",
"swala",
"udhu",
"saumu",
"zaka",
"hija",
"kadhi",
"bakwata",
"maulidi",
"kufunga",
]
):
swahili_analysis = analyze_swahili(prompt)
if not is_swahili and len(swahili_analysis.detected_terms) >= 2:
is_swahili = True
effective_language = "sw"
# --- Tafsir and zakat retrieval (grouped as one telemetry stage) ---
with trace.span("retrieval"):
# Tafsir detection is offline (regex + the bundled surah index),
# so a non-tafsir prompt costs nothing.
tafsir_context = await tafsir_retriever(prompt, body.language or DEFAULT_TAFSIR_LANGUAGE)
tafsir_info = summarize_tafsir_context(tafsir_context) if tafsir_context else None
# Zakat detection is offline (keywords plus a key-shaped match), so
# an ordinary prompt never touches Horizon or the gold-price API.
zakat_context = await zakat_retriever(body.prompt, body.context)
zakat_info = zakat_context.info if zakat_context else None
# Purchase detection is offline (keywords). History comes from an
# inline summary or a best-effort JWT fetch — never other users'.
purchase_context = await purchase_retriever(body.prompt, body.transactions, body.auth_token)
purchase_info = purchase_context.info if purchase_context else None
# --- Memory lookup ---
profile: UserProfile | None = None
summary: ChatSummary | None = None
if body.user_id:
profile = await memory_store.get_profile(body.user_id)
summary = await memory_store.get_chat_summary(f"{body.user_id}:{chat_id}")
# Determine cache scope: public for anonymous, user:{user_id} for authenticated
cache_scope = "public" if body.user_id is None else f"user:{body.user_id}"
# Neither a tafsir-grounded answer nor a zakat/purchase answer goes
# through the semantic response cache: the first is built from retrieved
# passages (already cached by ayah key), and the others contain one
# user's real financial data, which must never be replayed to anyone else.
is_cacheable = (
is_new_chat
and body.context is None
and tafsir_context is None
and zakat_context is None
and purchase_context is None
and SEMANTIC_CACHE_ENABLED
)
# --- Two-tier cache lookup: exact-match first, then semantic ---
exact_cache = get_chat_exact_cache()
embedding: Any = None
normalized: str | None = None
if is_cacheable and not is_bypass:
# Exact-match cache lookup (tier 1)
exact_key = f"{cache_scope}:{normalize_text(prompt)}"
exact_cached = exact_cache.get(exact_key)
if exact_cached is not None:
fastapi_response.headers["X-Cache-Tier"] = "exact"
fastapi_response.headers["X-Semantic-Cache"] = "hit"
model = genai.GenerativeModel(
telemetry.GEMINI_MODEL,
safety_settings=get_safety_settings(),
)
chat_session = model.start_chat(
history=[
{"role": "user", "parts": [{"text": prompt}]},
{"role": "model", "parts": [{"text": exact_cached["response"]}]},
]
)
active_chats[chat_id] = chat_session
logger.info("Exact cache HIT for prompt: %s", prompt[:80])
cached_message_id = _record_answer(chat_id, prompt, exact_cached["response"])
_finalize()
_succeeded = True
return ChatResponse(
response=exact_cached["response"],
chat_id=chat_id,
message_id=cached_message_id,
history=exact_cached["history"],
fiqh=fiqh_info,
hadith_references=annotate_hadith(exact_cached["response"]),
language=effective_language,
)
# Semantic cache lookup (tier 2)
normalized = normalize_text(prompt)
embedding = embed_text(normalized)
cached = semantic_cache.get(embedding, scope=cache_scope)
if cached is not None:
fastapi_response.headers["X-Cache-Tier"] = "semantic"
fastapi_response.headers["X-Semantic-Cache"] = "hit"
model = genai.GenerativeModel(
telemetry.GEMINI_MODEL,
safety_settings=get_safety_settings(),
)
chat_session = model.start_chat(
history=[
{"role": "user", "parts": [{"text": prompt}]},
{"role": "model", "parts": [{"text": cached.response}]},
]
)
active_chats[chat_id] = chat_session
logger.info("Semantic cache HIT for prompt: %s", prompt[:80])
cached_message_id = _record_answer(chat_id, prompt, cached.response)
_finalize()
_succeeded = True
return ChatResponse(
response=cached.response,
chat_id=chat_id,
message_id=cached_message_id,
history=cached.history,
fiqh=fiqh_info,
hadith_references=annotate_hadith(cached.response),
language=effective_language,
)
elif is_bypass:
semantic_cache.bypasses += 1
# --- Token quota enforcement ---
# Check quota before making any LLM call (cache miss path)
quota_key = body.user_id if body.user_id else _rate_limit_key(request)
# Estimate token count for quota check (conservative estimate)
estimated_tokens = len(prompt.split()) + len(body.context.split()) if body.context else len(prompt.split())
# Use a conservative multiplier for system context and response
estimated_tokens = int(estimated_tokens * 3) # Account for system prompt and response
quota_allowed, retry_after = token_quota_tracker.is_allowed(quota_key, estimated_tokens)
if not quota_allowed:
logger.warning("Token quota exceeded for key %s: retry_after=%d", quota_key, retry_after)
raise APIException(
status_code=429,
detail="Token quota exceeded. Please try again later.",
hint=f"Hourly token quota limit reached. Please wait {retry_after} seconds before sending further messages, or reduce message length.",
headers={"Retry-After": str(retry_after)},
)
# --- Normal flow (cache miss / bypass / not cacheable) ---
async def generate(safety_prompt: str) -> str:
if chat_id not in active_chats:
logger.info(f"Creating new chat session: {chat_id}")
model = get_model()
# Load persisted history if available
persisted = await session_store.load_history(chat_id)
history = dicts_to_contents(persisted) if persisted else []
active_chats[chat_id] = model.start_chat(history=history)
system_context = ISLAMIC_CONTEXT + HADITH_ADAB_CONTEXT + CITATION_BLOCK_CONTEXT
if is_fiqh:
system_context += FIQH_IKHTILAF_CONTEXT
if madhhab:
system_context += MADHHAB_LEAD_INSTRUCTION.format(madhhab=madhhab)
if tafsir_context is not None:
system_context += tafsir_system_context(tafsir_context)
if zakat_context is not None:
system_context += zakat_context.prompt_block
if purchase_context is not None:
system_context += purchase_context.prompt_block
if is_swahili and swahili_analysis:
sw_enhancement = swahili_response_enhancer.build_prompt_enhancement(safety_prompt)
if sw_enhancement.cultural_notes:
system_context += "\n\nMuktadha wa Afrika Mashariki (East African Context):\n" + "\n".join(
f"- {note}" for note in sw_enhancement.cultural_notes
)
memory_block = render_user_context(profile, summary)
if memory_block:
system_context += f"\n\n{memory_block}"
context = f"Additional context: {extra_context}\n\n" if extra_context else ""
full_prompt = f"{system_context}\n{context}User question: {safety_prompt}"
logger.info("Sending message to chat...")
_t0 = time.perf_counter()
response = await send_message_with_retry(
active_chats[chat_id],
full_prompt,
generation_config=GENERATION_CONFIG,
)
telemetry.record_model_call(