Kackle commited on
Commit
8a1c7db
·
verified ·
1 Parent(s): 1cdaadf

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +53 -93
app.py CHANGED
@@ -110,7 +110,7 @@ class KnowledgeBaseTool(Tool):
110
 
111
  class WikipediaSearchTool(Tool):
112
  name = "wikipedia_search"
113
- description = "Search Wikipedia for detailed information on topics, people, places, events"
114
  inputs = {"query": {"type": "string", "description": "The search query for Wikipedia"}}
115
  output_type = "string"
116
 
@@ -119,50 +119,19 @@ class WikipediaSearchTool(Tool):
119
  self.is_initialized = True
120
 
121
  def forward(self, query: str) -> str:
122
- """Search Wikipedia with multiple approaches."""
123
  try:
124
  import requests
125
-
126
- # Try direct page lookup first
127
  wiki_url = "https://en.wikipedia.org/api/rest_v1/page/summary/" + query.replace(" ", "_")
128
- response = requests.get(wiki_url, timeout=5)
129
  if response.status_code == 200:
130
  data = response.json()
131
  if 'extract' in data and data['extract']:
132
- return f"Wikipedia: {data['extract'][:800]}"
133
-
134
- # Try search API if direct lookup fails
135
- search_url = "https://en.wikipedia.org/w/api.php"
136
- search_params = {
137
- 'action': 'query',
138
- 'format': 'json',
139
- 'list': 'search',
140
- 'srsearch': query,
141
- 'srlimit': 3
142
- }
143
-
144
- search_response = requests.get(search_url, params=search_params, timeout=5)
145
- if search_response.status_code == 200:
146
- search_data = search_response.json()
147
- if 'query' in search_data and 'search' in search_data['query']:
148
- results = search_data['query']['search']
149
- if results:
150
- # Get the first result's content
151
- first_title = results[0]['title']
152
- content_url = "https://en.wikipedia.org/api/rest_v1/page/summary/" + first_title.replace(" ", "_")
153
- content_response = requests.get(content_url, timeout=5)
154
- if content_response.status_code == 200:
155
- content_data = content_response.json()
156
- if 'extract' in content_data and content_data['extract']:
157
- return f"Wikipedia ({first_title}): {content_data['extract'][:800]}"
158
-
159
- # Fallback to search snippet
160
- return f"Wikipedia search results: {results[0]['snippet'][:400]}"
161
-
162
  except Exception as e:
163
  print(f"Wikipedia search failed: {e}")
164
 
165
- return f"Wikipedia search unavailable for '{query}'. Try using google_search() instead."
166
 
167
  # --- Mathematical Tools ---
168
  class MathTool(Tool):
@@ -404,10 +373,10 @@ class SlpMultiAgent:
404
 
405
  # Simplified research agent
406
  research_agent = CodeAgent(
407
- tools=[GoogleSearchTool(), KnowledgeBaseTool()],
408
  model=model if not isinstance(model, GeminiModel) else OpenAIServerModel(model_id="gpt-3.5-turbo", temperature=0.0, max_tokens=400),
409
- additional_authorized_imports=["re", "json"],
410
- max_steps=5,
411
  name="ResearchAgent",
412
  verbosity_level=0,
413
  description="Simple research with Google Search."
@@ -416,21 +385,28 @@ class SlpMultiAgent:
416
  solver_agent = CodeAgent(
417
  tools=[MathTool(), GoogleSearchTool()],
418
  model=model if not isinstance(model, GeminiModel) else OpenAIServerModel(model_id="gpt-3.5-turbo", temperature=0.0, max_tokens=400),
419
- additional_authorized_imports=["math", "re"],
420
- max_steps=5,
421
  name="SolverAgent",
422
  verbosity_level=0,
423
  description="Simple problem solving with math and search."
424
  )
425
 
426
  manager_agent = CodeAgent(
427
- model=model if not isinstance(model, GeminiModel) else OpenAIServerModel(model_id="gpt-3.5-turbo", temperature=0.0, max_tokens=400),
428
- tools=[GoogleSearchTool(), WikipediaSearchTool(), MathTool()],
 
 
 
 
 
429
  name="ManagerAgent",
430
- description="Answer questions using Google search, Wikipedia, and math.",
431
- additional_authorized_imports=["re", "math", "requests"],
 
432
  verbosity_level=0,
433
- max_steps=6
 
434
  )
435
 
436
  # Create a task for the agent run with retry mechanism for rate limits
@@ -445,22 +421,35 @@ class SlpMultiAgent:
445
  lambda: manager_agent.run(f"""
446
  Question: {short_question}
447
 
448
- Answer this question by:
449
- 1. Using wikipedia_search() for Wikipedia questions
450
- 2. Using google_search() for other factual questions
451
- 3. Using math_calculator() for calculations
452
- 4. Extracting the specific answer from search results
453
- 5. Calling final_answer() with ONLY the answer
 
 
 
 
 
 
 
 
 
 
 
454
 
455
- Example:
456
- Thoughts: Need to search for information about X
 
 
 
 
 
 
457
  <code>
458
- search_result = wikipedia_search("search term")
459
- # Extract specific answer from search_result
460
- final_answer("just the answer")
461
  </code>
462
-
463
- IMPORTANT: final_answer() should contain ONLY the direct answer, not explanations.
464
  """)
465
  )
