Spaces:
Sleeping
Sleeping
auth
Browse filesFiles changed (3)
- config.py+6-1
- hf_agent.py+115-5
- test_agent.pyDeleted-42
11 unmodified lines1213141516171811 unmodified lines30313233343511 unmodified lines"code_model": "google/flan-t5-large", # For math/code"retrieval_model": "sentence-transformers/all-MiniLM-L6-v2", # For retrieval"temperature": 0.7,"max_new_tokens": 512,"top_p": 1.0,}11 unmodified lines"Answer the question using only the provided context. ""Be specific and cite relevant information from the context."),"evaluation": ("You are participating in the GAIA evaluation. ""Provide accurate, comprehensive, and concise answers. Focus on the task at hand."11 unmodified lines1213141516171811 unmodified lines303132333435363738394011 unmodified lines"code_model": "google/flan-t5-large", # For math/code"retrieval_model": "sentence-transformers/all-MiniLM-L6-v2", # For retrieval"temperature": 0.7,"max_new_tokens": 256, # Reduced to prevent over-generation"top_p": 1.0,}11 unmodified lines"Answer the question using only the provided context. ""Be specific and cite relevant information from the context."),"web_search": ("You cannot access real-time information or browse the internet. ""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."),"evaluation": ("You are participating in the GAIA evaluation. ""Provide accurate, comprehensive, and concise answers. Focus on the task at hand."
39 unmodified lines404142434445464720 unmodified lines6869707172737475767778796 unmodified lines86878889909192939495969798993 unmodified lines10310410510610710810939 unmodified linesreturn "\n".join(context)def is_math_or_code(self, question):keywords = ["calculate", "compute", "solve", "equation", "math", "code", "python", "step by step", "formula", "percentage", "sum", "average", "mean", "median", "algebra", "geometry", "calculus"]return any(k in question.lower() for k in keywords)def clean_response(self, generated_text, input_text):"""Clean the generated response by removing the input prompt"""20 unmodified linesif response.lower().startswith(prefix.lower()):response = response[len(prefix):].strip()# If response is still the generic introduction, provide a fallbackif "sophisticated ai language model" in response.lower() or len(response) < 10:return "I'm ready to help you with your question. Could you please provide more specific details about what you'd like to know?"return responsedef __call__(self, question, files=None):context = ""if files:6 unmodified linesprompt = f"Context: {context}\n\nQuestion: {question}\n\nAnswer:"input_text = f"{system_prompt}\n{prompt}"result = self.llm(input_text, do_sample=True, temperature=0.7, pad_token_id=self.llm.tokenizer.eos_token_id)generated_text = result[0]["generated_text"]return self.clean_response(generated_text, input_text)elif self.is_math_or_code(question):# Handle math/code questionsprompt = f"Question: {question}\nSolution:"result = self.code(prompt, do_sample=True, temperature=0.3)generated_text = result[0]["generated_text"]return self.clean_response(generated_text, prompt)3 unmodified linesprompt = f"Question: {question}\nAnswer:"input_text = f"{system_prompt}\n{prompt}"result = self.llm(input_text, do_sample=True, temperature=0.7, pad_token_id=self.llm.tokenizer.eos_token_id)generated_text = result[0]["generated_text"]return self.clean_response(generated_text, input_text)39 unmodified lines40414243444546474849505152535455565758596061626364656667686970717273747576777879808182838420 unmodified lines1051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631646 unmodified lines1711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002013 unmodified lines20520620720820921021121221321421521621721821939 unmodified linesreturn "\n".join(context)def is_math_or_code(self, question):math_keywords = ["calculate", "compute", "solve", "equation", "math", "formula", "percentage", "sum", "average", "mean", "median", "algebra", "geometry", "calculus", "multiply", "divide", "add", "subtract", "area", "volume", "circumference"]code_keywords = ["code", "python", "programming", "script", "function", "algorithm", "debug", "syntax"]question_lower = question.lower()math_score = sum(1 for k in math_keywords if k in question_lower)code_score = sum(1 for k in code_keywords if k in question_lower)# Return True if there are multiple math/code indicators or specific patternsreturn (math_score >= 2 or code_score >= 1 orany(pattern in question_lower for pattern in ["step by step", "show work", "how to calculate"]))def is_factual_question(self, question):"""Detect if a question is asking for factual information"""factual_patterns = ["what is", "who is", "where is", "when did", "which", "capital of", "largest", "smallest", "how many"]return any(pattern in question.lower() for pattern in factual_patterns)def needs_web_search(self, question):"""Detect if a question requires web search for current/recent information"""web_search_keywords = ["latest", "recent", "current", "today", "news", "breaking", "update","trending", "now", "live", "real-time", "search", "find", "happening","weather", "stock price", "score", "results", "election", "event"]temporal_keywords = ["2024", "2025", "this year", "this month", "yesterday", "last week"]question_lower = question.lower()# Check for explicit search requestsif any(phrase in question_lower for phrase in ["search for", "find", "look up", "get news"]):return True# Check for web search keywords + temporal indicatorsweb_score = sum(1 for k in web_search_keywords if k in question_lower)temporal_score = sum(1 for k in temporal_keywords if k in question_lower)return web_score >= 1 or temporal_score >= 1def clean_response(self, generated_text, input_text):"""Clean the generated response by removing the input prompt"""20 unmodified linesif response.lower().startswith(prefix.lower()):response = response[len(prefix):].strip()# Stop at common ending patterns to prevent over-generationstop_patterns = ["\nQuestion:","\nAnswer:","\n\nQ:","\n\nA:","\nUser:","\nAssistant:","\n---","\nExample:","\nNote:",]for pattern in stop_patterns:if pattern in response:response = response.split(pattern)[0].strip()# Limit response length for general questions (not math/code)if len(response) > 500:# Find the last complete sentence within 500 characterssentences = response[:500].split('.')if len(sentences) > 1:response = '.'.join(sentences[:-1]) + '.'else:response = response[:500].strip()# If response is still the generic introduction, provide a fallbackif "sophisticated ai language model" in response.lower() or len(response) < 10:return "I'm ready to help you with your question. Could you please provide more specific details about what you'd like to know?"return responsedef get_web_search_guidance(self, question):"""Provide specific guidance based on the type of web search needed"""question_lower = question.lower()if "news" in question_lower:if "vilnius" in question_lower or "lithuania" in question_lower:return "I cannot access real-time news. For the latest news in Vilnius, check: Delfi.lt, LRT.lt, Lietuvos Rytas (lrytas.lt), or 15min.lt."else:return "I cannot access current news. For the latest news, use Google News, BBC News, Reuters, or other reputable news sources."elif "weather" in question_lower:return "I cannot access current weather data. For accurate weather information, check Weather.com, AccuWeather, or your local weather service."elif "stock" in question_lower or "price" in question_lower:return "I cannot access real-time market data. For current stock prices, check Yahoo Finance, Google Finance, or Bloomberg."elif "score" in question_lower or "result" in question_lower:return "I cannot access live scores or recent results. Check ESPN, BBC Sport, or official sports websites for current information."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 __call__(self, question, files=None):context = ""if files:6 unmodified linesprompt = f"Context: {context}\n\nQuestion: {question}\n\nAnswer:"input_text = f"{system_prompt}\n{prompt}"result = self.llm(input_text,do_sample=True,temperature=0.7,max_new_tokens=256,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"]return self.clean_response(generated_text, input_text)elif self.needs_web_search(question):# Handle web search requests with specific guidancereturn self.get_web_search_guidance(question)elif self.is_math_or_code(question):# Handle math/code questionsprompt = f"Question: {question}\nSolution:"result = self.code(prompt,do_sample=True,temperature=0.3,max_new_tokens=256)generated_text = result[0]["generated_text"]return self.clean_response(generated_text, prompt)3 unmodified linesprompt = f"Question: {question}\nAnswer:"input_text = f"{system_prompt}\n{prompt}"result = self.llm(input_text,do_sample=True,temperature=0.7,max_new_tokens=256,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"]return self.clean_response(generated_text, input_text)
123456789101112131415161718192021222324252627282930313233343536373839404142#!/usr/bin/env python3"""Test script to verify HuggingFaceAgent functionality"""
from hf_agent import HuggingFaceAgent
def test_agent(): print("Testing HuggingFace Agent...") agent = HuggingFaceAgent() # Test cases test_questions = [ "What is the capital of France?", "How do you calculate the area of a circle?", "Explain photosynthesis in simple terms", "What is 2 + 2?", "Tell me about machine learning" ] for i, question in enumerate(test_questions, 1): print(f"\n--- Test {i} ---") print(f"Question: {question}") try: answer = agent(question) print(f"Answer: {answer}") print(f"Length: {len(answer)} characters") # Check if it's the problematic generic response if "sophisticated ai language model" in answer.lower(): print("❌ Still returning generic introduction!") else: print("✅ Proper response received") except Exception as e: print(f"❌ Error: {e}") print("\n" + "="*50) print("Agent testing completed!")
if __name__ == "__main__": test_agent() config.py+6-1
hf_agent.py+115-5
test_agent.pyDeleted-42