Spaces:
Sleeping
Sleeping
Update agents/assembler_agent.py
Browse files- agents/assembler_agent.py +204 -204
agents/assembler_agent.py
CHANGED
@@ -1,204 +1,204 @@
|
|
1 |
-
from typing import Dict, List
|
2 |
-
from models.model_config import ModelConfig
|
3 |
-
from models.data_models import AssemblerInput
|
4 |
-
from .base_agent import BaseAgent
|
5 |
-
import datetime
|
6 |
-
|
7 |
-
class AssemblerAgent(BaseAgent):
|
8 |
-
def __init__(self, name: str = "AssemblerAgent"):
|
9 |
-
super().__init__(name)
|
10 |
-
self.final_report: Dict = {}
|
11 |
-
|
12 |
-
|
13 |
-
def reason(self, input_data: AssemblerInput) -> List[str]:
|
14 |
-
"""
|
15 |
-
Plan how to assemble the final report from all agent results
|
16 |
-
"""
|
17 |
-
thoughts = []
|
18 |
-
|
19 |
-
try:
|
20 |
-
# Analyze available inputs
|
21 |
-
thoughts.append("Analyzing inputs from all agents:")
|
22 |
-
thoughts.append(f"- User input processing results available: {bool(input_data.user_input_results)}")
|
23 |
-
thoughts.append(f"- Context learning results available: {bool(input_data.context_results)}")
|
24 |
-
thoughts.append(f"- Image analysis results available: {bool(input_data.image_results)}")
|
25 |
-
|
26 |
-
# Plan report structure
|
27 |
-
thoughts.append("\nPlanning report structure:")
|
28 |
-
thoughts.append("1. User Query Summary")
|
29 |
-
thoughts.append("2. Context Analysis")
|
30 |
-
thoughts.append("3. Image Analysis Results")
|
31 |
-
thoughts.append("4. Model Performance Metrics")
|
32 |
-
thoughts.append("5. Final Recommendations")
|
33 |
-
|
34 |
-
# Consider report format
|
35 |
-
thoughts.append(f"\nReport Format: {input_data.report_format}")
|
36 |
-
if input_data.report_format == "detailed":
|
37 |
-
thoughts.append("- Will include full model decisions")
|
38 |
-
thoughts.append("- Will include confidence scores")
|
39 |
-
thoughts.append("- Will include processing statistics")
|
40 |
-
else:
|
41 |
-
thoughts.append("- Will provide condensed summary")
|
42 |
-
thoughts.append("- Will focus on key findings")
|
43 |
-
|
44 |
-
# Store thoughts in state
|
45 |
-
self.state.thoughts.extend(thoughts)
|
46 |
-
self.logger.info("Reasoning complete for report assembly")
|
47 |
-
|
48 |
-
return thoughts
|
49 |
-
|
50 |
-
except Exception as e:
|
51 |
-
error_msg = f"Error during assembly reasoning: {str(e)}"
|
52 |
-
self.state.errors.append(error_msg)
|
53 |
-
self.logger.error(error_msg)
|
54 |
-
return thoughts
|
55 |
-
|
56 |
-
def execute(self, input_data: AssemblerInput) -> Dict:
|
57 |
-
"""
|
58 |
-
Assemble final report from all agent results
|
59 |
-
"""
|
60 |
-
try:
|
61 |
-
if not self.validate(input_data):
|
62 |
-
return {
|
63 |
-
'status': 'error',
|
64 |
-
'error': self.state.errors[-1]
|
65 |
-
}
|
66 |
-
|
67 |
-
report = {
|
68 |
-
'summary': {
|
69 |
-
'user_query': {},
|
70 |
-
'context_analysis': {},
|
71 |
-
'image_analysis': {},
|
72 |
-
'recommendations': []
|
73 |
-
},
|
74 |
-
'details': {
|
75 |
-
'model_decisions': {},
|
76 |
-
'processing_stats': {},
|
77 |
-
'confidence_scores': {}
|
78 |
-
},
|
79 |
-
'metadata': {
|
80 |
-
'report_format': input_data.report_format,
|
81 |
-
'timestamp': datetime.now().isoformat()
|
82 |
-
},
|
83 |
-
'status': 'processing'
|
84 |
-
}
|
85 |
-
|
86 |
-
# Process user input results
|
87 |
-
if input_data.user_input_results:
|
88 |
-
report['summary']['user_query'] = {
|
89 |
-
'original_query': input_data.user_input_results.get('query', ''),
|
90 |
-
'constraints': input_data.user_input_results.get('constraints', []),
|
91 |
-
'intent': input_data.user_input_results.get('intent', '')
|
92 |
-
}
|
93 |
-
|
94 |
-
# Process context results
|
95 |
-
if input_data.context_results:
|
96 |
-
report['summary']['context_analysis'] = {
|
97 |
-
'key_findings': input_data.context_results.get('summaries', {}),
|
98 |
-
'relevant_keywords': list(input_data.context_results.get('keywords', set())),
|
99 |
-
'sources': list(input_data.context_results.get('gathered_context', {}).keys())
|
100 |
-
}
|
101 |
-
|
102 |
-
# Process image analysis results
|
103 |
-
if input_data.image_results:
|
104 |
-
report['summary']['image_analysis'] = {
|
105 |
-
'selected_images': input_data.image_results.get('selected_images', []),
|
106 |
-
'analysis_summary': {
|
107 |
-
path: results['caption']['text']
|
108 |
-
for path, results in input_data.image_results.get('analyzed_images', {}).items()
|
109 |
-
}
|
110 |
-
}
|
111 |
-
|
112 |
-
# Add detailed information if requested
|
113 |
-
if input_data.report_format == "detailed":
|
114 |
-
report['details']['model_decisions'] = {
|
115 |
-
'context_models': input_data.context_results.get('model_decisions', {}),
|
116 |
-
'image_models': input_data.image_results.get('model_decisions', {})
|
117 |
-
}
|
118 |
-
report['details']['processing_stats'] = {
|
119 |
-
'context_processing': input_data.context_results.get('model_decisions', {}).get('processing_stats', {}),
|
120 |
-
'image_processing': input_data.image_results.get('model_decisions', {}).get('processing_stats', {})
|
121 |
-
}
|
122 |
-
|
123 |
-
# Generate recommendations
|
124 |
-
report['summary']['recommendations'] = self._generate_recommendations(
|
125 |
-
report['summary']['context_analysis'],
|
126 |
-
report['summary']['image_analysis']
|
127 |
-
)
|
128 |
-
|
129 |
-
report['status'] = 'success'
|
130 |
-
self.final_report = report
|
131 |
-
|
132 |
-
# Log decision
|
133 |
-
self.log_decision({
|
134 |
-
'action': 'report_assembly',
|
135 |
-
'format': input_data.report_format,
|
136 |
-
'sections_completed': list(report['summary'].keys())
|
137 |
-
})
|
138 |
-
|
139 |
-
return report
|
140 |
-
|
141 |
-
except Exception as e:
|
142 |
-
error_msg = f"Error executing report assembly: {str(e)}"
|
143 |
-
self.state.errors.append(error_msg)
|
144 |
-
self.logger.error(error_msg)
|
145 |
-
return {'status': 'error', 'error': error_msg}
|
146 |
-
|
147 |
-
|
148 |
-
def _generate_recommendations(self, context_analysis: Dict, image_analysis: Dict) -> List[str]:
|
149 |
-
"""
|
150 |
-
Generate recommendations based on context and image analysis
|
151 |
-
|
152 |
-
Args:
|
153 |
-
context_analysis: Results from context learning
|
154 |
-
image_analysis: Results from image analysis
|
155 |
-
|
156 |
-
Returns:
|
157 |
-
List[str]: List of recommendations
|
158 |
-
"""
|
159 |
-
try:
|
160 |
-
recommendations = []
|
161 |
-
|
162 |
-
# Check if we have sufficient data
|
163 |
-
if not context_analysis or not image_analysis:
|
164 |
-
return ["Insufficient data to generate recommendations"]
|
165 |
-
|
166 |
-
# Analyze context findings
|
167 |
-
if context_analysis.get('key_findings'):
|
168 |
-
recommendations.append("Based on context analysis:")
|
169 |
-
for source, finding in context_analysis['key_findings'].items():
|
170 |
-
if finding: # Check if finding exists
|
171 |
-
recommendations.append(f"- {finding}")
|
172 |
-
|
173 |
-
# Analyze image findings
|
174 |
-
if image_analysis.get('selected_images'):
|
175 |
-
recommendations.append("\nBased on image analysis:")
|
176 |
-
recommendations.append(f"- Found {len(image_analysis['selected_images'])} relevant images")
|
177 |
-
|
178 |
-
# Add specific image recommendations
|
179 |
-
if image_analysis.get('analysis_summary'):
|
180 |
-
for img_path, caption in image_analysis['analysis_summary'].items():
|
181 |
-
if caption: # Check if caption exists
|
182 |
-
recommendations.append(f"- {caption}")
|
183 |
-
|
184 |
-
# Combine findings for final recommendations
|
185 |
-
recommendations.append("\nKey Recommendations:")
|
186 |
-
if context_analysis.get('relevant_keywords'):
|
187 |
-
keywords = context_analysis['relevant_keywords'][:5] # Top 5 keywords
|
188 |
-
recommendations.append(f"- Focus areas identified: {', '.join(keywords)}")
|
189 |
-
|
190 |
-
# Add source credibility note
|
191 |
-
if context_analysis.get('sources'):
|
192 |
-
recommendations.append(f"- Analysis based on {len(context_analysis['sources'])} credible sources")
|
193 |
-
|
194 |
-
# Add confidence note
|
195 |
-
recommendations.append("- Regular monitoring and updates recommended")
|
196 |
-
|
197 |
-
self.logger.info("Generated recommendations successfully")
|
198 |
-
return recommendations
|
199 |
-
|
200 |
-
except Exception as e:
|
201 |
-
error_msg = f"Error generating recommendations: {str(e)}"
|
202 |
-
self.logger.error(error_msg)
|
203 |
-
return ["Error generating recommendations. Please check the detailed report."]
|
204 |
-
|
|
|
1 |
+
from typing import Dict, List
|
2 |
+
from models.model_config import ModelConfig
|
3 |
+
from models.data_models import AssemblerInput
|
4 |
+
from .base_agent import BaseAgent
|
5 |
+
from datetime import datetime
|
6 |
+
|
7 |
+
class AssemblerAgent(BaseAgent):
|
8 |
+
def __init__(self, name: str = "AssemblerAgent"):
|
9 |
+
super().__init__(name)
|
10 |
+
self.final_report: Dict = {}
|
11 |
+
|
12 |
+
|
13 |
+
def reason(self, input_data: AssemblerInput) -> List[str]:
|
14 |
+
"""
|
15 |
+
Plan how to assemble the final report from all agent results
|
16 |
+
"""
|
17 |
+
thoughts = []
|
18 |
+
|
19 |
+
try:
|
20 |
+
# Analyze available inputs
|
21 |
+
thoughts.append("Analyzing inputs from all agents:")
|
22 |
+
thoughts.append(f"- User input processing results available: {bool(input_data.user_input_results)}")
|
23 |
+
thoughts.append(f"- Context learning results available: {bool(input_data.context_results)}")
|
24 |
+
thoughts.append(f"- Image analysis results available: {bool(input_data.image_results)}")
|
25 |
+
|
26 |
+
# Plan report structure
|
27 |
+
thoughts.append("\nPlanning report structure:")
|
28 |
+
thoughts.append("1. User Query Summary")
|
29 |
+
thoughts.append("2. Context Analysis")
|
30 |
+
thoughts.append("3. Image Analysis Results")
|
31 |
+
thoughts.append("4. Model Performance Metrics")
|
32 |
+
thoughts.append("5. Final Recommendations")
|
33 |
+
|
34 |
+
# Consider report format
|
35 |
+
thoughts.append(f"\nReport Format: {input_data.report_format}")
|
36 |
+
if input_data.report_format == "detailed":
|
37 |
+
thoughts.append("- Will include full model decisions")
|
38 |
+
thoughts.append("- Will include confidence scores")
|
39 |
+
thoughts.append("- Will include processing statistics")
|
40 |
+
else:
|
41 |
+
thoughts.append("- Will provide condensed summary")
|
42 |
+
thoughts.append("- Will focus on key findings")
|
43 |
+
|
44 |
+
# Store thoughts in state
|
45 |
+
self.state.thoughts.extend(thoughts)
|
46 |
+
self.logger.info("Reasoning complete for report assembly")
|
47 |
+
|
48 |
+
return thoughts
|
49 |
+
|
50 |
+
except Exception as e:
|
51 |
+
error_msg = f"Error during assembly reasoning: {str(e)}"
|
52 |
+
self.state.errors.append(error_msg)
|
53 |
+
self.logger.error(error_msg)
|
54 |
+
return thoughts
|
55 |
+
|
56 |
+
def execute(self, input_data: AssemblerInput) -> Dict:
|
57 |
+
"""
|
58 |
+
Assemble final report from all agent results
|
59 |
+
"""
|
60 |
+
try:
|
61 |
+
if not self.validate(input_data):
|
62 |
+
return {
|
63 |
+
'status': 'error',
|
64 |
+
'error': self.state.errors[-1]
|
65 |
+
}
|
66 |
+
|
67 |
+
report = {
|
68 |
+
'summary': {
|
69 |
+
'user_query': {},
|
70 |
+
'context_analysis': {},
|
71 |
+
'image_analysis': {},
|
72 |
+
'recommendations': []
|
73 |
+
},
|
74 |
+
'details': {
|
75 |
+
'model_decisions': {},
|
76 |
+
'processing_stats': {},
|
77 |
+
'confidence_scores': {}
|
78 |
+
},
|
79 |
+
'metadata': {
|
80 |
+
'report_format': input_data.report_format,
|
81 |
+
'timestamp': datetime.now().isoformat()
|
82 |
+
},
|
83 |
+
'status': 'processing'
|
84 |
+
}
|
85 |
+
|
86 |
+
# Process user input results
|
87 |
+
if input_data.user_input_results:
|
88 |
+
report['summary']['user_query'] = {
|
89 |
+
'original_query': input_data.user_input_results.get('query', ''),
|
90 |
+
'constraints': input_data.user_input_results.get('constraints', []),
|
91 |
+
'intent': input_data.user_input_results.get('intent', '')
|
92 |
+
}
|
93 |
+
|
94 |
+
# Process context results
|
95 |
+
if input_data.context_results:
|
96 |
+
report['summary']['context_analysis'] = {
|
97 |
+
'key_findings': input_data.context_results.get('summaries', {}),
|
98 |
+
'relevant_keywords': list(input_data.context_results.get('keywords', set())),
|
99 |
+
'sources': list(input_data.context_results.get('gathered_context', {}).keys())
|
100 |
+
}
|
101 |
+
|
102 |
+
# Process image analysis results
|
103 |
+
if input_data.image_results:
|
104 |
+
report['summary']['image_analysis'] = {
|
105 |
+
'selected_images': input_data.image_results.get('selected_images', []),
|
106 |
+
'analysis_summary': {
|
107 |
+
path: results['caption']['text']
|
108 |
+
for path, results in input_data.image_results.get('analyzed_images', {}).items()
|
109 |
+
}
|
110 |
+
}
|
111 |
+
|
112 |
+
# Add detailed information if requested
|
113 |
+
if input_data.report_format == "detailed":
|
114 |
+
report['details']['model_decisions'] = {
|
115 |
+
'context_models': input_data.context_results.get('model_decisions', {}),
|
116 |
+
'image_models': input_data.image_results.get('model_decisions', {})
|
117 |
+
}
|
118 |
+
report['details']['processing_stats'] = {
|
119 |
+
'context_processing': input_data.context_results.get('model_decisions', {}).get('processing_stats', {}),
|
120 |
+
'image_processing': input_data.image_results.get('model_decisions', {}).get('processing_stats', {})
|
121 |
+
}
|
122 |
+
|
123 |
+
# Generate recommendations
|
124 |
+
report['summary']['recommendations'] = self._generate_recommendations(
|
125 |
+
report['summary']['context_analysis'],
|
126 |
+
report['summary']['image_analysis']
|
127 |
+
)
|
128 |
+
|
129 |
+
report['status'] = 'success'
|
130 |
+
self.final_report = report
|
131 |
+
|
132 |
+
# Log decision
|
133 |
+
self.log_decision({
|
134 |
+
'action': 'report_assembly',
|
135 |
+
'format': input_data.report_format,
|
136 |
+
'sections_completed': list(report['summary'].keys())
|
137 |
+
})
|
138 |
+
|
139 |
+
return report
|
140 |
+
|
141 |
+
except Exception as e:
|
142 |
+
error_msg = f"Error executing report assembly: {str(e)}"
|
143 |
+
self.state.errors.append(error_msg)
|
144 |
+
self.logger.error(error_msg)
|
145 |
+
return {'status': 'error', 'error': error_msg}
|
146 |
+
|
147 |
+
|
148 |
+
def _generate_recommendations(self, context_analysis: Dict, image_analysis: Dict) -> List[str]:
|
149 |
+
"""
|
150 |
+
Generate recommendations based on context and image analysis
|
151 |
+
|
152 |
+
Args:
|
153 |
+
context_analysis: Results from context learning
|
154 |
+
image_analysis: Results from image analysis
|
155 |
+
|
156 |
+
Returns:
|
157 |
+
List[str]: List of recommendations
|
158 |
+
"""
|
159 |
+
try:
|
160 |
+
recommendations = []
|
161 |
+
|
162 |
+
# Check if we have sufficient data
|
163 |
+
if not context_analysis or not image_analysis:
|
164 |
+
return ["Insufficient data to generate recommendations"]
|
165 |
+
|
166 |
+
# Analyze context findings
|
167 |
+
if context_analysis.get('key_findings'):
|
168 |
+
recommendations.append("Based on context analysis:")
|
169 |
+
for source, finding in context_analysis['key_findings'].items():
|
170 |
+
if finding: # Check if finding exists
|
171 |
+
recommendations.append(f"- {finding}")
|
172 |
+
|
173 |
+
# Analyze image findings
|
174 |
+
if image_analysis.get('selected_images'):
|
175 |
+
recommendations.append("\nBased on image analysis:")
|
176 |
+
recommendations.append(f"- Found {len(image_analysis['selected_images'])} relevant images")
|
177 |
+
|
178 |
+
# Add specific image recommendations
|
179 |
+
if image_analysis.get('analysis_summary'):
|
180 |
+
for img_path, caption in image_analysis['analysis_summary'].items():
|
181 |
+
if caption: # Check if caption exists
|
182 |
+
recommendations.append(f"- {caption}")
|
183 |
+
|
184 |
+
# Combine findings for final recommendations
|
185 |
+
recommendations.append("\nKey Recommendations:")
|
186 |
+
if context_analysis.get('relevant_keywords'):
|
187 |
+
keywords = context_analysis['relevant_keywords'][:5] # Top 5 keywords
|
188 |
+
recommendations.append(f"- Focus areas identified: {', '.join(keywords)}")
|
189 |
+
|
190 |
+
# Add source credibility note
|
191 |
+
if context_analysis.get('sources'):
|
192 |
+
recommendations.append(f"- Analysis based on {len(context_analysis['sources'])} credible sources")
|
193 |
+
|
194 |
+
# Add confidence note
|
195 |
+
recommendations.append("- Regular monitoring and updates recommended")
|
196 |
+
|
197 |
+
self.logger.info("Generated recommendations successfully")
|
198 |
+
return recommendations
|
199 |
+
|
200 |
+
except Exception as e:
|
201 |
+
error_msg = f"Error generating recommendations: {str(e)}"
|
202 |
+
self.logger.error(error_msg)
|
203 |
+
return ["Error generating recommendations. Please check the detailed report."]
|
204 |
+
|