- unwind ai
- Posts
- Build an AI Legal Team run by AI Agents
Build an AI Legal Team run by AI Agents
Fully functional multi-agent app using GPT-4o, Agno and Qdrant (step-by-step instructions)
Legal document analysis is a fascinating as well as a complex domain where a team of legal experts traditionally work together to understand and interpret complex legal materials. Each team member brings their unique specialization - from contract analysts who dissect terms and conditions to strategists who develop comprehensive legal approaches.
But what if we could replicate this collaborative expertise using AI? By having multiple AI agents working together as a coordinated legal team, where just like their human counterparts, each agent specializes in a specific area of legal analysis.
In this tutorial, we'll bring this vision to life by creating a multi-agent AI legal team using OpenAI's GPT-4o, Agno, and Qdrant vector database. You'll build an AI application that mirrors a full-service legal team, where specialized AI agents collaborate just like their human counterparts - researching legal documents, analyzing contracts, and developing legal strategies - all working in concert to provide comprehensive legal insights.
We're using Agno, a powerful framework for building and orchestrating multiple AI agents, while Qdrant provides vector storage and retrieval for our document analysis needs.
What We’re Building
This Streamlit application simulates a full-service legal team using multiple AI agents to analyze legal documents and provide comprehensive legal insights. Each agent represents a different legal specialist role, from research and contract analysis to strategic planning, working together to provide thorough legal analysis and recommendations.
The AI Agent Team:
Legal Researcher - Equipped with DuckDuckGo search tool to find and cite relevant legal cases and precedents. Provides detailed research summaries with sources and references specific sections from uploaded documents.
Contract Analyst - Specializes in thorough contract review, identifying key terms, obligations, and potential issues. References specific clauses from documents for detailed analysis.
Legal Strategist - Focuses on developing comprehensive legal strategies, providing actionable recommendations while considering both risks and opportunities.
Team Lead - Coordinates analysis between team members, ensures comprehensive responses, properly sourced recommendations, and references to specific document parts. Acts as an Agent Team coordinator for all three agents.
How the App Works
Our application provides five distinct types of analysis, each activating different combinations of our specialized agents:
Analysis Types and Agent Deployment
Contract Review
Primary Agent: Contract Analyst
Focus: Detailed analysis of terms, conditions, obligations, and potential issues
Deliverables: Term breakdown, risk identification, and obligation summary
Legal Research
Primary Agent: Legal Researcher
Focus: Finding relevant cases, precedents, and legal context
Deliverables: Comprehensive research summary with citations and references
Risk Assessment
Active Agents: Legal Strategist, Contract Analyst
Focus: Identifying potential legal risks and liability exposure
Deliverables: Risk analysis report with mitigation strategies
Compliance Check
Active Agents: Legal Strategist, Legal Researcher, Contract Analyst
Focus: Comprehensive regulatory compliance analysis
Deliverables: Compliance status report with specific recommendations
Custom Queries
Active Agents: Full Legal Team (Legal Researcher, Legal Strategist, Contract Analyst)
Focus: Tailored analysis based on specific user questions
Deliverables: Customized reports addressing user's unique needs
Please note - The app:
Supports PDF documents only
Uses GPT-4o for analysis
Uses text-embedding-3-small for embeddings
Requires stable internet connection
API usage costs apply (OpenAI and Qdrant)
Prerequisites
Before we begin, make sure you have the following:
Python installed on your machine (version 3.10 or higher is recommended)
Your OpenAI and Qdrant API Key API key and URL from Qdrant Cloud
A code editor of your choice (we recommend VS Code or PyCharm for their excellent Python support)
Basic familiarity with Python programming
Step-by-Step Instructions
Setting Up the Environment
First, let's get our development environment ready:
Clone the GitHub repository:
git clone https://github.com/Shubhamsaboo/awesome-llm-apps.git
Go to the ai_legal_agent_team folder:
cd advanced_ai_agents/multi_agent_apps/agent_teams/ai_legal_agent_team
Install the required dependencies:
pip install -r requirements.txt
Configure API Keys:
Get OpenAI API key from OpenAI Platform
Get Qdrant API key and URL from Qdrant Cloud
Creating the Streamlit App
Let’s create our app. Create a new file legal_agent_team.py
and add the following code:
Import required libraries and setup:
import streamlit as st
from agno.agent import Agent
from agno.knowledge.pdf import PDFKnowledgeBase, PDFReader
from agno.vectordb.qdrant import Qdrant
from agno.tools.duckduckgo import DuckDuckGoTools
from agno.models.openai import OpenAIChat
from agno.embedder.openai import OpenAIEmbedder
import tempfile
import os
from agno.document.chunking.document import DocumentChunking
Initialize session state and configuration:
def init_session_state():
"""Initialize session state variables"""
if 'openai_api_key' not in st.session_state:
st.session_state.openai_api_key = None
if 'qdrant_api_key' not in st.session_state:
st.session_state.qdrant_api_key = None
if 'qdrant_url' not in st.session_state:
st.session_state.qdrant_url = None
if 'vector_db' not in st.session_state:
st.session_state.vector_db = None
if 'legal_team' not in st.session_state:
st.session_state.legal_team = None
if 'knowledge_base' not in st.session_state:
st.session_state.knowledge_base = None
if 'processed_files' not in st.session_state:
st.session_state.processed_files = set()
COLLECTION_NAME = "legal_documents"
Setting up our vector database connection with Qdrant:
def init_qdrant():
"""Initialize Qdrant client with configured settings."""
if not all([st.session_state.qdrant_api_key, st.session_state.qdrant_url]):
return None
try:
vector_db = Qdrant(
collection=COLLECTION_NAME,
url=st.session_state.qdrant_url,
api_key=st.session_state.qdrant_api_key,
embedder=OpenAIEmbedder(
id="text-embedding-3-small",
api_key=st.session_state.openai_api_key
)
)
return vector_db
except Exception as e:
st.error(f"🔴 Qdrant connection failed: {str(e)}")
return None
Time for document processing:
def process_document(uploaded_file, vector_db: Qdrant):
"""Process document, create embeddings and store in Qdrant vector database"""
if not st.session_state.openai_api_key:
raise ValueError("OpenAI API key not provided")
os.environ['OPENAI_API_KEY'] = st.session_state.openai_api_key
try:
with tempfile.NamedTemporaryFile(delete=False, suffix='.pdf') as temp_file:
temp_file.write(uploaded_file.getvalue())
temp_file_path = temp_file.name
st.info("Loading and processing document...")
knowledge_base = PDFKnowledgeBase(
path=temp_file_path,
vector_db=vector_db,
reader=PDFReader(),
chunking_strategy=DocumentChunking(
chunk_size=1000,
overlap=200
)
)
with st.spinner('📤 Loading documents into knowledge base...'):
knowledge_base.load(recreate=True, upsert=True)
st.success("✅ Documents stored successfully!")
os.unlink(temp_file_path)
return knowledge_base
except Exception as e:
st.error(f"Document processing error: {str(e)}")
raise Exception(f"Error processing document: {str(e)}")
Create specialized legal agents:
# Initialize agents within the document processing
legal_researcher = Agent(
name="Legal Researcher",
role="Legal research specialist",
model=OpenAIChat(id="gpt-4"),
tools=[DuckDuckGoTools()],
knowledge=st.session_state.knowledge_base,
search_knowledge=True,
instructions=[
"Find and cite relevant legal cases and precedents",
"Provide detailed research summaries with sources",
"Reference specific sections from the uploaded document",
"Always search the knowledge base for relevant information"
],
show_tool_calls=True,
markdown=True
)
contract_analyst = Agent(
name="Contract Analyst",
role="Contract analysis specialist",
model=OpenAIChat(id="gpt-4"),
knowledge=st.session_state.knowledge_base,
search_knowledge=True,
instructions=[
"Review contracts thoroughly",
"Identify key terms and potential issues",
"Reference specific clauses from the document"
],
markdown=True
)
legal_strategist = Agent(
name="Legal Strategist",
role="Legal strategy specialist",
model=OpenAIChat(id="gpt-4"),
knowledge=st.session_state.knowledge_base,
search_knowledge=True,
instructions=[
"Develop comprehensive legal strategies",
"Provide actionable recommendations",
"Consider both risks and opportunities"
],
markdown=True
)
Create the agent team coordinator:
st.session_state.legal_team = Agent(
name="Legal Team Lead",
role="Legal team coordinator",
model=OpenAIChat(id="gpt-4"),
team=[legal_researcher, contract_analyst, legal_strategist],
knowledge=st.session_state.knowledge_base,
search_knowledge=True,
instructions=[
"Coordinate analysis between team members",
"Provide comprehensive responses",
"Ensure all recommendations are properly sourced",
"Reference specific parts of the uploaded document",
"Always search the knowledge base before delegating tasks"
],
show_tool_calls=True,
markdown=True
)
Build the Streamlit interface:
def main():
st.set_page_config(page_title="Legal Document Analyzer", layout="wide")
init_session_state()
st.title("AI Legal Agent Team 👨⚖️")
with st.sidebar:
st.header("🔑 API Configuration")
openai_key = st.text_input("OpenAI API Key", type="password")
if openai_key:
st.session_state.openai_api_key = openai_key
qdrant_key = st.text_input("Qdrant API Key", type="password")
if qdrant_key:
st.session_state.qdrant_api_key = qdrant_key
qdrant_url = st.text_input("Qdrant URL")
if qdrant_url:
st.session_state.qdrant_url = qdrant_url
Implement analysis workflows:
analysis_configs = {
"Contract Review": {
"query": "Review this contract and identify key terms, obligations, and potential issues.",
"agents": ["Contract Analyst"],
"description": "Detailed contract analysis focusing on terms and obligations"
},
"Legal Research": {
"query": "Research relevant cases and precedents related to this document.",
"agents": ["Legal Researcher"],
"description": "Research on relevant legal cases and precedents"
},
"Risk Assessment": {
"query": "Analyze potential legal risks and liabilities in this document.",
"agents": ["Contract Analyst", "Legal Strategist"],
"description": "Combined risk analysis and strategic assessment"
},
"Compliance Check": {
"query": "Check this document for regulatory compliance issues.",
"agents": ["Legal Researcher", "Contract Analyst", "Legal Strategist"],
"description": "Comprehensive compliance analysis"
},
"Custom Query": {
"query": None,
"agents": ["Legal Researcher", "Contract Analyst", "Legal Strategist"],
"description": "Custom analysis using all available agents"
}
}
Running the App
With our code in place, it's time to launch the app.
In your terminal, navigate to the project folder, and run the following command
streamlit run legal_agent_team.py
Streamlit will provide a local URL (typically http://localhost:8501).
Working Application Demo
Conclusion
Congratulations! You've successfully built a sophisticated AI legal analysis system that replicates the collaborative dynamics of a human legal team.
As you continue developing your AI legal team, consider these powerful enhancements:
Enable side-by-side analysis of multiple legal documents
Track changes and variations between contract versions
Implement case history tracking
Create executive summaries for different audience types
Add jurisdiction-specific compliance checks
Keep experimenting and refining to build smarter AI solutions!
We share hands-on tutorials like this 2-3 times a week, to help you stay ahead in the world of AI. If you're serious about leveling up your AI skills and staying ahead of the curve, subscribe now and be the first to access our latest tutorials.
Reply