Skip to main content
This example demonstrates how to build a comprehensive Contract Analyzer Agent using Upsonic’s advanced features including custom ToolKits, KnowledgeBase integration, and session Memory.

Overview

The Contract Analyzer Agent is a production-ready example that showcases:
  1. Custom ToolKit — Specialized tools for extracting parties, dates, financial terms, and risks from contracts
  2. KnowledgeBase Integration — Legal reference information available as a searchable tool
  3. Session Memory — Conversation continuity with in-memory storage
  4. Configurable Settings — Dataclass-based configuration for easy customization
  5. Multiple Analysis Types — Full, summary, risk, extraction, and Q&A modes

Key Features

  • Structured Data Extraction: Extract parties, dates, financial terms, and obligations with pattern matching
  • Risk Assessment: Automatically identify high, medium, and low risk clauses
  • Executive Summaries: Generate quick overviews for business decision-makers
  • Legal Knowledge Base: Built-in legal terminology and clause reference information
  • API & Streamlit UI: Run as FastAPI server or interactive Streamlit app

Project Structure

Installation

Managing Dependencies

Sections: api, streamlit, development

Usage

Option 1: Run as API Server

Server starts at http://localhost:8000. API documentation at /docs. Example API call:

Option 2: Run Streamlit UI

Analysis Types

TypeDescription
fullComplete analysis with all extracted data
summaryExecutive summary for quick review
riskRisk assessment with recommendations
extractionStructured data extraction only
qaAnswer specific questions about the contract

Example Output

Streamlit UI

Contract Analyzer Streamlit UI

Sample Analysis Result

Complete Implementation

main.py

contract_analyzer/config.py

contract_analyzer/agent.py

""" if config is None: config = default_config session = config.get_session_id(session_id) memory = Memory( storage=InMemoryStorage(), session_id=session, full_session_memory=True ) tools: List[Any] = [] contract_toolkit = ContractAnalyzerToolKit() tools.append(contract_toolkit) if include_knowledge_base: kb = create_legal_knowledge_base(config) tools.append(kb) if additional_tools: tools.extend(additional_tools) agent = Agent( model=config.model, name=config.agent_name, role=config.agent_role, goal=config.agent_goal, system_prompt=config.system_prompt, memory=memory, tools=tools, debug=config.debug, show_tool_calls=True ) return agent def create_analysis_task( contract_text: str, analysis_type: str = “full”, specific_questions: Optional[List[str]] = None ) -> Task: """ Create a task for contract analysis. Args: contract_text: The contract text to analyze. analysis_type: Type of analysis:
  • “full”: Complete contract analysis
  • “summary”: Executive summary only
  • “risk”: Risk assessment focus
  • “extraction”: Data extraction only
  • “custom”: Custom questions specific_questions: Questions for “custom” analysis type.
Returns: A configured Task for the analysis. """ if analysis_type == “full”: description = f"""Perform a comprehensive analysis of the following contract: Please provide:
  1. Executive summary of the contract
  2. All parties involved and their roles
  3. Key dates (effective, termination, renewal)
  4. Financial terms and payment obligations
  5. Main obligations for each party
  6. Risk assessment with recommendations
If you need reference information about standard contract clauses or legal terminology, use the search tool to query the legal knowledge base.""" elif analysis_type == “summary”: description = f"""Provide an executive summary of the following contract: Focus on the key points a business executive would need to know for a quick review.""" elif analysis_type == “risk”: description = f"""Perform a risk assessment of the following contract: Identify:
  1. High-risk clauses requiring immediate attention
  2. Medium-risk items to review
  3. Unusual or non-standard terms
  4. Missing protective clauses
  5. Recommendations for negotiation
Use the legal knowledge base to reference standard risk indicators if needed.""" elif analysis_type == “extraction”: description = f"""Extract structured data from the following contract: Extract and organize:
  1. All parties (names, roles, entity types)
  2. All dates mentioned
  3. All financial terms and amounts
  4. All obligations for each party
