-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
161 lines (142 loc) · 4.69 KB
/
Copy pathmain.py
File metadata and controls
161 lines (142 loc) · 4.69 KB
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
"""Main module for the George_Was_Right project.
This module initializes and runs the CrewAI agents for the project.
Environment variables are loaded in config.py.
"""
import logging
import os
import traceback
from datetime import datetime
from crewai import Crew
from rich import print
from dotenv import load_dotenv
from src.config import (
log_researcher,
log_writer,
log_prompt_master,
log_editor,
log_crew,
llm_model_name,
planning_llm_name,
use_fallback,
fallback_llm_name,
log_directory,
)
from src.tools import search_tool
from src.llm import LLMFactory
from src.agents import (
PromptMasterAgent,
ResearcherAgent,
WriterAgent,
EditorAgent,
)
from src.tasks import create_tasks
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler(f"{log_directory}/app.log"),
logging.StreamHandler()
]
)
def create_crew() -> Crew:
"""Create and configure the CrewAI crew with agents and tasks.
Returns:
Crew: Configured CrewAI crew instance.
Raises:
Exception: If there is an error creating the crew.
"""
try:
# Create shared LLM instance
llm = LLMFactory.init_llm()
# Initialize agents
researcher = ResearcherAgent(search_tool=search_tool, llm=llm)
writer = WriterAgent(llm=llm)
prompt_master = PromptMasterAgent(llm=llm)
editor = EditorAgent(llm=llm)
# Create tasks for the agents
tasks = create_tasks(researcher, writer, prompt_master, editor)
return Crew(
agents=[researcher, writer, prompt_master, editor],
tasks=tasks,
verbose=True,
planning=True,
planning_llm=LLMFactory.init_planning_llm(),
output_log_file=log_crew
)
except Exception as e:
print(f"[ERROR] Failed to create crew: {str(e)}")
print(traceback.format_exc())
raise
def cleanup():
"""Cleanup resources properly when the application exits"""
print("Cleaning up resources...")
# Close and remove logging handlers
for handler in logging.getLogger().handlers[:]:
handler.close()
logging.getLogger().removeHandler(handler)
def main():
"""Main function to run the application.
This function creates the crew and kicks off the process.
It handles any exceptions that occur during execution.
"""
try:
# Check for configuration issues
from src.config import config_issues
if config_issues:
print("[ERROR] Configuration issues detected. Please fix them before continuing.")
return None
# Log and display the LLM models being used
logging.info(f"Using LLM models: {llm_model_name} (main), {planning_llm_name} (planning)")
print(
f"""
-------------------
LLM Models:
- llm_model_name = {llm_model_name}
- planning_llm_name = {planning_llm_name}
- Fallback Enabled = {use_fallback}
-------------------
"""
)
# Create and initialize the crew
crew = create_crew()
# Start the crew
result = crew.kickoff()
# Handle success
print(
f"""
-------------------
JOB DONE!
- llm_model_name = {llm_model_name}
- planning_llm_name = {planning_llm_name}
-------------------
"""
)
return result
except ConnectionError as e:
print(f"[ERROR] Connection failed: {str(e)}")
print("Please check if your LLM service is running or if you need to use a different model.")
logging.error("ConnectionError: LLM service unavailable. LLMFactory handles fallback internally.")
return None
except Exception as e:
print(f"[ERROR] Application error: {str(e)}")
print(traceback.format_exc())
# Log the error to a file for better debugging
error_log_path = f"{log_directory}/error-{datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}.log"
with open(error_log_path, "w") as error_file:
error_file.write(f"Error: {str(e)}\n\n")
error_file.write(traceback.format_exc())
print(f"Error details saved to {error_log_path}")
return None
if __name__ == "__main__":
try:
result = main()
if result is None:
print("Application completed with no result.")
exit(1)
exit(0)
except Exception as e:
print(f"Unhandled exception: {str(e)}")
exit(1)
finally:
cleanup()