<metadata>
purpose: Advanced lesson on building domain-specific agents for maximum effectiveness
type: educational-content
course: tactical-ai-consulting
lesson: 11
topic: domain-specific-agents
category: agentic-horizon
last-updated: 2025-09-30
</metadata>

<overview>
Lesson 11 explores the advanced practice of creating domain-specific AI agents that understand business logic, domain constraints, and specialized workflows. This represents the evolution from generic AI assistance to expert-level automation tailored to specific industries and use cases.
</overview>

# Lesson 11: Building Domain-Specific Agents

## The Domain Agent Paradigm

### From General to Specialized

```
EVOLUTION OF AI AGENTS

┌─────────────────────────────────────────────────┐
│  PHASE 1: Generic AI Assistant                  │
│  - Tries to help with everything                │
│  - No domain knowledge                          │
│  - Generic responses                            │
│  - Limited effectiveness                        │
└─────────────────────────────────────────────────┘
                      ↓
┌─────────────────────────────────────────────────┐
│  PHASE 2: Task-Specific Agents                  │
│  - Focused on specific tasks                    │
│  - Basic domain understanding                   │
│  - Improved consistency                         │
│  - Better results in narrow scope               │
└─────────────────────────────────────────────────┘
                      ↓
┌─────────────────────────────────────────────────┐
│  PHASE 3: Domain-Specific Agents (OPTIMAL)      │
│  - Deep domain expertise                        │
│  - Business logic understanding                 │
│  - Industry-specific workflows                  │
│  - Maximum effectiveness                        │
└─────────────────────────────────────────────────┘
```

### What Makes an Agent "Domain-Specific"?

**Core Characteristics:**

1. **Domain Knowledge**: Deep understanding of industry concepts, terminology, regulations
2. **Business Logic**: Encoded rules, constraints, and workflows specific to domain
3. **Specialized Tools**: Custom tooling for domain-specific operations
4. **Context Awareness**: Understanding of domain-specific context and implications
5. **Expert Decision Making**: Ability to make informed decisions using domain expertise

**Example Comparison:**

| Generic Agent | Domain-Specific Agent (FinTech) |
|---------------|--------------------------------|
| "Validate this input" | "Validate account number per ISO 13616 IBAN standard" |
| "Check for errors" | "Verify PCI-DSS compliance and flag any card data in logs" |
| "Process this data" | "Execute KYC verification workflow per AML regulations" |
| "Generate report" | "Create SOX-compliant audit trail report" |

## Domain Agent Architecture

### Architectural Components

```xml
<domain-agent>
  <identity>
    <domain>Healthcare</domain>
    <specialty>HIPAA Compliance Automation</specialty>
    <expertise>
      - HIPAA Privacy Rule
      - HIPAA Security Rule
      - ePHI handling requirements
      - Breach notification procedures
      - Risk assessment frameworks
    </expertise>
  </identity>

  <knowledge-base>
    <regulations>
      - HIPAA Privacy Rule (45 CFR 160, 164)
      - HITECH Act requirements
      - State-specific privacy laws
    </regulations>

    <standards>
      - NIST 800-66 (HIPAA Security)
      - HL7 FHIR standards
      - ICD-10/CPT coding systems
    </standards>

    <business-logic>
      - Minimum necessary rule
      - Patient consent workflows
      - Access control matrices
      - Audit logging requirements
    </business-logic>
  </knowledge-base>

  <capabilities>
    <assessment>
      - Scan code for ePHI exposure
      - Verify encryption implementation
      - Check access controls
      - Validate audit logging
    </assessment>

    <enforcement>
      - Block non-compliant deployments
      - Enforce encryption policies
      - Require authorization checks
      - Mandate audit trails
    </enforcement>

    <remediation>
      - Suggest compliant alternatives
      - Generate compliance documentation
      - Create risk mitigation plans
      - Produce audit reports
    </remediation>
  </capabilities>

  <interfaces>
    <input>
      - Code repositories
      - Infrastructure configs
      - Database schemas
      - API specifications
    </input>

    <output>
      - Compliance reports
      - Risk assessments
      - Remediation guidance
      - Audit documentation
    </output>
  </interfaces>
</domain-agent>
```

### Domain Knowledge Encoding

**Method 1: Rule-Based Knowledge**

