File size: 2,713 Bytes
95cc8f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
"""
Level-0 Summary Utilities for TRuCAL.
Provides raw evidence summarization for transparent AI reasoning.
"""
from typing import List, Dict, Optional
import json
from pathlib import Path
import logging
import time

logger = logging.getLogger(__name__)

class Level0Summary:
    """Handles Level-0 evidence collection and summarization."""
    
    def __init__(self, log_dir: str = "logs"):
        """Initialize with logging directory."""
        self.log_dir = Path(log_dir)
        self.log_dir.mkdir(exist_ok=True)
        self.audit_log = self.log_dir / "level0_audit.jsonl"
        
    def summarize(self, query: str, sources: List[str], metadata: Optional[Dict] = None) -> str:
        """
        Generate a Level-0 summary with raw evidence.
        
        Args:
            query: The original user query
            sources: List of source texts or evidence
            metadata: Optional metadata for auditing
            
        Returns:
            Formatted Level-0 summary string
        """
        if not query or not sources:
            return ""
            
        header = f"# Level-0 Summary\n"
        header += f"**Query:** {query}\n\n"
        header += "## Raw Evidence\n\n"
        
        evidence_sections = []
        for i, src in enumerate(sources, 1):
            if not src or not src.strip():
                continue
            evidence_sections.append(f"### Source {i}\n{src.strip()}\n")
        
        if not evidence_sections:
            return f"{header}*No valid evidence sources provided.*"
            
        summary = header + "\n".join(evidence_sections)
        
        # Log the summary for auditing
        self._log_summary(query, sources, summary, metadata)
        
        return summary
    
    def _log_summary(self, query: str, sources: List[str], summary: str, metadata: Optional[Dict] = None):
        """Log the summary to the audit log."""
        try:
            log_entry = {
                "timestamp": time.time(),
                "query": query,
                "source_count": len(sources),
                "summary": summary,
                "metadata": metadata or {}
            }
            
            with open(self.audit_log, "a", encoding="utf-8") as f:
                f.write(json.dumps(log_entry) + "\n")
                
        except Exception as e:
            logger.error(f"Failed to log Level-0 summary: {str(e)}")

# Singleton instance for easy import
level0_summarizer = Level0Summary()

def get_level0_summary(query: str, sources: List[str], metadata: Optional[Dict] = None) -> str:
    """Convenience function to get a Level-0 summary."""
    return level0_summarizer.summarize(query, sources, metadata)