Coool2 commited on
Commit
5f48ff2
·
verified ·
1 Parent(s): bac751d

Update agent.py

Browse files
Files changed (1) hide show
  1. agent.py +38 -52
agent.py CHANGED
@@ -257,68 +257,54 @@ analysis_agent = FunctionAgent(
257
 
258
  class IntelligentSourceRouter:
259
  def __init__(self):
260
- # Initialize ArXiv and DuckDuckGo as LlamaIndex tools
261
  self.arxiv_tool = ArxivToolSpec().to_tool_list()[0]
262
- self.duckduckgo_tool = DuckDuckGoSearchToolSpec().to_tool_list()[1]
263
 
264
- def detect_intent_and_extract_content(self, query: str, max_results = 1) -> str:
265
- # Use your LLM to decide between arxiv and web_search
 
 
266
  intent_prompt = f"""
267
- Analyze this query and determine if it's scientific research or general information:
268
- Query: "{query}"
269
- Choose ONE source:
270
- - arxiv: For scientific research, academic papers, technical studies, algorithms, experiments
271
- - web_search: For all other information (current events, general facts, weather, how-to guides, etc.)
272
- Respond with ONLY "arxiv" or "web_search".
273
  """
 
274
  response = proj_llm.complete(intent_prompt)
275
- selected_source = response.text.strip().lower()
276
-
277
- results = [f"**Query**: {query}", f"**Selected Source**: {selected_source}", "="*50]
278
  try:
279
- if selected_source == 'arxiv':
280
- result = self.arxiv_tool.call(query=query)
281
- results.append(f"**ArXiv Research:**\n{result}")
282
  else:
283
- result = self.duckduckgo_tool.call(query=query, max_results=max_results)
284
- # Format results if needed
285
  if isinstance(result, list):
286
- formatted = []
287
- for i, r in enumerate(result, 1):
288
- formatted.append(
289
- f"{i}. **{r.get('title', '')}**\n URL: {r.get('href', '')}\n {r.get('body', '')}"
290
- )
291
- result = "\n".join(formatted)
292
- results.append(f"**Web Search Results:**\n{result}")
293
  except Exception as e:
294
- results.append(f"**Search failed**: {str(e)}")
295
- return "\n\n".join(results)
296
-
297
- # Initialize router
298
- intelligent_router = IntelligentSourceRouter()
299
 
300
- # Create enhanced research tool
301
- def enhanced_smart_research_tool(query: str, task_context: str = "") -> str:
302
- full_query = f"{query} {task_context}".strip()
303
- return intelligent_router.detect_intent_and_extract_content(full_query)
 
304
 
 
305
  research_tool = FunctionTool.from_defaults(
306
- fn=enhanced_smart_research_tool,
307
- name="Research Tool",
308
- description="""Intelligent research specialist that automatically routes between scientific and general sources and extract content. Use this tool at least when you need:
309
-
310
- **Scientific Research (ArXiv + Content Extraction):**
311
-
312
- **General Research (Web + Content Extraction):**
313
-
314
- **Automatic Features:**
315
- - Intelligently selects between ArXiv and web search
316
- - Extracts full content from web pages (not just snippets)
317
- - Provides source attribution and detailed information
318
-
319
- **When to use:** Questions requiring external knowledge not in your training data, current events, scientific research, or factual verification.
320
-
321
- **Input format:** Provide the research query with any relevant context."""
322
  )
323
 
324
  def execute_python_code(code: str) -> str:
@@ -539,7 +525,7 @@ class EnhancedGAIAAgent:
539
 
540
  **2. research_tool** - Intelligent research specialist with automatic routing
541
  - Use for: External knowledge, current events, scientific papers
542
- - Capabilities: Auto-routes between ArXiv (scientific) and web search (general), extracts full content
543
  - When to use: Questions requiring external knowledge, factual verification, current information
544
 
545
  **3. code_tool** - Advanced computational specialist using ReAct reasoning
@@ -649,7 +635,7 @@ class EnhancedGAIAAgent:
649
 
650
  Additionnal instructions to system prompt :
651
  1. If a file is available, use the analysis_tool to process it
652
- 2. If a link is available, use the research_tool to extract the content in it
653
  """
654
 
655
  try:
 
257
 
258
  class IntelligentSourceRouter:
259
  def __init__(self):
 
260
  self.arxiv_tool = ArxivToolSpec().to_tool_list()[0]
261
+ self.duckduckgo_tool = DuckDuckGoSearchToolSpec().to_tool_list()[0]
262
 
263
+ def route_and_search(self, query: str) -> str:
264
+ """Simple routing between academic and general search"""
265
+
266
+ # Quick intent detection
267
  intent_prompt = f"""
268
+ Is this question about scientific research or general information?
269
+ Question: "{query}"
270
+
271
+ Answer "arxiv" for scientific/academic topics, "web" for everything else.
 
 
272
  """
273
+
274
  response = proj_llm.complete(intent_prompt)
275
+ source = "arxiv" if "arxiv" in response.text.lower() else "web"
276
+
 
277
  try:
278
+ if source == "arxiv":
279
+ return self.arxiv_tool.call(query=query)
 
280
  else:
281
+ result = self.duckduckgo_tool.call(query=query)
 
282
  if isinstance(result, list):
283
+ return "\n\n".join([f"{r.get('title', '')}: {r.get('body', '')}" for r in result])
284
+ return str(result)
 
 
 
 
 
285
  except Exception as e:
286
+ return f"Search failed: {str(e)}"
 
 
 
 
287
 
288
+ # Simple research function
289
+ def research_tool_function(query: str) -> str:
290
+ """Answers queries using intelligent source routing"""
291
+ router = IntelligentSourceRouter()
292
+ return router.route_and_search(query)
293
 
294
+ # Clean tool definition
295
  research_tool = FunctionTool.from_defaults(
296
+ fn=research_tool_function,
297
+ name="research_tool",
298
+ description="""Intelligent research tool that answers queries by automatically routing between academic (ArXiv) and general (web) search sources.
299
+
300
+ **When to Use:**
301
+ - Questions requiring external knowledge beyond training data
302
+ - Current or recent information (post-training cutoff)
303
+ - Scientific research requiring academic sources
304
+ - Factual verification of specific claims
305
+ - Any question where search results could provide the exact answer
306
+
307
+ Simply provide your question and get a direct answer."""
 
 
 
 
308
  )
309
 
310
  def execute_python_code(code: str) -> str:
 
525
 
526
  **2. research_tool** - Intelligent research specialist with automatic routing
527
  - Use for: External knowledge, current events, scientific papers
528
+ - Capabilities: Auto-routes between ArXiv (scientific) and web search (general), answers the question
529
  - When to use: Questions requiring external knowledge, factual verification, current information
530
 
531
  **3. code_tool** - Advanced computational specialist using ReAct reasoning
 
635
 
636
  Additionnal instructions to system prompt :
637
  1. If a file is available, use the analysis_tool to process it
638
+ 2. If a link is in the question, use the research_tool. It should provide a direct answer to the question.
639
  """
640
 
641
  try: