Delete agent.py
Browse files
agent.py
DELETED
@@ -1,177 +0,0 @@
|
|
1 |
-
import os
|
2 |
-
import re
|
3 |
-
import io
|
4 |
-
import base64
|
5 |
-
import requests
|
6 |
-
import pandas as pd
|
7 |
-
from openai import OpenAI
|
8 |
-
from word2number import w2n
|
9 |
-
from langchain_community.tools import DuckDuckGoSearchRun
|
10 |
-
|
11 |
-
class GaiaAgent:
|
12 |
-
def __init__(self):
|
13 |
-
self.client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
|
14 |
-
self.api_url = "https://agents-course-unit4-scoring.hf.space"
|
15 |
-
self.search_tool = DuckDuckGoSearchRun()
|
16 |
-
|
17 |
-
def fetch_file(self, task_id):
|
18 |
-
try:
|
19 |
-
url = f"{self.api_url}/files/{task_id}"
|
20 |
-
r = requests.get(url, timeout=10)
|
21 |
-
r.raise_for_status()
|
22 |
-
return r.content, r.headers.get("Content-Type", "")
|
23 |
-
except:
|
24 |
-
return None, None
|
25 |
-
|
26 |
-
def ask(self, prompt):
|
27 |
-
try:
|
28 |
-
r = self.client.chat.completions.create(
|
29 |
-
model="gpt-4-turbo",
|
30 |
-
messages=[{"role": "user", "content": prompt}],
|
31 |
-
temperature=0
|
32 |
-
)
|
33 |
-
return r.choices[0].message.content.strip()
|
34 |
-
except:
|
35 |
-
return "[ERROR: ask failed]"
|
36 |
-
|
37 |
-
def search_context(self, query):
|
38 |
-
try:
|
39 |
-
result = self.search_tool.run(query)
|
40 |
-
return result[:2000] if result else "[NO RESULT]"
|
41 |
-
except:
|
42 |
-
return "[WEB ERROR]"
|
43 |
-
|
44 |
-
def handle_file(self, content, ctype, question):
|
45 |
-
try:
|
46 |
-
if "image" in ctype:
|
47 |
-
b64 = base64.b64encode(content).decode("utf-8")
|
48 |
-
result = self.client.chat.completions.create(
|
49 |
-
model="gpt-4o",
|
50 |
-
messages=[
|
51 |
-
{"role": "system", "content": "You're a chess assistant. Give the best move in algebraic notation (e.g., Qd1#)."},
|
52 |
-
{"role": "user", "content": [
|
53 |
-
{"type": "text", "text": question},
|
54 |
-
{"type": "image_url", "image_url": {"url": f"data:image/png;base64,{b64}"}}
|
55 |
-
]}
|
56 |
-
]
|
57 |
-
)
|
58 |
-
return result.choices[0].message.content.strip()
|
59 |
-
|
60 |
-
if "audio" in ctype:
|
61 |
-
with open("/tmp/audio.mp3", "wb") as f:
|
62 |
-
f.write(content)
|
63 |
-
result = self.client.audio.transcriptions.create(model="whisper-1", file=open("/tmp/audio.mp3", "rb"))
|
64 |
-
return result.text
|
65 |
-
|
66 |
-
if "excel" in ctype:
|
67 |
-
df = pd.read_excel(io.BytesIO(content), engine="openpyxl")
|
68 |
-
df.columns = [c.lower().strip() for c in df.columns]
|
69 |
-
if 'sales' in df.columns:
|
70 |
-
df['sales'] = pd.to_numeric(df['sales'], errors='coerce')
|
71 |
-
if 'category' in df.columns:
|
72 |
-
df = df[df['category'].astype(str).str.lower().str.contains('food')]
|
73 |
-
return f"${df['sales'].sum():.2f}"
|
74 |
-
return "$0.00"
|
75 |
-
|
76 |
-
return content.decode("utf-8", errors="ignore")[:3000]
|
77 |
-
except:
|
78 |
-
return "[FILE ERROR]"
|
79 |
-
|
80 |
-
def extract_ingredients(self, text):
|
81 |
-
try:
|
82 |
-
tokens = re.findall(r"[a-zA-Z]+(?:\s[a-zA-Z]+)?", text)
|
83 |
-
blocked = {"add", "combine", "cook", "stir", "remove", "cool", "mixture", "saucepan", "until", "heat", "dash"}
|
84 |
-
filtered = [t.lower() for t in tokens if t.lower() not in blocked and len(t.split()) <= 3]
|
85 |
-
return ", ".join(sorted(set(filtered)))
|
86 |
-
except:
|
87 |
-
return text[:100]
|
88 |
-
|
89 |
-
def extract_pages(self, text):
|
90 |
-
try:
|
91 |
-
pages = sorted(set(re.findall(r"\b\d+\b", text)), key=int)
|
92 |
-
return ", ".join(pages)
|
93 |
-
except:
|
94 |
-
return text
|
95 |
-
|
96 |
-
def sanitize_commutative_set(self, raw):
|
97 |
-
s = re.findall(r"\b[a-e]\b", raw)
|
98 |
-
return ", ".join(sorted(set(s))) if s else raw
|
99 |
-
|
100 |
-
def format_answer(self, answer, question):
|
101 |
-
q = question.lower()
|
102 |
-
raw = answer.strip().strip("\"'")
|
103 |
-
if "ingredient" in q:
|
104 |
-
return self.extract_ingredients(raw)
|
105 |
-
if "commutative" in q:
|
106 |
-
return self.sanitize_commutative_set(raw)
|
107 |
-
if "algebraic notation" in q or "chess" in q:
|
108 |
-
m = re.search(r"[KQBNR]?[a-h]?[1-8]?x?[a-h][1-8][+#]?", raw)
|
109 |
-
return m.group(0) if m else raw
|
110 |
-
if "usd" in q or "at bat" in q:
|
111 |
-
m = re.search(r"\$?\d+(\.\d{2})?", raw)
|
112 |
-
return f"${m.group()}" if m else "$0.00"
|
113 |
-
if "year" in q or "when" in q:
|
114 |
-
m = re.search(r"\b(\d{4})\b", raw)
|
115 |
-
return m.group(0) if m else raw
|
116 |
-
if "award number" in q:
|
117 |
-
m = re.search(r"80NSSC[0-9A-Z]+", raw)
|
118 |
-
return m.group(0) if m else raw
|
119 |
-
if "ioc" in q:
|
120 |
-
m = re.search(r"\b[A-Z]{3}\b", raw)
|
121 |
-
return m.group(0) if m else raw
|
122 |
-
if "first name" in q:
|
123 |
-
return raw.split()[0]
|
124 |
-
if "page number" in q or "pages" in q:
|
125 |
-
return self.extract_pages(raw)
|
126 |
-
try:
|
127 |
-
return str(w2n.word_to_num(raw))
|
128 |
-
except:
|
129 |
-
m = re.search(r"\d+", raw)
|
130 |
-
return m.group(0) if m else raw
|
131 |
-
|
132 |
-
def reverse_sentence_logic(self, question):
|
133 |
-
try:
|
134 |
-
reversed_sentence = ''.join(reversed(question.strip('.'))).split()
|
135 |
-
return reversed_sentence[-1]
|
136 |
-
except:
|
137 |
-
return "[REVERSE ERROR]"
|
138 |
-
|
139 |
-
def answer_from_youtube(self, question):
|
140 |
-
try:
|
141 |
-
context = self.search_context(question)
|
142 |
-
return self.ask(f"Use this transcript or context to answer:\n{context}\n\n{question}\nAnswer:")
|
143 |
-
except:
|
144 |
-
return "[YOUTUBE ERROR]"
|
145 |
-
|
146 |
-
def __call__(self, question, task_id=None):
|
147 |
-
try:
|
148 |
-
q_lower = question.lower()
|
149 |
-
|
150 |
-
if q_lower.startswith('.rewsna'):
|
151 |
-
return self.reverse_sentence_logic(question)
|
152 |
-
|
153 |
-
if "youtube.com" in question:
|
154 |
-
return self.answer_from_youtube(question)
|
155 |
-
|
156 |
-
if "malko" in q_lower:
|
157 |
-
ctx = self.search_context("20th century Malko winner country that no longer exists")
|
158 |
-
fname = re.findall(r"\b[A-Z][a-z]{2,}", ctx)
|
159 |
-
return fname[0] if fname else "[MALKO ERROR]"
|
160 |
-
|
161 |
-
file_content, ctype = self.fetch_file(task_id) if task_id else (None, None)
|
162 |
-
if file_content:
|
163 |
-
context = self.handle_file(file_content, ctype, question)
|
164 |
-
else:
|
165 |
-
context = self.search_context(question)
|
166 |
-
|
167 |
-
prompt = f"Use this context to answer the question:\n{context}\n\nQuestion:\n{question}\nAnswer:"
|
168 |
-
answer = self.ask(prompt)
|
169 |
-
|
170 |
-
if not answer or "[ERROR" in answer or "step execution failed" in answer:
|
171 |
-
fallback = self.search_context(question)
|
172 |
-
retry_prompt = f"Use this context to answer:\n{fallback}\n\n{question}"
|
173 |
-
answer = self.ask(retry_prompt)
|
174 |
-
|
175 |
-
return self.format_answer(answer, question)
|
176 |
-
except Exception as e:
|
177 |
-
return f"[AGENT ERROR: {e}]"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|