Update app.py
Browse files
app.py
CHANGED
|
@@ -10,14 +10,151 @@ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
|
| 10 |
|
| 11 |
# --- Basic Agent Definition ---
|
| 12 |
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
class BasicAgent:
|
| 14 |
def __init__(self):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
print("BasicAgent initialized.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
def __call__(self, question: str) -> str:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
| 23 |
"""
|
|
|
|
| 10 |
|
| 11 |
# --- Basic Agent Definition ---
|
| 12 |
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
| 13 |
+
import os
|
| 14 |
+
from typing import List, Dict, Any, Optional
|
| 15 |
+
# from smolagents import CodeAgent, Tool
|
| 16 |
+
# from smolagents.models import ApiModel
|
| 17 |
+
from smolagents import CodeAgent, DuckDuckGoSearchTool, FinalAnswerTool, InferenceClientModel, Tool, tool, VisitWebpageTool
|
| 18 |
+
|
| 19 |
+
import json
|
| 20 |
+
from duckduckgo_search import DDGS
|
| 21 |
+
import wikipedia
|
| 22 |
+
import re
|
| 23 |
+
from datetime import datetime
|
| 24 |
+
|
| 25 |
+
class WebSearchTool(Tool):
|
| 26 |
+
name = "web_search"
|
| 27 |
+
description = "Search the web for information on a given query using DuckDuckGo"
|
| 28 |
+
|
| 29 |
+
def search(self, query: str, max_results: int = 5) -> List[Dict[str, str]]:
|
| 30 |
+
"""
|
| 31 |
+
Search the web for information using DuckDuckGo.
|
| 32 |
+
|
| 33 |
+
Args:
|
| 34 |
+
query: The search query
|
| 35 |
+
max_results: Maximum number of results to return
|
| 36 |
+
|
| 37 |
+
Returns:
|
| 38 |
+
List of search results with title, body, and href
|
| 39 |
+
"""
|
| 40 |
+
try:
|
| 41 |
+
with DDGS() as ddgs:
|
| 42 |
+
results = list(ddgs.text(query, max_results=max_results))
|
| 43 |
+
return results
|
| 44 |
+
except Exception as e:
|
| 45 |
+
return [{"title": "Error", "body": f"Search error: {str(e)}", "href": ""}]
|
| 46 |
+
|
| 47 |
+
class WikipediaTool(Tool):
|
| 48 |
+
name = "wikipedia"
|
| 49 |
+
description = "Search Wikipedia for information on a given topic"
|
| 50 |
+
|
| 51 |
+
def search(self, query: str, sentences: int = 3) -> str:
|
| 52 |
+
"""
|
| 53 |
+
Search Wikipedia for information on a topic.
|
| 54 |
+
|
| 55 |
+
Args:
|
| 56 |
+
query: The search query
|
| 57 |
+
sentences: Number of sentences to return in the summary
|
| 58 |
+
|
| 59 |
+
Returns:
|
| 60 |
+
Wikipedia summary as a string
|
| 61 |
+
"""
|
| 62 |
+
try:
|
| 63 |
+
result = wikipedia.summary(query, sentences=sentences)
|
| 64 |
+
return result
|
| 65 |
+
except wikipedia.exceptions.DisambiguationError as e:
|
| 66 |
+
return f"Multiple results found. Try one of these: {', '.join(e.options[:5])}"
|
| 67 |
+
except wikipedia.exceptions.PageError:
|
| 68 |
+
return f"No Wikipedia page found for '{query}'"
|
| 69 |
+
except Exception as e:
|
| 70 |
+
return f"Wikipedia search error: {str(e)}"
|
| 71 |
+
|
| 72 |
+
class DateTimeTool(Tool):
|
| 73 |
+
name = "datetime_tool"
|
| 74 |
+
description = "Get current date and time information"
|
| 75 |
+
|
| 76 |
+
def get_current_datetime(self) -> str:
|
| 77 |
+
"""Get the current date and time."""
|
| 78 |
+
now = datetime.now()
|
| 79 |
+
return now.strftime("%Y-%m-%d %H:%M:%S")
|
| 80 |
+
|
| 81 |
class BasicAgent:
|
| 82 |
def __init__(self):
|
| 83 |
+
"""
|
| 84 |
+
Initialize the GAIA dataset agent with SmoLagents.
|
| 85 |
+
|
| 86 |
+
Args:
|
| 87 |
+
api_key: API key for the LLM provider
|
| 88 |
+
model_name: Name of the LLM model to use
|
| 89 |
+
"""
|
| 90 |
print("BasicAgent initialized.")
|
| 91 |
+
|
| 92 |
+
# Initialize tools
|
| 93 |
+
self.web_search_tool = DuckDuckGoSearchTool()
|
| 94 |
+
# self.wiki_tool = WikipediaTool()
|
| 95 |
+
self.datetime_tool = DateTimeTool()
|
| 96 |
+
|
| 97 |
+
# Set up model
|
| 98 |
+
self.model = InferenceClientModel()
|
| 99 |
+
|
| 100 |
+
# Initialize the agent
|
| 101 |
+
self.agent = CodeAgent(
|
| 102 |
+
model=self.model,
|
| 103 |
+
tools=[
|
| 104 |
+
self.web_search_tool,
|
| 105 |
+
# self.wiki_tool,
|
| 106 |
+
self.datetime_tool,
|
| 107 |
+
],
|
| 108 |
+
verbose=False # Set to True for detailed logs
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
def __call__(self, question: str) -> str:
|
| 112 |
+
"""
|
| 113 |
+
Process a question and return an answer.
|
| 114 |
+
|
| 115 |
+
Args:
|
| 116 |
+
question: The question to answer
|
| 117 |
+
|
| 118 |
+
Returns:
|
| 119 |
+
The answer to the question
|
| 120 |
+
"""
|
| 121 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 122 |
+
|
| 123 |
+
# Create a prompt for the agent
|
| 124 |
+
system_prompt = """
|
| 125 |
+
You are a knowledgeable assistant answering questions from the GAIA dataset.
|
| 126 |
+
Your task is to provide accurate, well-researched answers based on the best available information.
|
| 127 |
+
Follow these guidelines:
|
| 128 |
+
1. Use search tools to find relevant information
|
| 129 |
+
2. Check Wikipedia for background knowledge
|
| 130 |
+
3. Verify facts when possible
|
| 131 |
+
4. Be transparent about uncertainty
|
| 132 |
+
5. Provide clear, concise answers with supporting evidence
|
| 133 |
+
6. If the question is unclear, ask for clarification
|
| 134 |
+
7. If information is unavailable, say so rather than making things up
|
| 135 |
+
|
| 136 |
+
Always cite your sources in your answer.
|
| 137 |
+
"""
|
| 138 |
+
|
| 139 |
+
full_prompt = f"{system_prompt}\n\nQuestion: {question}\n\nAnswer:"
|
| 140 |
+
|
| 141 |
+
try:
|
| 142 |
+
# Run the agent
|
| 143 |
+
response = self.agent.run(full_prompt)
|
| 144 |
+
|
| 145 |
+
# Clean up the response
|
| 146 |
+
# Remove any system-prompt-like text at the beginning
|
| 147 |
+
cleaned_response = re.sub(r'^.*?Answer:', '', response, flags=re.DOTALL).strip()
|
| 148 |
+
|
| 149 |
+
if not cleaned_response:
|
| 150 |
+
cleaned_response = response # Fallback to original if cleaning removes everything
|
| 151 |
+
|
| 152 |
+
print(f"Agent returning answer (first 50 chars): {cleaned_response[:50]}...")
|
| 153 |
+
return cleaned_response
|
| 154 |
+
except Exception as e:
|
| 155 |
+
error_msg = f"Error processing question: {str(e)}"
|
| 156 |
+
print(error_msg)
|
| 157 |
+
return error_msg
|
| 158 |
|
| 159 |
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
| 160 |
"""
|