How to Build an AI Legal Chatbot for Client Questions
Answer common legal questions and qualify clients with an AI chatbot.
Jay Banlasan
The AI Systems Guy
An AI legal chatbot for client questions and intake handles the repetitive inquiries that consume staff time without generating revenue. I built this for a firm's website where 70% of calls were people asking questions that could be answered from the FAQ page. The chatbot answers common questions, qualifies potential clients, and routes serious inquiries to the right attorney.
What You Need Before Starting
- Python 3.8+ with FastAPI
- Anthropic API key
- A knowledge base of your firm's FAQs and practice areas
- A website to embed the chat widget
Step 1: Build the Legal Knowledge Base
LEGAL_KB = {
"practice_areas": {
"personal_injury": "We handle car accidents, slip and falls, medical malpractice, and workplace injuries. Free consultation available.",
"family_law": "We assist with divorce, child custody, child support, and prenuptial agreements.",
"business_law": "We help with business formation, contracts, disputes, and mergers.",
"estate_planning": "We create wills, trusts, powers of attorney, and handle probate matters."
},
"common_questions": {
"cost": "Initial consultations are free for personal injury cases. Other practice areas charge $250 for the first hour. We offer payment plans.",
"timeline": "Every case is different. Personal injury cases typically take 6-18 months. Family law matters usually resolve in 3-12 months.",
"jurisdiction": "We practice in California. We can refer you to trusted attorneys in other states.",
"documents_needed": "Bring any relevant documents, police reports, medical records, contracts, or correspondence related to your case."
},
"disclaimers": {
"not_legal_advice": "This chatbot provides general information only and does not constitute legal advice. For specific legal guidance, please schedule a consultation.",
"confidentiality": "Information shared in this chat is not protected by attorney-client privilege. Do not share sensitive case details here."
}
}
Step 2: Build the Chat Engine
import anthropic
from dotenv import load_dotenv
load_dotenv()
def get_legal_chat_response(user_message, conversation_history):
client = anthropic.Anthropic()
kb_context = f"""Practice Areas: {str(LEGAL_KB['practice_areas'])}
Common Questions: {str(LEGAL_KB['common_questions'])}"""
system = f"""You are a helpful legal intake chatbot for a law firm.
Rules:
- Answer general legal questions using the knowledge base
- Always include the disclaimer that this is not legal advice
- If someone describes a specific legal situation, qualify them and suggest scheduling a consultation
- Never provide specific legal advice about their case
- Be warm and professional
- Keep responses under 150 words
- If you cannot answer, say so and offer to connect them with an attorney
Knowledge Base:
{kb_context}
Disclaimer to include when relevant:
{LEGAL_KB['disclaimers']['not_legal_advice']}"""
messages = conversation_history + [{"role": "user", "content": user_message}]
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=512,
system=system,
messages=messages
)
return response.content[0].text
Step 3: Add Lead Qualification
def check_for_qualification(message, response):
qualification_signals = [
"accident", "injured", "divorce", "custody", "sued", "contract dispute",
"need a lawyer", "need an attorney", "can you help", "how much"
]
message_lower = message.lower()
has_signal = any(signal in message_lower for signal in qualification_signals)
if has_signal:
return {
"qualified": True,
"should_capture": True,
"follow_up": "It sounds like you may have a case we can help with. Would you like to schedule a free consultation? I just need your name, email, and phone number."
}
return {"qualified": False, "should_capture": False}
Step 4: Build the API
from fastapi import FastAPI
from pydantic import BaseModel
from typing import List, Dict
import sqlite3
from datetime import datetime
app = FastAPI()
class ChatMessage(BaseModel):
message: str
session_id: str
history: List[Dict[str, str]] = []
class LeadCapture(BaseModel):
session_id: str
name: str
email: str
phone: str
case_summary: str
def init_chat_db():
conn = sqlite3.connect("chat_sessions.db")
conn.execute("""
CREATE TABLE IF NOT EXISTS chat_leads (
id INTEGER PRIMARY KEY AUTOINCREMENT,
session_id TEXT,
name TEXT,
email TEXT,
phone TEXT,
case_summary TEXT,
created_at TEXT
)
""")
conn.commit()
conn.close()
@app.post("/chat")
def chat(msg: ChatMessage):
response = get_legal_chat_response(msg.message, msg.history)
qualification = check_for_qualification(msg.message, response)
return {
"response": response,
"qualified": qualification["qualified"],
"capture_prompt": qualification.get("follow_up") if qualification["should_capture"] else None
}
@app.post("/chat/capture-lead")
def capture_lead(lead: LeadCapture):
conn = sqlite3.connect("chat_sessions.db")
conn.execute(
"INSERT INTO chat_leads (session_id, name, email, phone, case_summary, created_at) VALUES (?,?,?,?,?,?)",
(lead.session_id, lead.name, lead.email, lead.phone, lead.case_summary, datetime.utcnow().isoformat())
)
conn.commit()
conn.close()
return {"status": "captured", "message": "Thank you. An attorney will contact you within 24 hours."}
init_chat_db()
Step 5: Embed on Your Website
<div id="legal-chat" style="position:fixed;bottom:20px;right:20px;width:380px;">
<div id="chat-messages" style="height:400px;overflow-y:auto;padding:10px;background:#f9f9f9;border-radius:8px;"></div>
<input id="chat-input" type="text" placeholder="Ask a legal question..." style="width:100%;padding:10px;margin-top:5px;">
</div>
<script>
const history = [];
document.getElementById('chat-input').addEventListener('keypress', async (e) => {
if (e.key !== 'Enter') return;
const input = e.target;
const message = input.value;
input.value = '';
appendMessage('You', message);
history.push({role: 'user', content: message});
const res = await fetch('/chat', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({message, session_id: 'sess_' + Date.now(), history})
});
const data = await res.json();
appendMessage('Attorney Bot', data.response);
history.push({role: 'assistant', content: data.response});
});
function appendMessage(sender, text) {
const div = document.getElementById('chat-messages');
div.innerHTML += `<p><strong>${sender}:</strong> ${text}</p>`;
div.scrollTop = div.scrollHeight;
}
</script>
What to Build Next
Add after-hours routing. When the chatbot detects an urgent matter outside business hours, it captures the lead info and sends an immediate notification to the on-call attorney via SMS.
Related Reading
- Implementing Chatbots That Actually Help - chatbot design that works
- AI in Legal and Compliance - AI in law firms
- Lead Scoring with AI - qualifying leads automatically
Want this system built for your business?
Get a free assessment. We will map every system your business needs and show you the ROI.
Get Your Free Assessment