Update agent.py
Browse files
agent.py
CHANGED
@@ -4,11 +4,10 @@ import requests
|
|
4 |
import tempfile
|
5 |
import pandas as pd
|
6 |
from openai import OpenAI
|
7 |
-
|
8 |
try:
|
9 |
from duckduckgo_search import DDGS
|
10 |
except ImportError:
|
11 |
-
DDGS = None
|
12 |
|
13 |
PROMPT = (
|
14 |
"You are a general AI assistant. I will ask you a question. "
|
@@ -51,7 +50,6 @@ class BasicAgent:
|
|
51 |
f.flush()
|
52 |
excel_path = f.name
|
53 |
df = pd.read_excel(excel_path)
|
54 |
-
# Try to sum 'Sales' where 'Type' == 'food'
|
55 |
if "Type" in df.columns and "Sales" in df.columns:
|
56 |
total = df[df["Type"].str.lower() == "food"]["Sales"].sum()
|
57 |
return f"{round(total, 2)}"
|
@@ -60,40 +58,6 @@ class BasicAgent:
|
|
60 |
except Exception as e:
|
61 |
return ""
|
62 |
|
63 |
-
def transcribe_audio(self, file_url: str) -> str:
|
64 |
-
import openai
|
65 |
-
openai.api_key = os.getenv("OPENAI_API_KEY")
|
66 |
-
try:
|
67 |
-
r = requests.get(file_url, timeout=20)
|
68 |
-
r.raise_for_status()
|
69 |
-
# Guess extension from url or response
|
70 |
-
ext = ".mp3"
|
71 |
-
if file_url.endswith(".wav"):
|
72 |
-
ext = ".wav"
|
73 |
-
with tempfile.NamedTemporaryFile(suffix=ext, delete=False) as f:
|
74 |
-
f.write(r.content)
|
75 |
-
f.flush()
|
76 |
-
audio_path = f.name
|
77 |
-
transcript = openai.Audio.transcribe("whisper-1", open(audio_path, "rb"))
|
78 |
-
return transcript.get("text", "")
|
79 |
-
except Exception as e:
|
80 |
-
return ""
|
81 |
-
|
82 |
-
def execute_python(self, file_url: str) -> str:
|
83 |
-
try:
|
84 |
-
r = requests.get(file_url, timeout=20)
|
85 |
-
r.raise_for_status()
|
86 |
-
code = r.content.decode("utf-8")
|
87 |
-
import io, contextlib
|
88 |
-
buf = io.StringIO()
|
89 |
-
with contextlib.redirect_stdout(buf):
|
90 |
-
exec(code, {})
|
91 |
-
output = buf.getvalue().strip().split('\n')[-1]
|
92 |
-
numbers = re.findall(r'[-+]?\d*\.\d+|\d+', output)
|
93 |
-
return numbers[-1] if numbers else output
|
94 |
-
except Exception as e:
|
95 |
-
return ""
|
96 |
-
|
97 |
def fetch_file_url(self, task_id):
|
98 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
99 |
try:
|
@@ -105,34 +69,55 @@ class BasicAgent:
|
|
105 |
pass
|
106 |
return None
|
107 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
108 |
def __call__(self, question: str, task_id: str = None) -> str:
|
109 |
file_url = self.fetch_file_url(task_id) if task_id else None
|
110 |
file_result = None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
111 |
ext = file_url.split('.')[-1].lower() if file_url else ""
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
file_result = self.excel_tool(file_url)
|
117 |
-
if file_result and re.match(r'^\d+(\.\d+)?$', file_result):
|
118 |
-
return file_result
|
119 |
-
# Audio
|
120 |
-
elif ext in ["mp3", "wav"] or "audio" in question.lower() or "transcribe" in question.lower():
|
121 |
-
file_result = self.transcribe_audio(file_url)
|
122 |
-
if file_result and file_result.strip():
|
123 |
-
return file_result
|
124 |
-
# Python code
|
125 |
-
elif ext == "py":
|
126 |
-
file_result = self.execute_python(file_url)
|
127 |
-
if file_result and file_result.strip():
|
128 |
-
return file_result
|
129 |
-
# Fallback: try Excel anyway
|
130 |
-
if not file_result:
|
131 |
-
file_result = self.excel_tool(file_url)
|
132 |
-
if file_result and re.match(r'^\d+(\.\d+)?$', file_result):
|
133 |
-
return file_result
|
134 |
|
135 |
-
# --- Web search
|
136 |
search_snippet = self.web_search(question)
|
137 |
prompt = PROMPT + f"\n\nWeb search results:\n{search_snippet}\n\nQuestion: {question}"
|
138 |
response = self.llm.chat.completions.create(
|
|
|
4 |
import tempfile
|
5 |
import pandas as pd
|
6 |
from openai import OpenAI
|
|
|
7 |
try:
|
8 |
from duckduckgo_search import DDGS
|
9 |
except ImportError:
|
10 |
+
DDGS = None
|
11 |
|
12 |
PROMPT = (
|
13 |
"You are a general AI assistant. I will ask you a question. "
|
|
|
50 |
f.flush()
|
51 |
excel_path = f.name
|
52 |
df = pd.read_excel(excel_path)
|
|
|
53 |
if "Type" in df.columns and "Sales" in df.columns:
|
54 |
total = df[df["Type"].str.lower() == "food"]["Sales"].sum()
|
55 |
return f"{round(total, 2)}"
|
|
|
58 |
except Exception as e:
|
59 |
return ""
|
60 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
61 |
def fetch_file_url(self, task_id):
|
62 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
63 |
try:
|
|
|
69 |
pass
|
70 |
return None
|
71 |
|
72 |
+
def solve_chess_image(self, image_url: str) -> str:
|
73 |
+
"""Uses GPT-4o Vision to answer a chess image question (requires image URL)."""
|
74 |
+
prompt = (
|
75 |
+
"You are a chess engine. Only answer with the best move for Black in algebraic notation (e.g., Qd1#). "
|
76 |
+
"Do not explain your reasoning, do not include any commentary, only the move."
|
77 |
+
)
|
78 |
+
try:
|
79 |
+
response = self.llm.chat.completions.create(
|
80 |
+
model="gpt-4o",
|
81 |
+
messages=[
|
82 |
+
{"role": "system", "content": prompt},
|
83 |
+
{
|
84 |
+
"role": "user",
|
85 |
+
"content": [
|
86 |
+
{"type": "text", "text": prompt},
|
87 |
+
{"type": "image_url", "image_url": {"url": image_url}},
|
88 |
+
],
|
89 |
+
}
|
90 |
+
],
|
91 |
+
max_tokens=32,
|
92 |
+
temperature=0.0,
|
93 |
+
)
|
94 |
+
result = response.choices[0].message.content.strip()
|
95 |
+
# Remove commentary, keep only first move if any
|
96 |
+
move = re.findall(r"\b([KQRNB]?[a-h]?[1-8]?x?[a-h][1-8](?:=[QRNB])?#?)\b", result)
|
97 |
+
if move:
|
98 |
+
return move[0]
|
99 |
+
return result
|
100 |
+
except Exception as e:
|
101 |
+
return ""
|
102 |
+
|
103 |
def __call__(self, question: str, task_id: str = None) -> str:
|
104 |
file_url = self.fetch_file_url(task_id) if task_id else None
|
105 |
file_result = None
|
106 |
+
|
107 |
+
# --- Chess image detection (heuristic: "chess", "move", "image", or "position") ---
|
108 |
+
if file_url and ("chess" in question.lower() or "move" in question.lower() or "image" in question.lower() or "position" in question.lower()):
|
109 |
+
chess_result = self.solve_chess_image(file_url)
|
110 |
+
if chess_result and len(chess_result) < 10: # likely algebraic notation
|
111 |
+
return chess_result
|
112 |
+
|
113 |
+
# --- Excel heuristic (only try for likely Excel file) ---
|
114 |
ext = file_url.split('.')[-1].lower() if file_url else ""
|
115 |
+
if file_url and (ext in ["xlsx", "xls"] or "excel" in question.lower() or "spreadsheet" in question.lower()):
|
116 |
+
file_result = self.excel_tool(file_url)
|
117 |
+
if file_result and re.match(r'^\d+(\.\d+)?$', file_result):
|
118 |
+
return file_result
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
119 |
|
120 |
+
# --- Web search + LLM as before ---
|
121 |
search_snippet = self.web_search(question)
|
122 |
prompt = PROMPT + f"\n\nWeb search results:\n{search_snippet}\n\nQuestion: {question}"
|
123 |
response = self.llm.chat.completions.create(
|