GoodLuckChuck commited on
Commit
eeba6a8
·
verified ·
1 Parent(s): cc63890

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +100 -26
app.py CHANGED
@@ -182,11 +182,11 @@ class Calculator(Tool):
182
  return self._safe_eval(input_data)
183
 
184
  class LocalSearch(Tool):
185
- """Enhanced local search with vector storage"""
186
  def __init__(self, knowledge_base_path: Path):
187
  super().__init__(
188
  name="local_search",
189
- description="Vector-based local knowledge base search",
190
  type=ToolType.LOCAL_SEARCH
191
  )
192
  self.knowledge_base_path = knowledge_base_path
@@ -195,17 +195,68 @@ class LocalSearch(Tool):
195
  def _load_knowledge_base(self):
196
  if not self.knowledge_base_path.exists():
197
  os.makedirs(self.knowledge_base_path, exist_ok=True)
198
- # Initialize empty vector store
199
- self._initialize_vector_store()
200
 
201
- def _initialize_vector_store(self):
202
- # Implementation for vector store initialization
203
- pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
204
 
205
- @lru_cache(maxsize=1000)
206
- async def _execute_impl(self, query: str) -> Any:
207
- # Implement actual vector search
208
- return f"Search result for: {query}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
209
 
210
  class Memory(Tool):
211
  """New tool for persistent memory across agent steps"""
@@ -454,7 +505,7 @@ If you truly cannot find an answer after using the tools, explain what you tried
454
  )
455
 
456
  async def _process_step(self, question: Question) -> Optional[Answer]:
457
- """Process a single step with enhanced error handling"""
458
  try:
459
  # Prepare the context for the model
460
  context = self._prepare_context(question)
@@ -471,6 +522,31 @@ If you truly cannot find an answer after using the tools, explain what you tried
471
  'reasoning': parsed.get('reasoning', [])
472
  })
473
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
474
  # If tools are requested, execute them
475
  if parsed.get('tool_requests'):
476
  tool_results = await self._execute_tools(parsed['tool_requests'])
@@ -478,12 +554,13 @@ If you truly cannot find an answer after using the tools, explain what you tried
478
  self.state.tools_used.extend([req['tool'] for req in parsed['tool_requests']])
479
  self.state.intermediate_results[-1]['tool_results'] = tool_results
480
 
481
- # Store results in memory if needed
482
- if any(result['tool'] == 'memory' for result in tool_results):
483
- memory_results = [r for r in tool_results if r['tool'] == 'memory']
484
- for mem_result in memory_results:
485
- if mem_result['status'] == 'success':
486
- self.state.memory.update(mem_result['result'])
 
487
 
488
  # If we need more processing, return None to continue
489
  if not parsed.get('is_final', False):
@@ -501,18 +578,15 @@ If you truly cannot find an answer after using the tools, explain what you tried
501
  if step.get('tool_results'):
502
  for tool_result in step['tool_results']:
503
  if tool_result['status'] == 'success':
504
- reasoning_trace.append(
505
- f"Tool {tool_result['tool']} result: {str(tool_result['result'])}"
506
- )
507
- else:
508
- reasoning_trace.append(
509
- f"Tool {tool_result['tool']} error: {tool_result.get('error', 'unknown error')}"
510
- )
511
 
