Legal documents are notoriously complex, filled with specialized terminology, hidden risks, and critical obligations. Lawyers and legal professionals spend countless hours reviewing contracts, agreements, and other legal documents to identify key terms, assess risks, and summarize obligations. In this post, we'll build a Legal Document Analyzer using HazelJS that automates document parsing, term extraction, risk analysis, and obligation summarization.

The Problem

Legal document analysis presents several challenges:

  • Document Parsing: Extracting structure, key sections, and metadata from unstructured legal text
  • Term Extraction: Identifying legal terms and providing definitions with context
  • Risk Assessment: Identifying potential risks with severity levels and mitigation strategies
  • Obligation Tracking: Extracting obligations with deadlines and responsible parties

Our agent will address these challenges using HazelJS's multi-agent architecture, RAG-powered document search, and intelligent risk analysis.

Architecture Overview

The Legal Document Analyzer uses a multi-agent architecture where each agent specializes in a specific aspect of legal document analysis:

  • DocumentParserAgent: Parses legal documents to extract structure, key sections, and metadata
  • TermExtractorAgent: Extracts legal terms, definitions, and context from documents
  • RiskAnalyzerAgent: Analyzes legal documents for risks and provides mitigation strategies
  • ObligationSummarizerAgent: Summarizes legal obligations, deadlines, and responsible parties
  • LegalManagerAgent: Orchestrates the workflow using supervisor routing

This separation allows each agent to focus on its specialty while the supervisor ensures smooth coordination between them.

RAG-Powered Document Search

One of the key features of our agent is the ability to search through a database of legal documents using Retrieval-Augmented Generation (RAG). We maintain a knowledge base of legal documents with metadata including:

  • Category (contract, intellectual-property, employment, corporate, real-estate)
  • Risk type (liability, compliance, financial, operational, reputational)
  • Severity level (low, medium, high, critical)
  • Key clauses and provisions

When a legal professional asks about a document, the DocumentParserAgent uses semantic search to find relevant documents based on their query. For example, a query like "Find indemnification clauses in contracts" would return documents containing indemnification provisions.

The RAG implementation uses HazelJS's RAGPipeline with a MemoryVectorStore for efficient semantic search:

@Service()
export class LegalKnowledgeBaseService {
  private readonly embeddings = new LocalLegalEmbeddingProvider();
  private readonly vectorStore = new MemoryVectorStore(this.embeddings);
  private readonly rag = new RAGPipeline({
    vectorStore: this.vectorStore,
    embeddingProvider: this.embeddings,
    topK: 3,
  });

  async answer(query: string, topK = 3) {
    const sources = await this.search(query, topK);
    return {
      answer: sources.map((source) => source.content).join('\n\n'),
      sources: sources.map((source) => ({
        id: source.id,
        score: Number(source.score.toFixed(3)),
        category: source.metadata?.category,
        riskType: source.metadata?.riskType,
        severity: source.metadata?.severity,
      })),
    };
  }
}

Enter fullscreen mode Exit fullscreen mode

Intelligent Document Parsing

The DocumentParserAgent extracts structure and metadata from legal documents. It identifies:

  • Document type: Contract, agreement, NDA, employment, lease
  • Key sections: Preamble, terms and conditions, signatures
  • Key clauses: Indemnification, confidentiality, non-compete, force majeure, payment terms
  • Metadata: Presence of specific clauses, estimated complexity, word/character counts

This structured extraction provides a foundation for deeper analysis by other agents in the system.

Legal Term Extraction

The TermExtractorAgent identifies legal terms within documents and provides:

  • Term definitions: Clear explanations of legal terminology
  • Context: How the term is typically used in legal contexts
  • Category: Legal category (contract, intellectual-property, employment, etc.)
  • Cross-references: Related terms and concepts

This helps legal professionals quickly understand specialized language and ensures consistent interpretation across documents.

Risk Assessment

The RiskAnalyzerAgent analyzes documents for potential risks and provides:

  • Risk identification: Identifies liability, compliance, financial, operational, and reputational risks
  • Severity assessment: Rates risks as low, medium, high, or critical
  • Impact analysis: Describes the potential impact of each risk
  • Mitigation strategies: Provides actionable recommendations for addressing risks
  • Priority assignment: Suggests timeframes for addressing each risk

The agent calculates overall risk levels and provides comprehensive risk summaries, helping legal professionals prioritize their review efforts.

Obligation Summarization

The ObligationSummarizerAgent extracts and organizes obligations from legal documents:

  • Obligation types: Payment, delivery, performance, compliance, reporting
  • Deadlines: Specific timeframes for each obligation
  • Responsible parties: Identifies who is responsible for each obligation
  • Urgency assessment: Categorizes obligations by urgency
  • Timeline generation: Creates a chronological timeline of obligations

This systematic approach ensures that no obligations are overlooked and provides a clear roadmap for compliance.

Supervisor Routing

The LegalManagerAgent uses HazelJS's supervisor routing to coordinate between the specialist agents. When a legal professional makes a request, the supervisor analyzes the request and routes it to the appropriate specialist:

  • Document parsing requests go to DocumentParserAgent
  • Term extraction requests go to TermExtractorAgent
  • Risk analysis requests go to RiskAnalyzerAgent
  • Obligation summarization requests go to ObligationSummarizerAgent

The supervisor continues delegating until it has gathered enough information to provide a comprehensive legal analysis, then synthesizes the results into a cohesive report.

Production-Ready Features

Despite being a demo, the agent includes production-ready features:

  • Observability: OpenTelemetry integration for monitoring agent performance
  • Resilience: Retry logic and circuit breaker patterns for reliability
  • Rate limiting: Prevents abuse and ensures fair resource usage
  • Guardrails: PII redaction and content safety for secure document processing
  • Metrics: Built-in metrics for tracking agent performance

Running the Agent

The agent can be run with:

npm install
npm run build
npm run dev

Enter fullscreen mode Exit fullscreen mode

The app runs on http://localhost:3000 with the HazelJS Inspector available at /__hazel for real-time monitoring and debugging.

Try It Out

You can test the agent with a curl request:

curl -s -X POST http://localhost:3000/legal/supervisor \
  -H 'content-type: application/json' \
  -d '{"message":"Analyze this contract: Indemnification Clause: Party A agrees to indemnify and hold harmless Party B from any claims arising from negligence. Extract terms, analyze risks, and summarize obligations.","userId":"legal-analyst-1"}'

Enter fullscreen mode Exit fullscreen mode

The agent will analyze your request, parse the document, extract legal terms, identify risks, summarize obligations, and synthesize everything into a comprehensive legal analysis—all coordinated through the supervisor routing system.

Complete Project: Legal Document Analyzer
HazelJS Documentation: Docs

Key Takeaways

The Legal Document Analyzer demonstrates several key HazelJS capabilities:

  • Multi-agent architecture: Each agent specializes in a specific aspect of legal document analysis
  • RAG integration: Semantic search over legal document database
  • Supervisor routing: Intelligent delegation to specialist agents
  • Production-ready patterns: Observability, resilience, and guardrails
  • Local LLM provider: Deterministic behavior without requiring API keys

This agent shows how HazelJS can be used to build professional applications that solve complex domain-specific challenges while maintaining production-grade quality and reliability. The multi-agent approach makes it easy to extend the system with additional specialists (like compliance checkers or jurisdiction analyzers) as needed.