Spaces:
Sleeping
Sleeping
Update agent.py
Browse files
agent.py
CHANGED
|
@@ -1,153 +1,37 @@
|
|
| 1 |
import os
|
| 2 |
-
import
|
| 3 |
-
|
| 4 |
-
from
|
| 5 |
-
from transformers import pipeline, AutoTokenizer, AutoModelForSeq2SeqLM # Import AutoTokenizer and AutoModelForSeq2SeqLM
|
| 6 |
|
| 7 |
-
|
| 8 |
-
from
|
| 9 |
-
from
|
| 10 |
-
from tools.math_tool import calculate_math # Make sure to import your math tool
|
| 11 |
|
| 12 |
class GaiaAgent:
|
| 13 |
-
def __init__(self):
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
#
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
self.
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
device="cpu", # Consider "cuda" if you have a GPU
|
| 29 |
-
max_new_tokens=256,
|
| 30 |
-
do_sample=False, # Set to True if you want to use temperature and top_p/k
|
| 31 |
-
# temperature=0.1, # Removed, as it's not a valid pipeline initialization flag here
|
| 32 |
)
|
| 33 |
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
"""Extrahera det slutliga svaret från modellens output"""
|
| 38 |
-
final_answer_match = re.search(r'FINAL ANSWER:\s*(.+?)(?:\n|$)', text, re.IGNORECASE)
|
| 39 |
-
if final_answer_match:
|
| 40 |
-
return final_answer_match.group(1).strip()
|
| 41 |
-
sentences = text.strip().split('\n')
|
| 42 |
-
return sentences[-1].strip() if sentences else text.strip()
|
| 43 |
-
|
| 44 |
-
def needs_tool(self, question: str) -> Tuple[str, bool]:
|
| 45 |
-
"""Bestäm vilket verktyg som behövs baserat på frågan"""
|
| 46 |
-
question_lower = question.lower()
|
| 47 |
-
|
| 48 |
-
if any(ext in question_lower for ext in ['.mp3', '.wav', '.m4a', '.flac']):
|
| 49 |
-
return 'audio', True
|
| 50 |
-
if any(ext in question_lower for ext in ['.xlsx', '.xls', '.csv']):
|
| 51 |
-
return 'excel', True
|
| 52 |
-
if any(keyword in question_lower for keyword in ['search', 'find', 'lookup', 'http', 'www.', 'wikipedia', 'albums', 'discography', 'published', 'website']):
|
| 53 |
-
return 'search', True
|
| 54 |
-
if any(keyword in question_lower for keyword in ['calculate', 'compute', 'sum', 'average', 'count', 'what is', 'solve']):
|
| 55 |
-
return 'math', True
|
| 56 |
-
return 'llm', False
|
| 57 |
-
|
| 58 |
-
def process_with_tools(self, question: str, tool_type: str) -> Tuple[str, str]:
|
| 59 |
-
"""Bearbeta frågan med specifika verktyg"""
|
| 60 |
-
trace_log = f"Detected {tool_type} task. Processing...\n"
|
| 61 |
-
|
| 62 |
try:
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
result = transcribe_audio(audio_files[0])
|
| 67 |
-
trace_log += f"Audio transcription: {result}\n"
|
| 68 |
-
return result, trace_log
|
| 69 |
-
else:
|
| 70 |
-
return "No audio file mentioned in the question.", trace_log
|
| 71 |
-
|
| 72 |
-
elif tool_type == 'excel':
|
| 73 |
-
excel_files = re.findall(r'\b[\w\-_]+\.(xlsx|xls|csv)\b', question, re.IGNORECASE)
|
| 74 |
-
if excel_files:
|
| 75 |
-
result = analyze_excel(excel_files[0])
|
| 76 |
-
trace_log += f"Excel analysis: {result}\n"
|
| 77 |
-
return result, trace_log
|
| 78 |
-
else:
|
| 79 |
-
return "No Excel file mentioned in the question.", trace_log
|
| 80 |
-
|
| 81 |
-
elif tool_type == 'search':
|
| 82 |
-
search_query = question # This might need refinement to extract just the search query
|
| 83 |
-
result = search_duckduckgo(search_query)
|
| 84 |
-
trace_log += f"Search results: {result}\n"
|
| 85 |
-
return result, trace_log
|
| 86 |
-
|
| 87 |
-
elif tool_type == 'math':
|
| 88 |
-
math_expression_match = re.search(r'calculate (.+)', question, re.IGNORECASE)
|
| 89 |
-
if math_expression_match:
|
| 90 |
-
expression = math_expression_match.group(1).strip()
|
| 91 |
-
result = calculate_math(expression)
|
| 92 |
-
trace_log += f"Math calculation: {result}\n"
|
| 93 |
-
return result, trace_log
|
| 94 |
-
else:
|
| 95 |
-
return "No clear mathematical expression found in the question.", trace_log
|
| 96 |
-
|
| 97 |
except Exception as e:
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
return "No valid input found for tool", trace_log
|
| 102 |
-
|
| 103 |
-
def reason_with_llm(self, question: str, context: str = "") -> Tuple[str, str]:
|
| 104 |
-
"""Använd LLM för reasoning med kontext"""
|
| 105 |
-
trace_log = "Using LLM for reasoning...\n"
|
| 106 |
-
|
| 107 |
-
# Combine system prompt, context, and question, ensuring it fits token limit
|
| 108 |
-
if context:
|
| 109 |
-
prompt = f"{self.system_prompt}\n\nContext: {context}\n\nQuestion: {question}\n\nPlease analyze this step by step and provide your final answer."
|
| 110 |
-
else:
|
| 111 |
-
prompt = f"{self.system_prompt}\n\nQuestion: {question}\n\nPlease analyze this step by step and provide your final answer."
|
| 112 |
-
|
| 113 |
-
# Tokenize and truncate if necessary
|
| 114 |
-
inputs = self.tokenizer(prompt, return_tensors="pt", truncation=True, max_length=self.tokenizer.model_max_length)
|
| 115 |
-
|
| 116 |
-
try:
|
| 117 |
-
# Generate response using the model's generate method for more control
|
| 118 |
-
# You can add generation arguments here, e.g., temperature, top_k, etc.
|
| 119 |
-
outputs = self.model.generate(
|
| 120 |
-
inputs.input_ids,
|
| 121 |
-
max_new_tokens=256,
|
| 122 |
-
do_sample=False, # Set to True to enable temperature and other sampling parameters
|
| 123 |
-
# temperature=0.1, # Example: Only if do_sample is True
|
| 124 |
-
)
|
| 125 |
-
response = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 126 |
-
|
| 127 |
-
trace_log += f"LLM response: {response}\n"
|
| 128 |
-
return response, trace_log
|
| 129 |
-
except Exception as e:
|
| 130 |
-
trace_log += f"Error with LLM: {str(e)}\n"
|
| 131 |
-
return f"Error: {str(e)}", trace_log
|
| 132 |
-
|
| 133 |
-
def __call__(self, question: str) -> Tuple[str, str]:
|
| 134 |
-
"""Huvudfunktion som bearbetar frågan"""
|
| 135 |
-
total_trace = f"Processing question: {question}\n"
|
| 136 |
-
|
| 137 |
-
tool_type, needs_tool = self.needs_tool(question)
|
| 138 |
-
total_trace += f"Tool needed: {tool_type}\n"
|
| 139 |
-
|
| 140 |
-
context = ""
|
| 141 |
-
if needs_tool and tool_type != 'llm':
|
| 142 |
-
tool_result, tool_trace = self.process_with_tools(question, tool_type)
|
| 143 |
-
total_trace += tool_trace
|
| 144 |
-
context = tool_result
|
| 145 |
-
|
| 146 |
-
llm_response, llm_trace = self.reason_with_llm(question, context)
|
| 147 |
-
total_trace += llm_trace
|
| 148 |
-
|
| 149 |
-
final_answer = self.extract_final_answer(llm_response)
|
| 150 |
-
total_trace += f"Final answer extracted: {final_answer}\n"
|
| 151 |
-
|
| 152 |
-
return final_answer, total_trace
|
| 153 |
-
|
|
|
|
| 1 |
import os
|
| 2 |
+
from transformers import pipeline
|
| 3 |
+
# Assuming you still want to use your local Flan-T5 model
|
| 4 |
+
# from tools.search_tool import search_duckduckgo # REMOVE THIS LINE
|
|
|
|
| 5 |
|
| 6 |
+
# NEW IMPORTS for smolagents
|
| 7 |
+
from smolagents import CodeAgent, DuckDuckGoSearchTool
|
| 8 |
+
from smolagents import TransformersModel # To use your local Hugging Face model
|
|
|
|
| 9 |
|
| 10 |
class GaiaAgent:
|
| 11 |
+
def __init__(self, model_id: str = "google/flan-t5-large"):
|
| 12 |
+
# Initialize your LLM using smolagents's TransformersModel
|
| 13 |
+
# This allows smolagents to manage the interaction with your local model
|
| 14 |
+
self.llm_model = TransformersModel(model_id=model_id)
|
| 15 |
+
|
| 16 |
+
# Initialize the smolagents CodeAgent
|
| 17 |
+
# Pass the DuckDuckGoSearchTool directly to the agent's tools list
|
| 18 |
+
# You can add other tools here if needed
|
| 19 |
+
self.agent = CodeAgent(
|
| 20 |
+
model=self.llm_model,
|
| 21 |
+
tools=[DuckDuckGoSearchTool()],
|
| 22 |
+
# 'add_base_tools=True' can add common basic tools (like a Python interpreter)
|
| 23 |
+
# You might need to experiment with this. For now, let's keep it explicit.
|
| 24 |
+
add_base_tools=False,
|
| 25 |
+
verbose=True # This is helpful for debugging on Hugging Face Spaces logs
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
)
|
| 27 |
|
| 28 |
+
def process_task(self, task_description: str) -> str:
|
| 29 |
+
# The smolagents agent.run() method handles the entire process
|
| 30 |
+
# of planning, tool use, and generating a final answer.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
try:
|
| 32 |
+
# The agent will decide when to use DuckDuckGoSearchTool based on the prompt
|
| 33 |
+
response = self.agent.run(task_description)
|
| 34 |
+
return response
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
except Exception as e:
|
| 36 |
+
return f"An error occurred during agent processing: {e}"
|
| 37 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|