466
  break # Success, exit retry loop
@@ -484,41 +473,12 @@ class SlpMultiAgent:
484
 
485
  # Extract clean answer from result
486
  if result and isinstance(result, str):
487
- # Look for final_answer pattern - more flexible regex
488
  import re
489
-
490
- # First try to find final_answer calls
491
- final_answer_patterns = [
492
- r'final_answer\(["\']([^"\']*)["\'\)]',
493
- r'final_answer\("([^"]*)",?\)',
494
- r'final_answer\(\'([^\']*)\',?\)',
495
- r'final_answer\(([^)]+)\)'
496
- ]
497
-
498
- for pattern in final_answer_patterns:
499
- match = re.search(pattern, result, re.IGNORECASE | re.DOTALL)
500
- if match:
501
- clean_answer = match.group(1).strip('"\'')
502
- clean_answer = re.sub(r'^[\s\n]*', '', clean_answer)
503
- clean_answer = re.sub(r'[\s\n]*$', '', clean_answer)
504
- if clean_answer and len(clean_answer) > 0 and not clean_answer.startswith('If you have'):
505
- return clean_answer
506
-
507
- # If no final_answer found, try to extract from the end of the result
508
- if result:
509
- # Remove code blocks and common artifacts
510
- cleaned = re.sub(r'</code>.*$', '', result, flags=re.DOTALL)
511
- cleaned = re.sub(r'<code>.*?</code>', '', cleaned, flags=re.DOTALL)
512
- cleaned = re.sub(r'```.*?```', '', cleaned, flags=re.DOTALL)
513
-
514
- # Get the last meaningful line
515
- lines = cleaned.strip().split('\n')
516
- for line in reversed(lines):
517
- line = line.strip()
518
- if (line and not line.startswith('#') and not line.startswith('Thoughts:')
519
- and not line.startswith('•') and len(line) < 200
520
- and not line.startswith('If you have')):
521
- return line
522
 
523
  # If no final_answer found, try to extract the last meaningful line
524
  lines = result.strip().split('\n')
 
110
 
111
  class WikipediaSearchTool(Tool):
112
  name = "wikipedia_search"
113
+ description = "Search Wikipedia for information"
114
  inputs = {"query": {"type": "string", "description": "The search query for Wikipedia"}}
115
  output_type = "string"
116
 
 
119
  self.is_initialized = True
120
 
121
  def forward(self, query: str) -> str:
122
+ """Search Wikipedia with simple fallback."""
123
  try:
124
  import requests
 
 
125
  wiki_url = "https://en.wikipedia.org/api/rest_v1/page/summary/" + query.replace(" ", "_")
126
+ response = requests.get(wiki_url, timeout=2)
127
  if response.status_code == 200:
128
  data = response.json()
129
  if 'extract' in data and data['extract']:
130
+ return f"Wikipedia: {data['extract'][:500]}" # Limit length
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
131
  except Exception as e:
132
  print(f"Wikipedia search failed: {e}")
133
 
