Spaces:
Sleeping
Sleeping
Update agent.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153import osimport jsonimport refrom typing import Tuple, Dict, Anyfrom transformers import pipeline, AutoTokenizer, AutoModelForSeq2SeqLM # Import AutoTokenizer and AutoModelForSeq2SeqLMfrom tools.asr_tool import transcribe_audiofrom tools.excel_tool import analyze_excelfrom tools.search_tool import search_duckduckgofrom tools.math_tool import calculate_math # Make sure to import your math toolclass GaiaAgent:def __init__(self):token = os.getenv("HUGGINGFACEHUB_API_TOKEN")if not token:raise ValueError("Missing HUGGINGFACEHUB_API_TOKEN environment variable.")# Specify the model and load tokenizer and model separately for better controlmodel_name = "google/flan-t5-large"self.tokenizer = AutoTokenizer.from_pretrained(model_name, token=token)self.model = AutoModelForSeq2SeqLM.from_pretrained(model_name, token=token)# Use the pipeline with the loaded model and tokenizerself.llm = pipeline("text2text-generation",model=self.model,tokenizer=self.tokenizer,device="cpu", # Consider "cuda" if you have a GPUmax_new_tokens=256,do_sample=False, # Set to True if you want to use temperature and top_p/k# temperature=0.1, # Removed, as it's not a valid pipeline initialization flag here)self.system_prompt = """You are a general AI assistant. I will ask you a question. Report your thoughts, and finish your answer with the following template: FINAL ANSWER: [YOUR FINAL ANSWER]. YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings. If you are asked for a number, don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise. If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise. If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string."""def extract_final_answer(self, text: str) -> str:"""Extrahera det slutliga svaret från modellens output"""final_answer_match = re.search(r'FINAL ANSWER:\s*(.+?)(?:\n|$)', text, re.IGNORECASE)if final_answer_match:return final_answer_match.group(1).strip()sentences = text.strip().split('\n')return sentences[-1].strip() if sentences else text.strip()def needs_tool(self, question: str) -> Tuple[str, bool]:"""Bestäm vilket verktyg som behövs baserat på frågan"""question_lower = question.lower()if any(ext in question_lower for ext in ['.mp3', '.wav', '.m4a', '.flac']):return 'audio', Trueif any(ext in question_lower for ext in ['.xlsx', '.xls', '.csv']):return 'excel', Trueif any(keyword in question_lower for keyword in ['search', 'find', 'lookup', 'http', 'www.', 'wikipedia', 'albums', 'discography', 'published', 'website']):return 'search', Trueif any(keyword in question_lower for keyword in ['calculate', 'compute', 'sum', 'average', 'count', 'what is', 'solve']):return 'math', Truereturn 'llm', Falsedef process_with_tools(self, question: str, tool_type: str) -> Tuple[str, str]:"""Bearbeta frågan med specifika verktyg"""trace_log = f"Detected {tool_type} task. Processing...\n"try:if tool_type == 'audio':audio_files = re.findall(r'\b[\w\-_]+\.(mp3|wav|m4a|flac)\b', question, re.IGNORECASE)if audio_files:result = transcribe_audio(audio_files[0])trace_log += f"Audio transcription: {result}\n"return result, trace_logelse:return "No audio file mentioned in the question.", trace_logelif tool_type == 'excel':excel_files = re.findall(r'\b[\w\-_]+\.(xlsx|xls|csv)\b', question, re.IGNORECASE)if excel_files:result = analyze_excel(excel_files[0])trace_log += f"Excel analysis: {result}\n"return result, trace_logelse:return "No Excel file mentioned in the question.", trace_logelif tool_type == 'search':search_query = question # This might need refinement to extract just the search queryresult = search_duckduckgo(search_query)trace_log += f"Search results: {result}\n"return result, trace_logelif tool_type == 'math':math_expression_match = re.search(r'calculate (.+)', question, re.IGNORECASE)if math_expression_match:expression = math_expression_match.group(1).strip()result = calculate_math(expression)trace_log += f"Math calculation: {result}\n"return result, trace_logelse:return "No clear mathematical expression found in the question.", trace_logexcept Exception as e:trace_log += f"Error using {tool_type} tool: {str(e)}\n"return f"Error: {str(e)}", trace_logreturn "No valid input found for tool", trace_logdef reason_with_llm(self, question: str, context: str = "") -> Tuple[str, str]:"""Använd LLM för reasoning med kontext"""trace_log = "Using LLM for reasoning...\n"# Combine system prompt, context, and question, ensuring it fits token limitif context:prompt = f"{self.system_prompt}\n\nContext: {context}\n\nQuestion: {question}\n\nPlease analyze this step by step and provide your final answer."else:prompt = f"{self.system_prompt}\n\nQuestion: {question}\n\nPlease analyze this step by step and provide your final answer."# Tokenize and truncate if necessaryinputs = self.tokenizer(prompt, return_tensors="pt", truncation=True, max_length=self.tokenizer.model_max_length)try:# Generate response using the model's generate method for more control# You can add generation arguments here, e.g., temperature, top_k, etc.outputs = self.model.generate(inputs.input_ids,max_new_tokens=256,do_sample=False, # Set to True to enable temperature and other sampling parameters# temperature=0.1, # Example: Only if do_sample is True)response = self.tokenizer.decode(outputs[0], skip_special_tokens=True)trace_log += f"LLM response: {response}\n"return response, trace_logexcept Exception as e:trace_log += f"Error with LLM: {str(e)}\n"return f"Error: {str(e)}", trace_logdef __call__(self, question: str) -> Tuple[str, str]:"""Huvudfunktion som bearbetar frågan"""total_trace = f"Processing question: {question}\n"tool_type, needs_tool = self.needs_tool(question)total_trace += f"Tool needed: {tool_type}\n"context = ""if needs_tool and tool_type != 'llm':tool_result, tool_trace = self.process_with_tools(question, tool_type)total_trace += tool_tracecontext = tool_resultllm_response, llm_trace = self.reason_with_llm(question, context)total_trace += llm_tracefinal_answer = self.extract_final_answer(llm_response)total_trace += f"Final answer extracted: {final_answer}\n"return final_answer, total_trace12345678910111213141516171819202122232425262728293031323334353637import osfrom transformers import pipeline# Assuming you still want to use your local Flan-T5 model# from tools.search_tool import search_duckduckgo # REMOVE THIS LINE# NEW IMPORTS for smolagentsfrom smolagents import CodeAgent, DuckDuckGoSearchToolfrom smolagents import TransformersModel # To use your local Hugging Face modelclass GaiaAgent:def __init__(self, model_id: str = "google/flan-t5-large"):# Initialize your LLM using smolagents's TransformersModel# This allows smolagents to manage the interaction with your local modelself.llm_model = TransformersModel(model_id=model_id)# Initialize the smolagents CodeAgent# Pass the DuckDuckGoSearchTool directly to the agent's tools list# You can add other tools here if neededself.agent = CodeAgent(model=self.llm_model,tools=[DuckDuckGoSearchTool()],# 'add_base_tools=True' can add common basic tools (like a Python interpreter)# You might need to experiment with this. For now, let's keep it explicit.add_base_tools=False,verbose=True # This is helpful for debugging on Hugging Face Spaces logs)def process_task(self, task_description: str) -> str:# The smolagents agent.run() method handles the entire process# of planning, tool use, and generating a final answer.try:# The agent will decide when to use DuckDuckGoSearchTool based on the promptresponse = self.agent.run(task_description)return responseexcept Exception as e:return f"An error occurred during agent processing: {e}"
agent.py+29-145