-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
2696 lines (2445 loc) · 131 KB
/
main.py
File metadata and controls
2696 lines (2445 loc) · 131 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
"""
╔══════════════════════════════════════════════════════════════════════╗
║ ADVANCED MATHEMATICS ASSISTANT — main.py ║
║ All 7 pipeline steps in one file ║
║ ║
║ USAGE: ║
║ python3.11 -m streamlit run main.py → Launch UI ║
║ python3.11 main.py --setup → Build knowledge base ║
║ python3.11 main.py --test → Run all tests ║
║ python3.11 main.py --eval → Evaluate RAG pipeline ║
║ python3.11 main.py --rebuild → Force rebuild KB ║
╚══════════════════════════════════════════════════════════════════════╝
"""
import os, re, sys, json, time, uuid, hashlib, logging, argparse, unittest, ast, tempfile
from datetime import datetime, timezone
from pathlib import Path
from typing import List, Dict, Any, Optional, Tuple
from knowledge_base import MATH_KNOWLEDGE_BASE, CLASS_EXAMPLES
from dotenv import load_dotenv
# Load .env locally — works regardless of launch directory
load_dotenv(dotenv_path=Path(__file__).parent / ".env", override=True)
# Streamlit Cloud: load secrets into environment variables
try:
import streamlit as st
for _k, _v in st.secrets.items():
if _k not in os.environ:
os.environ[_k] = str(_v)
except Exception:
pass # Not running on Streamlit Cloud or secrets not configured
logging.basicConfig(level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s")
logger = logging.getLogger("math_assistant")
GROQ_API_KEY = os.getenv("GROQ_API_KEY", "")
# llama-3.3-70b-versatile: powerful but low RPM on Groq free tier (30 RPM)
# llama3-8b-8192: higher RPM limit (30 RPM but faster + less likely to hit TPM limits)
# mixtral-8x7b-32768: good balance — use this if hitting rate limits
LLM_MODEL = os.getenv("LLM_MODEL", "llama-3.3-70b-versatile")
EMBEDDING_MODEL = os.getenv("EMBEDDING_MODEL", "sentence-transformers/all-MiniLM-L6-v2")
VECTOR_DB_TYPE = os.getenv("VECTOR_DB_TYPE", "chroma").lower()
CHROMA_PERSIST_DIR = os.getenv("CHROMA_PERSIST_DIR", "./chroma_db")
FAISS_INDEX_PATH = os.getenv("FAISS_INDEX_PATH", "./faiss_index")
TOP_K_RESULTS = int(os.getenv("TOP_K_RESULTS", "5"))
CHUNK_SIZE = int(os.getenv("CHUNK_SIZE", "1000"))
CHUNK_OVERLAP = int(os.getenv("CHUNK_OVERLAP", "200"))
MONGODB_URI = os.getenv("MONGODB_URI", "")
MONGODB_DB_NAME = os.getenv("MONGODB_DB_NAME", "math_assistant")
MONGODB_COLLECTION = os.getenv("MONGODB_COLLECTION", "chat_history")
COLLECTION_NAME = "math_knowledge_base"
try:
from langchain_core.documents import Document
except ImportError:
try:
from langchain.schema import Document
except ImportError:
class Document:
def __init__(self, page_content: str, metadata: dict = None):
self.page_content = page_content
self.metadata = metadata or {}
try:
from langchain_core.messages import HumanMessage, AIMessage
except ImportError:
from langchain.schema import HumanMessage, AIMessage
try:
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
except ImportError:
from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder
# ╔══════════════════════════════════════════════════════════════════════╗
# ║ STEP 1 — DATA SOURCES ║
# ╚══════════════════════════════════════════════════════════════════════╝
class MathDataLoader:
def __init__(self):
self.documents = []
def load_builtin_knowledge(self):
logger.info(f"Loading {len(MATH_KNOWLEDGE_BASE)} built-in knowledge documents")
return list(MATH_KNOWLEDGE_BASE)
def load_pdf(self, pdf_path: str):
try:
from langchain_community.document_loaders import PyPDFLoader
docs = PyPDFLoader(pdf_path).load()
logger.info(f"Loaded {len(docs)} pages from: {pdf_path}")
return docs
except Exception as e:
logger.error(f"Failed to load PDF {pdf_path}: {e}")
return []
def load_pdfs_from_directory(self, dir_path: str):
try:
from langchain_community.document_loaders import DirectoryLoader, PyPDFLoader
docs = DirectoryLoader(dir_path, glob="**/*.pdf", loader_cls=PyPDFLoader).load()
logger.info(f"Loaded {len(docs)} documents from: {dir_path}")
return docs
except Exception as e:
logger.error(f"Failed to load PDFs from {dir_path}: {e}")
return []
def load_web_pages(self, urls: List[str]):
from langchain_community.document_loaders import WebBaseLoader
import socket
docs = []
for url in urls:
try:
loader = WebBaseLoader(url)
loader.requests_kwargs = {"timeout": 15}
docs.extend(loader.load())
logger.info(f"Loaded: {url}")
except Exception as e:
logger.warning(f"Failed URL {url}: {e}")
return docs
def load_text_file(self, file_path: str):
try:
if file_path.endswith(".md"):
from langchain_community.document_loaders import UnstructuredMarkdownLoader
loader = UnstructuredMarkdownLoader(file_path)
else:
from langchain_community.document_loaders import TextLoader
loader = TextLoader(file_path, encoding="utf-8")
docs = loader.load()
logger.info(f"Loaded: {file_path}")
return docs
except Exception as e:
logger.error(f"Failed to load {file_path}: {e}")
return []
def load_all(self, pdf_paths=None, urls=None, text_paths=None, pdf_directory=None):
all_docs = self.load_builtin_knowledge()
if pdf_paths:
for p in pdf_paths: all_docs.extend(self.load_pdf(p))
if pdf_directory and os.path.exists(pdf_directory):
all_docs.extend(self.load_pdfs_from_directory(pdf_directory))
if urls:
all_docs.extend(self.load_web_pages(urls))
if text_paths:
for p in text_paths: all_docs.extend(self.load_text_file(p))
logger.info(f"Total documents loaded: {len(all_docs)}")
self.documents = all_docs
return all_docs
# ╔══════════════════════════════════════════════════════════════════════╗
# ║ STEP 2 — DATA PREPROCESSING ║
# ╚══════════════════════════════════════════════════════════════════════╝
class MathDataPreprocessor:
TOPIC_KEYWORDS: Dict[str, List[str]] = {
"calculus": ["derivative", "integral", "differentiate", "integrate", "limit", "continuity", "taylor"],
"linear_algebra": ["matrix", "vector", "eigenvalue", "determinant", "rank", "span", "basis"],
"statistics": ["probability", "distribution", "mean", "variance", "regression", "hypothesis"],
"algebra": ["polynomial", "equation", "quadratic", "factor", "root", "logarithm", "exponent"],
"trigonometry": ["sine", "cosine", "tangent", "angle", "radian", "unit circle", "trig"],
"discrete_math": ["graph", "combinatorics", "permutation", "combination", "modular", "prime"],
"geometry": ["triangle", "circle", "area", "volume", "perimeter", "pythagorean", "coordinate"],
"number_theory": ["prime", "divisor", "gcd", "lcm", "modular", "congruence", "integer"],
}
def __init__(self):
self._seen_hashes: set = set()
def _clean(self, text: str) -> str:
text = re.sub(r"\n{3,}", "\n\n", text)
text = re.sub(r"[ \t]{2,}", " ", text)
text = re.sub(r"Page\s+\d+\s+of\s+\d+", "", text, flags=re.IGNORECASE)
text = re.sub(r"https?://\S+", "[URL]", text)
text = re.sub(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]", "", text)
replacements = {
"\u2019": "'", "\u201c": '"', "\u201d": '"',
"\u2013": "-", "\u2014": "--", "\u00a0": " ",
"\u03c0": "pi", "\u221e": "infinity",
"\u2264": "<=", "\u2265": ">="
}
for old, new in replacements.items():
text = text.replace(old, new)
return text.strip()
def _detect_topic(self, text: str) -> str:
tl = text.lower()
scores = {t: sum(1 for kw in kws if kw in tl) for t, kws in self.TOPIC_KEYWORDS.items()}
scores = {k: v for k, v in scores.items() if v > 0}
return max(scores, key=scores.get) if scores else "general_math"
def _difficulty(self, text: str) -> str:
adv = ["eigenvalue", "differential equation", "fourier", "laplace", "manifold", "tensor"]
mid = ["derivative", "integral", "matrix", "probability", "polynomial", "logarithm"]
tl = text.lower()
if sum(1 for t in adv if t in tl) >= 2: return "advanced"
if sum(1 for t in mid if t in tl) >= 2: return "intermediate"
return "beginner"
def preprocess_document(self, doc):
text = doc.page_content
if len(text.strip()) < 50:
return None
text = self._clean(text)
h = hashlib.md5(text.strip().lower().encode()).hexdigest()
if h in self._seen_hashes:
return None
self._seen_hashes.add(h)
meta = doc.metadata.copy()
meta.update({
"topic": meta.get("topic") or self._detect_topic(text),
"difficulty": self._difficulty(text),
"char_count": len(text),
"word_count": len(text.split()),
"content_hash": h,
})
return Document(page_content=text, metadata=meta)
def preprocess_documents(self, documents):
logger.info(f"Preprocessing {len(documents)} documents...")
self._seen_hashes.clear()
processed = [r for doc in documents if (r := self.preprocess_document(doc)) is not None]
logger.info(f"Done: {len(processed)} kept, {len(documents)-len(processed)} skipped")
return processed
# ╔══════════════════════════════════════════════════════════════════════╗
# ║ STEP 3 — SPLITTING AND CHUNKING ║
# ╚══════════════════════════════════════════════════════════════════════╝
class MathTextSplitter:
def __init__(self, chunk_size: int = CHUNK_SIZE, chunk_overlap: int = CHUNK_OVERLAP):
from langchain_text_splitters import RecursiveCharacterTextSplitter, MarkdownHeaderTextSplitter
self.chunk_size = chunk_size
self.chunk_overlap = chunk_overlap
self.recursive = RecursiveCharacterTextSplitter(
chunk_size=chunk_size, chunk_overlap=chunk_overlap,
separators=["\n\n", "\n", ". ", "! ", "? ", "; ", ": ", " ", ""])
self.markdown_splitter = MarkdownHeaderTextSplitter(
headers_to_split_on=[("#", "H1"), ("##", "H2"), ("###", "H3")])
def split_document(self, doc):
source = doc.metadata.get("source", "").lower()
if source.endswith(".md") or "markdown" in source:
try:
splits = self.markdown_splitter.split_text(doc.page_content)
chunks = [Document(page_content=s.page_content,
metadata={**doc.metadata, **s.metadata}) for s in splits]
except Exception:
chunks = self.recursive.split_documents([doc])
else:
chunks = self.recursive.split_documents([doc])
for i, chunk in enumerate(chunks):
chunk.metadata.update({
"chunk_index": i,
"total_chunks": len(chunks),
"chunk_size": len(chunk.page_content),
})
return chunks
def split_documents(self, documents):
logger.info(f"Splitting {len(documents)} documents...")
all_chunks = []
for doc in documents:
all_chunks.extend(self.split_document(doc))
logger.info(f"Created {len(all_chunks)} chunks")
return all_chunks
# ╔══════════════════════════════════════════════════════════════════════╗
# ║ STEP 4 — EMBEDDINGS, VECTOR DB & KNOWLEDGE BASE ║
# ╚══════════════════════════════════════════════════════════════════════╝
_EMBEDDINGS_CACHE = {}
def get_embeddings():
if "model" not in _EMBEDDINGS_CACHE:
from langchain_huggingface import HuggingFaceEmbeddings
logger.info(f"Loading embedding model: {EMBEDDING_MODEL}")
_EMBEDDINGS_CACHE["model"] = HuggingFaceEmbeddings(
model_name=EMBEDDING_MODEL,
model_kwargs={"device": "cpu"},
encode_kwargs={"normalize_embeddings": True})
return _EMBEDDINGS_CACHE["model"]
class MathVectorStore:
def __init__(self):
self.embeddings = get_embeddings()
self.vectorstore = None
self.db_type = VECTOR_DB_TYPE
self._load_existing()
def _load_existing(self):
if self.db_type == "chroma":
self._try_chroma()
else:
self._try_faiss()
def _try_chroma(self, documents=None):
try:
from langchain_community.vectorstores import Chroma
persist_path = Path(CHROMA_PERSIST_DIR)
persist_path.mkdir(parents=True, exist_ok=True)
if documents:
self.vectorstore = Chroma.from_documents(
documents=documents, embedding=self.embeddings,
collection_name=COLLECTION_NAME,
persist_directory=str(persist_path))
logger.info("ChromaDB created.")
elif list(persist_path.glob("*.sqlite3")):
self.vectorstore = Chroma(
collection_name=COLLECTION_NAME,
embedding_function=self.embeddings,
persist_directory=str(persist_path))
logger.info(f"ChromaDB loaded ({self.vectorstore._collection.count()} docs)")
except Exception as e:
logger.warning(f"ChromaDB failed ({type(e).__name__}: {e}), switching to FAISS")
self.db_type = "faiss"
if documents:
self._try_faiss(documents)
def _try_faiss(self, documents=None):
try:
from langchain_community.vectorstores import FAISS
index_path = Path(FAISS_INDEX_PATH)
if documents:
self.vectorstore = FAISS.from_documents(documents, self.embeddings)
index_path.mkdir(parents=True, exist_ok=True)
self.vectorstore.save_local(str(index_path))
logger.info(f"FAISS saved to {index_path}")
elif index_path.exists() and any(index_path.iterdir()):
self.vectorstore = FAISS.load_local(
str(index_path), self.embeddings,
allow_dangerous_deserialization=True)
logger.info("FAISS loaded.")
except Exception as e:
logger.error(f"FAISS failed: {e}")
def build_knowledge_base(self, documents):
logger.info(f"Building knowledge base with {len(documents)} chunks...")
if self.db_type == "chroma":
self._try_chroma(documents)
else:
self._try_faiss(documents)
logger.info("Knowledge base ready.")
def add_documents(self, documents):
if self.vectorstore is None:
self.build_knowledge_base(documents)
else:
self.vectorstore.add_documents(documents)
def similarity_search(self, query: str, k: int = TOP_K_RESULTS, filter_topic: str = None):
if self.vectorstore is None:
return []
try:
if filter_topic and self.db_type == "chroma":
return self.vectorstore.similarity_search(query, k=k, filter={"topic": filter_topic})
return self.vectorstore.similarity_search(query, k=k)
except Exception as e:
logger.error(f"Search failed: {e}")
return []
def as_retriever(self, k: int = TOP_K_RESULTS):
return self.vectorstore.as_retriever(search_kwargs={"k": k}) if self.vectorstore else None
def get_document_count(self) -> int:
if self.vectorstore is None:
return 0
try:
return (self.vectorstore._collection.count() if self.db_type == "chroma"
else self.vectorstore.index.ntotal)
except Exception as e:
logger.error(f"get_document_count failed: {e}")
return 0
def is_ready(self) -> bool:
return self.vectorstore is not None and self.get_document_count() > 0
_PIPELINE_CACHE = {}
def build_pipeline(pdf_paths=None, urls=None, text_paths=None, force_rebuild=False) -> MathVectorStore:
"""Cached — runs once per process. Embedding model + KB build only happens on cold start."""
if "store" in _PIPELINE_CACHE and not force_rebuild:
return _PIPELINE_CACHE["store"]
store = MathVectorStore()
if store.is_ready() and not force_rebuild:
logger.info(f"Knowledge base already built ({store.get_document_count()} docs).")
_PIPELINE_CACHE["store"] = store
return store
raw_docs = MathDataLoader().load_all(pdf_paths=pdf_paths or [], urls=urls or [], text_paths=text_paths or [])
clean_docs = MathDataPreprocessor().preprocess_documents(raw_docs)
chunks = MathTextSplitter().split_documents(clean_docs)
store.build_knowledge_base(chunks)
_PIPELINE_CACHE["store"] = store
return store
# ╔══════════════════════════════════════════════════════════════════════╗
# ║ STEP 5 — QUERY PROCESSING & AI ENGINE ║
# ╚══════════════════════════════════════════════════════════════════════╝
SYSTEM_TEMPLATE = """You are an Indian mathematics teacher writing on a whiteboard.
⚠️ NON-MATH QUESTIONS:
If NOT about mathematics → reply ONLY: "❌ I only teach math! Ask me any math problem."
Stop immediately. Nothing else.
════════════════════════════════════════
THE GOLDEN RULE — READ THIS FIRST:
════════════════════════════════════════
NEVER write paragraphs. NEVER write long sentences explaining theory.
Write SHORT lines. Like a teacher writing on a board.
Every line = one idea. One calculation. One small result.
If a student can't follow in 5 seconds → you wrote too much.
WRONG (too much theory, paragraph style):
"The Commutative Property of Addition states that when we add numbers,
the order does not matter. This means that 3+4 gives the same result
as 4+3, which we can verify by counting on a number line..."
RIGHT (whiteboard style):
Step 1 — Check: does order matter in addition?
3 + 4 = 7
4 + 3 = 7 ← same answer!
✓ Yes — order doesn't matter. This is called Commutative Property.
════════════════════════════════════════
FORMAT — FOLLOW EXACTLY EVERY TIME:
════════════════════════════════════════
[One short opening — max 1 line. Like reading the problem aloud.]
"Okay, quadratic equation. Let's use the formula."
"Right — we need HCF of two numbers."
"Alright, let's integrate this step by step."
━━━━━━━━━━━━━━━━━━━━━━━━━━━
Question: [restate question clearly]
━━━━━━━━━━━━━━━━━━━━━━━━━━━
Step 1 — [title: what and why, max 1 line]
[calculation line 1]
[calculation line 2]
[short teacher note if needed — max 1 line]
Step 2 — [title]
[calculation]
[result]
[only as many steps as needed — no fake steps]
━━━━━━━━━━━━━━━━━━━━━━━━━━━
✅ Answer: [final answer]
━━━━━━━━━━━━━━━━━━━━━━━━━━━
[One closing line max — "Key thing: watch the sign here!" or "Make sense?"]
════════════════════════════════════════
INSIDE EACH STEP — RULES:
════════════════════════════════════════
✅ DO write like this:
a = 2, b = 5, c = -3
b² - 4ac = 25 - 4(2)(-3) = 25 + 24 = 49 ← careful: minus×minus = plus!
√49 = 7 ← clean number, good sign!
x = (-5 ± 7) / 4
✅ DO add ONE short teacher reaction inline:
"← careful here" "← minus × minus = plus!" "← nice, simplifies!"
"← most students miss this" "← remember this!"
❌ NEVER write:
- Paragraphs or long sentences
- Theory blocks explaining what a property IS
- Repeated explanations of the same idea
- More than 1 line of teacher commentary per step
- Sentences like "In this case, we can see that..." or "This demonstrates..."
- Definitions ("The quadratic formula is used when...")
- History or background ("This property was discovered...")
════════════════════════════════════════
DETECT LEVEL — CHANGE DEPTH NOT STYLE:
════════════════════════════════════════
Class 1–5:
→ Ultra simple. Real objects. ("3 apples + 4 apples = 7 apples")
→ No jargon. Max 3 steps.
→ Lots of ✓ and encouragement inline.
Class 6–8:
→ Short friendly lines. Explain WHY in 3-4 words inline.
→ "← because negative × negative = positive"
Class 9–10:
→ Full working, every line shown.
→ One inline note on common exam mistake.
→ "← board exams always ask this"
Class 11–12:
→ State theorem/formula name once, then just use it.
→ Show every substitution clearly.
JEE Advanced:
→ Full clean solution first.
→ Then add:
💡 Key Insight: [one line — the clever observation]
⏱️ Exam Tip: [one line — what to write quickly]
════════════════════════════════════════
SYMBOLS — STRICT:
════════════════════════════════════════
→ NEVER LaTeX or $. Unicode only.
→ √ not sqrt(). x² not x^2. π not pi. ± not +/-
→ Fractions: (a+b)/(c+d)
→ Hindi/Hinglish question → answer in same language
Context from knowledge base:
{context}
"""
class MongoDBChatMemory:
def __init__(self, session_id: str = "default"):
self.session_id = session_id
self.collection = None
self._memory: List[Dict] = []
self._connect()
def _connect(self):
if not MONGODB_URI:
return
try:
from pymongo import MongoClient
client = MongoClient(MONGODB_URI, serverSelectionTimeoutMS=5000)
client.admin.command("ping")
self.collection = client[MONGODB_DB_NAME][MONGODB_COLLECTION]
logger.info("MongoDB connected")
except Exception as e:
logger.warning(f"MongoDB unavailable ({e}), using in-memory history")
def add_message(self, role: str, content: str):
msg = {"session_id": self.session_id, "role": role,
"content": content, "timestamp": datetime.now(timezone.utc)}
if self.collection is not None:
try:
self.collection.insert_one(msg)
return
except Exception:
pass
self._memory.append(msg)
def get_history(self, limit: int = 20) -> List[Dict]:
if self.collection is not None:
try:
msgs = list(self.collection.find(
{"session_id": self.session_id}).sort("timestamp", -1).limit(limit))
msgs.reverse()
return msgs
except Exception:
pass
return self._memory[-limit:]
def get_langchain_messages(self, limit: int = 10):
history = self.get_history(limit)
result = []
for msg in history:
if msg["role"] == "human":
result.append(HumanMessage(content=msg["content"]))
elif msg["role"] == "assistant":
result.append(AIMessage(content=msg["content"]))
return result
def clear_history(self):
if self.collection is not None:
try:
self.collection.delete_many({"session_id": self.session_id})
except Exception:
pass
self._memory.clear()
class SymbolicMathEngine:
@staticmethod
def differentiate(expression: str, variable: str = "x") -> Optional[str]:
try:
import sympy as sp
var = sp.Symbol(variable)
expr = sp.sympify(re.sub(r'\^', '**', expression.strip()))
return f"d/d{variable}[{expression}] = {sp.simplify(sp.diff(expr, var))}"
except Exception:
return None
@staticmethod
def integrate(expression: str, variable: str = "x") -> Optional[str]:
try:
import sympy as sp
var = sp.Symbol(variable)
expr = sp.sympify(re.sub(r'\^', '**', expression.strip()))
return f"integral({expression}) d{variable} = {sp.integrate(expr, var)} + C"
except Exception:
return None
@staticmethod
def solve_equation(equation: str, variable: str = "x") -> Optional[str]:
try:
import sympy as sp
var = sp.Symbol(variable)
eq_str = re.sub(r'\^', '**', equation.strip())
if "=" in eq_str:
lhs, rhs = eq_str.split("=", 1)
eq = sp.Eq(sp.sympify(lhs), sp.sympify(rhs))
else:
eq = sp.sympify(eq_str)
return f"Solutions for {variable}: {sp.solve(eq, var)}"
except Exception:
return None
@staticmethod
def try_solve(expression: str) -> Optional[str]:
try:
import sympy as sp
x, y, z, t = sp.symbols('x y z t')
expr_str = re.sub(r'\^', '**', expression.strip())
result = sp.simplify(sp.sympify(expr_str, locals={
'x': x, 'y': y, 'z': z, 't': t,
'sin': sp.sin, 'cos': sp.cos, 'exp': sp.exp,
'log': sp.log, 'sqrt': sp.sqrt, 'pi': sp.pi}))
return str(result)
except Exception:
return None
@staticmethod
def matrix_operations(matrix_str: str) -> Optional[Dict[str, Any]]:
try:
import sympy as sp
M = sp.Matrix(ast.literal_eval(matrix_str))
return {"determinant": str(M.det()), "rank": M.rank(),
"eigenvalues": str(M.eigenvals()), "trace": str(M.trace())}
except Exception:
return None
_LLM_CACHE = {}
# Fallback model order — if primary hits daily token limit, auto-switch
GROQ_MODEL_FALLBACKS = [
os.getenv("LLM_MODEL", "llama-3.3-70b-versatile"),
"llama3-8b-8192",
"mixtral-8x7b-32768",
]
def _get_llm(model=None):
key = model or GROQ_MODEL_FALLBACKS[0]
if key not in _LLM_CACHE:
from langchain_groq import ChatGroq
api_key = os.getenv("GROQ_API_KEY", "") or GROQ_API_KEY
if not api_key:
raise ValueError("GROQ_API_KEY not set. Add it to your .env file.")
logger.info(f"Initializing Groq LLM: {key}")
_LLM_CACHE[key] = ChatGroq(groq_api_key=api_key, model_name=key,
temperature=0.1, max_tokens=2048)
return _LLM_CACHE[key]
class MathAIEngine:
def __init__(self, vector_store: MathVectorStore = None, session_id: str = "default"):
self.llm = self._init_llm()
self.vector_store = vector_store
self.memory = MongoDBChatMemory(session_id=session_id)
self.symbolic = SymbolicMathEngine()
self.session_id = session_id
def _init_llm(self):
# Eagerly init the primary model; fallbacks are created on demand
return _get_llm(GROQ_MODEL_FALLBACKS[0])
def _retrieve_context(self, query: str) -> Tuple[list, str]:
if not self.vector_store or not self.vector_store.is_ready():
return [], "No knowledge base available. Using general mathematical knowledge."
docs = self.vector_store.similarity_search(query, k=3)
if not docs:
return [], "No specific context found."
parts = [f"[Reference {i+1} - {d.metadata.get('topic','math')}]\n{d.page_content}"
for i, d in enumerate(docs)]
return docs, "\n\n---\n\n".join(parts)
def _symbolic_hint(self, query: str) -> Optional[str]:
ql = query.lower()
for pattern, action in [
(r"(?:differentiate|derivative of|d/dx)\s+(.+?)(?:\s+with respect|\s*$)", "diff"),
(r"(?:integrate|integral of)\s+(.+?)(?:\s+with respect|\s+dx|\s*$)", "int"),
(r"solve\s+(.+?)\s+(?:for|=)", "solve"),
]:
m = re.search(pattern, ql)
if m:
expr = m.group(1).strip()
result = (self.symbolic.differentiate(expr) if action == "diff"
else self.symbolic.integrate(expr) if action == "int"
else self.symbolic.solve_equation(expr))
if result:
return f"[Symbolic verification: {result}]"
return None
def query(self, user_input: str) -> Dict[str, Any]:
hint = self._symbolic_hint(user_input)
source_docs, context = self._retrieve_context(user_input)
chat_history = self.memory.get_langchain_messages(limit=4)
# Build the messages list manually — NEVER pass math content through
# LangChain format_messages(), because curly braces in math (e.g. {x|x>0},
# set notation, matrices) are treated as template variables and crash with
# a KeyError, silently swallowed → user sees no answer at all.
system_text = SYSTEM_TEMPLATE.replace("{context}", context)
llm_messages = []
# System message — use LangChain tuple form which bypasses brace parsing
from langchain_core.messages import SystemMessage
llm_messages.append(SystemMessage(content=system_text))
# Inject chat history
for msg in chat_history:
llm_messages.append(msg)
# Current user question
llm_messages.append(HumanMessage(content=user_input))
# Store human message BEFORE LLM call so history order is correct
self.memory.add_message("human", user_input)
# Auto-retry with model fallback — if daily limit hit, switch to next model
answer = None
last_error = None
used_models = []
for model_name in GROQ_MODEL_FALLBACKS:
if model_name in used_models:
continue
used_models.append(model_name)
llm = _get_llm(model_name)
for _attempt in range(2): # 2 attempts per model
try:
raw = llm.invoke(llm_messages).content
if raw and not any(p in raw.lower() for p in
["rate limit", "too many requests", "service unavailable"]):
answer = raw
if model_name != GROQ_MODEL_FALLBACKS[0]:
answer = f"*(Using fallback model: {model_name})*\n\n" + answer
break
else:
raise Exception(raw or "Empty response")
except Exception as e:
last_error = e
err = str(e).lower()
full_err = str(e)
logger.warning(f"Model {model_name} attempt {_attempt+1} failed: {e}")
if "per day" in full_err or "tokens per day" in full_err:
# Daily limit — skip to next model immediately
logger.info(f"Daily limit on {model_name}, trying next model...")
break
elif "429" in full_err or "rate_limit" in err:
time.sleep(2 ** _attempt)
continue
elif "timeout" in err or "connect" in err or "503" in err:
time.sleep(1)
continue
else:
break # non-retryable
if answer:
break
if answer is None:
full_err = str(last_error)
err = full_err.lower()
logger.error(f"LLM failed: [{type(last_error).__name__}] {full_err}")
if "401" in full_err or "invalid_api_key" in err:
answer = "⚠️ Invalid API key. Check GROQ_API_KEY in your .env file."
elif "429" in full_err or "rate_limit_exceeded" in err:
# Extract the retry time from Groq's message if present
import re as _re
retry_match = _re.search(r'try again in (.+?)\.', full_err)
retry_info = f" Groq says: try again in **{retry_match.group(1)}**." if retry_match else ""
# Check if it is TPD (daily) or TPM (per minute)
if "per day" in full_err or "tokens per day" in full_err or "TPD" in full_err:
answer = f"⚠️ **Daily token limit reached** (Groq free tier: 100,000 tokens/day).{retry_info}\n\nTo keep using the app now, change your `.env`:\n```\nLLM_MODEL=llama3-8b-8192\n```\nThen restart Streamlit. The 8B model has a separate 500k/day quota."
else:
answer = f"⚠️ **Rate limit hit** (too many requests per minute).{retry_info} Wait 20–30 seconds and try again."
elif "context_length" in err or ("context" in err and "length" in err):
answer = "⚠️ Question + context too long. Try a shorter question."
elif "connect" in err or "connection" in err:
answer = "⚠️ Cannot reach Groq API. Check your internet connection."
elif "timeout" in err:
answer = "⚠️ Request timed out. Try again."
else:
answer = f"⚠️ Error ({type(last_error).__name__}): {full_err}"
self.memory.add_message("assistant", answer)
sources = [{"topic": d.metadata.get("topic", "unknown"),
"source": d.metadata.get("source", "kb"),
"difficulty": d.metadata.get("difficulty", "unknown")}
for d in source_docs]
return {"answer": answer, "sources": sources, "symbolic_hint": hint,
"session_id": self.session_id, "context_docs": len(source_docs)}
def clear_memory(self):
self.memory.clear_history()
def get_history(self):
return self.memory.get_history(limit=50)
# ╔══════════════════════════════════════════════════════════════════════╗
# ║ OCR / IMAGE SCAN HELPER ║
# ╚══════════════════════════════════════════════════════════════════════╝
def ocr_extract_text(image) -> str:
try:
from PIL import Image
import PIL.ImageEnhance as enhance
import pytesseract
# Set tesseract binary path for common install locations
for _tess_path in [
"/opt/homebrew/bin/tesseract", # macOS Apple Silicon (brew)
"/usr/local/bin/tesseract", # macOS Intel (brew)
"/usr/bin/tesseract", # Linux
]:
if os.path.exists(_tess_path):
pytesseract.pytesseract.tesseract_cmd = _tess_path
break
gray = image.convert("L")
contrast = enhance.Contrast(gray).enhance(2.0)
sharpened = enhance.Sharpness(contrast).enhance(2.0)
text = pytesseract.image_to_string(sharpened, config='--psm 6').strip()
text = ' '.join(text.replace('\n', ' ').split())
return text
except ImportError:
return "ERROR_NO_PYTESSERACT"
except Exception as e:
logger.error(f"OCR error: {e}")
return ""
# ╔══════════════════════════════════════════════════════════════════════╗
# ║ STEP 6 — STREAMLIT UI ║
# ╚══════════════════════════════════════════════════════════════════════╝
def render_graph(expression: str, x_range: tuple = (-10, 10), title: str = ""):
import streamlit as st
try:
import numpy as np
import plotly.graph_objects as go
_dark = st.session_state.get("theme", "dark") == "dark"
_bg = "#0d1220" if _dark else "#ffffff"
_paper = "#080c14" if _dark else "#f8fafc"
_grid = "#1e293b" if _dark else "#e2e8f0"
_text = "#94a3b8" if _dark else "#475569"
_colors = ["#4f8ef7", "#4ecca3", "#f5c842", "#ff6b6b", "#c792ea"]
x = np.linspace(x_range[0], x_range[1], 1000)
ns = {
"__builtins__": {},
"x": x, "np": np,
"sin": np.sin, "cos": np.cos, "tan": np.tan,
"exp": np.exp, "log": np.log, "sqrt": np.sqrt,
"abs": np.abs, "pi": np.pi, "e": np.e,
"arcsin": np.arcsin, "arccos": np.arccos, "arctan": np.arctan,
"sinh": np.sinh, "cosh": np.cosh, "tanh": np.tanh,
}
fig = go.Figure()
plotted = 0
for idx, expr in enumerate(expression.split(",")[:5]):
expr = expr.strip()
try:
y = eval(re.sub(r'\^', '**', expr), ns)
y = np.where(np.abs(y) > 1e10, np.nan, y)
fig.add_trace(go.Scatter(
x=x, y=y,
mode="lines",
name=f"y = {expr}",
line=dict(color=_colors[idx % len(_colors)], width=2.5),
hovertemplate=f"y = {expr}<br>x = %{{x:.3f}}<br>y = %{{y:.3f}}<extra></extra>",
))
plotted += 1
except Exception:
st.warning(f"Could not plot: {expr}")
if plotted == 0:
return
fig.update_layout(
title=dict(text=title, font=dict(color=_text, size=14)) if title else None,
paper_bgcolor=_paper,
plot_bgcolor=_bg,
font=dict(color=_text, family="DM Sans"),
xaxis=dict(
showgrid=True, gridcolor=_grid, gridwidth=0.5,
zeroline=True, zerolinecolor=_text, zerolinewidth=1,
tickfont=dict(color=_text), title="x",
showspikes=True, spikecolor=_text, spikethickness=1,
),
yaxis=dict(
showgrid=True, gridcolor=_grid, gridwidth=0.5,
zeroline=True, zerolinecolor=_text, zerolinewidth=1,
tickfont=dict(color=_text), title="y",
showspikes=True, spikecolor=_text, spikethickness=1,
),
legend=dict(
bgcolor=_bg, bordercolor=_grid, borderwidth=1,
font=dict(color=_text),
),
hovermode="x unified",
margin=dict(l=50, r=20, t=40 if title else 20, b=50),
height=420,
)
st.plotly_chart(fig, use_container_width=True)
except Exception as e:
st.error(f"Graph error: {e}")
def run_streamlit_app():
import streamlit as st
st.set_page_config(page_title="Advanced Mathematics Assistant",
page_icon="∫", layout="wide")
# ── Theme: dark (default) or light ────────────────────────────────
if "theme" not in st.session_state:
st.session_state.theme = "dark"
dark = st.session_state.theme == "dark"
theme_vars = """
:root {
--bg: #080c14;
--bg2: #0d1220;
--card: #111827;
--card2: #161f30;
--blue: #3b82f6;
--blue2: #60a5fa;
--cyan: #22d3ee;
--green: #10b981;
--gold: #f59e0b;
--purple: #8b5cf6;
--tx: #f1f5f9;
--tx2: #94a3b8;
--tx3: #475569;
--border: #1e293b;
--border2: #243044;
--glow: rgba(59,130,246,0.15);
}""" if dark else """
:root {
--bg: #f8fafc;
--bg2: #f1f5f9;
--card: #ffffff;
--card2: #f8fafc;
--blue: #2563eb;
--blue2: #1d4ed8;
--cyan: #0891b2;
--green: #059669;
--gold: #d97706;
--purple: #7c3aed;
--tx: #0f172a;
--tx2: #475569;
--tx3: #94a3b8;
--border: #e2e8f0;
--border2: #cbd5e1;
--glow: rgba(37,99,235,0.1);
}"""
st.markdown(f"""
<style>
@import url('https://fonts.googleapis.com/css2?family=Syne:wght@400;600;700;800&family=DM+Mono:wght@400;500&family=DM+Sans:wght@300;400;500;600&display=swap');
{theme_vars}
/* ── Base ── */
.stApp {{ background-color: var(--bg) !important; color: var(--tx) !important; font-family: 'DM Sans', sans-serif; }}
.main .block-container {{ padding-top: 1.5rem !important; max-width: 900px; }}
section[data-testid="stSidebar"] {{ background: var(--bg2) !important; border-right: 1px solid var(--border) !important; }}
section[data-testid="stSidebar"] .block-container {{ padding-top: 1.5rem !important; }}
/* ── Light mode global text fixes ── */
.stMarkdown p, .stMarkdown li, .stMarkdown span,
.stMarkdown strong, .stMarkdown em,
[data-testid="stMarkdownContainer"] p,
[data-testid="stMarkdownContainer"] li,
[data-testid="stMarkdownContainer"] span,
[data-testid="stMarkdownContainer"] strong,
[data-testid="stMarkdownContainer"] em {{
color: var(--tx) !important;
}}
/* ── Hero Header ── */
.hero-wrap {{
text-align: center;
padding: 2.5rem 1rem 1.5rem;
position: relative;
}}