Spaces:
Sleeping
Sleeping
Upload folder using huggingface_hub
Browse filesFiles changed (3)
- requirements.txt+13-11
- src/agent_v2.py+22-9
- src/llm.py+34-110
123456789101112131415fastapiuvicornpydantichuggingface_hubsentence-transformersnumpygroqgoogle-generativeaitenacitypython-dotenvtransformersfaiss-cputorchkagglehubpytest1234567891011121314151617torchtransformerssentence-transformersfaiss-cpufastapiuvicornpython-dotenvgroqdvcmlflowoptunapytestkagglehubpymupdftenacityseqevalhttpx
24 unmodified lines2526272829303132333435363738125 unmodified lines164165166167168169170171172173144 unmodified lines31831932032132232332432532632724 unmodified linesfrom src.verify import verify_citationsfrom src.system_prompt import build_prompt, ANALYSIS_PROMPTfrom src.ner import extract_entities, augment_queryfrom src.llm import call_llm_rawlogger = logging.getLogger(__name__)from tenacity import retry, stop_after_attempt, wait_exponentialfrom dotenv import load_dotenvload_dotenv()# ── Session store ─────────────────────────────────────────sessions: Dict[str, Dict] = {}125 unmodified lines- Update hypothesis confidence based on new evidence- search_queries must be specific legal questions for vector search"""raw = call_llm_raw([{"role": "system", "content": ANALYSIS_PROMPT},{"role": "user", "content": user_content}]).strip()raw = raw.replace("```json", "").replace("```", "").strip()try:144 unmodified lines- Opposition war-gaming: if giving strategy, include what the other side will argue{radar_instruction}"""return call_llm_raw([{"role": "system", "content": system_prompt},{"role": "user", "content": user_content}])# ── Main entry point ──────────────────────────────────────24 unmodified lines252627282930313233343536373839125 unmodified lines165166167168169170171172173174175176177178179180144 unmodified lines32532632732832933033133233333433533633733833934024 unmodified linesfrom src.verify import verify_citationsfrom src.system_prompt import build_prompt, ANALYSIS_PROMPTfrom src.ner import extract_entities, augment_querylogger = logging.getLogger(__name__)from groq import Groqfrom tenacity import retry, stop_after_attempt, wait_exponentialfrom dotenv import load_dotenvload_dotenv()_client = Groq(api_key=os.getenv("GROQ_API_KEY"))# ── Session store ─────────────────────────────────────────sessions: Dict[str, Dict] = {}125 unmodified lines- Update hypothesis confidence based on new evidence- search_queries must be specific legal questions for vector search"""response = _client.chat.completions.create(model="llama-3.3-70b-versatile",messages=[{"role": "system", "content": ANALYSIS_PROMPT},{"role": "user", "content": user_content}],temperature=0.1,max_tokens=900)raw = response.choices[0].message.content.strip()raw = raw.replace("```json", "").replace("```", "").strip()try:144 unmodified lines- Opposition war-gaming: if giving strategy, include what the other side will argue{radar_instruction}"""response = _client.chat.completions.create(model="llama-3.3-70b-versatile",messages=[{"role": "system", "content": system_prompt},{"role": "user", "content": user_content}],temperature=0.3,max_tokens=1500)return response.choices[0].message.content# ── Main entry point ──────────────────────────────────────
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091922 unmodified lines9596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136"""LLM module. Gemini Flash as primary, Groq as fallback.Gemini works reliably from HF Spaces. Groq is backup."""import osimport loggingfrom tenacity import retry, stop_after_attempt, wait_exponentialfrom dotenv import load_dotenvload_dotenv()logger = logging.getLogger(__name__)# ── Gemini setup ──────────────────────────────────────────import google.generativeai as genai_gemini_client = None_gemini_model = Nonedef _init_gemini():global _gemini_client, _gemini_modelapi_key = os.getenv("GEMINI_API_KEY")if not api_key:logger.warning("GEMINI_API_KEY not set")return Falsetry:genai.configure(api_key=api_key)_gemini_model = genai.GenerativeModel("gemini-1.5-flash")logger.info("Gemini Flash ready")return Trueexcept Exception as e:logger.error(f"Gemini init failed: {e}")return False# ── Groq setup ────────────────────────────────────────────_groq_client = Nonedef _init_groq():global _groq_clientapi_key = os.getenv("GROQ_API_KEY")if not api_key:return Falsetry:from groq import Groq_groq_client = Groq(api_key=api_key)logger.info("Groq ready as fallback")return Trueexcept Exception as e:logger.error(f"Groq init failed: {e}")return False_gemini_ready = _init_gemini()_groq_ready = _init_groq()SYSTEM_PROMPT = """You are NyayaSetu — a sharp, street-smart Indian legal advisor.You work FOR the user. Your job is to find the angle, identify the leverage,and tell the user exactly what to do — the way a senior lawyer would in aprivate consultation, not the way a textbook would explain it.Be direct. Be human. Vary your response style naturally.Sometimes short and punchy. Sometimes detailed and structured.Match the energy of what the user needs right now.When citing sources, reference the Judgment ID naturally in your response.Always end with: "Note: This is not legal advice. Consult a qualified advocate.""""def _call_gemini(messages: list) -> str:"""Call Gemini Flash."""# Convert messages to Gemini formatsystem = next((m["content"] for m in messages if m["role"] == "system"), "")user_parts = [m["content"] for m in messages if m["role"] == "user"]full_prompt = f"{system}\n\n{chr(10).join(user_parts)}"response = _gemini_model.generate_content(full_prompt,generation_config=genai.types.GenerationConfig(temperature=0.3,max_output_tokens=1500,))return response.textdef _call_groq(messages: list) -> str:"""Call Groq Llama as fallback."""response = _groq_client.chat.completions.create(model="llama-3.3-70b-versatile",messages=messages,temperature=0.3,2 unmodified linesreturn response.choices[0].message.content@retry(stop=stop_after_attempt(2), wait=wait_exponential(min=1, max=4))def call_llm(query: str, context: str) -> str:"""Call LLM with Gemini primary, Groq fallback.Used by V1 agent (src/agent.py)."""messages = [{"role": "system", "content": SYSTEM_PROMPT},{"role": "user", "content": f"QUESTION: {query}\n\nSOURCES:\n{context}\n\nAnswer based on sources. Cite judgment IDs."}]return _call_llm_with_fallback(messages)def call_llm_raw(messages: list) -> str:"""Call LLM with pre-built messages list.Used by V2 agent (src/agent_v2.py) for Pass 1 and Pass 3."""return _call_llm_with_fallback(messages)def _call_llm_with_fallback(messages: list) -> str:"""Try Gemini first, fall back to Groq."""# Try Gemini firstif _gemini_ready and _gemini_model:try:return _call_gemini(messages)except Exception as e:logger.warning(f"Gemini failed: {e}, trying Groq")# Fall back to Groqif _groq_ready and _groq_client:try:return _call_groq(messages)except Exception as e:logger.error(f"Groq also failed: {e}")raise Exception("All LLM providers failed")1234567891011121314151617181920212223242526272 unmodified lines30313233343536373839404142434445464748495051525354555657585960"""LLM module. Single Groq API call with tenacity retry.WHY Groq? Free tier, fastest inference (~500 tokens/sec).WHY temperature=0.1? Lower = more deterministic, less hallucination.WHY one call per query? Multi-step chains add latency and failure points."""import osfrom groq import Groqfrom tenacity import retry, stop_after_attempt, wait_exponentialfrom dotenv import load_dotenvload_dotenv()_client = Groq(api_key=os.getenv("GROQ_API_KEY"))def call_llm_raw(messages: list) -> str:"""Call Groq with pre-built messages list.Used by V2 agent for Pass 1 and Pass 3."""response = _client.chat.completions.create(model="llama-3.3-70b-versatile",messages=messages,temperature=0.3,2 unmodified linesreturn response.choices[0].message.content@retry(stop=stop_after_attempt(3),wait=wait_exponential(multiplier=1, min=2, max=8))def call_llm(query: str, context: str) -> str:"""Call Groq Llama-3. Used by V1 agent.Retries 3 times with exponential backoff."""user_message = f"""QUESTION: {query}SUPREME COURT JUDGMENT EXCERPTS:{context}Answer based only on the excerpts above. Cite judgment IDs.Use proper markdown formatting."""response = _client.chat.completions.create(model="llama-3.3-70b-versatile",messages=[{"role": "system", "content": "You are NyayaSetu, an Indian legal research assistant. Answer only from provided excerpts. Cite judgment IDs. End with: NOTE: This is not legal advice."},{"role": "user", "content": user_message}],temperature=0.1,max_tokens=1500)return response.choices[0].message.content
requirements.txt+13-11
src/agent_v2.py+22-9
src/llm.py+34-110