```python
class HealthcareComplianceAgent:
    """Domain-specific agent for HIPAA compliance"""

    # Domain-specific constants
    EPHI_IDENTIFIERS = [
        "patient_id", "medical_record_number", "ssn",
        "date_of_birth", "diagnosis", "prescription"
    ]

    REQUIRED_ENCRYPTION = ["AES-256-GCM", "RSA-2048+"]

    MINIMUM_AUDIT_FIELDS = [
        "user_id", "action", "timestamp", "resource_accessed",
        "result", "ip_address"
    ]

    def __init__(self):
        self.regulations = self._load_hipaa_rules()
        self.risk_matrix = self._load_risk_framework()

    def assess_data_access(self, code_path: str) -> ComplianceReport:
        """Assess code for HIPAA-compliant data access"""

        findings = []

        # Rule: All ePHI access must have authorization check
        ephi_access = self._find_ephi_access(code_path)
        for access in ephi_access:
            if not self._has_authorization_check(access):
                findings.append({
                    "rule": "HIPAA Privacy Rule 164.502(a)",
                    "severity": "critical",
                    "violation": "ePHI access without authorization",
                    "location": access.location,
                    "ephi_type": access.data_type,
                    "remediation": self._generate_auth_implementation(access)
                })

        # Rule: ePHI must be encrypted at rest
        storage = self._find_data_storage(code_path)
        for store in storage:
            if store.contains_ephi and not store.encrypted:
                findings.append({
                    "rule": "HIPAA Security Rule 164.312(a)(2)(iv)",
                    "severity": "critical",
                    "violation": "Unencrypted ePHI storage",
                    "remediation": self._generate_encryption_implementation(store)
                })

        # Rule: All ePHI access must be audited
        operations = self._find_ephi_operations(code_path)
        for op in operations:
            if not self._has_audit_logging(op):
                findings.append({
                    "rule": "HIPAA Security Rule 164.312(b)",
                    "severity": "high",
                    "violation": "ePHI access not logged",
                    "remediation": self._generate_audit_implementation(op)
                })

        return self._generate_compliance_report(findings)

    def _generate_auth_implementation(self, access) -> str:
        """Generate domain-specific authorization code"""
        return f"""
// HIPAA-Compliant Authorization Check
async function access{access.resource}(userId, resourceId) {{
    // 1. Verify user has valid credentials
    const user = await authenticateUser(userId);
    if (!user) throw new UnauthorizedError();

    // 2. Check role-based access (RBAC)
    const hasRole = await checkRolePermission(user.role, '{access.resource}');
    if (!hasRole) throw new ForbiddenError();

    // 3. Verify patient consent (if applicable)
    if (requiresPatientConsent('{access.resource}')) {{
        const consent = await verifyPatientConsent(resourceId, userId);
        if (!consent.granted) throw new ConsentRequiredError();
    }}

    // 4. Apply minimum necessary rule
    const allowedFields = getMinimumNecessaryFields(user.role, user.purpose);

    // 5. Audit the access
    await logEphiAccess({{
        userId: user.id,
        action: 'READ',
        resource: '{access.resource}',
        resourceId: resourceId,
        timestamp: new Date(),
        result: 'SUCCESS'
    }});

    // 6. Return filtered data
    return await fetchData(resourceId, allowedFields);
}}
"""
```

**Method 2: Constraint-Based Knowledge**

```python
class FinTechComplianceAgent:
    """Domain agent for financial services compliance"""

    def __init__(self):
        # Domain constraints
        self.constraints = {
            "pci_dss": PCIDSSConstraints(),
            "sox": SOXConstraints(),
            "aml": AMLConstraints(),
            "kyc": KYCConstraints()
        }

    class PCIDSSConstraints:
        """PCI-DSS specific constraints"""

        PROHIBITED_STORAGE = [
            "full_track_data",
            "card_verification_code",
            "pin_block"
        ]

        REQUIRED_CONTROLS = {
            "cardholder_data": {
                "encryption": "AES-256",
                "key_rotation": "90_days",
                "access_control": "role_based",
                "audit_logging": "all_access"
            }
        }

        def validate_payment_handler(self, code):
            """Validate payment processing code"""
            violations = []

            # Constraint: Never store CVV
            if self._stores_cvv(code):
                violations.append({
                    "standard": "PCI-DSS 3.2",
                    "requirement": "3.2.2",
                    "severity": "critical",
                    "violation": "CVV storage prohibited",
                    "consequence": "Immediate PCI compliance failure"
                })

            # Constraint: Cardholder data must be encrypted
            card_data = self._find_card_data_storage(code)
            for data in card_data:
                if not self._uses_encryption(data, "AES-256"):
                    violations.append({
                        "requirement": "3.4",
                        "violation": "Unencrypted cardholder data"
                    })

            # Constraint: Strong cryptography required
            crypto_usage = self._find_crypto_usage(code)
            for crypto in crypto_usage:
                if crypto.algorithm in ["DES", "MD5", "SHA1"]:
                    violations.append({
                        "requirement": "4.1",
                        "violation": f"Weak algorithm: {crypto.algorithm}",
                        "required": "Use AES-256 or RSA-2048+"
                    })

            return violations
```

