""" Simple debug logger for AI prompts and responses. Writes files chronologically to gateway/test-chat/ai/ with sequential numbering. """ import os from datetime import datetime, UTC from typing import List, Optional def _getDebugDir() -> str: """Get the debug directory path.""" gatewayDir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) return os.path.join(gatewayDir, 'test-chat', 'ai') def _getNextSequenceNumber() -> int: """Get the next sequence number by counting existing files.""" debugDir = _getDebugDir() if not os.path.exists(debugDir): return 1 # Count existing numbered files files = [f for f in os.listdir(debugDir) if f.startswith(('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'))] return len(files) + 1 def writeDebugFile(content: str, fileType: str, documents: Optional[List] = None) -> None: """ Write debug content to a file with sequential numbering. Writes the content as-is since it's already the final integrated prompt. Includes document list labels for tracing enhancement. Args: content: The main content to write (already integrated) fileType: Type of file (e.g., 'prompt_final', 'response') documents: Optional list of documents for tracing """ try: debugDir = _getDebugDir() os.makedirs(debugDir, exist_ok=True) seqNum = _getNextSequenceNumber() ts = datetime.now(UTC).strftime('%Y%m%d-%H%M%S') # Add 3-digit sequence number for uniqueness tsWithSeq = f"{ts}-{seqNum:03d}" filename = f"{tsWithSeq}-{fileType}.txt" filepath = os.path.join(debugDir, filename) # Build content with document tracing debug_content = content # Add document list labels for tracing enhancement if documents: debug_content += "\n\n=== DOCUMENT LIST FOR TRACING ===\n" for i, doc in enumerate(documents): if hasattr(doc, 'fileName'): debug_content += f"Document {i+1}: {doc.fileName} ({doc.mimeType})\n" elif hasattr(doc, 'fileId'): debug_content += f"Document {i+1}: {doc.fileId} ({getattr(doc, 'mimeType', 'unknown')})\n" else: debug_content += f"Document {i+1}: {str(doc)[:100]}...\n" # Write the content with document tracing with open(filepath, 'w', encoding='utf-8') as f: f.write(debug_content) except Exception as e: # Silent fail - don't break the main flow pass