File size: 7,291 Bytes
e00e744
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
#!/usr/bin/env python3
"""
Main CLI entry point for lineagentic framework.
"""

import asyncio
import argparse
import sys
import os
import logging
from pathlib import Path

# Add the project root to the Python path
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

from lf_algorithm.framework_agent import FrameworkAgent


def configure_logging(verbose: bool = False, quiet: bool = False):
    """Configure logging for the CLI application."""
    if quiet:
        # Quiet mode: only show errors
        logging.basicConfig(
            level=logging.ERROR,
            format='%(levelname)s: %(message)s'
        )
    elif verbose:
        # Verbose mode: show all logs with detailed format
        logging.basicConfig(
            level=logging.INFO,
            format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
            datefmt='%Y-%m-%d %H:%M:%S'
        )
    else:
        # Normal mode: show only important logs with clean format
        logging.basicConfig(
            level=logging.WARNING,  # Only show warnings and errors by default
            format='%(levelname)s: %(message)s'
        )
        
        # Set specific loggers to INFO level for better user experience
        logging.getLogger('lf_algorithm').setLevel(logging.INFO)
        logging.getLogger('lf_algorithm.framework_agent').setLevel(logging.INFO)
        logging.getLogger('lf_algorithm.agent_manager').setLevel(logging.INFO)
    
    # Suppress noisy server logs from MCP tools
    logging.getLogger('mcp').setLevel(logging.WARNING)
    logging.getLogger('agents.mcp').setLevel(logging.WARNING)
    logging.getLogger('agents.mcp.server').setLevel(logging.WARNING)
    logging.getLogger('agents.mcp.server.stdio').setLevel(logging.WARNING)
    logging.getLogger('agents.mcp.server.stdio.stdio').setLevel(logging.WARNING)
    
    # Suppress MCP library logs specifically
    logging.getLogger('mcp.server').setLevel(logging.WARNING)
    logging.getLogger('mcp.server.fastmcp').setLevel(logging.WARNING)
    logging.getLogger('mcp.server.stdio').setLevel(logging.WARNING)
    
    # Suppress any logger that contains 'server' in the name
    for logger_name in logging.root.manager.loggerDict:
        if 'server' in logger_name.lower():
            logging.getLogger(logger_name).setLevel(logging.WARNING)
    
    # Additional MCP-specific suppressions
    logging.getLogger('mcp.server.stdio.stdio').setLevel(logging.WARNING)
    logging.getLogger('mcp.server.stdio.stdio.stdio').setLevel(logging.WARNING)

def create_parser():
    """Create and configure the argument parser."""
    parser = argparse.ArgumentParser(
        description="Lineagentic - Agentic approach for code analysis and lineage extraction",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:

  lineagentic analyze --agent-name sql-lineage-agent --query "SELECT a,b FROM table1"
  lineagentic analyze --agent-name python-lineage-agent --query-file "my_script.py"
        """
    )
    
    # Create subparsers for the two main operations
    subparsers = parser.add_subparsers(dest='command', help='Available commands')
    
    # Analyze query subparser
    analyze_parser = subparsers.add_parser('analyze', help='Analyze code or query for lineage information')
    analyze_parser.add_argument(
        "--agent-name",
        type=str,
        default="sql",
        help="Name of the agent to use (e.g., sql, airflow, spark, python, java) (default: sql)"
    )
    analyze_parser.add_argument(
        "--model-name",
        type=str,
        default="gpt-4o-mini",
        help="Model to use for the agents (default: gpt-4o-mini)"
    )
    analyze_parser.add_argument(
        "--query",
        type=str,
        help="Code or query to analyze"
    )
    analyze_parser.add_argument(
        "--query-file",
        type=str,
        help="Path to file containing the query/code to analyze"
    )

    # Common output options
    analyze_parser.add_argument(
        "--output",
        type=str,
        help="Output file path for results (JSON format)"
    )
    analyze_parser.add_argument(
        "--pretty",
        action="store_true",
        help="Pretty print the output"
    )
    analyze_parser.add_argument(
        "--verbose",
        action="store_true",
        help="Enable verbose output with detailed logging"
    )
    analyze_parser.add_argument(
        "--quiet",
        action="store_true",
        help="Suppress all output except errors"
    )
    
    return parser


def read_query_file(file_path: str) -> str:
    """Read query from a file."""
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            return f.read()
    except FileNotFoundError:
        print(f"Error: File '{file_path}' not found.")
        sys.exit(1)
    except Exception as e:
        print(f"Error reading file '{file_path}': {e}")
        sys.exit(1)





def save_output(result, output_file: str = None, pretty: bool = False):
    """Save or print the result."""
    # Convert AgentResult to dict if needed
    if hasattr(result, 'to_dict'):
        result_dict = result.to_dict()
    else:
        result_dict = result
    
    if output_file:
        import json
        with open(output_file, 'w', encoding='utf-8') as f:
            json.dump(result_dict, f, indent=2 if pretty else None)
        print(f"Results saved to '{output_file}'")
    else:
        if pretty:
            import json
            print("\n" + "="*50)
            print("ANALYSIS RESULTS")
            print("="*50)
            print(json.dumps(result_dict, indent=2))
            print("="*50)
        else:
            print("\nResults:", result_dict)


async def run_analyze_query(args):
    """Run analyze_query operation."""
    logger = logging.getLogger(__name__)
    
    # Get the query
    query = args.query
    if args.query_file:
        query = read_query_file(args.query_file)
    
    if not query:
        logger.error("Either --query or --query-file must be specified.")
        sys.exit(1)
    
    logger.info(f"Running agent '{args.agent_name}' with query...")
    
    try:
        # Create FrameworkAgent instance
        agent = FrameworkAgent(
            agent_name=args.agent_name,
            model_name=args.model_name,
            source_code=query
        )
        
        # Run the agent
        result = await agent.run_agent()
        
        save_output(result, args.output, args.pretty)
        
    except Exception as e:
        logger.error(f"Error running agent '{args.agent_name}': {e}")
        sys.exit(1)





async def main_async():
    """Main CLI function."""
    parser = create_parser()
    args = parser.parse_args()
    
    # Check if a command was provided
    if not args.command:
        parser.print_help()
        sys.exit(1)
    
    # Configure logging based on verbosity
    configure_logging(verbose=args.verbose, quiet=args.quiet)
    
    # Run the appropriate command
    if args.command == 'analyze':
        await run_analyze_query(args)
    else:
        print(f"Unknown command: {args.command}")
        sys.exit(1)


def main():
    """Synchronous wrapper for the async main function."""
    asyncio.run(main_async())


if __name__ == "__main__":
    main()