**Method 3: Workflow-Based Knowledge**

```python
class LegalDocumentAgent:
    """Domain agent for legal document processing"""

    def __init__(self):
        self.workflows = self._load_legal_workflows()
        self.precedents = self._load_case_law_db()

    def process_contract(self, contract_text: str, contract_type: str):
        """Process contract using domain-specific workflow"""

        workflow = self.workflows[contract_type]

        for step in workflow.steps:
            result = step.execute(contract_text)
            if not result.valid:
                return self._handle_workflow_failure(step, result)

        return self._generate_approval_package(contract_text, workflow.results)

    def _load_legal_workflows(self):
        """Load domain-specific legal workflows"""
        return {
            "nda": NDAReviewWorkflow(),
            "employment": EmploymentContractWorkflow(),
            "vendor": VendorAgreementWorkflow()
        }

class NDAReviewWorkflow:
    """Workflow for reviewing Non-Disclosure Agreements"""

    steps = [
        IdentifyPartiesStep(),
        VerifyDefinitionsStep(),
        AssessConfidentialityScope(),
        CheckExclusionsStep(),
        VerifyTermDurationStep(),
        AssessLiabilityClausesStep(),
        CheckJurisdictionStep(),
        ReviewTerminationProvisionsStep()
    ]

    def execute(self, contract_text):
        """Execute NDA review workflow"""
        results = {}

        for step in self.steps:
            result = step.analyze(contract_text)
            results[step.name] = result

            if result.risk_level == "high":
                results["recommendation"] = "Reject - High risk"
                results["negotiation_points"] = result.issues
                break

        return results

class VerifyDefinitionsStep:
    """Verify critical legal definitions are present and clear"""

    REQUIRED_DEFINITIONS = [
        "Confidential Information",
        "Purpose",
        "Disclosing Party",
        "Receiving Party"
    ]

    def analyze(self, contract_text):
        """Check that all required definitions exist and are clear"""

        definitions = self._extract_definitions(contract_text)

        issues = []
        for required in self.REQUIRED_DEFINITIONS:
            if required not in definitions:
                issues.append({
                    "type": "missing_definition",
                    "term": required,
                    "risk": "high",
                    "explanation": f"'{required}' must be clearly defined"
                })
            elif self._is_definition_vague(definitions[required]):
                issues.append({
                    "type": "vague_definition",
                    "term": required,
                    "risk": "medium",
                    "explanation": f"Definition of '{required}' is too broad"
                })

        return StepResult(
            valid=len(issues) == 0,
            issues=issues,
            risk_level=self._calculate_risk(issues)
        )
```

## Building Domain-Specific Agents

### Step-by-Step Process

**Step 1: Domain Analysis**

```yaml
domain-analysis:
  domain: E-commerce

  key-concepts:
    - Inventory management
    - Order fulfillment
    - Payment processing
    - Shipping logistics
    - Customer service
    - Returns/refunds

  regulations:
    - PCI-DSS (payment security)
    - GDPR/CCPA (customer data)
    - Consumer protection laws
    - Tax compliance

  common-workflows:
    - Order placement
    - Payment authorization
    - Inventory allocation
    - Shipping coordination
    - Return processing

  pain-points:
    - Overselling (inventory sync)
    - Failed payments
    - Shipping delays
    - Fraudulent orders
    - Return abuse

  success-metrics:
    - Order fulfillment rate
    - Payment success rate
    - Time to ship
    - Return rate
    - Customer satisfaction
```

**Step 2: Expertise Codification**