512
  return Answer(
513
  text=parsed['final_answer'],
514
  confidence=parsed.get('confidence', 0.0),
515
- reasoning_trace=reasoning_trace, # Now properly formatted as list of strings
516
  tools_used=self.state.tools_used,
517
  processing_time=0.0, # Will be updated in process_question
518
  metadata={'memory_used': bool(self.state.memory)}
 
182
  return self._safe_eval(input_data)
183
 
184
  class LocalSearch(Tool):
185
+ """Enhanced local search with vector storage and file handling"""
186
  def __init__(self, knowledge_base_path: Path):
187
  super().__init__(
188
  name="local_search",
189
+ description="Search and analyze content including text, code, Excel files, and other attachments",
190
  type=ToolType.LOCAL_SEARCH
191
  )
192
  self.knowledge_base_path = knowledge_base_path
 
195
  def _load_knowledge_base(self):
196
  if not self.knowledge_base_path.exists():
197
  os.makedirs(self.knowledge_base_path, exist_ok=True)
 
 
198
 
199
+ async def _execute_impl(self, input_data: Dict[str, Any]) -> Any:
200
+ """Enhanced execution with attachment handling"""
201
+ try:
202
+ query = input_data.get('query', '')
203
+ attachment = input_data.get('attachment', None)
204
+ attachment_type = input_data.get('attachment_type', None)
205
+
206
+ if attachment:
207
+ if attachment_type == 'excel':
208
+ return await self._process_excel(attachment)
209
+ elif attachment_type == 'python':
210
+ return await self._process_python(attachment)
211
+ elif attachment_type == 'audio':
212
+ return {"error": "Audio processing not supported. Please provide transcription."}
213
+ elif attachment_type == 'video':
214
+ return {"error": "Video processing not supported. Please provide description or transcript."}
215
+
216
+ # Perform knowledge base search
217
+ results = await self._search_knowledge_base(query)
218
+ return {
219
+ "query": query,
220
+ "results": results,
221
+ "source": "knowledge_base"
222
+ }
223
+
224
+ except Exception as e:
225
+ logger.error(f"Error in LocalSearch: {str(e)}")
226
+ return {"error": str(e)}
227
 
228
+ async def _process_excel(self, file_path: str) -> Dict[str, Any]:
229
+ """Process Excel files"""
230
+ try:
231
+ df = pd.read_excel(file_path)
232
+ return {
233
+ "columns": list(df.columns),
234
+ "summary": df.describe().to_dict(),
235
+ "data": df.to_dict(orient='records')
236
+ }
237
+ except Exception as e:
238
+ return {"error": f"Error processing Excel file: {str(e)}"}
239
+
240
+ async def _process_python(self, code: str) -> Dict[str, Any]:
241
+ """Analyze Python code"""
242
+ try:
243
+ import ast
244
+ tree = ast.parse(code)
245
+ return {
246
+ "type": "python_code",
247
+ "analysis": {
248
+ "functions": [n.name for n in ast.walk(tree) if isinstance(n, ast.FunctionDef)],
249
+ "variables": [n.id for n in ast.walk(tree) if isinstance(n, ast.Name) and isinstance(n.ctx, ast.Store)],
250
+ "imports": [n.names[0].name for n in ast.walk(tree) if isinstance(n, ast.Import)]
251
+ }
252
+ }
253
+ except Exception as e:
254
+ return {"error": f"Error analyzing Python code: {str(e)}"}
255
+
256
+ async def _search_knowledge_base(self, query: str) -> List[Dict[str, Any]]:
257
+ """Search the knowledge base"""
258
+ # Implement actual search logic here
259
+ return [{"text": f"Search result for: {query}", "relevance": 0.8}]
260
 
261
  class Memory(Tool):
262
  """New tool for persistent memory across agent steps"""
 
505
  )
506
 
507
  async def _process_step(self, question: Question) -> Optional[Answer]:
508
+ """Process a single step with enhanced error handling and attachment processing"""
509
  try:
510
  # Prepare the context for the model
511
  context = self._prepare_context(question)
 
522
  'reasoning': parsed.get('reasoning', [])
523
  })
524
 
525
+ # Process attachments if present
526
+ if question.attachments:
527
+ for attachment in question.attachments:
528
+ # Determine attachment type
529
+ if attachment.endswith('.xlsx') or attachment.endswith('.xls'):
530
+ parsed['tool_requests'].append({
531
+ 'tool': 'local_search',
532
+ 'input': {'attachment': attachment, 'attachment_type': 'excel'}
533
+ })
534
+ elif attachment.endswith('.py'):
535
+ parsed['tool_requests'].append({
536
+ 'tool': 'local_search',
537
+ 'input': {'attachment': attachment, 'attachment_type': 'python'}
538
+ })
539
+ elif attachment.endswith(('.mp3', '.wav', '.m4a')):
540
+ parsed['tool_requests'].append({
541
+ 'tool': 'local_search',
542
+ 'input': {'attachment': attachment, 'attachment_type': 'audio'}
543
+ })
544
+ elif attachment.endswith(('.mp4', '.avi', '.mov')):
545
+ parsed['tool_requests'].append({
546
+ 'tool': 'local_search',
547
+ 'input': {'attachment': attachment, 'attachment_type': 'video'}
548
+ })
549
+
550
  # If tools are requested, execute them
551
  if parsed.get('tool_requests'):
552
  tool_results = await self._execute_tools(parsed['tool_requests'])
 
554
  self.state.tools_used.extend([req['tool'] for req in parsed['tool_requests']])
555
  self.state.intermediate_results[-1]['tool_results'] = tool_results
556
 
557
+ # Process tool results
558
+ for result in tool_results:
559
+ if result['status'] == 'success' and isinstance(result['result'], dict):
560
+ if 'error' in result['result']:
561
+ parsed['reasoning'].append(f"Tool error: {result['result']['error']}")
562
+ else:
563
+ self.state.memory[f"tool_result_{self.state.current_step}"] = result['result']
564
 
565
  # If we need more processing, return None to continue
566
  if not parsed.get('is_final', False):
 
578
  if step.get('tool_results'):
579
  for tool_result in step['tool_results']:
580
  if tool_result['status'] == 'success':
581
+ if isinstance(tool_result['result'], dict) and 'error' in tool_result['result']:
582
+ reasoning_trace.append(f"Tool {tool_result['tool']} error: {tool_result['result']['error']}")
583
+ else:
584
+ reasoning_trace.append(f"Tool {tool_result['tool']} result: {str(tool_result['result'])}")
 
 
 
585
 
586
  return Answer(
587
  text=parsed['final_answer'],
588
  confidence=parsed.get('confidence', 0.0),
589
+ reasoning_trace=reasoning_trace,
590
  tools_used=self.state.tools_used,
591
  processing_time=0.0, # Will be updated in process_question
592
  metadata={'memory_used': bool(self.state.memory)}