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