Encode domain expertise into structured knowledge:

```python
class EcommerceAgent:
    """Domain agent for e-commerce operations"""

    def __init__(self):
        self.domain_knowledge = {
            "inventory": InventoryExpertise(),
            "fraud": FraudDetectionExpertise(),
            "shipping": ShippingExpertise(),
            "pricing": PricingExpertise()
        }

    class InventoryExpertise:
        """Inventory management domain knowledge"""

        # Domain rule: Safety stock levels
        def calculate_safety_stock(self, product):
            """Calculate safety stock using domain formulas"""

            # Domain formula: Safety Stock = Z × σ × √L
            # Z = service level factor
            # σ = demand standard deviation
            # L = lead time

            z_score = self._get_service_level_factor(product.priority)
            demand_std = self._calculate_demand_variance(product)
            lead_time = self._get_supplier_lead_time(product.supplier)

            safety_stock = z_score * demand_std * math.sqrt(lead_time)

            return {
                "safety_stock": math.ceil(safety_stock),
                "reorder_point": safety_stock + (demand_std * lead_time),
                "confidence": self._calculate_confidence(demand_std)
            }

        # Domain rule: Overselling prevention
        def validate_order(self, product_id, quantity):
            """Validate order against inventory rules"""

            # Get current available inventory
            available = self._get_available_inventory(product_id)

            # Account for pending orders (domain-specific logic)
            pending = self._get_pending_allocations(product_id)

            # Apply safety stock rule
            safety = self._get_safety_stock(product_id)

            # Effective available = actual - pending - safety
            effective_available = available - pending - safety

            if quantity > effective_available:
                return ValidationResult(
                    valid=False,
                    reason="Insufficient inventory",
                    available=effective_available,
                    requested=quantity,
                    recommendation=self._suggest_alternatives(product_id)
                )

            return ValidationResult(valid=True)

    class FraudDetectionExpertise:
        """Fraud detection domain knowledge"""

        # Domain knowledge: Fraud indicators
        FRAUD_SIGNALS = {
            "velocity": {
                "orders_per_hour": 5,
                "cards_per_day": 3,
                "addresses_per_week": 5
            },
            "mismatches": [
                "billing_shipping_mismatch",
                "ip_location_mismatch",
                "email_domain_suspicious"
            ],
            "high_risk": {
                "first_order_high_value": 500,
                "multiple_failed_payments": 3,
                "unusual_quantity": 10
            }
        }

        def assess_order_risk(self, order):
            """Assess fraud risk using domain expertise"""

            risk_score = 0
            signals = []

            # Check velocity patterns
            velocity = self._check_velocity(order.customer_id)
            if velocity.orders_per_hour > self.FRAUD_SIGNALS["velocity"]["orders_per_hour"]:
                risk_score += 40
                signals.append("high_velocity_orders")

            # Check mismatches
            if order.billing_address != order.shipping_address:
                if self._is_high_risk_mismatch(order.billing_address, order.shipping_address):
                    risk_score += 30
                    signals.append("suspicious_address_mismatch")

            # Check first-order patterns
            if self._is_first_order(order.customer_id):
                if order.total > self.FRAUD_SIGNALS["high_risk"]["first_order_high_value"]:
                    risk_score += 25
                    signals.append("high_value_first_order")

            # Domain-specific: Check product mix
            if self._is_suspicious_product_mix(order.items):
                risk_score += 20
                signals.append("suspicious_product_mix")

            return RiskAssessment(
                score=risk_score,
                level=self._risk_level(risk_score),
                signals=signals,
                recommendation=self._fraud_recommendation(risk_score)
            )

        def _fraud_recommendation(self, risk_score):
            """Domain-specific fraud handling recommendation"""
            if risk_score >= 70:
                return "block_order"
            elif risk_score >= 40:
                return "require_verification"
            elif risk_score >= 20:
                return "flag_for_review"
            else:
                return "approve"
```

**Step 3: Tool Integration**

Provide domain-specific tools:

