mnds18/agentic-ts-forecasting-system
0
1"""2orchestration_agent.py3Tracks and logs execution time and outputs of each agent4"""5 6import os7import csv8from datetime import datetime9import time10from functools import wraps # Ensures metadata preservation for decorators11import traceback # For capturing detailed exceptions12 13LOG_PATH = "outputs/orchestration_log.csv"14 15# Write structured log entry to CSV16def log_event(agent_name, step, start_time, end_time, output_summary):17 os.makedirs("outputs", exist_ok=True)18 duration = round(end_time - start_time, 2)19 now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")20 21 file_exists = os.path.isfile(LOG_PATH)22 with open(LOG_PATH, mode="a", newline="", encoding="utf-8") as f:23 writer = csv.DictWriter(f, fieldnames=[24 "Timestamp", "Agent Name", "Step", "Start Time", "End Time", "Duration (s)", "Output Summary"])25 26 if not file_exists:27 writer.writeheader()28 29 writer.writerow({30 "Timestamp": now,31 "Agent Name": agent_name,32 "Step": step,33 "Start Time": start_time,34 "End Time": end_time,35 "Duration (s)": duration,36 "Output Summary": output_summary37 })38 39 print(f"✅ {agent_name} completed in {duration}s | Output: {output_summary[:80]}...")40 41# Decorator to wrap agent function calls with execution logging42def agent_logger(agent_name, step):43 def decorator(func):44 @wraps(func)45 def wrapper(*args, **kwargs):46 start_time = time.time()47 try:48 result = func(*args, **kwargs)49 output_summary = str(result)[:200] # Truncate for concise logs50 except Exception as e:51 end_time = time.time()52 tb = traceback.format_exc()53 output_summary = f"Exception: {str(e)}\n{tb}"54 log_event(agent_name, step, start_time, end_time, output_summary)55 raise # Re-raise after logging56 end_time = time.time()57 log_event(agent_name, step, start_time, end_time, output_summary)58 return result59 return wrapper60 return decorator