Spaces:
Sleeping
Sleeping
Qscar KIM commited on
Commit ยท
267b38b
1
Parent(s): 7c2f842
update app code
Browse files- agent.py +0 -33
- app.py +13 -68
- requirements.txt +0 -1
agent.py
DELETED
|
@@ -1,33 +0,0 @@
|
|
| 1 |
-
import os
|
| 2 |
-
from smolagents import CodeAgent, HfApiClientModel, Tool
|
| 3 |
-
from langchain_community.tools import DuckDuckGoSearchRun
|
| 4 |
-
|
| 5 |
-
class WebSearchTool(Tool):
|
| 6 |
-
name = "web_search"
|
| 7 |
-
description = "์ธํฐ๋ท์์ ์ต์ ์ ๋ณด๋ ์ง์์ ๊ฒ์ํ ๋ ์ฌ์ฉํฉ๋๋ค."
|
| 8 |
-
inputs = {"query": {"type": "string", "description": "๊ฒ์ํ ๋จ์ด๋ ๋ฌธ์ฅ"}}
|
| 9 |
-
output_type = "string"
|
| 10 |
-
|
| 11 |
-
def __init__(self):
|
| 12 |
-
super().__init__()
|
| 13 |
-
self.search = DuckDuckGoSearchRun()
|
| 14 |
-
|
| 15 |
-
def forward(self, query: str) -> str:
|
| 16 |
-
try:
|
| 17 |
-
return self.search.run(query)
|
| 18 |
-
except Exception as e:
|
| 19 |
-
return f"๊ฒ์ ์คํจ: {str(e)}"
|
| 20 |
-
|
| 21 |
-
def create_gaia_agent():
|
| 22 |
-
model = HfApiClientModel(
|
| 23 |
-
model_id="Qwen/Qwen2.5-Coder-32B-Instruct"
|
| 24 |
-
)
|
| 25 |
-
|
| 26 |
-
search_tool = WebSearchTool()
|
| 27 |
-
agent = CodeAgent(
|
| 28 |
-
tools=[search_tool],
|
| 29 |
-
model=model,
|
| 30 |
-
additional_authorized_imports=["pandas", "numpy", "json", "math", "re"]
|
| 31 |
-
)
|
| 32 |
-
|
| 33 |
-
return agent
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
app.py
CHANGED
|
@@ -4,49 +4,31 @@ import requests
|
|
| 4 |
import inspect
|
| 5 |
import pandas as pd
|
| 6 |
import random
|
| 7 |
-
import
|
| 8 |
-
from smolagents import CodeAgent, LiteLLMModel, DuckDuckGoSearchTool, VisitWebpageTool
|
| 9 |
|
| 10 |
# --- Constants ---
|
| 11 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 12 |
|
| 13 |
# --- Basic Agent Definition ---
|
| 14 |
-
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
| 15 |
class BasicAgent:
|
| 16 |
def __init__(self):
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
base_model = LiteLLMModel(
|
| 21 |
-
model_id="gemini/gemini-2.5-flash",
|
| 22 |
-
api_key=gemini_key
|
| 23 |
)
|
| 24 |
-
|
| 25 |
-
# 2. ๋ผ์ด๋ธ๋ฌ๋ฆฌ ์ถฉ๋์ ๋ง๊ธฐ ์ํด ๋ชจ๋ธ ํธ์ถ ์์ฒด๋ฅผ ์ธํฐ์
ํธํ์ฌ 10์ด ํ์ด์ฑ(Pacing) ๊ฐ์ ์ฃผ์
|
| 26 |
-
original_call = base_model.__call__
|
| 27 |
-
def paced_call(*args, **kwargs):
|
| 28 |
-
print("โณ [RPM Guard] Free tier burst protection sleep (10s)...")
|
| 29 |
-
time.sleep(10.0)
|
| 30 |
-
return original_call(*args, **kwargs)
|
| 31 |
-
|
| 32 |
-
base_model.__call__ = paced_call
|
| 33 |
-
self.model = base_model
|
| 34 |
|
| 35 |
-
|
| 36 |
-
self.visit_tool = VisitWebpageTool()
|
| 37 |
|
| 38 |
-
# 45์ ๋ฒ ์ด์ค๋ผ์ธ
|
| 39 |
self.alfred = CodeAgent(
|
| 40 |
-
tools=[
|
| 41 |
-
model=
|
| 42 |
add_base_tools=True,
|
| 43 |
planning_interval=3
|
| 44 |
)
|
| 45 |
|
| 46 |
def __call__(self, question: str) -> str:
|
| 47 |
try:
|
| 48 |
-
# ๋ฌธ์ ์ ๋ฌธ์ ์ฌ์ด์ ์์ ํ ์ธ์
์ด๊ธฐํ๋ฅผ ์ํด 5์ด ์ถ๊ฐ ๋๊ธฐ
|
| 49 |
-
time.sleep(5.0)
|
| 50 |
result = self.alfred.run(question)
|
| 51 |
if result is None:
|
| 52 |
return "unknown"
|
|
@@ -55,15 +37,14 @@ class BasicAgent:
|
|
| 55 |
print(f"Error during agent runtime execution: {e}")
|
| 56 |
return "unknown"
|
| 57 |
|
| 58 |
-
def run_and_submit_all(
|
| 59 |
"""
|
| 60 |
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
| 61 |
and displays the results.
|
| 62 |
"""
|
| 63 |
space_id = os.getenv("SPACE_ID")
|
| 64 |
-
|
| 65 |
if profile:
|
| 66 |
-
username= f"{profile.username}"
|
| 67 |
print(f"User logged in: {username}")
|
| 68 |
else:
|
| 69 |
print("User not logged in.")
|
|
@@ -80,7 +61,6 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 80 |
return f"Error initializing agent: {e}", None
|
| 81 |
|
| 82 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 83 |
-
print(agent_code)
|
| 84 |
|
| 85 |
print(f"Fetching questions from: {questions_url}")
|
| 86 |
try:
|
|
@@ -88,19 +68,11 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 88 |
response.raise_for_status()
|
| 89 |
questions_data = response.json()
|
| 90 |
if not questions_data:
|
| 91 |
-
print("Fetched questions list is empty.")
|
| 92 |
return "Fetched questions list is empty or invalid format.", None
|
| 93 |
print(f"Fetched {len(questions_data)} questions.")
|
| 94 |
-
except
|
| 95 |
print(f"Error fetching questions: {e}")
|
| 96 |
return f"Error fetching questions: {e}", None
|
| 97 |
-
except requests.exceptions.JSONDecodeError as e:
|
| 98 |
-
print(f"Error decoding JSON response from questions endpoint: {e}")
|
| 99 |
-
print(f"Response text: {response.text[:500]}")
|
| 100 |
-
return f"Error decoding server response for questions: {e}", None
|
| 101 |
-
except Exception as e:
|
| 102 |
-
print(f"An unexpected error occurred fetching questions: {e}")
|
| 103 |
-
return f"An unexpected error occurred fetching questions: {e}", None
|
| 104 |
|
| 105 |
results_log = []
|
| 106 |
answers_payload = []
|
|
@@ -109,7 +81,6 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 109 |
task_id = item.get("task_id")
|
| 110 |
question_text = item.get("question")
|
| 111 |
if not task_id or question_text is None:
|
| 112 |
-
print(f"Skipping item with missing task_id or question: {item}")
|
| 113 |
continue
|
| 114 |
try:
|
| 115 |
submitted_answer = agent(question_text)
|
|
@@ -120,14 +91,11 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 120 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
| 121 |
|
| 122 |
if not answers_payload:
|
| 123 |
-
print("Agent did not produce any answers to submit.")
|
| 124 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 125 |
|
| 126 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 127 |
-
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
| 128 |
-
print(status_update)
|
| 129 |
-
|
| 130 |
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
|
|
|
| 131 |
try:
|
| 132 |
response = requests.post(submit_url, json=submission_data, timeout=60)
|
| 133 |
response.raise_for_status()
|
|
@@ -139,33 +107,10 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 139 |
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
| 140 |
f"Message: {result_data.get('message', 'No message received.')}"
|
| 141 |
)
|
| 142 |
-
print("Submission successful.")
|
| 143 |
results_df = pd.DataFrame(results_log)
|
| 144 |
return final_status, results_df
|
| 145 |
-
except requests.exceptions.HTTPError as e:
|
| 146 |
-
error_detail = f"Server responded with status {e.response.status_code}."
|
| 147 |
-
try:
|
| 148 |
-
error_json = e.response.json()
|
| 149 |
-
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
| 150 |
-
except requests.exceptions.JSONDecodeError:
|
| 151 |
-
error_detail += f" Response: {e.response.text[:500]}"
|
| 152 |
-
status_message = f"Submission Failed: {error_detail}"
|
| 153 |
-
print(status_message)
|
| 154 |
-
results_df = pd.DataFrame(results_log)
|
| 155 |
-
return status_message, results_df
|
| 156 |
-
except requests.exceptions.Timeout:
|
| 157 |
-
status_message = "Submission Failed: The request timed out."
|
| 158 |
-
print(status_message)
|
| 159 |
-
results_df = pd.DataFrame(results_log)
|
| 160 |
-
return status_message, results_df
|
| 161 |
-
except requests.exceptions.RequestException as e:
|
| 162 |
-
status_message = f"Submission Failed: Network error - {e}"
|
| 163 |
-
print(status_message)
|
| 164 |
-
results_df = pd.DataFrame(results_log)
|
| 165 |
-
return status_message, results_df
|
| 166 |
except Exception as e:
|
| 167 |
-
status_message = f"
|
| 168 |
-
print(status_message)
|
| 169 |
results_df = pd.DataFrame(results_log)
|
| 170 |
return status_message, results_df
|
| 171 |
|
|
|
|
| 4 |
import inspect
|
| 5 |
import pandas as pd
|
| 6 |
import random
|
| 7 |
+
from smolagents import CodeAgent, InferenceClientModel, DuckDuckGoSearchTool
|
|
|
|
| 8 |
|
| 9 |
# --- Constants ---
|
| 10 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 11 |
|
| 12 |
# --- Basic Agent Definition ---
|
|
|
|
| 13 |
class BasicAgent:
|
| 14 |
def __init__(self):
|
| 15 |
+
# model_id๋ฅผ ์ง์ ํ์ง ์๊ณ ํ๋ ์์ํฌ ๊ธฐ๋ณธ ๋นํธ์ธ ๋ชจ๋ธ์ ์ฌ์ฉํ๋ฉฐ HF_TOKEN ์ฐ๋
|
| 16 |
+
model = InferenceClientModel(
|
| 17 |
+
token=os.getenv("HF_TOKEN")
|
|
|
|
|
|
|
|
|
|
| 18 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
|
| 20 |
+
search_tool = DuckDuckGoSearchTool()
|
|
|
|
| 21 |
|
| 22 |
+
# 45์ ๋ฒ ์ด์ค๋ผ์ธ์ ๋ค๋จ๊ณ ๊ณํ ์๋ฆฝ ๋ฐ ๋ด์ฅ ํ์ด์ฌ ์ธํฐํ๋ฆฌํฐ ํด์
๊ณ ์
|
| 23 |
self.alfred = CodeAgent(
|
| 24 |
+
tools=[search_tool],
|
| 25 |
+
model=model,
|
| 26 |
add_base_tools=True,
|
| 27 |
planning_interval=3
|
| 28 |
)
|
| 29 |
|
| 30 |
def __call__(self, question: str) -> str:
|
| 31 |
try:
|
|
|
|
|
|
|
| 32 |
result = self.alfred.run(question)
|
| 33 |
if result is None:
|
| 34 |
return "unknown"
|
|
|
|
| 37 |
print(f"Error during agent runtime execution: {e}")
|
| 38 |
return "unknown"
|
| 39 |
|
| 40 |
+
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 41 |
"""
|
| 42 |
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
| 43 |
and displays the results.
|
| 44 |
"""
|
| 45 |
space_id = os.getenv("SPACE_ID")
|
|
|
|
| 46 |
if profile:
|
| 47 |
+
username = f"{profile.username}"
|
| 48 |
print(f"User logged in: {username}")
|
| 49 |
else:
|
| 50 |
print("User not logged in.")
|
|
|
|
| 61 |
return f"Error initializing agent: {e}", None
|
| 62 |
|
| 63 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
|
|
|
| 64 |
|
| 65 |
print(f"Fetching questions from: {questions_url}")
|
| 66 |
try:
|
|
|
|
| 68 |
response.raise_for_status()
|
| 69 |
questions_data = response.json()
|
| 70 |
if not questions_data:
|
|
|
|
| 71 |
return "Fetched questions list is empty or invalid format.", None
|
| 72 |
print(f"Fetched {len(questions_data)} questions.")
|
| 73 |
+
except Exception as e:
|
| 74 |
print(f"Error fetching questions: {e}")
|
| 75 |
return f"Error fetching questions: {e}", None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
|
| 77 |
results_log = []
|
| 78 |
answers_payload = []
|
|
|
|
| 81 |
task_id = item.get("task_id")
|
| 82 |
question_text = item.get("question")
|
| 83 |
if not task_id or question_text is None:
|
|
|
|
| 84 |
continue
|
| 85 |
try:
|
| 86 |
submitted_answer = agent(question_text)
|
|
|
|
| 91 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
| 92 |
|
| 93 |
if not answers_payload:
|
|
|
|
| 94 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 95 |
|
| 96 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
|
|
|
|
|
|
|
|
|
| 97 |
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
| 98 |
+
|
| 99 |
try:
|
| 100 |
response = requests.post(submit_url, json=submission_data, timeout=60)
|
| 101 |
response.raise_for_status()
|
|
|
|
| 107 |
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
| 108 |
f"Message: {result_data.get('message', 'No message received.')}"
|
| 109 |
)
|
|
|
|
| 110 |
results_df = pd.DataFrame(results_log)
|
| 111 |
return final_status, results_df
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
except Exception as e:
|
| 113 |
+
status_message = f"Submission Failed: {e}"
|
|
|
|
| 114 |
results_df = pd.DataFrame(results_log)
|
| 115 |
return status_message, results_df
|
| 116 |
|
requirements.txt
CHANGED
|
@@ -1,6 +1,5 @@
|
|
| 1 |
smolagents>=1.1.0
|
| 2 |
duckduckgo-search>=6.2.1
|
| 3 |
-
litellm
|
| 4 |
pandas
|
| 5 |
requests
|
| 6 |
gradio
|
|
|
|
| 1 |
smolagents>=1.1.0
|
| 2 |
duckduckgo-search>=6.2.1
|
|
|
|
| 3 |
pandas
|
| 4 |
requests
|
| 5 |
gradio
|