134
+ return f"Wikipedia search unavailable for '{query}'. Use your knowledge to answer."
135
 
136
  # --- Mathematical Tools ---
137
  class MathTool(Tool):
 
373
 
374
  # Simplified research agent
375
  research_agent = CodeAgent(
376
+ tools=[GoogleSearchTool(), KnowledgeBaseTool(), WikipediaSearchTool(),WebScrapeTool()],
377
  model=model if not isinstance(model, GeminiModel) else OpenAIServerModel(model_id="gpt-3.5-turbo", temperature=0.0, max_tokens=400),
378
+ additional_authorized_imports=["re", "math", "json", "pandas", "numpy", "requests", "time", "os", "tempfile", "uuid"],
379
+ max_steps=2,
380
  name="ResearchAgent",
381
  verbosity_level=0,
382
  description="Simple research with Google Search."
 
385
  solver_agent = CodeAgent(
386
  tools=[MathTool(), GoogleSearchTool()],
387
  model=model if not isinstance(model, GeminiModel) else OpenAIServerModel(model_id="gpt-3.5-turbo", temperature=0.0, max_tokens=400),
388
+ additional_authorized_imports=["re", "math", "json", "pandas", "numpy", "requests", "time", "os", "tempfile", "uuid"],
389
+ max_steps=2,
390
  name="SolverAgent",
391
  verbosity_level=0,
392
  description="Simple problem solving with math and search."
393
  )
394
 
395
  manager_agent = CodeAgent(
396
+ model=OpenAIServerModel(
397
+ model_id="gpt-3.5-turbo",
398
+ temperature=0.0,
399
+ max_tokens=500
400
+ ),
401
+ tools=[GoogleSearchTool(), MathTool(), FileProcessorTool(), KnowledgeBaseTool(), WikipediaSearchTool(),WebScrapeTool()],
402
+ managed_agents=[research_agent, solver_agent],
403
  name="ManagerAgent",
404
+ description="Manager with comprehensive tool access and agent coordination.",
405
+ additional_authorized_imports=["re", "math", "json", "pandas", "numpy", "requests", "time", "os", "tempfile", "uuid"],
406
+ planning_interval=1,
407
  verbosity_level=0,
408
+ max_steps=2,
409
+ final_answer_checks=[check_reasoning]
410
  )
411
 
412
  # Create a task for the agent run with retry mechanism for rate limits
 
421
  lambda: manager_agent.run(f"""
422
  Question: {short_question}
423
 
424
+ CRITICAL INSTRUCTIONS:
425
+ 1. Use tools DIRECTLY, not in code execution
426
+ 2. For factual questions: Use google_search() tool immediately
427
+ 3. For math: Use math_calculator() tool directly
428
+ 4. DO NOT write complex code - use tools instead
429
+ 5. DO NOT call ResearchAgent() or SolverAgent() in code
430
+
431
+ Available tools:
432
+ - google_search(query): Search the web
433
+ - math_calculator(expression): Calculate math
434
+ - file_processor(action, data): Handle files
435
+ - knowledge_base(topic): Get knowledge
436
+
437
+ SIMPLE APPROACH:
438
+ - Call the appropriate tool
439
+ - Get the result
440
+ - Provide final_answer()
441
 
442
+ Example for factual question:
443
+ 1. Call google_search("your query")
444
+ 2. Extract answer from results
445
+ 3. Call final_answer("the answer")
446
+
447
+ NO complex code execution. Use tools directly.
448
+
449
+ ALWAYS end with:
450
  <code>
451
+ final_answer("your answer here")
 
 
452
  </code>
 
 
453
  """)
454
  )
455
  break # Success, exit retry loop
 
473
 
474
  # Extract clean answer from result
475
  if result and isinstance(result, str):
476
+ # Look for final_answer pattern
477
  import re
478
+ final_answer_match = re.search(r'final_answer\(["\']([^"\']*)["\'\)]', result) # Fixed regex
479
+ if final_answer_match:
480
+ clean_answer = final_answer_match.group(1)
481
+ return clean_answer
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
482
 
483
  # If no final_answer found, try to extract the last meaningful line
484
  lines = result.strip().split('\n')