```python
class EcommerceDomainTools:
    """Specialized tools for e-commerce domain agent"""

    def __init__(self):
        self.payment_gateway = StripeIntegration()
        self.shipping_api = ShipStationIntegration()
        self.inventory_db = InventoryDatabase()
        self.fraud_service = FraudCheckService()

    def check_inventory_availability(self, sku: str, quantity: int) -> dict:
        """Domain tool: Check real-time inventory"""

        return self.inventory_db.query("""
            SELECT
                available_quantity,
                reserved_quantity,
                safety_stock,
                next_restock_date
            FROM inventory
            WHERE sku = %s
        """, (sku,))

    def calculate_shipping_cost(self, order: dict) -> dict:
        """Domain tool: Calculate accurate shipping costs"""

        # Domain logic: Consider weight, dimensions, destination
        package = self._calculate_package_requirements(order.items)

        return self.shipping_api.get_rates(
            from_zip=order.warehouse_zip,
            to_zip=order.shipping_zip,
            weight=package.weight,
            dimensions=package.dimensions,
            service_level=order.shipping_speed
        )

    def authorize_payment(self, payment_info: dict) -> dict:
        """Domain tool: Process payment authorization"""

        # Domain logic: Pre-authorization for inventory hold
        return self.payment_gateway.authorize(
            amount=payment_info.amount,
            currency=payment_info.currency,
            payment_method=payment_info.method,
            capture=False,  # Don't capture until shipment
            metadata={
                "order_id": payment_info.order_id,
                "inventory_reserved": True
            }
        )
```

**Step 4: Workflow Implementation**

Implement domain-specific workflows:

```python
class OrderFulfillmentWorkflow:
    """E-commerce order fulfillment workflow"""

    def __init__(self, agent: EcommerceAgent):
        self.agent = agent
        self.tools = agent.tools

    async def process_order(self, order_data: dict) -> WorkflowResult:
        """Execute complete order fulfillment workflow"""

        workflow_state = WorkflowState(order_data)

        try:
            # Step 1: Fraud check (domain-specific)
            fraud_result = await self._check_fraud(workflow_state)
            if fraud_result.risk_level == "high":
                return self._reject_order(workflow_state, "fraud_risk")

            # Step 2: Inventory validation (domain-specific)
            inventory_result = await self._validate_inventory(workflow_state)
            if not inventory_result.available:
                return self._handle_out_of_stock(workflow_state)

            # Step 3: Payment authorization
            payment_result = await self._authorize_payment(workflow_state)
            if not payment_result.success:
                return self._handle_payment_failure(workflow_state)

            # Step 4: Reserve inventory (domain-critical)
            reservation = await self._reserve_inventory(workflow_state)
            workflow_state.inventory_reserved = True

            # Step 5: Calculate shipping
            shipping = await self._calculate_shipping(workflow_state)
            workflow_state.shipping_cost = shipping.cost

            # Step 6: Create fulfillment order
            fulfillment = await self._create_fulfillment_order(workflow_state)

            # Step 7: Capture payment (domain timing)
            capture = await self._capture_payment(workflow_state)

            return WorkflowResult(
                success=True,
                order_id=workflow_state.order_id,
                fulfillment_id=fulfillment.id,
                estimated_ship_date=fulfillment.estimated_ship
            )

        except Exception as e:
            # Domain-specific rollback
            await self._rollback_workflow(workflow_state)
            return WorkflowResult(
                success=False,
                error=str(e),
                state=workflow_state.to_dict()
            )

    async def _validate_inventory(self, state):
        """Validate inventory with domain rules"""

        results = []

        for item in state.order_items:
            # Check availability with safety stock
            available = self.tools.check_inventory_availability(
                sku=item.sku,
                quantity=item.quantity
            )

            # Domain rule: Don't sell below safety stock
            effective_available = (
                available.available_quantity -
                available.reserved_quantity -
                available.safety_stock
            )

            if item.quantity > effective_available:
                results.append({
                    "sku": item.sku,
                    "requested": item.quantity,
                    "available": effective_available,
                    "next_restock": available.next_restock_date
                })

        return InventoryValidation(
            available=len(results) == 0,
            shortages=results
        )
```

## Domain Agent Examples

### Example 1: Healthcare Diagnosis Assistant

