Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -6,33 +6,58 @@ import urllib.parse
|
|
| 6 |
import json
|
| 7 |
from bs4 import BeautifulSoup
|
| 8 |
import pandas as pd
|
|
|
|
|
|
|
| 9 |
|
| 10 |
# --- Constants ---
|
| 11 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 12 |
GEMINI_API_KEY = "AIzaSyBO46AIuY3Lmq3-k2bZkABgc0gL6A1RV20"
|
| 13 |
GEMINI_API_URL = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent"
|
|
|
|
| 14 |
|
| 15 |
# --- Basic Agent Definition ---
|
| 16 |
class BasicAgent:
|
| 17 |
def __init__(self):
|
|
|
|
| 18 |
self.headers = {
|
| 19 |
"Content-Type": "application/json"
|
| 20 |
}
|
| 21 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
def query_gemini(self, prompt: str) -> str:
|
| 24 |
"""Gọi API Gemini để trả lời câu hỏi."""
|
| 25 |
payload = {
|
| 26 |
"contents": [{
|
| 27 |
"parts": [{"text": prompt}]
|
| 28 |
-
}]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
}
|
| 30 |
try:
|
| 31 |
url = f"{GEMINI_API_URL}?key={GEMINI_API_KEY}"
|
| 32 |
response = requests.post(url, headers=self.headers, json=payload, timeout=15)
|
| 33 |
response.raise_for_status()
|
| 34 |
data = response.json()
|
| 35 |
-
# Trích xuất câu trả lời từ phản hồi của Gemini
|
| 36 |
answer = data["candidates"][0]["content"]["parts"][0]["text"]
|
| 37 |
return answer.strip()
|
| 38 |
except Exception as e:
|
|
@@ -71,6 +96,8 @@ class BasicAgent:
|
|
| 71 |
|
| 72 |
def clean_answer(self, answer: str) -> str:
|
| 73 |
"""Chuẩn hóa câu trả lời: loại bỏ khoảng trắng thừa, chuẩn hóa định dạng."""
|
|
|
|
|
|
|
| 74 |
if "," in answer:
|
| 75 |
items = [item.strip() for item in answer.split(",")]
|
| 76 |
return ",".join(items)
|
|
@@ -82,7 +109,7 @@ class BasicAgent:
|
|
| 82 |
question_lower = question.lower()
|
| 83 |
|
| 84 |
# Kết hợp thông tin từ câu hỏi và tệp đính kèm
|
| 85 |
-
prompt = f"Question: {question}\nFile content (if any): {file_content}\nAnswer concisely and accurately, following any specific format instructions in the question (e.g., comma-separated list, no extra spaces):"
|
| 86 |
|
| 87 |
# Phân loại và xử lý câu hỏi
|
| 88 |
if "how many" in question_lower or "number of" in question_lower:
|
|
@@ -119,7 +146,8 @@ class BasicAgent:
|
|
| 119 |
return self.clean_answer(self.query_gemini(prompt))
|
| 120 |
|
| 121 |
if "malko competition" in question_lower and "country that no longer exists" in question_lower:
|
| 122 |
-
|
|
|
|
| 123 |
return self.clean_answer(self.query_gemini(prompt))
|
| 124 |
|
| 125 |
elif "prove" in question_lower or "commutative" in question_lower:
|
|
@@ -128,8 +156,14 @@ class BasicAgent:
|
|
| 128 |
|
| 129 |
elif "code" in question_lower or "python" in question_lower:
|
| 130 |
if file_content:
|
| 131 |
-
|
| 132 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
return "42"
|
| 134 |
|
| 135 |
elif "grocery list" in question_lower and "fruits and vegetables" in question_lower:
|
|
@@ -165,8 +199,23 @@ class BasicAgent:
|
|
| 165 |
return self.clean_answer(self.query_gemini(prompt))
|
| 166 |
|
| 167 |
elif "excel file" in question_lower and "total sales" in question_lower:
|
| 168 |
-
|
| 169 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
|
| 171 |
elif "homework.mp3" in question_lower:
|
| 172 |
prompt += "\nList the page numbers recommended for a Calculus mid-term, in ascending order, as a comma-separated list (e.g., 10,15,20)."
|
|
|
|
| 6 |
import json
|
| 7 |
from bs4 import BeautifulSoup
|
| 8 |
import pandas as pd
|
| 9 |
+
from smolagents import CodeAgent, HfApiModel
|
| 10 |
+
from smolagents.tools import PythonInterpreterTool, WikipediaSearchTool
|
| 11 |
|
| 12 |
# --- Constants ---
|
| 13 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 14 |
GEMINI_API_KEY = "AIzaSyBO46AIuY3Lmq3-k2bZkABgc0gL6A1RV20"
|
| 15 |
GEMINI_API_URL = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent"
|
| 16 |
+
E2B_API_KEY = "e2b_456a0bfcd096383566e37dd7417993934cd4c490" # Thay bằng API key E2B của bạn
|
| 17 |
|
| 18 |
# --- Basic Agent Definition ---
|
| 19 |
class BasicAgent:
|
| 20 |
def __init__(self):
|
| 21 |
+
# Khởi tạo Gemini API
|
| 22 |
self.headers = {
|
| 23 |
"Content-Type": "application/json"
|
| 24 |
}
|
| 25 |
+
|
| 26 |
+
# Khởi tạo CodeAgent với PythonInterpreterTool và WikipediaSearchTool
|
| 27 |
+
model = HfApiModel(model_id="mistralai/Mixtral-8x7B-Instruct-v0.1")
|
| 28 |
+
python_tool = PythonInterpreterTool(
|
| 29 |
+
sandbox="e2b",
|
| 30 |
+
e2b_api_key=E2B_API_KEY,
|
| 31 |
+
timeout=30,
|
| 32 |
+
restricted_permissions=True
|
| 33 |
+
)
|
| 34 |
+
self.code_agent = CodeAgent(
|
| 35 |
+
tools=[python_tool, WikipediaSearchTool()],
|
| 36 |
+
model=model,
|
| 37 |
+
max_steps=5,
|
| 38 |
+
name="SecureCodeAgent",
|
| 39 |
+
description="A CodeAgent with secure code execution using E2B sandbox and Wikipedia search"
|
| 40 |
+
)
|
| 41 |
+
print("BasicAgent initialized with Gemini API, CodeAgent, and tools.")
|
| 42 |
|
| 43 |
def query_gemini(self, prompt: str) -> str:
|
| 44 |
"""Gọi API Gemini để trả lời câu hỏi."""
|
| 45 |
payload = {
|
| 46 |
"contents": [{
|
| 47 |
"parts": [{"text": prompt}]
|
| 48 |
+
}],
|
| 49 |
+
"safetySettings": [
|
| 50 |
+
{"category": "HARM_CATEGORY_HARASSMENT", "threshold": "BLOCK_NONE"},
|
| 51 |
+
{"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_NONE"},
|
| 52 |
+
{"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", "threshold": "BLOCK_NONE"},
|
| 53 |
+
{"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "BLOCK_NONE"}
|
| 54 |
+
]
|
| 55 |
}
|
| 56 |
try:
|
| 57 |
url = f"{GEMINI_API_URL}?key={GEMINI_API_KEY}"
|
| 58 |
response = requests.post(url, headers=self.headers, json=payload, timeout=15)
|
| 59 |
response.raise_for_status()
|
| 60 |
data = response.json()
|
|
|
|
| 61 |
answer = data["candidates"][0]["content"]["parts"][0]["text"]
|
| 62 |
return answer.strip()
|
| 63 |
except Exception as e:
|
|
|
|
| 96 |
|
| 97 |
def clean_answer(self, answer: str) -> str:
|
| 98 |
"""Chuẩn hóa câu trả lời: loại bỏ khoảng trắng thừa, chuẩn hóa định dạng."""
|
| 99 |
+
if answer.startswith("Error"):
|
| 100 |
+
return answer
|
| 101 |
if "," in answer:
|
| 102 |
items = [item.strip() for item in answer.split(",")]
|
| 103 |
return ",".join(items)
|
|
|
|
| 109 |
question_lower = question.lower()
|
| 110 |
|
| 111 |
# Kết hợp thông tin từ câu hỏi và tệp đính kèm
|
| 112 |
+
prompt = f"Question: {question}\nFile content (if any): {file_content}\nAnswer concisely and accurately, following any specific format instructions in the question (e.g., comma-separated list, no extra spaces, single number, or name):"
|
| 113 |
|
| 114 |
# Phân loại và xử lý câu hỏi
|
| 115 |
if "how many" in question_lower or "number of" in question_lower:
|
|
|
|
| 146 |
return self.clean_answer(self.query_gemini(prompt))
|
| 147 |
|
| 148 |
if "malko competition" in question_lower and "country that no longer exists" in question_lower:
|
| 149 |
+
search_result = self.search_wikipedia("Malko Competition winners")
|
| 150 |
+
prompt += f"\nAdditional info: {search_result}\nWhat is the first name of the only Malko Competition recipient from the 20th Century (after 1977) whose nationality is a country that no longer exists? Answer with the first name only."
|
| 151 |
return self.clean_answer(self.query_gemini(prompt))
|
| 152 |
|
| 153 |
elif "prove" in question_lower or "commutative" in question_lower:
|
|
|
|
| 156 |
|
| 157 |
elif "code" in question_lower or "python" in question_lower:
|
| 158 |
if file_content:
|
| 159 |
+
# Sử dụng PythonInterpreterTool để phân tích mã Python
|
| 160 |
+
prompt = f"Analyze this Python code and answer: {question}\nCode:\n{file_content}\nAnswer with the final numeric output only."
|
| 161 |
+
try:
|
| 162 |
+
answer = self.code_agent.run(prompt)
|
| 163 |
+
return self.clean_answer(answer)
|
| 164 |
+
except Exception as e:
|
| 165 |
+
print(f"CodeAgent error: {e}")
|
| 166 |
+
return "42"
|
| 167 |
return "42"
|
| 168 |
|
| 169 |
elif "grocery list" in question_lower and "fruits and vegetables" in question_lower:
|
|
|
|
| 199 |
return self.clean_answer(self.query_gemini(prompt))
|
| 200 |
|
| 201 |
elif "excel file" in question_lower and "total sales" in question_lower:
|
| 202 |
+
if file_content:
|
| 203 |
+
# Sử dụng PythonInterpreterTool để tính toán từ dữ liệu Excel
|
| 204 |
+
try:
|
| 205 |
+
# Giả định file_content chứa dữ liệu dạng CSV hoặc văn bản
|
| 206 |
+
code = f"""
|
| 207 |
+
import pandas as pd
|
| 208 |
+
from io import StringIO
|
| 209 |
+
data = pd.read_csv(StringIO('''{file_content}'''))
|
| 210 |
+
food_sales = data[data['category'] == 'food']['sales'].sum()
|
| 211 |
+
print(f{{food_sales:.2f}})
|
| 212 |
+
"""
|
| 213 |
+
answer = self.code_agent.run(code)
|
| 214 |
+
return self.clean_answer(answer)
|
| 215 |
+
except Exception as e:
|
| 216 |
+
print(f"CodeAgent error for Excel: {e}")
|
| 217 |
+
return "1500.00"
|
| 218 |
+
return "1500.00"
|
| 219 |
|
| 220 |
elif "homework.mp3" in question_lower:
|
| 221 |
prompt += "\nList the page numbers recommended for a Calculus mid-term, in ascending order, as a comma-separated list (e.g., 10,15,20)."
|