Skip to main content

Overview

The AI Legal Agent Team is a Streamlit application that 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.

Tutorial Available

Follow our complete step-by-step tutorial to build this from scratch

Architecture

Multi-Agent Team Structure

The Legal Agent Team uses a coordinated team pattern with RAG (Retrieval-Augmented Generation) for document analysis:

Agent Roles

Role: Contract analysis specialistResponsibilities:
  • Review contracts thoroughly
  • Identify key terms and potential issues
  • Reference specific clauses from documents
  • Analyze obligations and liabilities
Tools:
  • Knowledge base search
  • Document reference
Model: GPT-4o
Role: Coordination and synthesisResponsibilities:
  • Coordinate analysis between team members
  • Provide comprehensive responses
  • Ensure all recommendations are properly sourced
  • Reference specific parts of uploaded documents
  • Delegate tasks to appropriate specialists
Model: GPT-4o

Implementation

from agno.agent import Agent
from agno.team import Team
from agno.models.openai import OpenAIChat
from agno.knowledge.knowledge import Knowledge
from agno.vectordb.qdrant import Qdrant
from agno.tools.duckduckgo import DuckDuckGoTools
from agno.knowledge.embedder.openai import OpenAIEmbedder

# Initialize Qdrant vector database
vector_db = Qdrant(
    collection="legal_documents",
    url=qdrant_url,
    api_key=qdrant_api_key,
    embedder=OpenAIEmbedder(
        id="text-embedding-3-small",
        api_key=openai_api_key
    )
)

# Create knowledge base
knowledge_base = Knowledge(vector_db=vector_db)
knowledge_base.add_content(path=document_path)

# Legal Researcher
legal_researcher = Agent(
    name="Legal Researcher",
    role="Legal research specialist",
    model=OpenAIChat(id="gpt-4o"),
    tools=[DuckDuckGoTools()],
    knowledge=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"
    ],
    markdown=True
)

# Contract Analyst
contract_analyst = Agent(
    name="Contract Analyst",
    role="Contract analysis specialist",
    model=OpenAIChat(id="gpt-4o"),
    knowledge=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
legal_strategist = Agent(
    name="Legal Strategist",
    role="Legal strategy specialist",
    model=OpenAIChat(id="gpt-4o"),
    knowledge=knowledge_base,
    search_knowledge=True,
    instructions=[
        "Develop comprehensive legal strategies",
        "Provide actionable recommendations",
        "Consider both risks and opportunities"
    ],
    markdown=True
)

# Legal Agent Team
legal_team = Team(
    name="Legal Team Lead",
    model=OpenAIChat(id="gpt-4o"),
    members=[legal_researcher, contract_analyst, legal_strategist],
    knowledge=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"
    ],
    markdown=True
)

Document Analysis Types

Contract Review

Performed by: Contract AnalystAnalysis includes:
  • Key terms identification
  • Obligations and responsibilities
  • Potential issues and risks
  • Clause-by-clause review
  • Liability assessment

Legal Research

Performed by: Legal ResearcherAnalysis includes:
  • Relevant case law
  • Legal precedents
  • Statutory references
  • Jurisdictional considerations
  • Citation summaries

Risk Assessment

Performed by: Contract Analyst + Legal StrategistAnalysis includes:
  • Legal risk identification
  • Liability exposure
  • Compliance gaps
  • Mitigation strategies
  • Risk prioritization

Compliance Check

Performed by: All AgentsAnalysis includes:
  • Regulatory compliance
  • Industry standards
  • Legal requirements
  • Best practices
  • Remediation steps

Key Features

RAG-Powered Analysis

1

Document Upload

User uploads PDF legal document through Streamlit interface
2

Embedding Creation

Document is chunked and embedded using OpenAI’s text-embedding-3-small model
3

Vector Storage

Embeddings stored in Qdrant vector database for semantic search
4

Knowledge Base

All agents have access to the knowledge base for document references
5

Semantic Search

Agents search knowledge base to find relevant document sections
6

Grounded Analysis

Analysis grounded in actual document content with specific citations

Team Coordination

# Query routing example
if analysis_type == "Contract Review":
    # Routes to Contract Analyst
    focus_agents = ["Contract Analyst"]
elif analysis_type == "Legal Research":
    # Routes to Legal Researcher
    focus_agents = ["Legal Researcher"]
elif analysis_type == "Risk Assessment":
    # Uses both Contract Analyst and Legal Strategist
    focus_agents = ["Contract Analyst", "Legal Strategist"]
else:
    # Uses all agents
    focus_agents = ["Legal Researcher", "Contract Analyst", "Legal Strategist"]

# Team Lead coordinates agent collaboration
response = legal_team.run(query)

Installation

1

Clone Repository

git clone https://github.com/Shubhamsaboo/awesome-llm-apps.git
cd advanced_ai_agents/multi_agent_apps/agent_teams/ai_legal_agent_team
2

Install Dependencies

pip install -r requirements.txt
Required packages:
  • agno>=2.2.10
  • streamlit
  • qdrant-client
  • openai
  • pypdf
  • duckduckgo-search
3

Configure API Keys

Get your API keys:
4

Run Application

streamlit run legal_agent_team.py

Usage Examples

