Spaces:
Sleeping
Sleeping
auth
Browse filesFiles changed (5)
- .gitignore+4-1
- config.py+11
- evaluation.py+11-1
- hf_agent.py+265-2
- requirements.txt+5-1
1233456venv/.env__pycache__/__pycache__/
.cursorrules/.cursor/13 unmodified lines14151617181920212223242515 unmodified lines414243444546474849505113 unmodified lines "temperature": 0.7, "max_new_tokens": 256, # Reduced to prevent over-generation "top_p": 1.0, "enable_web_search": True, # Enable/disable web search functionality "max_search_results": 5, # Maximum number of search results to return "search_timeout": 10, # Timeout for web search requests in seconds "enable_article_extraction": True, # Enable/disable article content extraction "max_articles_to_read": 3, # Maximum number of articles to read full content "max_article_length": 2000, # Maximum length of extracted article content}
# --- System Prompts ---15 unmodified lines "When users ask for current/recent information, acknowledge this limitation clearly and provide specific, actionable guidance on where they can find this information themselves. " "Be direct and helpful about the best sources for their query." ), "web_search_with_content": ( "You have been provided with current web search results that include extracted article content. " "Synthesize the information from the articles to provide a comprehensive answer to the user's question. " "Cite specific sources when mentioning information. Be accurate and informative." ), "evaluation": ( "You are participating in the GAIA evaluation. " "Provide accurate, comprehensive, and concise answers. Focus on the task at hand."93 unmodified lines9495969798991001011023 unmodified lines10610710810911010611111211311411511611711811993 unmodified lines <span style='color:#555'> - **Free models only** (no OpenAI) - **Real-time web search** with DuckDuckGo integration - **Article content extraction** - reads full articles from search results - **Intelligent synthesis** - combines information from multiple sources - Handles all question types and file attachments - Beautiful, modern UI - Robust agentic flows for GAIA evaluation3 unmodified lines **Instructions:** 1. Login with your Hugging Face account. 2. Ask any question, optionally upload files (PDF, CSV, TXT, DOCX, images). 3. **Web Search**: Ask for latest news, current information, or real-time data. 4. **Article Extraction**: Use keywords like "detailed", "full analysis", or "comprehensive" for in-depth article reading. 3. Or run the full GAIA evaluation and submit your answers. 5. Or run the full GAIA evaluation and submit your answers. **Search Tips:** - For quick results: "brief news about X" or "quick summary of Y" - For detailed analysis: "comprehensive report on X" or "detailed analysis of Y" - For news: "latest news in [location]" automatically extracts article content """) if not ON_SPACES: gr.Markdown("<span style='color:red'><b>Warning:</b> OAuth login and profile are only available on Hugging Face Spaces. Evaluation will use a dummy profile.</span>")5 unmodified lines678910111213141516172 unmodified lines2021222324252660 unmodified lines8788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119273 unmodified lines26626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438519 unmodified lines4054064071871884084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534545 unmodified linesfrom docx import Documentfrom PIL import Imageimport iofrom ddgs import DDGSfrom newspaper import Articlefrom bs4 import BeautifulSoupimport requestsfrom urllib.parse import urljoin, urlparseimport time
class HuggingFaceAgent: def __init__(self):2 unmodified lines self.code = pipeline("text2text-generation", model=self.config["code_model"], max_new_tokens=self.config["max_new_tokens"]) # Retrieval pipeline can be added here if needed self.supported_file_types = get_supported_file_types() self.ddgs = DDGS()
def extract_file_context(self, files): context = []60 unmodified lines return web_score >= 1 or temporal_score >= 1
def perform_web_search(self, query, max_results=None): """Perform web search using DuckDuckGo and optionally extract article content""" if max_results is None: max_results = self.config.get("max_search_results", 5) try: # Improve query processing for better results cleaned_query = query.lower().strip() # Remove search-related terms but preserve important context search_terms_to_remove = ["search", "find", "look up", "get"] for term in search_terms_to_remove: if cleaned_query.startswith(term): cleaned_query = cleaned_query[len(term):].strip() # Handle specific patterns for better results if "news" in cleaned_query: if "vilnius" in cleaned_query or "lithuania" in cleaned_query: cleaned_query = "Vilnius Lithuania news" elif "latest news" in cleaned_query: cleaned_query = cleaned_query.replace("latest", "").strip() + " news today" elif "weather" in cleaned_query: # Extract location for weather queries if "in " in cleaned_query: location = cleaned_query.split("in ")[-1].strip() cleaned_query = f"weather {location} today" # Ensure we have a meaningful query if not cleaned_query or len(cleaned_query.strip()) < 3: cleaned_query = query # fallback to original # Add timeout handling timeout = self.config.get("search_timeout", 10) results = self.ddgs.text(cleaned_query, max_results=max_results) if not results: return "No search results found for your query. Try rephrasing or being more specific." # Check if article extraction is enabled and recommended for this query extract_articles = (self.config.get("enable_article_extraction", True) and self.should_extract_articles(query)) if extract_articles: # Extract URLs for article reading urls = [result.get('href', '') for result in results if result.get('href')] max_articles = self.config.get("max_articles_to_read", 3) # Extract article content articles = self.extract_multiple_articles(urls, max_articles) # Format results with article content formatted_results = [] for i, (result, article) in enumerate(zip(results, articles), 1): title = result.get('title', 'No title') snippet = result.get('body', 'No description') url = result.get('href', '') if len(snippet) > 150: snippet = snippet[:150] + "..." result_text = f"**{i}. {title}**\n{snippet}\nSource: {url}" # Add extracted article content if successful if article['success'] and i <= max_articles: result_text += f"\n\n**Article Content:**\n{article['content']}" elif i <= max_articles: result_text += f"\n\n**Article Content:** {article['content']}" formatted_results.append(result_text) search_summary = f"Found {len(results)} results for '{cleaned_query}' (extracted content from first {min(max_articles, len(results))} articles):\n\n" return search_summary + "\n\n" + "="*80 + "\n\n".join(formatted_results) else: # Standard search results without article extraction formatted_results = [] for i, result in enumerate(results, 1): title = result.get('title', 'No title') snippet = result.get('body', 'No description') url = result.get('href', '') # Limit snippet length if len(snippet) > 200: snippet = snippet[:200] + "..." formatted_results.append(f"**{i}. {title}**\n{snippet}\nSource: {url}") search_summary = f"Found {len(results)} results for '{cleaned_query}':\n\n" return search_summary + "\n\n".join(formatted_results) except Exception as e: error_msg = str(e).lower() if "timeout" in error_msg or "connection" in error_msg: return "Web search timed out or connection failed. Please try again later." elif "rate limit" in error_msg: return "Search rate limit exceeded. Please wait a moment and try again." else: return f"Web search encountered an error. Please try rephrasing your query."
def clean_response(self, generated_text, input_text): """Clean the generated response by removing the input prompt""" # Remove the input text from the beginning if present73 unmodified lines else: return "I cannot access real-time information from the internet. For current data, please use a search engine or visit relevant official websites."
def extract_article_content(self, url, max_length=2000): """Extract article content from a URL""" try: # First try with newspaper3k (best for news articles) article = Article(url) article.download() article.parse() if article.text and len(article.text.strip()) > 100: content = article.text.strip() title = article.title or "Article" # Limit content length if len(content) > max_length: content = content[:max_length] + "..." return { "title": title, "content": content, "success": True } except Exception as e: pass # Fallback: try with BeautifulSoup try: headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36' } response = requests.get(url, headers=headers, timeout=10) response.raise_for_status() soup = BeautifulSoup(response.content, 'html.parser') # Remove script and style elements for script in soup(["script", "style", "nav", "footer", "header", "aside"]): script.decompose() # Try to find main content content_selectors = [ 'article', '.article-content', '.post-content', '.entry-content', '.content', '#content', 'main', '.main-content', 'p' ] content = "" title = soup.find('title') title = title.get_text().strip() if title else "Article" for selector in content_selectors: elements = soup.select(selector) if elements: content = ' '.join([elem.get_text().strip() for elem in elements]) if len(content) > 100: break if content and len(content.strip()) > 100: content = content.strip() # Limit content length if len(content) > max_length: content = content[:max_length] + "..." return { "title": title, "content": content, "success": True } except Exception as e: pass return { "title": "Failed to extract", "content": "Could not extract article content from this URL.", "success": False }
def extract_multiple_articles(self, urls, max_articles=3): """Extract content from multiple URLs with rate limiting""" extracted_articles = [] for i, url in enumerate(urls[:max_articles]): if i > 0: time.sleep(1) # Rate limiting article_data = self.extract_article_content(url) article_data['url'] = url extracted_articles.append(article_data) return extracted_articles
def should_extract_articles(self, question): """Determine if we should extract article content based on the query""" # Skip article extraction for simple/quick queries quick_query_indicators = [ "quick", "fast", "summary", "brief", "short", "overview" ] question_lower = question.lower() if any(indicator in question_lower for indicator in quick_query_indicators): return False # Extract articles for news and detailed information requests detailed_query_indicators = [ "details", "full", "complete", "comprehensive", "in-depth", "article", "report", "analysis", "explain" ] if any(indicator in question_lower for indicator in detailed_query_indicators): return True # Default: extract articles for news queries, skip for others return "news" in question_lower
def __call__(self, question, files=None): context = "" if files:19 unmodified lines return self.clean_response(generated_text, input_text) elif self.needs_web_search(question): # Handle web search requests with specific guidance return self.get_web_search_guidance(question) # Handle web search requests if self.config.get("enable_web_search", True): try: search_results = self.perform_web_search(question) # If article extraction is enabled, try to synthesize the information if (self.config.get("enable_article_extraction", True) and "Article Content:" in search_results and len(search_results) > 1000): # Only synthesize if we have substantial content try: # Use LLM to synthesize the article content system_prompt = get_system_prompt("web_search_with_content") prompt = f"Search Results with Article Content:\n{search_results}\n\nUser Question: {question}\n\nSynthesized Answer:" input_text = f"{system_prompt}\n{prompt}" result = self.llm( input_text, do_sample=True, temperature=0.7, max_new_tokens=512, # More tokens for synthesis pad_token_id=self.llm.tokenizer.eos_token_id, eos_token_id=self.llm.tokenizer.eos_token_id, repetition_penalty=1.1 ) generated_text = result[0]["generated_text"] synthesized_answer = self.clean_response(generated_text, input_text) # Return both synthesized answer and full search results return f"**Synthesized Answer:**\n{synthesized_answer}\n\n{'='*80}\n\n**Full Search Results:**\n{search_results}" except Exception as e: # If synthesis fails, return raw search results return search_results else: # Return search results as-is return search_results except Exception as e: # Fallback to guidance if search fails return self.get_web_search_guidance(question) else: # Web search disabled, provide guidance return self.get_web_search_guidance(question) elif self.is_math_or_code(question): # Handle math/code questions4 unmodified lines5678891011124 unmodified linespdfplumber>=0.10.0python-docx>=0.8.11Pillow>=9.0.0requests>=2.28.0requests>=2.28.0ddgs>=9.4.0beautifulsoup4>=4.13.0newspaper3k>=0.2.8lxml[html_clean]>=6.0.0.gitignore+4-1
config.py+11
evaluation.py+11-1
hf_agent.py+265-2
requirements.txt+5-1