Spaces:
Sleeping
Sleeping
Update agent.py
Browse files
agent.py
CHANGED
@@ -2,110 +2,128 @@ import os
|
|
2 |
import json
|
3 |
import re
|
4 |
from typing import Tuple, Dict, Any
|
5 |
-
from transformers import pipeline
|
|
|
6 |
from tools.asr_tool import transcribe_audio
|
7 |
from tools.excel_tool import analyze_excel
|
8 |
from tools.search_tool import search_duckduckgo
|
|
|
9 |
|
10 |
class GaiaAgent:
|
11 |
def __init__(self):
|
12 |
token = os.getenv("HUGGINGFACEHUB_API_TOKEN")
|
13 |
if not token:
|
14 |
raise ValueError("Missing HUGGINGFACEHUB_API_TOKEN environment variable.")
|
15 |
-
|
16 |
-
#
|
|
|
|
|
|
|
|
|
|
|
17 |
self.llm = pipeline(
|
18 |
"text2text-generation",
|
19 |
-
model=
|
20 |
-
|
21 |
-
device="cpu",
|
22 |
max_new_tokens=256,
|
23 |
-
do_sample=False,
|
24 |
-
temperature=0.1,
|
25 |
)
|
26 |
-
|
27 |
-
# System prompt enligt GAIA:s instruktioner
|
28 |
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."""
|
29 |
|
30 |
def extract_final_answer(self, text: str) -> str:
|
31 |
"""Extrahera det slutliga svaret från modellens output"""
|
32 |
-
# Leta efter FINAL ANSWER: mönster
|
33 |
final_answer_match = re.search(r'FINAL ANSWER:\s*(.+?)(?:\n|$)', text, re.IGNORECASE)
|
34 |
if final_answer_match:
|
35 |
return final_answer_match.group(1).strip()
|
36 |
-
|
37 |
-
# Fallback: ta sista meningen om inget FINAL ANSWER hittas
|
38 |
sentences = text.strip().split('\n')
|
39 |
return sentences[-1].strip() if sentences else text.strip()
|
40 |
|
41 |
def needs_tool(self, question: str) -> Tuple[str, bool]:
|
42 |
"""Bestäm vilket verktyg som behövs baserat på frågan"""
|
43 |
question_lower = question.lower()
|
44 |
-
|
45 |
-
# Kontrollera för audio-filer
|
46 |
if any(ext in question_lower for ext in ['.mp3', '.wav', '.m4a', '.flac']):
|
47 |
return 'audio', True
|
48 |
-
|
49 |
-
# Kontrollera för Excel-filer
|
50 |
if any(ext in question_lower for ext in ['.xlsx', '.xls', '.csv']):
|
51 |
return 'excel', True
|
52 |
-
|
53 |
-
# Kontrollera för web-sökning
|
54 |
-
if any(keyword in question_lower for keyword in ['search', 'find', 'lookup', 'http', 'www.', 'wikipedia', 'albums', 'discography', 'published' 'website']):
|
55 |
return 'search', True
|
56 |
-
|
57 |
-
# Kontrollera för matematiska beräkningar
|
58 |
-
if any(keyword in question_lower for keyword in ['calculate', 'compute', 'sum', 'average', 'count']):
|
59 |
return 'math', True
|
60 |
-
|
61 |
return 'llm', False
|
62 |
|
63 |
def process_with_tools(self, question: str, tool_type: str) -> Tuple[str, str]:
|
64 |
"""Bearbeta frågan med specifika verktyg"""
|
65 |
trace_log = f"Detected {tool_type} task. Processing...\n"
|
66 |
-
|
67 |
try:
|
68 |
if tool_type == 'audio':
|
69 |
-
# Extrahera filnamn från frågan
|
70 |
audio_files = re.findall(r'\b[\w\-_]+\.(mp3|wav|m4a|flac)\b', question, re.IGNORECASE)
|
71 |
if audio_files:
|
72 |
result = transcribe_audio(audio_files[0])
|
73 |
trace_log += f"Audio transcription: {result}\n"
|
74 |
return result, trace_log
|
75 |
-
|
|
|
|
|
76 |
elif tool_type == 'excel':
|
77 |
-
# Extrahera filnamn från frågan
|
78 |
excel_files = re.findall(r'\b[\w\-_]+\.(xlsx|xls|csv)\b', question, re.IGNORECASE)
|
79 |
if excel_files:
|
80 |
result = analyze_excel(excel_files[0])
|
81 |
trace_log += f"Excel analysis: {result}\n"
|
82 |
return result, trace_log
|
83 |
-
|
|
|
|
|
84 |
elif tool_type == 'search':
|
85 |
-
#
|
86 |
-
search_query = question
|
87 |
result = search_duckduckgo(search_query)
|
88 |
trace_log += f"Search results: {result}\n"
|
89 |
return result, trace_log
|
90 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
91 |
except Exception as e:
|
92 |
trace_log += f"Error using {tool_type} tool: {str(e)}\n"
|
93 |
return f"Error: {str(e)}", trace_log
|
94 |
-
|
95 |
return "No valid input found for tool", trace_log
|
96 |
|
97 |
def reason_with_llm(self, question: str, context: str = "") -> Tuple[str, str]:
|
98 |
"""Använd LLM för reasoning med kontext"""
|
99 |
trace_log = "Using LLM for reasoning...\n"
|
100 |
-
|
101 |
-
#
|
102 |
if context:
|
103 |
prompt = f"{self.system_prompt}\n\nContext: {context}\n\nQuestion: {question}\n\nPlease analyze this step by step and provide your final answer."
|
104 |
else:
|
105 |
prompt = f"{self.system_prompt}\n\nQuestion: {question}\n\nPlease analyze this step by step and provide your final answer."
|
106 |
-
|
|
|
|
|
|
|
107 |
try:
|
108 |
-
response
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
109 |
trace_log += f"LLM response: {response}\n"
|
110 |
return response, trace_log
|
111 |
except Exception as e:
|
@@ -115,35 +133,21 @@ class GaiaAgent:
|
|
115 |
def __call__(self, question: str) -> Tuple[str, str]:
|
116 |
"""Huvudfunktion som bearbetar frågan"""
|
117 |
total_trace = f"Processing question: {question}\n"
|
118 |
-
|
119 |
-
# Bestäm vilka verktyg som behövs
|
120 |
tool_type, needs_tool = self.needs_tool(question)
|
121 |
total_trace += f"Tool needed: {tool_type}\n"
|
122 |
-
|
123 |
context = ""
|
124 |
if needs_tool and tool_type != 'llm':
|
125 |
-
# Använd verktyg för att samla kontext
|
126 |
tool_result, tool_trace = self.process_with_tools(question, tool_type)
|
127 |
total_trace += tool_trace
|
128 |
context = tool_result
|
129 |
-
|
130 |
-
# Använd LLM för reasoning
|
131 |
llm_response, llm_trace = self.reason_with_llm(question, context)
|
132 |
total_trace += llm_trace
|
133 |
-
|
134 |
-
# Extrahera slutligt svar
|
135 |
final_answer = self.extract_final_answer(llm_response)
|
136 |
total_trace += f"Final answer extracted: {final_answer}\n"
|
137 |
-
|
138 |
-
return final_answer, total_trace
|
139 |
|
140 |
-
|
141 |
-
"""Formatera svar för GAIA-submission"""
|
142 |
-
answer, trace = self.__call__(question)
|
143 |
-
|
144 |
-
return {
|
145 |
-
"task_id": task_id,
|
146 |
-
"model_answer": answer,
|
147 |
-
"reasoning_trace": trace
|
148 |
-
}
|
149 |
|
|
|
2 |
import json
|
3 |
import re
|
4 |
from typing import Tuple, Dict, Any
|
5 |
+
from transformers import pipeline, AutoTokenizer, AutoModelForSeq2SeqLM # Import AutoTokenizer and AutoModelForSeq2SeqLM
|
6 |
+
|
7 |
from tools.asr_tool import transcribe_audio
|
8 |
from tools.excel_tool import analyze_excel
|
9 |
from tools.search_tool import search_duckduckgo
|
10 |
+
from tools.math_tool import calculate_math # Make sure to import your math tool
|
11 |
|
12 |
class GaiaAgent:
|
13 |
def __init__(self):
|
14 |
token = os.getenv("HUGGINGFACEHUB_API_TOKEN")
|
15 |
if not token:
|
16 |
raise ValueError("Missing HUGGINGFACEHUB_API_TOKEN environment variable.")
|
17 |
+
|
18 |
+
# Specify the model and load tokenizer and model separately for better control
|
19 |
+
model_name = "google/flan-t5-large"
|
20 |
+
self.tokenizer = AutoTokenizer.from_pretrained(model_name, token=token)
|
21 |
+
self.model = AutoModelForSeq2SeqLM.from_pretrained(model_name, token=token)
|
22 |
+
|
23 |
+
# Use the pipeline with the loaded model and tokenizer
|
24 |
self.llm = pipeline(
|
25 |
"text2text-generation",
|
26 |
+
model=self.model,
|
27 |
+
tokenizer=self.tokenizer,
|
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 |
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."""
|
35 |
|
36 |
def extract_final_answer(self, text: str) -> str:
|
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 |
if tool_type == 'audio':
|
|
|
64 |
audio_files = re.findall(r'\b[\w\-_]+\.(mp3|wav|m4a|flac)\b', question, re.IGNORECASE)
|
65 |
if audio_files:
|
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 |
trace_log += f"Error using {tool_type} tool: {str(e)}\n"
|
99 |
return f"Error: {str(e)}", trace_log
|
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:
|
|
|
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 |
|