The Detective Story: How My AI Legal Assistant Became a Query Whisperer π΅οΈββοΈ
Turning messy questions into sharp legal queries β the magic of preprocessing

Chapter 1: The Raw Input Arrives π¨
Picture this: A user types "What happens if someone breaks Section 120B IPC contract law?" and hits send. To most systems, this looks like a perfectly fine question. But to my AI legal assistant, this is like receiving a mysterious letter that needs to be decoded, investigated, and understood before any meaningful response can be crafted.
# The journey begins here
query_analysis = query_processor.preprocess_query(payload.question)
This single line is where the magic starts - but what actually happens here is far more exciting than it appears!
Chapter 2: The Unicode Detective π
Our first detective on the case is the Unicode Normalizer. Legal text comes from all corners of the internet - some users copy-paste from PDFs with weird characters, others use fancy smart quotes from Word documents. Our normalizer is like that friend who can read anyone's handwriting:
query = " Section 320 IPC β βGrievous hurtβ under Indian Penal Code βdefinitionβ "
q_norm = unicodedata.normalize("NFKC", str(query))
q_norm = q_norm.replace("'", "'").replace("'", "'").replace(""", '"').replace(""", '"')
q_norm = " ".join(q_norm.split())
# result -> Section 320 IPC β 'Grievous hurt' under Indian Penal Code "definition"
This detective transforms those sneaky curly quotes into honest straight ones, normalizes weird Unicode characters, and even cleans up that extra whitespace. It's like having a universal translator for text messiness!
Chapter 3: The Pattern Hunter π―
Next up is our Pattern Hunter - the Sherlock Holmes of legal references. This detective has memorized every possible way users might mention legal sections and acts. Watch it work:
# Extract section references - the hunter never misses
section_matches = re.findall(r'section\s+(\d+[a-z]*)', query_lower)
# Extract act references with pattern matching
act_patterns = {
r'\b(?:ipc|indian penal code|penal code|45 of 1860|1860)\b': 'Indian Penal Code, 1860',
r'\b(?:crpc|code of criminal procedure|criminal procedure code|1973)\b': 'Code of Criminal Procedure, 1973',
r'\b(?:constitution|constitution of india)\b': 'Constitution of India',
r'\b(?:evidence act|evidence)\b': 'Evidence Act'
}
Whether you say "IPC", "Indian Penal Code", "Penal Code", or even just "1860" (the year it was enacted), our Pattern Hunter recognizes them all and normalizes them into a consistent format. It's like having a legal librarian who knows every nickname for every law book!
Chapter 4: The Mind Reader (Intent Classification) π§
But wait - there's more! Our system doesn't just extract what you mentioned; it tries to understand why you're asking. Enter the Intent Classifier:
# Determine query intent
intent = 'general'
if any(word in query_lower for word in ['what is', 'explain', 'meaning']):
intent = 'explanation'
elif any(word in query_lower for word in ['similar case', 'precedent', 'judgment']):
intent = 'case_search'
elif any(word in query_lower for word in ['procedure', 'process', 'how to']):
intent = 'procedural'
This is where the system gets a bit psychological! The system analyzes your word choices to understand whether you want:
An explanation of a legal concept
Case precedents and judgments
Procedural guidance on how to do something
Or just general legal information
It's like having a therapist who understands exactly what kind of help you need before you even finish explaining your problem!
Chapter 5: The Domain Detective ποΈ
Our Domain Detective takes this one step further by figuring out which area of law you're dealing with:
# Determine legal domain
legal_domain = 'general'
if any(word in query_lower for word in ['murder', 'theft', 'criminal', 'police']):
legal_domain = 'criminal'
elif any(word in query_lower for word in ['marriage', 'divorce', 'family']):
legal_domain = 'family'
elif any(word in query_lower for word in ['contract', 'property', 'civil']):
legal_domain = 'civil'
This detective is like that friend who can instantly tell whether your problem needs a criminal lawyer, a family lawyer, or someone who specializes in contracts. One whiff of your question and it knows exactly which legal universe you're operating in!
Chapter 6: The Security Guard π‘οΈ
Before we get too excited about all this analysis, there's a vigilant Security Guard standing at the entrance, checking every query for potential threats:
# From security validator
suspicious_patterns = [
r'ignore\s+previous\s+instructions',
r'override\s+your\s+programming',
r'pretend\s+to\s+be\s+a',
r'help\s+me\s+break\s+the\s+law',
]
This guard is trained to spot prompt injection attempts, malicious instructions, and requests for illegal advice. It's like having a bouncer who can smell trouble from a mile away and won't let it into your legal consultation!
Chapter 7: The Legal Context Validator βοΈ
Not every question deserves the full legal treatment. Our Legal Context Validator makes sure you're actually asking about legal matters:
# Legal keywords that suggest a legitimate legal question
legal_indicators = [
'law', 'legal', 'court', 'judge', 'advocate', 'contract', 'liability',
'act', 'section', 'article', 'case', 'precedent', 'jurisdiction',
'suit', 'petition', 'writ', 'litigation', 'criminal', 'civil',
# Even Hindi legal terms!
'kya main kar sakta hun', 'kya yeh legal hai'
]
This validator is bilingual and culturally aware - it even recognizes Hindi legal questions! It's like having a gatekeeper who can distinguish between "What's the weather like?" and "What's the legal precedent like?"
Chapter 8: The Filter Factory π
All this analysis culminates in the Filter Factory, where your processed query gets transformed into a sophisticated search strategy:
filters = {
'legal_topics': [legal_domain] if legal_domain != 'general' else [],
'acts': act_matches,
'sections': section_matches
}
cleaned_filters = {k: v for k, v in filters.items() if v}
Instead of throwing your raw question at a pile of legal documents and hoping for the best, the system now has a precise targeting system. It knows to look for documents from specific acts, containing particular sections, within the right legal domain.
It's like upgrading from a flashlight to a laser-guided spotlight!
Chapter 9: The Grand Finale π
Finally, all this preprocessing magic gets packaged up into a comprehensive analysis:
return {
'original_query': query,
'processed_query': query_lower,
'sections': section_matches,
'acts': act_matches,
'intent': intent,
'legal_domain': legal_domain,
'filters': cleaned_filters
}
This analysis becomes the treasure map that guides the rest of the system. The document retriever knows exactly what to look for, the response generator understands the context and intent, and the whole system works in harmony to deliver precisely what you need.
The Plot Twist: Real-World Impact π
Remember our example query: "What happens if someone breaks Section 120B IPC contract law?"
After preprocessing, the system now knows:
Sections: [
120B] - criminal conspiracyActs: [
Indian Penal Code, 1860] - criminal law, not contract lawIntent: explanation - user wants understanding, not procedure
Domain:
civil- flagged because it saw "contract law"Filters: Focused search on IPC documents and Section 120B specifically
Here's the honest truth: The system creates conflicting information rather than catching the user's conceptual error. It extracts IPC (criminal law) but flags the domain as civil law because of the "contract" keyword.
The real intelligence happens downstream when the document retrieval finds Section 120B documents about criminal conspiracy, and the LLM provides the correct context, essentially auto-correcting the user's misconception through better information rather than explicit error detection.
Epilogue: Why This Matters π―
Query preprocessing might happen in milliseconds, but it's the difference between:
β "Here are 50 random legal documents that mention your keywords"
β "Here's exactly what Section 120B of the IPC says about criminal conspiracy, with relevant case precedents"
It transforms a simple search engine into an intelligent legal assistant that understands context, catches user errors, prevents security threats, and delivers precise, relevant guidance.
Every time a user gets a perfectly tailored legal response, it's because this invisible army of text detectives worked tirelessly behind the scenes to understand not just what was asked, but what was really needed.
What I Would Do Differently: Lessons from the Trenches π οΈ
While writing this article, I discovered a fascinating gap between what I thought my system was doing and what it actually does. Here are the key improvements I'd make:
Conflict Detection
I would implement a validation layer that detects when users mention contradictory legal concepts, like criminal sections in civil law contexts that would either correct the query automatically or ask for clarification.
When conflicts are detected, it would prompt users with something like "I see you mentioned Section 120B (criminal law) and contract law. Did you mean criminal conspiracy or contract violations?"
π‘ **Technical Note:**
This entire preprocessing pipeline runs before every query to keep responses consistent, secure, and context-aware. Itβs invisible to the user β they just get smarter, safer answers β but itβs a huge part of what makes the system reliable.
Wrapping Up π―
Query preprocessing might seem invisible, but itβs the silent workhorse that turns vague, messy legal questions into something your AI system can actually reason about. Behind every quick, precise answer is a flurry of normalization, detection, intent analysis, and safety checks β all happening in milliseconds.
Key lesson: the better you prepare and structure a userβs query, the smarter and safer your AI becomes.
But this is just one part of the journey.
Next up: Iβll share how I measure answer quality and make the whole system faster and cheaper β caching strategies, evaluation datasets, and performance tuning. Stay tuned!
Comments
Join the discussionNo comments yet. Be the first to comment.
Smart Legal QA β Building an AI Legal Assistant with RAG & LangChain
Documenting how I designed and built an AI assistant that can answer complex legal questions from uploaded PDFs. Learn about RAG pipelines, LangChain, embeddings, evaluation datasets, and architectural choices.