Present the information in a structured format.""" elif analysis_type == “custom” and specific_questions: questions_formatted = “\n”.join(f”- ” for q in specific_questions) description = f"""Analyze the following contract to answer these specific questions: Provide detailed answers to each question.""" else: description = f"""Analyze the following contract: Provide a helpful analysis based on the content.""" return Task(description=description) async def analyze_contract_async( contract_text: str, analysis_type: str = “full”, config: Optional[ContractAnalyzerConfig] = None, session_id: Optional[str] = None ) -> str: """ Analyze a contract asynchronously. Convenience function that creates an agent and task, runs the analysis, and returns the result. Args: contract_text: The contract text to analyze. analysis_type: Type of analysis (“full”, “summary”, “risk”, “extraction”). config: Optional configuration settings. session_id: Optional session ID for memory continuity. Returns: The analysis result as a string. """ agent = create_contract_analyzer_agent(config=config, session_id=session_id) task = create_analysis_task(contract_text, analysis_type) result = await agent.do_async(task) return str(result) def analyze_contract( contract_text: str, analysis_type: str = “full”, config: Optional[ContractAnalyzerConfig] = None, session_id: Optional[str] = None ) -> str: """ Analyze a contract synchronously. Convenience function that creates an agent and task, runs the analysis, and returns the result. Args: contract_text: The contract text to analyze. analysis_type: Type of analysis (“full”, “summary”, “risk”, “extraction”). config: Optional configuration settings. session_id: Optional session ID for memory continuity. Returns: The analysis result as a string. """ agent = create_contract_analyzer_agent(config=config, session_id=session_id) task = create_analysis_task(contract_text, analysis_type) result = agent.do(task) return str(result)

contract_analyzer/knowledge/legal_kb.py

""" if config is None: config = default_config embedding_config = OpenAIEmbeddingConfig( model_name=“text-embedding-3-small” ) embedding_provider = OpenAIEmbedding(embedding_config) vectordb_path = Path(config.vectordb_path) vectordb_path.mkdir(parents=True, exist_ok=True) connection_config = ConnectionConfig( mode=Mode.EMBEDDED, db_path=str(vectordb_path) ) chroma_config = ChromaConfig( connection=connection_config, collection_name=config.collection_name, vector_size=config.vector_size, distance_metric=DistanceMetric.COSINE, index=HNSWIndexConfig() ) vectordb = ChromaProvider(config=chroma_config) sources = [] legal_templates_dir = config.knowledge_sources_dir if legal_templates_dir.exists(): for file_path in legal_templates_dir.glob(“.txt”): sources.append(str(file_path)) for file_path in legal_templates_dir.glob(“.md”): sources.append(str(file_path)) if additional_sources: sources.extend(additional_sources) if not sources: default_content = _get_default_legal_content() sources = [default_content] kb = KnowledgeBase( sources=sources, embedding_provider=embedding_provider, vectordb=vectordb, name=“Legal Contract References”, description=“A knowledge base containing legal contract terminology, ” “common clause types, red flags, and contract analysis best practices. ” “Search this when you need reference information about contract clauses, ” “legal terms, or standard contract provisions.”, topics=[“contract law”, “legal clauses”, “contract analysis”, “legal terminology”] ) return kb def _get_default_legal_content() -> str: """Get default legal reference content if no files are available.""" return """

Legal Contract Reference Guide

Common Contract Clauses

1. Indemnification Clause

An indemnification clause requires one party to compensate the other for certain damages or losses. Key considerations:
  • Scope of indemnification (what events trigger it)
  • Cap on liability
  • Whether indemnification is mutual or one-sided
  • Carve-outs and exceptions

2. Limitation of Liability

Limits the amount of damages a party can recover. Important aspects:
  • Types of damages excluded (consequential, punitive)
  • Cap amount (often tied to contract value)
  • Carve-outs for gross negligence or willful misconduct
  • RED FLAG: One-sided limitations or unlimited liability for one party

3. Termination Provisions

Defines how and when the contract can be ended. Consider:
  • Termination for cause vs. convenience
  • Notice requirements
  • Cure periods for breach
  • Effect of termination (survival clauses)
  • RED FLAG: Termination at will with no notice period

4. Confidentiality/Non-Disclosure

Protects sensitive information shared between parties. Key elements:
  • Definition of confidential information
  • Permitted disclosures
  • Duration of confidentiality obligation
  • Return or destruction of information

5. Intellectual Property Rights

Addresses ownership and licensing of IP. Important provisions:
  • Work product ownership
  • Pre-existing IP
  • License grants
  • Assignment rights

6. Warranties and Representations

Statements of fact or commitments about the subject matter. Types:
  • Express warranties
  • Implied warranties
  • Disclaimers
  • Warranty period

Red Flags in Contracts

High Risk Items

  1. Unlimited liability - No cap on potential damages
  2. One-sided indemnification - Only one party bears risk
  3. Automatic renewal without notice - Trapped in unfavorable terms
  4. Broad non-compete clauses - Excessive restrictions
  5. Waiver of jury trial - Giving up important rights
  6. Unfavorable governing law - Distant or unfamiliar jurisdiction

Medium Risk Items

  1. Short cure periods - Limited time to fix breaches
  2. Broad definition of confidential information
  3. Restrictive assignment clauses
  4. Mandatory arbitration - May limit remedies
  5. Most favored nation clauses - Pricing commitments

Items Requiring Attention

  1. Insurance requirements - Ensure compliance capability
  2. Audit rights - Consider operational impact
  3. Change of control provisions
  4. Force majeure scope
  5. Payment terms and late fees

Contract Analysis Best Practices

  1. Read the entire contract - Don’t skip sections
  2. Identify the parties - Verify legal names and authority
  3. Understand the scope - What exactly is being agreed to
  4. Check all dates - Effective, termination, renewal
  5. Review financial terms - All payments, fees, penalties
  6. Identify your obligations - What must you do
  7. Assess risk allocation - Who bears what risks
  8. Review termination rights - How can you exit
  9. Check governing law - Where disputes are resolved
  10. Seek legal counsel - For significant contracts
  • Force Majeure: Unforeseeable circumstances preventing contract fulfillment
  • Severability: Invalid provisions don’t void entire contract
  • Waiver: Giving up a right (usually requires writing)
  • Assignment: Transferring rights/obligations to another party
  • Novation: Replacing a party or obligation with consent
  • Material Breach: Significant violation justifying termination
  • Liquidated Damages: Pre-determined penalty amount
  • Good Faith: Acting honestly and fairly
  • Time is of the Essence: Deadlines are strictly enforced
  • Entire Agreement: Contract supersedes prior discussions """