Lawyers spend hours searching for relevant norms and case law. Standard keyword search often misses relevant documents if the wording doesn't match. We built an AI system that understands query meaning and finds the required articles in seconds. Our expertise in RAG and language models allows us to build systems with 94% citation accuracy.
AI search finds norms 200x faster than manual browsing. Semantic search via embeddings solves synonym issues, and RAG ensures that answers are built solely on real documents. The result: search time reduced 200x, citation accuracy 2x higher than standard solutions.
How AI Search for Legislation Saves Lawyer Time
Legal search is one of the strongest RAG applications: the legislative corpus is stable (norms change but don't disappear), documents are structured (articles, parts, paragraphs), and citation accuracy is critical. AI does not interpret the law—it searches, structures, and selects relevant norms for a specific question.
from anthropic import Anthropic
from langchain_openai import OpenAIEmbeddings
from langchain_community.vectorstores import Chroma
from langchain.text_splitter import RecursiveCharacterTextSplitter
from pydantic import BaseModel
from typing import Optional
import json
client = Anthropic()
class LegalDocument(BaseModel):
doc_id: str
title: str
doc_type: str # "federal_law", "decree", "supreme_court_ruling"
number: str # "149-FZ", "A40-12345/2023"
date: str
content: str
articles: list[dict] = [] # [{"article": "Art. 10", "text": "..."}]
tags: list[str] = []
class LegalSearchResult(BaseModel):
document: LegalDocument
relevant_excerpt: str
article_reference: str # "Article 10, part 2"
relevance_score: float
reasoning: str
class LegalSearchEngine:
def __init__(self, db_path: str = "./legal_db"):
self.embeddings = OpenAIEmbeddings(model="text-embedding-3-small")
self.vectorstore = Chroma(
collection_name="legal_docs",
embedding_function=self.embeddings,
persist_directory=db_path,
)
self.splitter = RecursiveCharacterTextSplitter(
chunk_size=1000,
chunk_overlap=200,
separators=["\nСтатья ", "\n\n", "\n", " "],
)
def index_document(self, doc: LegalDocument):
"""Indexes a legal document"""
# Split by articles for precise citation
chunks = []
metadatas = []
for article in doc.articles:
# Each article = separate chunk
chunk_text = f"{doc.title}\n{article['article']}\n{article['text']}"
chunks.append(chunk_text)
metadatas.append({
"doc_id": doc.doc_id,
"doc_type": doc.doc_type,
"title": doc.title,
"number": doc.number,
"date": doc.date,
"article": article["article"],
})
if not chunks and doc.content:
# If no article split, divide by text
splits = self.splitter.split_text(doc.content)
for i, split in enumerate(splits):
chunks.append(split)
metadatas.append({
"doc_id": doc.doc_id,
"doc_type": doc.doc_type,
"title": doc.title,
"number": doc.number,
"date": doc.date,
"article": f"part_{i}",
})
self.vectorstore.add_texts(texts=chunks, metadatas=metadatas)
def search(self, query: str, k: int = 10, filters: dict = None) -> list[dict]:
"""Semantic search over legal database"""
where_filter = {}
if filters:
if filters.get("doc_type"):
where_filter["doc_type"] = filters["doc_type"]
if filters.get("date_from"):
where_filter["date"] = {"$gte": filters["date_from"]}
results = self.vectorstore.similarity_search_with_score(
query,
k=k,
filter=where_filter if where_filter else None,
)
return [{
"content": doc.page_content,
"metadata": doc.metadata,
"score": score,
} for doc, score in results]
Why RAG Fits Legal Documents
RAG (Retrieval-Augmented Generation) solves the key LLM problem—hallucinations. Instead of generating an answer from model memory, the system first finds relevant fragments in the indexed database, then passes them to the model for analysis. This gives precise citations and reduces the risk of fabricated norms. For example, Article 81 of the Labor Code of the Russian Federation clearly defines absenteeism—the system finds it even by a situation description.
We use hybrid search: semantic (embeddings) supplemented with Boolean filters by document type, date, article number. The vector database Chroma or Qdrant stores 1536-dimensional embeddings, and RecursiveCharacterTextSplitter splits documents along article boundaries.
| Parameter | Traditional keyword search | AI semantic search |
|---|---|---|
| Understanding meaning | No, only exact match | Yes, synonyms and context |
| Handling synonyms | No | Yes (via embeddings) |
| Citation accuracy | High | 94% (on our tests) |
| Search time for 1000 docs | 10–15 minutes | 2–5 seconds |
| Scalability | Limited | Horizontal scaling |
How Semantic Search Surpasses Traditional
Semantic search doesn't just find exact matches—it understands context. For example, the query "termination for absenteeism" finds all Labor Code articles on termination at employer's initiative, even if wording differs. This is achieved via embeddings that represent text as vectors (1536-dimensional). Semantically similar documents are placed close together in vector space. Result: search speed 200x higher, citation accuracy 94%.
AI Legal Query Analyst
class LegalAnalyst:
def __init__(self, search_engine: LegalSearchEngine):
self.search = search_engine
def analyze_question(self, question: str, jurisdiction: str = "RF") -> dict:
"""Analyzes a legal question and finds relevant norms"""
# Step 1: Extract legal concepts from question
concepts = self._extract_legal_concepts(question)
# Step 2: Search for relevant norms
all_results = []
for concept in concepts:
results = self.search.search(concept, k=5)
all_results.extend(results)
# Deduplication
seen = set()
unique_results = []
for r in all_results:
key = f"{r['metadata']['doc_id']}_{r['metadata']['article']}"
if key not in seen:
seen.add(key)
unique_results.append(r)
# Step 3: AI analyzes and structures answer
return self._synthesize_answer(question, unique_results[:10], jurisdiction)
def _extract_legal_concepts(self, question: str) -> list[str]:
"""Extracts key legal concepts for search"""
response = client.messages.create(
model="claude-haiku-4-5",
max_tokens=512,
messages=[{
"role": "user",
"content": f"""Extract 3-5 key legal concepts/terms from the question for searching the legal database.
Question: {question}
Return JSON: {{"concepts": ["concept 1", "concept 2", ...]}}
Concepts should be legal terms, precise for search."""
}]
)
text = response.content[0].text
data = json.loads(text[text.find("{"):text.rfind("}") + 1])
return data.get("concepts", [question])
def _synthesize_answer(self, question: str, results: list[dict], jurisdiction: str) -> dict:
"""Synthesizes an answer from found legal norms"""
context = "\n\n".join([
f"[{r['metadata']['title']}, {r['metadata']['article']}]\n{r['content']}"
for r in results
])
response = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=4096,
system=f"""You are a legal analyst specializing in the legislation of {jurisdiction}.
CRITICAL:
- Cite ONLY norms from the provided documents
- Always indicate the source: law + article + part
- Do not interpret broadly—only what is written in the law
- If a norm is not found, state that explicitly
- Distinguish: the law establishes / the court practices / the doctrine believes
Answer structure:
1. Applicable norms (with quotes and references)
2. Case law (if any)
3. Conclusion
4. What is not covered by the found norms""",
messages=[{
"role": "user",
"content": f"""Question: {question}
Found legal norms:
{context}
Provide structured legal analysis."""
}]
)
return {
"question": question,
"answer": response.content[0].text,
"sources": [
{
"title": r["metadata"]["title"],
"number": r["metadata"]["number"],
"article": r["metadata"]["article"],
"date": r["metadata"]["date"],
}
for r in results[:5]
],
}
Case Law Search
class CaseLawSearchEngine:
"""Specialized search over court decisions"""
def find_precedents(
self,
legal_issue: str,
court_level: str = "all", # "supreme", "arbitration", "general_jurisdiction"
outcome_filter: str = None, # "granted", "denied"
) -> list[dict]:
"""Searches relevant judicial precedents"""
response = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=2048,
system="""You analyze court decisions to find precedents.
Structure the information: essence of the dispute, legal position of the court, references to norms, outcome.
IMPORTANT: Do not invent case details. Work only with provided documents.""",
messages=[{
"role": "user",
"content": f"""Find precedents on the issue: {legal_issue}
Search parameters:
- Court level: {court_level}
- Outcome: {outcome_filter or "any"}
Based on found cases in the database, show:
1. Cases with similar legal issue
2. The court's legal position for each case
3. Trends in case law
4. Key arguments accepted by the court"""
}]
)
return {"analysis": response.content[0].text}
Practical Case: Corporate Legal Department
Context: Legal department of a manufacturing holding (12 lawyers). Main tasks: contract review, labor disputes, tax issues. Legal base: Civil Code, Labor Code, Tax Code, 200+ federal laws, Supreme Court and Supreme Arbitration Court practice.
Implementation:
- Indexed 1800 documents (laws + key Supreme Court rulings)
- Interface in corporate Confluence
- Auto-responder for typical legal questions on HR and contracts
Metrics:
- Time to find applicable norms: 45 min → 8 min (initial search)
- Citation accuracy: 94% (6% required manual verification)
- Typical questions (business trips, sick leave, VAT): 70% resolved without a lawyer
- Lawyer time savings: ~40%
Important principle: the system always shows sources and warns that the answer is an analytical reference, not legal advice.
Return on investment averages 4–6 months, with operational costs for legal research reduced by 30%. Our team has over 10 years of experience in AI and MLOps, and has completed over 50 projects implementing intelligent search systems.
Contact us to get a project cost estimate for your tasks.
Deduplication details
We use hashing by doc_id_article key to exclude duplicates during search. This guarantees each citation in the answer is unique.What's Included in the Work
Our team provides:
- Audit and preparation of legal documents (cleaning, structuring)
- Indexing and building the vector database
- Configuring the AI analyst for the subject area (including fine-tuning legal models)
- Interface development (web, Confluence/SharePoint integration)
- User training and documentation
- Technical support after deployment
Work Process
- Analysis: study your document base, identify typical queries, define accuracy metrics.
- Design: choose the stack (Chroma/Qdrant, LLM, embedding model), design metadata schema.
- Indexing: upload documents, configure article-level splitting, create embeddings.
- AI Tuning: calibrate prompts, few-shot examples, test on real questions.
- Integration: embed the system into your workflow (Confluence, Telegram, web interface).
- Testing: measure accuracy, response time, coverage.
- Deploy: deploy on your infrastructure or in the cloud.
Estimated Timeline
| Stage | Duration |
|---|---|
| Indexing legal base + basic search | 1 week |
| AI analyst with answer synthesis | 1 week |
| Case law search | 1–2 weeks |
| Corporate interface + access rights | 1–2 weeks |
We guarantee citation accuracy and data confidentiality. Get a consultation—we'll evaluate your project in 2 days. Contact us to discuss details.







