File size: 10,129 Bytes
c75184e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
075ecd2
c75184e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bf47217
c75184e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a1fc38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c75184e
 
 
 
 
 
 
 
 
 
 
8a1fc38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c75184e
 
 
 
 
d056dcd
 
4f811d2
 
c75184e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Application configuration β€” Pydantic Settings loaded from environment variables.

All configuration values are centralized here. Modules import from this file
instead of reading os.environ directly. This is the single source of truth
for all runtime configuration across the backend.
"""

import os
from pathlib import Path
from typing import List
from pydantic_settings import BaseSettings, SettingsConfigDict

# Ensure .env is loaded for local development
from dotenv import load_dotenv
load_dotenv(dotenv_path=Path(__file__).resolve().parent.parent / ".env", override=True)


class Settings(BaseSettings):
    """Application settings loaded from environment variables and .env file."""

    model_config = SettingsConfigDict(
        env_file=".env",
        env_file_encoding="utf-8",
        extra="ignore",
    )

    # ── LLM Configuration ──────────────────────────────────────────────
    groq_api_key: str = ""
    llm_model: str = "llama-3.3-70b-versatile"
    groq_model_fallbacks: List[str] = [
        "llama-3.3-70b-versatile",
        "llama3-8b-8192",
        "mixtral-8x7b-32768",
    ]

    # ── Gemini Configuration ───────────────────────────────────────────
    gemini_api_key: str = ""
    use_gemini: bool = True  # Feature flag: True = Gemini primary, False = Groq
    gemini_primary_model: str = "gemini-2.0-flash"
    gemini_fallback_model: str = "gemini-flash-latest"
    gemini_vision_model: str = "gemini-2.0-flash"
    gemini_temperature: float = 0.1
    gemini_max_tokens: int = 2048

    # ── Embeddings ─────────────────────────────────────────────────────
    embedding_model: str = "sentence-transformers/all-MiniLM-L6-v2"

    # ── Vector Database ────────────────────────────────────────────────
    vector_db_type: str = "chroma"
    chroma_persist_dir: str = "./chroma_db"
    faiss_index_path: str = "./faiss_index"
    top_k_results: int = 5
    chunk_size: int = 1000
    chunk_overlap: int = 200
    collection_name: str = "math_knowledge_base"

    # ── Firebase ───────────────────────────────────────────────────────
    use_firebase: bool = True
    firebase_credentials_path: str = ""

    # ── ADK Multi-Agent ────────────────────────────────────────────────
    use_adk: bool = True

    # ── LangGraph ──────────────────────────────────────────────────────
    use_langgraph: bool = True
    langchain_api_key: str = ""

    # ── Vector DB ──────────────────────────────────────────────────────
    vector_db: str = "qdrant"
    qdrant_url: str = ":memory:"
    qdrant_api_key: str = ""


    # ── Server ─────────────────────────────────────────────────────────
    host: str = "0.0.0.0"
    port: int = 8080
    environment: str = "development"
    log_level: str = "INFO"


# Singleton settings instance
settings = Settings()

def setup_logging():
    import logging
    import os
    
    # Check if running in a GCP environment (Cloud Run, App Engine) or has ADC setup
    use_cloud_logging = os.getenv("GOOGLE_APPLICATION_CREDENTIALS") or os.getenv("GOOGLE_CLOUD_PROJECT")
    
    if use_cloud_logging:
        try:
            import google.cloud.logging
            client = google.cloud.logging.Client()
            client.setup_logging()
            logging.info("Google Cloud Logging integrated successfully.")
            return
        except ImportError:
            logging.warning("google-cloud-logging not installed. Falling back to standard logging.")
        except Exception as e:
            logging.warning(f"Failed to initialize Cloud Logging: {e}. Falling back to standard logging.")
            
    # Standard local logging fallback
    logging.basicConfig(
        level=logging.INFO,
        format="%(asctime)s [%(levelname)s] %(name)s: %(message)s"
    )

# Initialize logging when config is imported
setup_logging()


# ── System Prompt Template ─────────────────────────────────────────────
# Extracted from main.py L404-L522. This is the master prompt template
# used by MathAIEngine to instruct the LLM on response format.

SYSTEM_TEMPLATE = r"""
You are an elite Indian mathematics teacher for Class 6 to 12 and JEE aspirants.
Your goal is to explain math concepts and solve problems step-by-step.
If a user asks a non-math question, 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:
════════════════════════════════════════

β†’ USE LaTeX math mode ($...$ for inline, $$...$$ for block) for all mathematical expressions.
β†’ Example: $x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}$
β†’ Use proper LaTeX symbols (e.g. \sqrt, \pi, \pm, \int)
β†’ Hindi/Hinglish question β†’ answer in same language

Context from knowledge base:
{context}
"""