Spaces:
Sleeping
Sleeping
Upload 17 files
Browse files- server.py +26 -5
- src/.DS_Store +0 -0
- src/db.py +35 -0
- src/rag_engine.py +175 -24
- src/retriever.py +38 -2
server.py
CHANGED
|
@@ -33,6 +33,7 @@ import src.db as db
|
|
| 33 |
class UserAuthRequest(BaseModel):
|
| 34 |
username: str
|
| 35 |
name: Optional[str] = None
|
|
|
|
| 36 |
|
| 37 |
class CreateSessionRequest(BaseModel):
|
| 38 |
session_id: Optional[str] = None
|
|
@@ -56,10 +57,25 @@ class QueryRequest(BaseModel):
|
|
| 56 |
|
| 57 |
@app.post("/api/auth")
|
| 58 |
def auth_endpoint(req: UserAuthRequest):
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
|
| 64 |
@app.get("/api/sessions")
|
| 65 |
def list_sessions_endpoint(username: Optional[str] = None):
|
|
@@ -88,9 +104,12 @@ def create_session_endpoint(req: CreateSessionRequest):
|
|
| 88 |
def get_info():
|
| 89 |
chapters = ["All"] + sorted(list(set(item["chapter"] for item in ICAI_MANIFEST)))
|
| 90 |
groq_keys = engine.get_groq_keys()
|
|
|
|
|
|
|
|
|
|
| 91 |
return {
|
| 92 |
"models": CLOUDFLARE_MODELS,
|
| 93 |
-
"default_model":
|
| 94 |
"chapters": chapters,
|
| 95 |
"total_chunks": len(retriever.indexed_chunks),
|
| 96 |
"groq_keys_count": len(groq_keys)
|
|
@@ -137,6 +156,8 @@ def tts_endpoint(req: TTSRequest):
|
|
| 137 |
def chat_endpoint(req: QueryRequest):
|
| 138 |
if not req.query.strip():
|
| 139 |
raise HTTPException(status_code=400, detail="Query cannot be empty")
|
|
|
|
|
|
|
| 140 |
|
| 141 |
session_id = req.session_id
|
| 142 |
if not session_id:
|
|
|
|
| 33 |
class UserAuthRequest(BaseModel):
|
| 34 |
username: str
|
| 35 |
name: Optional[str] = None
|
| 36 |
+
mode: Optional[str] = "create" # "create" | "login"
|
| 37 |
|
| 38 |
class CreateSessionRequest(BaseModel):
|
| 39 |
session_id: Optional[str] = None
|
|
|
|
| 57 |
|
| 58 |
@app.post("/api/auth")
|
| 59 |
def auth_endpoint(req: UserAuthRequest):
|
| 60 |
+
uname = req.username.strip()
|
| 61 |
+
if not uname:
|
| 62 |
+
raise HTTPException(status_code=400, detail="Username cannot be empty.")
|
| 63 |
+
|
| 64 |
+
# Mode 1: Login / Sign In (Existing user)
|
| 65 |
+
if req.mode == "login":
|
| 66 |
+
user = db.get_user(uname)
|
| 67 |
+
if not user:
|
| 68 |
+
raise HTTPException(status_code=404, detail=f"User '@{uname}' not found. Please create a profile.")
|
| 69 |
+
return user
|
| 70 |
+
|
| 71 |
+
# Mode 2: Create / Register (Unique check)
|
| 72 |
+
try:
|
| 73 |
+
user = db.create_user(uname, req.name.strip() if req.name else None)
|
| 74 |
+
return user
|
| 75 |
+
except ValueError as e:
|
| 76 |
+
raise HTTPException(status_code=409, detail=str(e))
|
| 77 |
+
except Exception as e:
|
| 78 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 79 |
|
| 80 |
@app.get("/api/sessions")
|
| 81 |
def list_sessions_endpoint(username: Optional[str] = None):
|
|
|
|
| 104 |
def get_info():
|
| 105 |
chapters = ["All"] + sorted(list(set(item["chapter"] for item in ICAI_MANIFEST)))
|
| 106 |
groq_keys = engine.get_groq_keys()
|
| 107 |
+
default_m = os.getenv("CLOUDFLARE_MODEL")
|
| 108 |
+
if not default_m or default_m == "@cf/deepseek-ai/deepseek-r1-distill-qwen-32b":
|
| 109 |
+
default_m = "groq:openai/gpt-oss-120b"
|
| 110 |
return {
|
| 111 |
"models": CLOUDFLARE_MODELS,
|
| 112 |
+
"default_model": default_m,
|
| 113 |
"chapters": chapters,
|
| 114 |
"total_chunks": len(retriever.indexed_chunks),
|
| 115 |
"groq_keys_count": len(groq_keys)
|
|
|
|
| 156 |
def chat_endpoint(req: QueryRequest):
|
| 157 |
if not req.query.strip():
|
| 158 |
raise HTTPException(status_code=400, detail="Query cannot be empty")
|
| 159 |
+
if not req.username or not req.username.strip():
|
| 160 |
+
raise HTTPException(status_code=401, detail="Profile creation is compulsory. Please provide your username.")
|
| 161 |
|
| 162 |
session_id = req.session_id
|
| 163 |
if not session_id:
|
src/.DS_Store
ADDED
|
Binary file (6.15 kB). View file
|
|
|
src/db.py
CHANGED
|
@@ -87,6 +87,41 @@ def init_db():
|
|
| 87 |
# Run schema setup
|
| 88 |
init_db()
|
| 89 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
def get_or_create_user(username: str, name: Optional[str] = None) -> Dict[str, Any]:
|
| 91 |
username = username.strip().lower()
|
| 92 |
disp_name = (name or username).strip()
|
|
|
|
| 87 |
# Run schema setup
|
| 88 |
init_db()
|
| 89 |
|
| 90 |
+
def get_user(username: str) -> Optional[Dict[str, Any]]:
|
| 91 |
+
username = username.strip().lower()
|
| 92 |
+
try:
|
| 93 |
+
conn = get_connection()
|
| 94 |
+
with conn.cursor() as cursor:
|
| 95 |
+
cursor.execute("SELECT username, name, created_at FROM users WHERE username = %s;", (username,))
|
| 96 |
+
user = cursor.fetchone()
|
| 97 |
+
conn.close()
|
| 98 |
+
return user
|
| 99 |
+
except Exception as e:
|
| 100 |
+
print(f"Error in get_user: {e}")
|
| 101 |
+
return None
|
| 102 |
+
|
| 103 |
+
def create_user(username: str, name: Optional[str] = None) -> Dict[str, Any]:
|
| 104 |
+
username = username.strip().lower()
|
| 105 |
+
disp_name = (name or username).strip()
|
| 106 |
+
if not username:
|
| 107 |
+
raise ValueError("Username cannot be empty")
|
| 108 |
+
try:
|
| 109 |
+
conn = get_connection()
|
| 110 |
+
with conn.cursor() as cursor:
|
| 111 |
+
cursor.execute("SELECT username, name, created_at FROM users WHERE username = %s;", (username,))
|
| 112 |
+
existing = cursor.fetchone()
|
| 113 |
+
if existing:
|
| 114 |
+
conn.close()
|
| 115 |
+
raise ValueError(f"Username '@{username}' is already taken. Please choose another username.")
|
| 116 |
+
cursor.execute("INSERT INTO users (username, name) VALUES (%s, %s);", (username, disp_name))
|
| 117 |
+
conn.close()
|
| 118 |
+
return {"username": username, "name": disp_name}
|
| 119 |
+
except ValueError:
|
| 120 |
+
raise
|
| 121 |
+
except Exception as e:
|
| 122 |
+
print(f"Database error creating user: {e}")
|
| 123 |
+
raise RuntimeError(f"Database error creating user: {e}")
|
| 124 |
+
|
| 125 |
def get_or_create_user(username: str, name: Optional[str] = None) -> Dict[str, Any]:
|
| 126 |
username = username.strip().lower()
|
| 127 |
disp_name = (name or username).strip()
|
src/rag_engine.py
CHANGED
|
@@ -12,6 +12,7 @@ from groq import Groq
|
|
| 12 |
|
| 13 |
# Supported frontier models across Cloudflare Workers AI and Groq
|
| 14 |
CLOUDFLARE_MODELS = {
|
|
|
|
| 15 |
"Groq: Qwen 3.8 (27B Ultra Fast)": "groq:qwen/qwen3.8-27b",
|
| 16 |
"DeepSeek R1 (32B Frontier Reasoning)": "@cf/deepseek-ai/deepseek-r1-distill-qwen-32b",
|
| 17 |
"Gemma 4 (26B MoE Google Reasoning)": "@cf/google/gemma-4-26b-a4b-it",
|
|
@@ -29,6 +30,26 @@ CLOUDFLARE_MODELS = {
|
|
| 29 |
CBQ_SYSTEM_PROMPT = """You are JurisAI, an elite legal intelligence assistant designed, architected, and trained by Shashwat specifically for CA Foundation Paper-2: Business Laws.
|
| 30 |
When asked about your identity or creator, state that you are JurisAI, designed and trained by Shashwat.
|
| 31 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
You are answering a **Practical / Case-Based Question (CBQ)**.
|
| 33 |
In CA Foundation, you MUST strictly follow the statutory 3-step master rule:
|
| 34 |
**LAW → FACTS → RESULT (Provision → Application → Conclusion)**.
|
|
@@ -42,8 +63,14 @@ Structure your response using these exact markdown headers:
|
|
| 42 |
|
| 43 |
### 📑 Detailed Legal Explanation & Case Principles
|
| 44 |
**1. Provision / Legal Rule**:
|
| 45 |
-
- State the governing Act and Section (e.g., *According to Section
|
| 46 |
-
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
|
| 48 |
**2. Application / Analysis**:
|
| 49 |
- Connect the specific facts of the question to the legal rule (e.g., *In the present case, ...*).
|
|
@@ -61,6 +88,25 @@ Official ICAI Book Excerpts:
|
|
| 61 |
THEORY_SYSTEM_PROMPT = """You are JurisAI, an elite legal intelligence assistant designed, architected, and trained by Shashwat specifically for CA Foundation Paper-2: Business Laws.
|
| 62 |
When asked about your identity or creator, state that you are JurisAI, designed and trained by Shashwat.
|
| 63 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
You are answering a **Theory / Descriptive Syllabus Question**.
|
| 65 |
In CA Foundation, theory questions must be presented with structured headings and numbered points, not large unstructured essays.
|
| 66 |
|
|
@@ -75,7 +121,10 @@ Provide a sharp, authoritative summary statement:
|
|
| 75 |
Structure with clear headings and numbered points:
|
| 76 |
- **Essential Elements / Conditions / Rules**: Use numbered lists for conditions (e.g. 1, 2, 3...).
|
| 77 |
- **Key Distinctions / Sub-parts / Exceptions**: Distinct sub-headings for each aspect.
|
| 78 |
-
|
|
|
|
|
|
|
|
|
|
| 79 |
|
| 80 |
Official ICAI Book Excerpts:
|
| 81 |
----------------------------------------
|
|
@@ -208,8 +257,91 @@ class LegalRAGEngine:
|
|
| 208 |
except Exception as e:
|
| 209 |
return {"clean_answer": f"Error connecting to Cloudflare Workers AI: {e}", "thinking": ""}
|
| 210 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 211 |
def decide_and_route(self, query: str, history: List[Dict[str, str]]) -> Dict[str, Any]:
|
| 212 |
-
|
|
|
|
| 213 |
casual = {
|
| 214 |
"hi", "hello", "hey", "who are you", "what is your name", "who made you",
|
| 215 |
"who created you", "who designed you", "who trained you", "what can you do",
|
|
@@ -262,38 +394,50 @@ class LegalRAGEngine:
|
|
| 262 |
|
| 263 |
# 1. CBQ classification
|
| 264 |
if is_cbq and (has_legal or len(query.split()) >= 4):
|
|
|
|
| 265 |
return {
|
| 266 |
"needs_rag": True,
|
| 267 |
"question_type": "cbq",
|
| 268 |
-
"search_query":
|
| 269 |
"intent_reason": "Practical Case-Based Question (CBQ) identified. Applying Provision → Application → Conclusion (Law → Facts → Result) format."
|
| 270 |
}
|
| 271 |
|
| 272 |
# 2. Theory / Concept query
|
| 273 |
if has_legal or len(query.split()) >= 4:
|
| 274 |
-
# If current query is
|
| 275 |
-
search_q =
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 283 |
return {
|
| 284 |
"needs_rag": True,
|
| 285 |
"question_type": "theory",
|
| 286 |
-
"search_query":
|
| 287 |
"intent_reason": "Theory / Syllabus Concept identified. Applying Definition → Section → Essential Conditions & Rules structure."
|
| 288 |
}
|
| 289 |
|
| 290 |
if prev_has_legal and len(query.split()) <= 3:
|
| 291 |
last_user_queries = [m.get("content", "") for m in history if m.get("role") == "user"]
|
| 292 |
-
search_q = f"{last_user_queries[-1]} {
|
|
|
|
| 293 |
return {
|
| 294 |
"needs_rag": True,
|
| 295 |
"question_type": "theory",
|
| 296 |
-
"search_query":
|
| 297 |
"intent_reason": "Contextual follow-up to prior legal inquiry."
|
| 298 |
}
|
| 299 |
|
|
@@ -317,7 +461,9 @@ class LegalRAGEngine:
|
|
| 317 |
|
| 318 |
cf_token = os.getenv("CLOUDFLARE_API_TOKEN")
|
| 319 |
cf_acc_id = os.getenv("CLOUDFLARE_ACCOUNT_ID")
|
| 320 |
-
model_id = model_name or os.getenv("CLOUDFLARE_MODEL"
|
|
|
|
|
|
|
| 321 |
|
| 322 |
routing = self.decide_and_route(query, history)
|
| 323 |
provider = "Groq" if (model_id.startswith("groq:") or not cf_token) else "Cloudflare"
|
|
@@ -402,8 +548,9 @@ class LegalRAGEngine:
|
|
| 402 |
if model_id.startswith("groq:") or not cf_token:
|
| 403 |
clean_model = model_id.replace("groq:", "")
|
| 404 |
# Ensure model passed to Groq is a valid Groq model name, not a Cloudflare @cf/ path
|
| 405 |
-
|
| 406 |
-
|
|
|
|
| 407 |
|
| 408 |
groq_clients = self.get_groq_clients_in_rotation()
|
| 409 |
streamed = False
|
|
@@ -411,20 +558,23 @@ class LegalRAGEngine:
|
|
| 411 |
|
| 412 |
# Fallback candidate models if one exceeds token or rate limit
|
| 413 |
candidate_models = [clean_model]
|
| 414 |
-
for m in ["
|
| 415 |
if m not in candidate_models:
|
| 416 |
candidate_models.append(m)
|
| 417 |
|
| 418 |
for g_model in candidate_models:
|
| 419 |
if streamed:
|
| 420 |
break
|
|
|
|
|
|
|
|
|
|
| 421 |
for client in groq_clients:
|
| 422 |
try:
|
| 423 |
completion = client.chat.completions.create(
|
| 424 |
model=g_model,
|
| 425 |
messages=messages,
|
| 426 |
temperature=0.6,
|
| 427 |
-
max_completion_tokens=
|
| 428 |
top_p=0.95,
|
| 429 |
stream=True
|
| 430 |
)
|
|
@@ -516,18 +666,19 @@ class LegalRAGEngine:
|
|
| 516 |
yield f"event: thinking\ndata: {json.dumps({'text': 'Cloudflare rate limited. Switching smoothly to Groq (with multi-key & model rotation)...'})}\n\n"
|
| 517 |
fallback_success = False
|
| 518 |
last_fallback_err = None
|
| 519 |
-
fallback_models = ["
|
| 520 |
|
| 521 |
for g_model in fallback_models:
|
| 522 |
if fallback_success:
|
| 523 |
break
|
|
|
|
| 524 |
for client in groq_clients:
|
| 525 |
try:
|
| 526 |
completion = client.chat.completions.create(
|
| 527 |
model=g_model,
|
| 528 |
messages=messages,
|
| 529 |
temperature=0.6,
|
| 530 |
-
max_completion_tokens=
|
| 531 |
top_p=0.95,
|
| 532 |
stream=True
|
| 533 |
)
|
|
|
|
| 12 |
|
| 13 |
# Supported frontier models across Cloudflare Workers AI and Groq
|
| 14 |
CLOUDFLARE_MODELS = {
|
| 15 |
+
"Groq: GPT-OSS (120B Flagship Reasoning)": "groq:openai/gpt-oss-120b",
|
| 16 |
"Groq: Qwen 3.8 (27B Ultra Fast)": "groq:qwen/qwen3.8-27b",
|
| 17 |
"DeepSeek R1 (32B Frontier Reasoning)": "@cf/deepseek-ai/deepseek-r1-distill-qwen-32b",
|
| 18 |
"Gemma 4 (26B MoE Google Reasoning)": "@cf/google/gemma-4-26b-a4b-it",
|
|
|
|
| 30 |
CBQ_SYSTEM_PROMPT = """You are JurisAI, an elite legal intelligence assistant designed, architected, and trained by Shashwat specifically for CA Foundation Paper-2: Business Laws.
|
| 31 |
When asked about your identity or creator, state that you are JurisAI, designed and trained by Shashwat.
|
| 32 |
|
| 33 |
+
CRITICAL EXAM INTEGRITY RULE:
|
| 34 |
+
You MUST cite ONLY case laws, sections, and legal principles that are explicitly taught in the official ICAI CA Foundation Business Laws study material (provided in the excerpts below).
|
| 35 |
+
NEVER fabricate, hallucinate, or import irrelevant external Indian cases (e.g. D. N. Banerji, Sham Lal, Balwant Rai, etc.) that are NOT part of the ICAI curriculum.
|
| 36 |
+
|
| 37 |
+
STATUTORY MAPPING FOR COMMON TOPICS:
|
| 38 |
+
1. Appropriation of Payments (Where debtor owes several distinct debts):
|
| 39 |
+
- Governed SOLELY by **Sections 59, 60, and 61 of the Indian Contract Act, 1872**.
|
| 40 |
+
- NEVER confuse with Section 73 (Section 73 is compensation for loss or damage caused by breach of contract).
|
| 41 |
+
- **Section 59 (Debtor indicates)**: Where debtor intimates to which debt payment is to be applied, the payment, *if accepted, must be applied accordingly*. The debtor's contention to specify the debt is legally valid and binding upon acceptance; creditor cannot unilaterally alter debtor's express appropriation.
|
| 42 |
+
- **Section 60 (Debtor omits to indicate)**: If debtor does not indicate, creditor has discretion to apply to any lawful debt actually due and payable (including time-barred debts, but not disputed debts).
|
| 43 |
+
- **Section 61 (Neither party indicates)**: Applied in order of time (FIFO); if debts are of equal standing, applied proportionately.
|
| 44 |
+
|
| 45 |
+
2. Lifting of Corporate Veil:
|
| 46 |
+
- Salomon v. Salomon & Co. Ltd. (Corporate personality)
|
| 47 |
+
- Daimler Co. Ltd. v. Continental Tyre & Rubber Co. (Enemy character)
|
| 48 |
+
- Dinshaw Maneckjee Petit, Re (Tax evasion / Protection of revenue)
|
| 49 |
+
- Workmen of Associated Rubber Industries Ltd. (Avoidance of welfare / legal obligation)
|
| 50 |
+
- Gilford Motor Co. v. Horne (Fraud / sham cloak)
|
| 51 |
+
- Merchandise Transport Ltd. (Mere agent)
|
| 52 |
+
|
| 53 |
You are answering a **Practical / Case-Based Question (CBQ)**.
|
| 54 |
In CA Foundation, you MUST strictly follow the statutory 3-step master rule:
|
| 55 |
**LAW → FACTS → RESULT (Provision → Application → Conclusion)**.
|
|
|
|
| 63 |
|
| 64 |
### 📑 Detailed Legal Explanation & Case Principles
|
| 65 |
**1. Provision / Legal Rule**:
|
| 66 |
+
- State the governing Act and Section (e.g., *According to Section 59 of the Indian Contract Act, 1872...*).
|
| 67 |
+
- When summarizing sections in a table, ALWAYS use clean, standard Markdown table syntax with a blank line before and after, proper headers, and divider lines:
|
| 68 |
+
|
| 69 |
+
| Section | Statutory Rule (as per ICAI study material) |
|
| 70 |
+
|---|---|
|
| 71 |
+
| Section 59 | When debtor intimates debt, if accepted, must be applied accordingly. |
|
| 72 |
+
| Section 60 | If debtor omits to intimate, creditor has discretion to apply to lawful debts. |
|
| 73 |
+
| Section 61 | If neither indicates, applied in order of time (or proportionately if equal). |
|
| 74 |
|
| 75 |
**2. Application / Analysis**:
|
| 76 |
- Connect the specific facts of the question to the legal rule (e.g., *In the present case, ...*).
|
|
|
|
| 88 |
THEORY_SYSTEM_PROMPT = """You are JurisAI, an elite legal intelligence assistant designed, architected, and trained by Shashwat specifically for CA Foundation Paper-2: Business Laws.
|
| 89 |
When asked about your identity or creator, state that you are JurisAI, designed and trained by Shashwat.
|
| 90 |
|
| 91 |
+
CRITICAL EXAM INTEGRITY RULE:
|
| 92 |
+
You MUST cite ONLY case laws, sections, and legal principles that are explicitly taught in the official ICAI CA Foundation Business Laws study material (provided in the excerpts below).
|
| 93 |
+
NEVER fabricate, hallucinate, or import irrelevant external Indian cases (e.g. D. N. Banerji, Sham Lal, Balwant Rai, etc.) that are NOT part of the ICAI curriculum.
|
| 94 |
+
STATUTORY MAPPING FOR COMMON TOPICS:
|
| 95 |
+
1. Appropriation of Payments (Where debtor owes several distinct debts):
|
| 96 |
+
- Governed SOLELY by **Sections 59, 60, and 61 of the Indian Contract Act, 1872**.
|
| 97 |
+
- NEVER confuse with Section 73 (Section 73 is compensation for loss or damage caused by breach of contract).
|
| 98 |
+
- **Section 59 (Debtor indicates)**: Where debtor intimates to which debt payment is to be applied, the payment, *if accepted, must be applied accordingly*.
|
| 99 |
+
- **Section 60 (Debtor omits to indicate)**: If debtor does not indicate, creditor has discretion to apply to any lawful debt actually due and payable.
|
| 100 |
+
- **Section 61 (Neither party indicates)**: Applied in order of time (FIFO); if debts are of equal standing, applied proportionately.
|
| 101 |
+
|
| 102 |
+
2. Lifting of Corporate Veil:
|
| 103 |
+
- Salomon v. Salomon & Co. Ltd. (Foundation of independent corporate personality)
|
| 104 |
+
- Daimler Co. Ltd. v. Continental Tyre & Rubber Co. Ltd. (Determination of character of company / enemy company)
|
| 105 |
+
- Dinshaw Maneckjee Petit, Re (Protection of revenue / evading tax)
|
| 106 |
+
- Workmen of Associated Rubber Industries Ltd. (Avoidance of welfare / legal obligation)
|
| 107 |
+
- Gilford Motor Co. v. Horne (Company formed to act as a device or cloak to commit fraud or circumvent law)
|
| 108 |
+
- Merchandise Transport Ltd. (Company acting as a mere agent of shareholders)
|
| 109 |
+
|
| 110 |
You are answering a **Theory / Descriptive Syllabus Question**.
|
| 111 |
In CA Foundation, theory questions must be presented with structured headings and numbered points, not large unstructured essays.
|
| 112 |
|
|
|
|
| 121 |
Structure with clear headings and numbered points:
|
| 122 |
- **Essential Elements / Conditions / Rules**: Use numbered lists for conditions (e.g. 1, 2, 3...).
|
| 123 |
- **Key Distinctions / Sub-parts / Exceptions**: Distinct sub-headings for each aspect.
|
| 124 |
+
COMPLETENESS MANDATE:
|
| 125 |
+
- When asked for a list of points, circumstances, grounds, or exceptions (e.g., all 5 grounds for lifting the corporate veil), you MUST provide ALL of them completely in a single comprehensive response.
|
| 126 |
+
- Do NOT stop after 3 points or summarize prematurely. Always enumerate every single ground/case law with its rule and decision.
|
| 127 |
+
- Ensure your markdown tables, lists, and sections are completely closed and fully written.
|
| 128 |
|
| 129 |
Official ICAI Book Excerpts:
|
| 130 |
----------------------------------------
|
|
|
|
| 257 |
except Exception as e:
|
| 258 |
return {"clean_answer": f"Error connecting to Cloudflare Workers AI: {e}", "thinking": ""}
|
| 259 |
|
| 260 |
+
def _normalize_legal_query(self, query: str) -> str:
|
| 261 |
+
"""Corrects common student typos in legal terminology to ensure high precision retrieval."""
|
| 262 |
+
corrections = {
|
| 263 |
+
r"\bvieel\b": "veil",
|
| 264 |
+
r"\bviel\b": "veil",
|
| 265 |
+
r"\bvail\b": "veil",
|
| 266 |
+
r"\bcorparate\b": "corporate",
|
| 267 |
+
r"\bcorporte\b": "corporate",
|
| 268 |
+
r"\bpromisor\b": "promisor",
|
| 269 |
+
r"\bpromiser\b": "promisor",
|
| 270 |
+
r"\blibility\b": "liability",
|
| 271 |
+
r"\bliabilty\b": "liability",
|
| 272 |
+
r"\bseverel\b": "several",
|
| 273 |
+
r"\bseverall\b": "several",
|
| 274 |
+
r"\bagrement\b": "agreement",
|
| 275 |
+
r"\bpartnr\b": "partner",
|
| 276 |
+
r"\bpartneship\b": "partnership",
|
| 277 |
+
r"\bconsideratn\b": "consideration",
|
| 278 |
+
r"\bultra viers\b": "ultra vires",
|
| 279 |
+
r"\bultravires\b": "ultra vires",
|
| 280 |
+
r"\bcaveat emptre\b": "caveat emptor",
|
| 281 |
+
r"\bminority\b": "minor",
|
| 282 |
+
r"\bindeminty\b": "indemnity",
|
| 283 |
+
r"\bgaurentee\b": "guarantee",
|
| 284 |
+
r"\bgurantee\b": "guarantee",
|
| 285 |
+
r"\bqusi\b": "quasi",
|
| 286 |
+
r"\bnegociable\b": "negotiable",
|
| 287 |
+
r"\bcheq\b": "cheque",
|
| 288 |
+
r"\bcheck\b": "cheque",
|
| 289 |
+
r"\bsole of goods\b": "sale of goods",
|
| 290 |
+
r"\bcompnay\b": "company",
|
| 291 |
+
r"\bcompnies\b": "companies"
|
| 292 |
+
}
|
| 293 |
+
normalized = query
|
| 294 |
+
for pattern, replacement in corrections.items():
|
| 295 |
+
normalized = re.sub(pattern, replacement, normalized, flags=re.IGNORECASE)
|
| 296 |
+
return normalized
|
| 297 |
+
|
| 298 |
+
def _enhance_search_query(self, query: str) -> str:
|
| 299 |
+
"""Intelligently enhances search query with ICAI statutory sections for maximum hybrid precision."""
|
| 300 |
+
q_lower = query.lower()
|
| 301 |
+
additions = []
|
| 302 |
+
|
| 303 |
+
# 1. Appropriation of payments / adjustment of debts
|
| 304 |
+
if any(w in q_lower for w in ["appropriat", "several debts", "adjust debt", "debt of", "oldest debt"]):
|
| 305 |
+
if "59" not in q_lower:
|
| 306 |
+
additions.append("Section 59 Section 60 Section 61 appropriation of payments")
|
| 307 |
+
|
| 308 |
+
# 2. Corporate veil / Salomon
|
| 309 |
+
if any(w in q_lower for w in ["corporate veil", "veil", "piercing", "lifting", "salomon"]):
|
| 310 |
+
if "salomon" not in q_lower:
|
| 311 |
+
additions.append("Salomon lifting of corporate veil Section 2(20) Dinshaw Daimler")
|
| 312 |
+
|
| 313 |
+
# 3. Minor's agreement / Mohori Bibee
|
| 314 |
+
if any(w in q_lower for w in ["minor", "minority", "age of majority"]):
|
| 315 |
+
if "mohori" not in q_lower:
|
| 316 |
+
additions.append("Section 11 Section 68 Mohori Bibee void ab initio necessaries")
|
| 317 |
+
|
| 318 |
+
# 4. Joint promises / joint and several liability
|
| 319 |
+
if any(w in q_lower for w in ["joint promise", "joint promisors", "several liability", "joint liability"]):
|
| 320 |
+
if "42" not in q_lower and "43" not in q_lower:
|
| 321 |
+
additions.append("Section 42 Section 43 Section 44 Devolution of joint liabilities")
|
| 322 |
+
|
| 323 |
+
# 5. Caveat Emptor
|
| 324 |
+
if any(w in q_lower for w in ["caveat emptor", "buyer beware", "implied condition"]):
|
| 325 |
+
if "16" not in q_lower:
|
| 326 |
+
additions.append("Section 16 Caveat Emptor implied warranty exceptions")
|
| 327 |
+
|
| 328 |
+
# 6. Unpaid seller rights
|
| 329 |
+
if any(w in q_lower for w in ["unpaid seller", "stoppage in transit", "lien on goods"]):
|
| 330 |
+
if "45" not in q_lower and "46" not in q_lower:
|
| 331 |
+
additions.append("Section 45 Section 46 Section 47 Section 50 right of lien stoppage in transit")
|
| 332 |
+
|
| 333 |
+
# 7. Ultra vires
|
| 334 |
+
if any(w in q_lower for w in ["ultra vires", "ashbury", "objects clause"]):
|
| 335 |
+
if "ashbury" not in q_lower:
|
| 336 |
+
additions.append("Ashbury Railway Memorandum doctrine of ultra vires")
|
| 337 |
+
|
| 338 |
+
if additions:
|
| 339 |
+
return f"{query} {' '.join(additions)}"
|
| 340 |
+
return query
|
| 341 |
+
|
| 342 |
def decide_and_route(self, query: str, history: List[Dict[str, str]]) -> Dict[str, Any]:
|
| 343 |
+
normalized_query = self._normalize_legal_query(query)
|
| 344 |
+
q_lower = normalized_query.strip().lower().rstrip("?!.,")
|
| 345 |
casual = {
|
| 346 |
"hi", "hello", "hey", "who are you", "what is your name", "who made you",
|
| 347 |
"who created you", "who designed you", "who trained you", "what can you do",
|
|
|
|
| 394 |
|
| 395 |
# 1. CBQ classification
|
| 396 |
if is_cbq and (has_legal or len(query.split()) >= 4):
|
| 397 |
+
enhanced_q = self._enhance_search_query(normalized_query)
|
| 398 |
return {
|
| 399 |
"needs_rag": True,
|
| 400 |
"question_type": "cbq",
|
| 401 |
+
"search_query": enhanced_q,
|
| 402 |
"intent_reason": "Practical Case-Based Question (CBQ) identified. Applying Provision → Application → Conclusion (Law → Facts → Result) format."
|
| 403 |
}
|
| 404 |
|
| 405 |
# 2. Theory / Concept query
|
| 406 |
if has_legal or len(query.split()) >= 4:
|
| 407 |
+
# If current query is follow-up like "where are rest 2", "what about section 44?", "explain remaining", etc.
|
| 408 |
+
search_q = normalized_query
|
| 409 |
+
followup_indicators = [
|
| 410 |
+
"it", "its", "their", "that", "this", "above", "also", "exception", "exceptions",
|
| 411 |
+
"what about", "rest", "remaining", "other", "others", "next", "more", "why", "where"
|
| 412 |
+
]
|
| 413 |
+
is_followup = any(w in q_lower for w in followup_indicators)
|
| 414 |
+
if is_followup and history:
|
| 415 |
+
# Find the most recent user query with substantive legal context
|
| 416 |
+
user_queries = [
|
| 417 |
+
m.get("content", "") for m in history
|
| 418 |
+
if m.get("role") == "user" and m.get("content", "").strip()
|
| 419 |
+
]
|
| 420 |
+
if user_queries:
|
| 421 |
+
# Prepend the last substantive query to keep context intact
|
| 422 |
+
last_q = self._normalize_legal_query(user_queries[-1])
|
| 423 |
+
search_q = f"{last_q} {normalized_query}"
|
| 424 |
+
|
| 425 |
+
enhanced_q = self._enhance_search_query(search_q)
|
| 426 |
return {
|
| 427 |
"needs_rag": True,
|
| 428 |
"question_type": "theory",
|
| 429 |
+
"search_query": enhanced_q,
|
| 430 |
"intent_reason": "Theory / Syllabus Concept identified. Applying Definition → Section → Essential Conditions & Rules structure."
|
| 431 |
}
|
| 432 |
|
| 433 |
if prev_has_legal and len(query.split()) <= 3:
|
| 434 |
last_user_queries = [m.get("content", "") for m in history if m.get("role") == "user"]
|
| 435 |
+
search_q = f"{self._normalize_legal_query(last_user_queries[-1])} {normalized_query}" if last_user_queries else normalized_query
|
| 436 |
+
enhanced_q = self._enhance_search_query(search_q)
|
| 437 |
return {
|
| 438 |
"needs_rag": True,
|
| 439 |
"question_type": "theory",
|
| 440 |
+
"search_query": enhanced_q,
|
| 441 |
"intent_reason": "Contextual follow-up to prior legal inquiry."
|
| 442 |
}
|
| 443 |
|
|
|
|
| 461 |
|
| 462 |
cf_token = os.getenv("CLOUDFLARE_API_TOKEN")
|
| 463 |
cf_acc_id = os.getenv("CLOUDFLARE_ACCOUNT_ID")
|
| 464 |
+
model_id = model_name or os.getenv("CLOUDFLARE_MODEL")
|
| 465 |
+
if not model_id or model_id == "@cf/deepseek-ai/deepseek-r1-distill-qwen-32b":
|
| 466 |
+
model_id = "groq:openai/gpt-oss-120b"
|
| 467 |
|
| 468 |
routing = self.decide_and_route(query, history)
|
| 469 |
provider = "Groq" if (model_id.startswith("groq:") or not cf_token) else "Cloudflare"
|
|
|
|
| 548 |
if model_id.startswith("groq:") or not cf_token:
|
| 549 |
clean_model = model_id.replace("groq:", "")
|
| 550 |
# Ensure model passed to Groq is a valid Groq model name, not a Cloudflare @cf/ path
|
| 551 |
+
valid_groq_models = ["openai/gpt-oss-120b", "openai/gpt-oss-20b", "qwen/qwen3.8-27b", "llama-3.3-70b-versatile", "llama-3.1-8b-instant"]
|
| 552 |
+
if clean_model.startswith("@cf/") or clean_model not in valid_groq_models:
|
| 553 |
+
clean_model = "openai/gpt-oss-120b"
|
| 554 |
|
| 555 |
groq_clients = self.get_groq_clients_in_rotation()
|
| 556 |
streamed = False
|
|
|
|
| 558 |
|
| 559 |
# Fallback candidate models if one exceeds token or rate limit
|
| 560 |
candidate_models = [clean_model]
|
| 561 |
+
for m in ["openai/gpt-oss-120b", "openai/gpt-oss-20b", "qwen/qwen3.8-27b"]:
|
| 562 |
if m not in candidate_models:
|
| 563 |
candidate_models.append(m)
|
| 564 |
|
| 565 |
for g_model in candidate_models:
|
| 566 |
if streamed:
|
| 567 |
break
|
| 568 |
+
# Set max_completion_tokens safely according to model tier limits
|
| 569 |
+
# qwen models have 1000 OTPM limit on Groq free tier; gpt-oss models have 4096+ OTPM!
|
| 570 |
+
max_tokens = 950 if "qwen" in g_model else 2500
|
| 571 |
for client in groq_clients:
|
| 572 |
try:
|
| 573 |
completion = client.chat.completions.create(
|
| 574 |
model=g_model,
|
| 575 |
messages=messages,
|
| 576 |
temperature=0.6,
|
| 577 |
+
max_completion_tokens=max_tokens,
|
| 578 |
top_p=0.95,
|
| 579 |
stream=True
|
| 580 |
)
|
|
|
|
| 666 |
yield f"event: thinking\ndata: {json.dumps({'text': 'Cloudflare rate limited. Switching smoothly to Groq (with multi-key & model rotation)...'})}\n\n"
|
| 667 |
fallback_success = False
|
| 668 |
last_fallback_err = None
|
| 669 |
+
fallback_models = ["openai/gpt-oss-120b", "openai/gpt-oss-20b", "qwen/qwen3.8-27b"]
|
| 670 |
|
| 671 |
for g_model in fallback_models:
|
| 672 |
if fallback_success:
|
| 673 |
break
|
| 674 |
+
max_tokens = 950 if "qwen" in g_model else 2500
|
| 675 |
for client in groq_clients:
|
| 676 |
try:
|
| 677 |
completion = client.chat.completions.create(
|
| 678 |
model=g_model,
|
| 679 |
messages=messages,
|
| 680 |
temperature=0.6,
|
| 681 |
+
max_completion_tokens=max_tokens,
|
| 682 |
top_p=0.95,
|
| 683 |
stream=True
|
| 684 |
)
|
src/retriever.py
CHANGED
|
@@ -1,4 +1,5 @@
|
|
| 1 |
import os
|
|
|
|
| 2 |
import json
|
| 3 |
import pickle
|
| 4 |
import numpy as np
|
|
@@ -10,6 +11,35 @@ from dotenv import load_dotenv
|
|
| 10 |
|
| 11 |
load_dotenv()
|
| 12 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
class HybridLegalRetriever:
|
| 14 |
def __init__(
|
| 15 |
self,
|
|
@@ -140,6 +170,10 @@ class HybridLegalRetriever:
|
|
| 140 |
|
| 141 |
print("✔ Cloudflare Hybrid Indexing complete!")
|
| 142 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 143 |
def retrieve(
|
| 144 |
self,
|
| 145 |
query: str,
|
|
@@ -151,11 +185,13 @@ class HybridLegalRetriever:
|
|
| 151 |
if not self.indexed_chunks:
|
| 152 |
return []
|
| 153 |
|
|
|
|
|
|
|
| 154 |
# 1. Dense Semantic Search via Cloudflare embedding (with BM25 fallback on quota limit)
|
| 155 |
vector_scores: Dict[str, float] = {}
|
| 156 |
if self.collection is not None:
|
| 157 |
try:
|
| 158 |
-
query_embedding = self._get_cloudflare_embeddings([
|
| 159 |
where_filter = {"chapter": chapter_filter} if chapter_filter and chapter_filter != "All" else None
|
| 160 |
|
| 161 |
vector_res = self.collection.query(
|
|
@@ -176,7 +212,7 @@ class HybridLegalRetriever:
|
|
| 176 |
# 2. Sparse BM25 Search
|
| 177 |
bm25_scores: Dict[str, float] = {}
|
| 178 |
if self.bm25:
|
| 179 |
-
tokens = self._tokenize(
|
| 180 |
doc_scores = self.bm25.get_scores(tokens)
|
| 181 |
max_bm25 = np.max(doc_scores) if len(doc_scores) > 0 and np.max(doc_scores) > 0 else 1.0
|
| 182 |
|
|
|
|
| 1 |
import os
|
| 2 |
+
import re
|
| 3 |
import json
|
| 4 |
import pickle
|
| 5 |
import numpy as np
|
|
|
|
| 11 |
|
| 12 |
load_dotenv()
|
| 13 |
|
| 14 |
+
LEGAL_SPELL_MAP = {
|
| 15 |
+
r"\bvieel\b": "veil",
|
| 16 |
+
r"\bviel\b": "veil",
|
| 17 |
+
r"\bvail\b": "veil",
|
| 18 |
+
r"\bcorparate\b": "corporate",
|
| 19 |
+
r"\bcorporte\b": "corporate",
|
| 20 |
+
r"\bpromisor\b": "promisor",
|
| 21 |
+
r"\bpromiser\b": "promisor",
|
| 22 |
+
r"\blibility\b": "liability",
|
| 23 |
+
r"\bliabilty\b": "liability",
|
| 24 |
+
r"\bseverel\b": "several",
|
| 25 |
+
r"\bseverall\b": "several",
|
| 26 |
+
r"\bagrement\b": "agreement",
|
| 27 |
+
r"\bpartnr\b": "partner",
|
| 28 |
+
r"\bpartneship\b": "partnership",
|
| 29 |
+
r"\bconsideratn\b": "consideration",
|
| 30 |
+
r"\bultra viers\b": "ultra vires",
|
| 31 |
+
r"\bultravires\b": "ultra vires",
|
| 32 |
+
r"\bcaveat emptre\b": "caveat emptor",
|
| 33 |
+
r"\bcompnay\b": "company",
|
| 34 |
+
r"\bcompnies\b": "companies"
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
def normalize_legal_spelling(text: str) -> str:
|
| 38 |
+
cleaned = text
|
| 39 |
+
for pattern, rep in LEGAL_SPELL_MAP.items():
|
| 40 |
+
cleaned = re.sub(pattern, rep, cleaned, flags=re.IGNORECASE)
|
| 41 |
+
return cleaned
|
| 42 |
+
|
| 43 |
class HybridLegalRetriever:
|
| 44 |
def __init__(
|
| 45 |
self,
|
|
|
|
| 170 |
|
| 171 |
print("✔ Cloudflare Hybrid Indexing complete!")
|
| 172 |
|
| 173 |
+
def _tokenize(self, text: str) -> List[str]:
|
| 174 |
+
cleaned = normalize_legal_spelling(text)
|
| 175 |
+
return [w.lower() for w in cleaned.split() if w.isalnum()]
|
| 176 |
+
|
| 177 |
def retrieve(
|
| 178 |
self,
|
| 179 |
query: str,
|
|
|
|
| 185 |
if not self.indexed_chunks:
|
| 186 |
return []
|
| 187 |
|
| 188 |
+
clean_query = normalize_legal_spelling(query)
|
| 189 |
+
|
| 190 |
# 1. Dense Semantic Search via Cloudflare embedding (with BM25 fallback on quota limit)
|
| 191 |
vector_scores: Dict[str, float] = {}
|
| 192 |
if self.collection is not None:
|
| 193 |
try:
|
| 194 |
+
query_embedding = self._get_cloudflare_embeddings([clean_query])[0]
|
| 195 |
where_filter = {"chapter": chapter_filter} if chapter_filter and chapter_filter != "All" else None
|
| 196 |
|
| 197 |
vector_res = self.collection.query(
|
|
|
|
| 212 |
# 2. Sparse BM25 Search
|
| 213 |
bm25_scores: Dict[str, float] = {}
|
| 214 |
if self.bm25:
|
| 215 |
+
tokens = self._tokenize(clean_query)
|
| 216 |
doc_scores = self.bm25.get_scores(tokens)
|
| 217 |
max_bm25 = np.max(doc_scores) if len(doc_scores) > 0 and np.max(doc_scores) > 0 else 1.0
|
| 218 |
|