```python
class DiagnosisAssistantAgent:
    """Domain agent for clinical diagnosis assistance"""

    def __init__(self):
        self.knowledge = MedicalKnowledgeBase()
        self.icd10 = ICD10Database()
        self.drug_interactions = DrugInteractionDB()

    def analyze_symptoms(self, patient_data: dict) -> DiagnosisReport:
        """Analyze symptoms using medical domain knowledge"""

        # Domain-specific symptom analysis
        symptom_clusters = self._identify_symptom_clusters(
            patient_data.symptoms
        )

        # Apply clinical reasoning
        differential_diagnoses = []

        for cluster in symptom_clusters:
            # Domain knowledge: Common diagnoses for symptom patterns
            possible_conditions = self.knowledge.query_by_symptoms(
                symptoms=cluster.symptoms,
                patient_age=patient_data.age,
                patient_sex=patient_data.sex,
                medical_history=patient_data.history
            )

            # Score each possibility
            for condition in possible_conditions:
                score = self._calculate_diagnostic_probability(
                    condition=condition,
                    symptoms=cluster.symptoms,
                    patient=patient_data
                )

                if score > 0.3:  # Clinical threshold
                    differential_diagnoses.append({
                        "condition": condition.name,
                        "icd10": condition.icd10_code,
                        "probability": score,
                        "reasoning": self._generate_clinical_reasoning(
                            condition, patient_data
                        ),
                        "recommended_tests": condition.diagnostic_tests,
                        "red_flags": self._check_red_flags(condition, patient_data)
                    })

        # Sort by probability
        differential_diagnoses.sort(key=lambda x: x["probability"], reverse=True)

        return DiagnosisReport(
            primary_consideration=differential_diagnoses[0] if differential_diagnoses else None,
            differential_diagnoses=differential_diagnoses,
            recommended_workup=self._recommend_diagnostic_workup(differential_diagnoses),
            urgency_level=self._assess_urgency(patient_data, differential_diagnoses),
            clinical_notes=self._generate_clinical_notes(patient_data, differential_diagnoses)
        )

    def _calculate_diagnostic_probability(self, condition, symptoms, patient):
        """Calculate likelihood using Bayesian reasoning"""

        # Start with prior probability (domain knowledge)
        prior = self.knowledge.get_prevalence(
            condition=condition,
            age=patient.age,
            sex=patient.sex
        )

        # Update with symptom likelihoods
        likelihood = 1.0
        for symptom in symptoms:
            symptom_likelihood = self.knowledge.get_symptom_likelihood(
                condition=condition,
                symptom=symptom
            )
            likelihood *= symptom_likelihood

        # Bayesian update
        posterior = (likelihood * prior) / self._calculate_marginal(symptoms)

        return posterior
```

### Example 2: Legal Contract Analyzer

```python
class ContractAnalyzerAgent:
    """Domain agent for legal contract analysis"""

    def __init__(self):
        self.precedents = CaseLawDatabase()
        self.statutes = StatutoryDatabase()
        self.contract_templates = TemplateLibrary()

    def analyze_contract(self, contract_text: str, jurisdiction: str) -> ContractAnalysis:
        """Analyze contract using legal domain knowledge"""

        # Parse contract structure
        contract_structure = self._parse_contract_structure(contract_text)

        # Identify parties and obligations
        parties = self._identify_parties(contract_structure)
        obligations = self._extract_obligations(contract_structure)

        # Analyze each clause
        clause_analysis = []

        for clause in contract_structure.clauses:
            analysis = self._analyze_clause(
                clause=clause,
                jurisdiction=jurisdiction,
                parties=parties
            )
            clause_analysis.append(analysis)

        # Check for missing critical clauses
        missing_clauses = self._check_for_missing_clauses(
            contract_structure,
            contract_type=contract_structure.type
        )

        # Assess risk factors
        risk_assessment = self._assess_contract_risks(
            clauses=clause_analysis,
            missing=missing_clauses,
            jurisdiction=jurisdiction
        )

        return ContractAnalysis(
            parties=parties,
            obligations=obligations,
            clause_analysis=clause_analysis,
            missing_clauses=missing_clauses,
            risk_assessment=risk_assessment,
            recommendations=self._generate_recommendations(
                analysis=clause_analysis,
                risks=risk_assessment
            )
        )

    def _analyze_clause(self, clause, jurisdiction, parties):
        """Deep analysis of individual clause"""

        # Classify clause type (domain knowledge)
        clause_type = self._classify_clause(clause.text)

        # Check enforceability
        enforceability = self._check_enforceability(
            clause=clause,
            jurisdiction=jurisdiction,
            clause_type=clause_type
        )

        # Find relevant case law
        relevant_cases = self.precedents.search(
            clause_type=clause_type,
            jurisdiction=jurisdiction,
            keywords=clause.keywords
        )

        # Assess fairness
        fairness = self._assess_fairness(clause, parties)

        return ClauseAnalysis(
            type=clause_type,
            text=clause.text,
            enforceability=enforceability,
            precedents=relevant_cases,
            fairness_assessment=fairness,
            recommended_modifications=self._suggest_modifications(clause, fairness)
        )
```