Document: Employment AgreementQuery: “Review this employment contract”Contract Analyst Analysis:Key Terms Identified:
  • Employment term: 2 years (Section 2.1)
  • Compensation: $150,000 annual salary (Section 3.1)
  • Non-compete: 12 months post-termination (Section 8.2)
  • Confidentiality obligations (Section 9)
Potential Issues:
  • Non-compete clause may be overly broad
  • Termination provisions favor employer
  • Intellectual property assignment is comprehensive
Recommendations:
  • Negotiate narrower non-compete scope
  • Request severance provisions
  • Clarify IP rights for prior work
Document: Software License AgreementQuery: “Assess legal risks in this agreement”Contract Analyst + Legal Strategist Analysis:High Risk Items:
  1. Unlimited liability for data breaches (Section 12.3)
  2. Broad indemnification obligations (Section 11)
  3. Automatic renewal with difficult opt-out (Section 4.2)
Medium Risk Items:
  1. Unilateral modification rights (Section 15.1)
  2. Broad audit rights (Section 7.4)
Mitigation Strategies:
  • Cap liability at 12 months of fees
  • Limit indemnification to direct damages
  • Require 90-day renewal notice
  • Add mutual modification consent
Document: Data Processing AgreementQuery: “Check GDPR compliance”All Agents Analysis:Legal Researcher:
  • Reviews GDPR requirements (Articles 28, 32)
  • Checks relevant case law and guidance
  • Identifies applicable data protection laws
Contract Analyst:
  • Verifies required GDPR clauses present
  • Checks data subject rights provisions
  • Reviews security obligation specificity
Legal Strategist:
  • Assesses overall compliance posture
  • Identifies compliance gaps
  • Recommends remediation steps
Findings: ✅ Data processing purposes clearly defined ✅ Sub-processor provisions included ❌ Missing specific security measures (Article 32) ❌ Data subject rights procedures incomplete ⚠️ Data retention periods not specified

Technical Architecture

Vector Database Integration

from agno.vectordb.qdrant import Qdrant
from agno.knowledge.embedder.openai import OpenAIEmbedder

# Initialize Qdrant with OpenAI embeddings
vector_db = Qdrant(
    collection="legal_documents",
    url=qdrant_url,
    api_key=qdrant_api_key,
    embedder=OpenAIEmbedder(
        id="text-embedding-3-small",  # 1536 dimensions
        api_key=openai_api_key
    )
)

# Benefits:
# - Semantic search across documents
# - Efficient similarity matching
# - Scalable to large document sets
# - Fast retrieval (<100ms)
# Agents automatically search knowledge base
search_knowledge=True

# Search flow:
# 1. Agent receives query
# 2. Query embedded using same model
# 3. Semantic search in vector DB
# 4. Top relevant chunks retrieved
# 5. Chunks added to agent context
# 6. Agent generates grounded response

Multi-Tab Results

# Structured output in three tabs
tabs = st.tabs(["Analysis", "Key Points", "Recommendations"])

with tabs[0]:
    # Detailed analysis from team
    st.markdown(response.content)

with tabs[1]:
    # Extracted key points
    key_points = legal_team.run(
        f"Summarize key points from: {response.content}"
    )
    st.markdown(key_points.content)

with tabs[2]:
    # Strategic recommendations
    recommendations = legal_team.run(
        f"Provide key recommendations based on: {response.content}"
    )
    st.markdown(recommendations.content)

Best Practices

Document Preparation

  • Use clear, searchable PDFs
  • Ensure text is extractable (not scanned images)
  • Remove unnecessary pages
  • Organize multi-document reviews

Query Formulation

  • Be specific about what you need
  • Reference specific sections when applicable
  • Ask follow-up questions for clarity
  • Combine analysis types as needed

Result Interpretation

  • Review all three tabs (Analysis, Key Points, Recommendations)
  • Cross-reference with original document
  • Verify agent citations
  • Consider context and jurisdiction

Privacy & Security

  • Use private Qdrant instance
  • Review OpenAI data policies
  • Don’t upload highly sensitive documents
  • Clear data after analysis if needed
Important Legal Disclaimer:This application is a supportive tool and does not replace professional legal counsel.
  • Analysis is for informational purposes only
  • Not a substitute for licensed attorney advice
  • Always verify critical legal matters with qualified professionals
  • Consider jurisdiction-specific requirements
  • AI may miss nuanced legal issues

Advanced Features

Custom Query Mode

For specialized analysis beyond predefined types:
# Example custom queries
"Identify force majeure clauses and assess their scope"
"Compare this agreement's IP provisions with industry standards"
"Analyze dispute resolution mechanisms and suggest improvements"
"Review termination rights and assess balance between parties"

Multi-Document Analysis

# Process multiple related documents
documents = ["agreement.pdf", "amendment_1.pdf", "amendment_2.pdf"]

for doc in documents:
    knowledge_base.add_content(path=doc)

# Agents can now search across all documents
query = "Compare obligations across all amendments"

Performance Considerations

  • Document upload: ~5-10 seconds
  • Embedding creation: ~2-5 seconds per page
  • Vector storage: ~1-2 seconds
  • Agent analysis: ~30-60 seconds
  • Follow-up queries: ~20-30 seconds (cached embeddings)

Finance Agent Team

Financial analysis with agent teams

Game Design Team

Collaborative game design agents

Deep Research Agent

Comprehensive research capabilities

Build docs developers (and LLMs) love