The Problem: Legal Asymmetry in Real Estate
Indian homebuyers sign 80–120 page sale agreements drafted entirely by builder legal teams. Most contain clauses that directly violate the Maharashtra Real Estate (Regulation and Development) Act, 2016 — yet buyers sign without realizing it, because identifying a Section 13 advance-payment violation requires knowing Section 13 exists.
The asymmetry is structural. The builder's team has drafted hundreds of these agreements. The buyer reads their first one, under time pressure, often without a lawyer.
This project builds the buyer's side of that equation: a two-agent AI system that reads the raw agreement text, identifies MahaRERA regulatory violations with section references, and generates a ready-to-send negotiation letter calibrated to the severity of what it found.
Project Overview
Target Users: Maharashtra homebuyers, tenant rights advocates, housing lawyers conducting preliminary reviews.
Core Capabilities:
| Capability | Description |
|---|---|
| Clause Extraction | Cleans and normalizes raw PDF-extracted agreement text |
| Violation Detection | Identifies 6 major MahaRERA violation categories with severity ratings |
| Legal Anchoring | Maps each violation to exact section, penalty clause, and reference URL |
| Tiered Drafting | Generates TIER_1 (polite), TIER_2 (legal notice), or TIER_3 (pre-litigation) letters |
| Chat Interface | Conversational session that collects documents and answers follow-up questions |
| Dual Persistence | Raw docs in MongoDB, structured audit reports in PostgreSQL |
| Workflow Tracing | Full 15-step trace per analysis for debugging and explainability |
Why Two Agents? Legal analysis and negotiation strategy are distinct cognitive tasks. Mixing them into a single prompt produces worse output on both dimensions. Separating them lets each agent be specialized via its system prompt and keeps the reasoning auditable.
System Architecture
Two entry points share identical business logic: a REST endpoint for programmatic use and a chat interface that walks users through collecting the required document details conversationally. The Google ADK web UI provides a third entry point during development for tracing agent reasoning interactively.
Agent Workflow
Technical Deep Dive
Agent Design
Agent 1 — Legal Analyzer is prompted as a 15-year MahaRERA property lawyer. Its sole job: read the cleaned agreement text and return a structured JSON array of violations. Temperature is set to 0.1 to minimize creative interpretation — this is a compliance task, not a creative one.
The six violation categories it knows:
| Category | MahaRERA Section | Severity | Key Rule |
|---|---|---|---|
advance_payment | Section 13 | CRITICAL | No >10% advance before registered agreement |
delayed_possession | Section 18 | HIGH | Compensation must be ≥ SBI MCLR+2% (~10.5% p.a.) |
carpet_area | Section 12 | HIGH | Zero tolerance for carpet area shortfall |
liability_cap | Section 89 | CRITICAL | Any builder liability cap is void ab initio |
maintenance_charges | Section 17 | MEDIUM | Cannot charge maintenance advance > 12 months |
force_majeure | Section 6 | MEDIUM | Broadly self-declared force majeure is challengeable |
Agent 2 — Negotiation Strategist receives the risk profile and has access to two tools before calling Gemini: maharera_rule_lookup (fetches the exact statutory text, penalty clause, and official URL for each violation category) and generate_negotiation_draft (produces the tier-specific template). Gemini then adds the strategic next steps layer on top of this pre-structured context.
This two-step pattern — deterministic tools first, then LLM synthesis — is deliberate. The tools produce facts that cannot be hallucinated. Gemini only adds what requires judgment: what to do next.
The Three Escalation Tiers
The system generates fundamentally different letters depending on escalation_level:
TIER_1 — Request for Clarification: Non-threatening. Asks the builder to explain the clause in writing. Used when the buyer wants to keep the relationship intact but needs documentation.
TIER_2 — Legal Notice (default): Cites specific MahaRERA sections. Gives the builder 7 days to comply. Structured as a formal notice, suitable for sending via registered email.
TIER_3 — Pre-Litigation Escalation: 48-hour ultimatum. Explicitly names MahaRERA, NCDRC, CCI, and the public complaint portal as parallel tracks. Used when CRITICAL violations exist and the buyer is prepared to escalate.
Fallback Architecture
The system remains useful even when Gemini is unavailable. Agent 1 falls back to regex patterns:
(\d+)\s*%.*(?:advance|upfront)— detects advance percentage violationsliability.*(?:limit|cap).*(\d+)%— detects liability capsdelay.*interest+ percentage comparison — detects below-threshold delay interest rates
Agent 2 falls back to a hardcoded six-step playbook appropriate for CRITICAL findings. Both fallbacks produce usable output, they just lack the nuanced reasoning that Gemini provides.
Workflow Execution Example
Agreement text submitted: "The Purchaser shall pay 25% as advance payment immediately upon signing. The Builder's liability shall be limited to 5% of the agreement value. Delay compensation shall be calculated at 6% per annum."
Challenges & Solutions
| Challenge | Impact | Solution |
|---|---|---|
| Gemini refusing "legal advice" | Agent 1 would return empty risks or disclaimers | Framed as "compliance review" not "legal advice"; system prompt defines LLM as analyst, not advisor |
| Hallucinated section numbers | Agent citing non-existent MahaRERA sections | Baked all 6 section references into the system prompt; rule_lookup enforces valid categories |
| Inconsistent JSON from Gemini | Response parsing failures | response_mime_type: application/json + JSON parse with markdown fence stripping |
| Both DBs down in dev | App refusing to start | Availability flags at startup; app runs in mock mode without persistence |
| Long agreements hitting token limits | Context window exceeded | clause_extractor normalizes and compresses; 50-char minimum ensures real content |
| TIER_3 letters being over-aggressive | Risk of buyer liability | Tier selection is explicit user choice, not auto-escalation; defaults to TIER_2 |
The hallucinated section number problem was the most dangerous. Early versions of Agent 1 would sometimes cite "Section 22A" or "Section 47B" which don't exist in MahaRERA. The fix was not better prompting — it was removing the LLM's ability to invent sections at all. The system prompt now lists exactly the six categories and their sections. If Gemini tries to add a seventh, the Pydantic validator rejects it at the schema level.
Observability
Every analysis produces a workflow_trace — a 15-step ordered record of every action taken by every actor (orchestrator, agents, tools), with timestamps and payload snapshots.
The trace serves two purposes: debugging (which step failed?) and explainability (the chat interface uses the trace to answer "why did you flag that clause?"). Both agents log their reasoning in agent1_reasoning and agent2_reasoning fields that appear in the trace.
Security & Privacy
Agreement text sensitivity: Raw agreement text can contain buyer PII (name, PAN, address). MongoDB stores the raw text in an unstructured collection keyed to request_id, with rera_number as the only indexed field used for lookups. No PII is indexed or searchable.
Gemini API calls: Calls include response_mime_type: application/json and low temperature. No system-level logging of request content on the application side beyond structlog rotation.
Database degradation: If PostgreSQL or MongoDB is unavailable at startup, the app sets an availability flag and skips persistence silently. The analysis still runs and the full AuditReportResponse is returned to the caller — no data loss for the user.
Future Enhancements
Phase 1 — Broader Coverage
- Extend beyond MahaRERA to RERA acts of other states (Karnataka, Delhi, Telangana)
- OCR integration: accept scanned PDF uploads via multipart form
- Live MahaRERA portal integration: verify RERA number and project registration status
Phase 2 — Legal Intelligence
- RAG over MahaRERA case law and tribunal orders
- Section cross-referencing: if Section 18 is violated, surface related Section 31 complaint precedents
- Severity calibration using actual penalty amounts from historical cases
Phase 3 — Workflow Automation
- Auto-send negotiation letter via registered email API
- Follow-up tracking: flag if builder does not respond within stated deadline
- MahaRERA complaint form auto-fill if TIER_3 escalation is not resolved
Key Learnings
Separate analysis from strategy in two agents. The first iteration put both violation detection and negotiation advice into a single Gemini call. The output was mediocre at both — the model hedged on violations and was generic in advice. Separating them into two agents with distinct roles and system prompts improved both dramatically.
Deterministic tools beat prompting for facts. The maharera_rule_lookup tool is a Python dictionary. It cannot hallucinate a section number. The negotiation draft templates are Python string templates — no LLM involved. Using Gemini only for the parts that require judgment (risk classification, strategic advice) and deterministic code for everything else produces more reliable and verifiable output.
The chat interface is more useful than the REST API for most users. The REST API requires knowing all five fields (builder name, project name, RERA number, raw text, escalation level) upfront. The chat interface collects them through conversation, asks for clarification, and handles "I don't have the RERA number" gracefully. The same orchestrator code runs in both — the chat layer is just a better input collector.
Workflow tracing is not optional. The trace was added as an afterthought but became the most useful feature for debugging. When Gemini returned unexpected output, the trace showed exactly which step produced it and what the input was. Ship tracing from day one.
Conclusion
The MahaRERA AI Negotiation Agent demonstrates that domain-specific regulatory AI does not require vast training data or fine-tuning — it requires careful system prompt engineering, deterministic tools for factual grounding, and a clean separation between analysis and synthesis agents.
The two-agent architecture makes the system both more accurate and more auditable. Every analysis produces a 15-step trace that shows exactly what happened and why. Users can question the system's reasoning, and the chat interface can explain it using the stored trace.
The result is a meaningful reduction in legal asymmetry for a buyer reading their first sale agreement: not a replacement for a lawyer, but a first line of defense that knows MahaRERA section by section.
That's all for now, folks!