### Example 3: Manufacturing Process Optimizer

```python
class ManufacturingOptimizationAgent:
    """Domain agent for manufacturing process optimization"""

    def __init__(self):
        self.process_knowledge = ManufacturingProcessDB()
        self.equipment_specs = EquipmentDatabase()
        self.quality_standards = QualityStandardsDB()

    def optimize_production_line(self, line_config: dict) -> OptimizationPlan:
        """Optimize production line using manufacturing domain knowledge"""

        # Analyze current state
        current_performance = self._analyze_current_performance(line_config)

        # Identify bottlenecks (domain-specific)
        bottlenecks = self._identify_bottlenecks(
            line_config,
            current_performance
        )

        # Calculate theoretical maximum (domain formula)
        theoretical_max = self._calculate_theoretical_throughput(line_config)

        # Generate optimization recommendations
        optimizations = []

        for bottleneck in bottlenecks:
            # Domain knowledge: Optimization strategies
            strategies = self._get_optimization_strategies(bottleneck)

            for strategy in strategies:
                # Calculate impact
                impact = self._simulate_optimization(
                    line_config=line_config,
                    bottleneck=bottleneck,
                    strategy=strategy
                )

                # Calculate ROI
                roi = self._calculate_roi(
                    investment=strategy.cost,
                    throughput_gain=impact.throughput_increase,
                    quality_improvement=impact.quality_gain
                )

                optimizations.append({
                    "bottleneck": bottleneck.station,
                    "strategy": strategy.name,
                    "implementation": strategy.steps,
                    "expected_gain": impact.throughput_increase,
                    "investment_required": strategy.cost,
                    "roi": roi,
                    "payback_period": self._calculate_payback(strategy.cost, impact)
                })

        # Sort by ROI
        optimizations.sort(key=lambda x: x["roi"], reverse=True)

        return OptimizationPlan(
            current_throughput=current_performance.throughput,
            theoretical_maximum=theoretical_max,
            efficiency=current_performance.throughput / theoretical_max,
            bottlenecks=bottlenecks,
            optimizations=optimizations,
            implementation_phases=self._create_implementation_plan(optimizations)
        )
```

## When to Build Domain-Specific Agents

### Decision Framework

```
┌─────────────────────────────────────────────────┐
│  Should You Build a Domain-Specific Agent?      │
└─────────────────────────────────────────────────┘

EVALUATE THESE FACTORS:

1. Domain Complexity
   ├─ Simple: Generic agent sufficient
   ├─ Moderate: Consider domain agent
   └─ Complex: Domain agent essential

2. Regulation/Compliance
   ├─ None: Generic may work
   ├─ Some: Domain agent beneficial
   └─ Strict: Domain agent required

3. Specialized Knowledge Required
   ├─ No: Generic agent ok
   ├─ Some: Consider domain agent
   └─ Extensive: Domain agent critical

4. Frequency of Use
   ├─ Rare: Generic sufficient
   ├─ Regular: Domain agent worthwhile
   └─ Constant: Domain agent essential

5. Error Consequences
   ├─ Low: Generic acceptable
   ├─ Medium: Domain agent beneficial
   └─ High: Domain agent mandatory

DECISION MATRIX:

Score each factor (1-3) and sum:

5-7:   Use generic agent
8-11:  Consider domain agent
12-15: Build domain agent
```

### Use Case Evaluation

| Use Case | Generic Agent | Domain Agent | Rationale |
|----------|---------------|--------------|-----------|
| Customer support chatbot | ✅ | Optional | Basic NLP sufficient |
| Medical diagnosis assistant | ❌ | ✅ Required | Life-critical, requires medical knowledge |
| Legal contract review | ❌ | ✅ Required | Requires legal expertise, precedent knowledge |
| Code review | ✅ | Optional | Generic works, specialized better for specific languages |
| Financial fraud detection | ❌ | ✅ Required | Complex domain rules, regulatory requirements |
| Content moderation | ✅ | Optional | Basic detection ok, specialized better for context |
| Manufacturing optimization | ❌ | ✅ Required | Domain-specific physics, process knowledge |
| Email categorization | ✅ | ❌ Not needed | Simple classification task |

