Update app.py
Browse files
app.py
CHANGED
|
@@ -1,38 +1,73 @@
|
|
| 1 |
import os
|
| 2 |
import gradio as gr
|
| 3 |
import requests
|
| 4 |
-
import inspect
|
| 5 |
import pandas as pd
|
|
|
|
|
|
|
| 6 |
|
| 7 |
-
# (Keep Constants as is)
|
| 8 |
-
# --- Constants ---
|
| 9 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 10 |
|
| 11 |
-
# --- Basic Agent Definition ---
|
| 12 |
-
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
| 13 |
class BasicAgent:
|
| 14 |
def __init__(self):
|
| 15 |
-
print("
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
def __call__(self, question: str) -> str:
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
"""
|
| 24 |
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
| 25 |
and displays the results.
|
| 26 |
"""
|
| 27 |
# --- Determine HF Space Runtime URL and Repo URL ---
|
| 28 |
-
space_id = os.getenv("SPACE_ID")
|
| 29 |
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
print(f"User logged in: {username}")
|
| 33 |
-
else:
|
| 34 |
-
print("User not logged in.")
|
| 35 |
-
return "Please Login to Hugging Face with the button.", None
|
| 36 |
|
| 37 |
api_url = DEFAULT_API_URL
|
| 38 |
questions_url = f"{api_url}/questions"
|
|
@@ -51,23 +86,35 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 51 |
# 2. Fetch Questions
|
| 52 |
print(f"Fetching questions from: {questions_url}")
|
| 53 |
try:
|
| 54 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
response.raise_for_status()
|
| 56 |
questions_data = response.json()
|
|
|
|
| 57 |
if not questions_data:
|
| 58 |
-
|
| 59 |
-
|
|
|
|
| 60 |
print(f"Fetched {len(questions_data)} questions.")
|
|
|
|
| 61 |
except requests.exceptions.RequestException as e:
|
| 62 |
print(f"Error fetching questions: {e}")
|
| 63 |
return f"Error fetching questions: {e}", None
|
|
|
|
| 64 |
except requests.exceptions.JSONDecodeError as e:
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
except Exception as e:
|
| 69 |
-
print(f"
|
| 70 |
-
return f"
|
| 71 |
|
| 72 |
# 3. Run your Agent
|
| 73 |
results_log = []
|
|
@@ -146,11 +193,9 @@ with gr.Blocks() as demo:
|
|
| 146 |
gr.Markdown(
|
| 147 |
"""
|
| 148 |
**Instructions:**
|
| 149 |
-
|
| 150 |
1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
|
| 151 |
2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
|
| 152 |
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
| 153 |
-
|
| 154 |
---
|
| 155 |
**Disclaimers:**
|
| 156 |
Once clicking on the "submit button, it can take quite some time ( this is the time for the agent to go through all the questions).
|
|
|
|
| 1 |
import os
|
| 2 |
import gradio as gr
|
| 3 |
import requests
|
|
|
|
| 4 |
import pandas as pd
|
| 5 |
+
from openai import OpenAI
|
| 6 |
+
from ddgs import DDGS
|
| 7 |
|
|
|
|
|
|
|
| 8 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 9 |
|
|
|
|
|
|
|
| 10 |
class BasicAgent:
|
| 11 |
def __init__(self):
|
| 12 |
+
print("OpenAI Agent initialized.")
|
| 13 |
+
self.client = OpenAI(api_key="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")
|
| 14 |
+
|
| 15 |
+
def web_search(self, query, max_results=5):
|
| 16 |
+
try:
|
| 17 |
+
with DDGS() as ddgs:
|
| 18 |
+
results = list(ddgs.text(query, max_results=max_results))
|
| 19 |
+
return "\n".join([
|
| 20 |
+
f"{r.get('title')}: {r.get('body')}"
|
| 21 |
+
for r in results
|
| 22 |
+
])
|
| 23 |
+
except Exception as e:
|
| 24 |
+
print("SEARCH ERROR:", e)
|
| 25 |
+
return ""
|
| 26 |
+
|
| 27 |
+
def clean(self, ans):
|
| 28 |
+
ans = str(ans).strip()
|
| 29 |
+
for x in ["FINAL ANSWER:", "Final Answer:", "Answer:"]:
|
| 30 |
+
ans = ans.replace(x, "")
|
| 31 |
+
return ans.split("\n")[0].strip()
|
| 32 |
+
|
| 33 |
def __call__(self, question: str) -> str:
|
| 34 |
+
context = self.web_search(question)
|
| 35 |
+
|
| 36 |
+
prompt = f"""
|
| 37 |
+
Return ONLY the exact final answer.
|
| 38 |
+
No explanation.
|
| 39 |
+
No extra words.
|
| 40 |
+
Do not write FINAL ANSWER.
|
| 41 |
+
Question:
|
| 42 |
+
{question}
|
| 43 |
+
Search context:
|
| 44 |
+
{context}
|
| 45 |
+
"""
|
| 46 |
|
| 47 |
+
try:
|
| 48 |
+
response = self.client.chat.completions.create(
|
| 49 |
+
model="gpt-4o-mini",
|
| 50 |
+
messages=[
|
| 51 |
+
{"role": "system", "content": "Return exact final answers only."},
|
| 52 |
+
{"role": "user", "content": prompt}
|
| 53 |
+
],
|
| 54 |
+
temperature=0
|
| 55 |
+
)
|
| 56 |
+
return self.clean(response.choices[0].message.content)
|
| 57 |
+
except Exception as e:
|
| 58 |
+
print("AGENT ERROR:", e)
|
| 59 |
+
return "unknown"
|
| 60 |
+
|
| 61 |
+
def run_and_submit_all(profile):
|
| 62 |
"""
|
| 63 |
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
| 64 |
and displays the results.
|
| 65 |
"""
|
| 66 |
# --- Determine HF Space Runtime URL and Repo URL ---
|
| 67 |
+
space_id = os.getenv("SPACE_ID")
|
| 68 |
|
| 69 |
+
username = os.getenv("SPACE_AUTHOR_NAME", "ahmer64")
|
| 70 |
+
print(f"Using username: {username}")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
|
| 72 |
api_url = DEFAULT_API_URL
|
| 73 |
questions_url = f"{api_url}/questions"
|
|
|
|
| 86 |
# 2. Fetch Questions
|
| 87 |
print(f"Fetching questions from: {questions_url}")
|
| 88 |
try:
|
| 89 |
+
import time
|
| 90 |
+
|
| 91 |
+
for attempt in range(3):
|
| 92 |
+
response = requests.get(questions_url, timeout=15)
|
| 93 |
+
if response.status_code != 429:
|
| 94 |
+
break
|
| 95 |
+
print("Rate limited. Waiting 30 seconds...")
|
| 96 |
+
time.sleep(30)
|
| 97 |
+
|
| 98 |
response.raise_for_status()
|
| 99 |
questions_data = response.json()
|
| 100 |
+
|
| 101 |
if not questions_data:
|
| 102 |
+
print("Fetched questions list is empty.")
|
| 103 |
+
return "Fetched questions list is empty or invalid format.", None
|
| 104 |
+
|
| 105 |
print(f"Fetched {len(questions_data)} questions.")
|
| 106 |
+
|
| 107 |
except requests.exceptions.RequestException as e:
|
| 108 |
print(f"Error fetching questions: {e}")
|
| 109 |
return f"Error fetching questions: {e}", None
|
| 110 |
+
|
| 111 |
except requests.exceptions.JSONDecodeError as e:
|
| 112 |
+
print(f"Error decoding JSON response: {e}")
|
| 113 |
+
return f"Error decoding server response: {e}", None
|
| 114 |
+
|
| 115 |
except Exception as e:
|
| 116 |
+
print(f"Unexpected error: {e}")
|
| 117 |
+
return f"Unexpected error: {e}", None
|
| 118 |
|
| 119 |
# 3. Run your Agent
|
| 120 |
results_log = []
|
|
|
|
| 193 |
gr.Markdown(
|
| 194 |
"""
|
| 195 |
**Instructions:**
|
|
|
|
| 196 |
1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
|
| 197 |
2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
|
| 198 |
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
|
|
|
| 199 |
---
|
| 200 |
**Disclaimers:**
|
| 201 |
Once clicking on the "submit button, it can take quite some time ( this is the time for the agent to go through all the questions).
|