## Best Practices

### 1. Start with Core Domain Knowledge

**DO:**
- Identify the top 10 domain concepts/rules
- Encode fundamental domain logic first
- Validate with domain experts
- Build incrementally

**DON'T:**
- Try to encode all domain knowledge at once
- Rely solely on LLM knowledge
- Skip expert validation
- Build without clear success criteria

### 2. Maintain Domain Knowledge Separately

```python
# GOOD: Separate domain knowledge from agent logic

# domain/healthcare/hipaa_rules.py
HIPAA_PRIVACY_RULES = {
    "rule_164_502_a": {
        "requirement": "Authorization required for ePHI use/disclosure",
        "exceptions": ["treatment", "payment", "operations"],
        "violation_severity": "critical"
    }
}

# agents/healthcare_compliance_agent.py
class HealthcareComplianceAgent:
    def __init__(self):
        self.rules = load_hipaa_rules()  # Load from separate module
```

### 3. Provide Clear Explanations

Domain agents should explain their reasoning:

```python
class TaxComplianceAgent:
    def assess_deduction(self, expense: dict) -> DeductionAssessment:
        """Assess tax deduction validity"""

        assessment = self._evaluate_deduction(expense)

        # Provide clear explanation
        assessment.explanation = f"""
        Deduction Assessment: {assessment.decision}

        Analysis:
        - Expense Category: {expense.category}
        - Amount: ${expense.amount}
        - Business Purpose: {expense.purpose}

        Tax Code Application:
        - IRC Section 162(a) - Ordinary and necessary business expense
        - Your expense qualifies as "ordinary" because {assessment.ordinary_reasoning}
        - Your expense qualifies as "necessary" because {assessment.necessary_reasoning}

        Applicable Limitations:
        {self._format_limitations(assessment.limitations)}

        Documentation Required:
        {self._format_required_docs(assessment.required_documentation)}

        Confidence: {assessment.confidence}%
        """

        return assessment
```

### 4. Handle Edge Cases

Domain agents must handle domain-specific edge cases:

```python
class PharmacyAgent:
    def check_prescription(self, prescription: dict) -> PrescriptionCheck:
        """Check prescription safety"""

        checks = []

        # Edge case: Drug interactions
        interactions = self._check_drug_interactions(
            new_drug=prescription.medication,
            current_drugs=prescription.patient.current_medications
        )

        # Edge case: Contraindications
        contraindications = self._check_contraindications(
            drug=prescription.medication,
            conditions=prescription.patient.medical_conditions
        )

        # Edge case: Dosage for special populations
        if prescription.patient.age < 18:
            dosage_check = self._check_pediatric_dosage(prescription)
        elif prescription.patient.age > 65:
            dosage_check = self._check_geriatric_dosage(prescription)
        elif prescription.patient.is_pregnant:
            dosage_check = self._check_pregnancy_safety(prescription)
        else:
            dosage_check = self._check_standard_dosage(prescription)

        return PrescriptionCheck(
            safe=self._is_safe(interactions, contraindications, dosage_check),
            interactions=interactions,
            contraindications=contraindications,
            dosage_assessment=dosage_check
        )
```

## Summary

**Key Principles:**

1. **Deep Domain Knowledge**: Encode expertise from domain experts
2. **Specialized Tools**: Provide domain-specific capabilities
3. **Business Logic**: Implement domain rules and constraints
4. **Clear Reasoning**: Explain decisions in domain terms
5. **Continuous Learning**: Update knowledge as domain evolves

**The Formula:**
```
Domain Agent = Domain Knowledge + Specialized Tools + Business Logic + Context Awareness
```

**When to Use:**
- Complex, regulated domains
- High error consequences
- Specialized expertise required
- Frequent domain-specific tasks

**Implementation Path:**
1. Analyze domain requirements
2. Encode core knowledge
3. Build specialized tools
4. Implement workflows
5. Validate with experts
6. Deploy and iterate

<references>
- agent-design-patterns.md (Architecture patterns)
- specialization-strategy.md (Specialization decisions)
- lesson-06-review-documentation.md (Foundation concepts)
</references>