Spaces:
Configuration error
Configuration error
Arvid Zöllner commited on
Commit ·
af4fcb2
1
Parent(s): 44dfaf5
Agent llm changed to duckduckgo
Browse files
app.py
CHANGED
|
@@ -1,40 +1,43 @@
|
|
| 1 |
import os
|
| 2 |
-
import gradio as gr
|
| 3 |
import requests
|
| 4 |
-
import
|
| 5 |
-
|
| 6 |
-
from smolagents import Tool
|
| 7 |
-
from duckduckgo_search import DDGS
|
| 8 |
from smolagents import CodeAgent
|
|
|
|
|
|
|
| 9 |
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
def __call__(self,
|
| 17 |
-
|
| 18 |
-
if not query:
|
| 19 |
-
return "No query provided."
|
| 20 |
-
|
| 21 |
try:
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
return "No results found."
|
| 26 |
-
return "\n\n".join(r.get("body", "") for r in results if r.get("body"))
|
| 27 |
except Exception as e:
|
| 28 |
-
return f"
|
| 29 |
|
| 30 |
-
#
|
| 31 |
class MySmolAgent:
|
| 32 |
def __init__(self):
|
| 33 |
print("Initializing SmolAgent...")
|
| 34 |
-
login(token=os.getenv("HF_TOKEN")) # sicheres Laden über Umgebungsvariable
|
| 35 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
self.model = HfApiModel(model="mistralai/Mistral-7B-Instruct-v0.1")
|
| 37 |
|
|
|
|
| 38 |
self.agent = CodeAgent(
|
| 39 |
tools=[DuckDuckGoTool()],
|
| 40 |
model=self.model,
|
|
@@ -47,74 +50,138 @@ class MySmolAgent:
|
|
| 47 |
print(f"Agent running for question: {question[:60]}...")
|
| 48 |
return self.agent.run(question)
|
| 49 |
|
| 50 |
-
#
|
| 51 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
api_url = "https://agents-course-unit4-scoring.hf.space"
|
| 53 |
questions_url = f"{api_url}/questions"
|
| 54 |
submit_url = f"{api_url}/submit"
|
| 55 |
-
username = profile.username if profile else None
|
| 56 |
-
|
| 57 |
-
if not username:
|
| 58 |
-
return "Please login with Hugging Face", None
|
| 59 |
|
|
|
|
| 60 |
try:
|
| 61 |
agent = MySmolAgent()
|
| 62 |
except Exception as e:
|
| 63 |
-
|
|
|
|
| 64 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
try:
|
| 66 |
response = requests.get(questions_url, timeout=15)
|
| 67 |
response.raise_for_status()
|
| 68 |
questions_data = response.json()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
except Exception as e:
|
| 70 |
-
|
|
|
|
| 71 |
|
|
|
|
| 72 |
results_log = []
|
| 73 |
answers_payload = []
|
|
|
|
| 74 |
for item in questions_data:
|
| 75 |
task_id = item.get("task_id")
|
| 76 |
question_text = item.get("question")
|
| 77 |
-
if not task_id or
|
|
|
|
| 78 |
continue
|
| 79 |
try:
|
| 80 |
-
|
| 81 |
-
answers_payload.append({"task_id": task_id, "submitted_answer":
|
| 82 |
-
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer":
|
| 83 |
except Exception as e:
|
| 84 |
-
|
|
|
|
| 85 |
|
| 86 |
if not answers_payload:
|
| 87 |
-
|
|
|
|
| 88 |
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
}
|
| 94 |
|
|
|
|
|
|
|
| 95 |
try:
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
f"Submission
|
| 101 |
-
f"User: {
|
| 102 |
-
f"Score: {
|
| 103 |
-
f"({
|
|
|
|
| 104 |
)
|
| 105 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 106 |
except Exception as e:
|
| 107 |
-
|
|
|
|
|
|
|
|
|
|
| 108 |
|
| 109 |
-
#
|
| 110 |
with gr.Blocks() as demo:
|
| 111 |
-
gr.Markdown("#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
gr.LoginButton()
|
| 113 |
-
run_button = gr.Button("Fragen beantworten und abschicken")
|
| 114 |
-
status = gr.Textbox(label="Status", lines=5)
|
| 115 |
-
results = gr.DataFrame(label="Antworten")
|
| 116 |
|
| 117 |
-
run_button.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
|
| 119 |
if __name__ == "__main__":
|
| 120 |
-
|
|
|
|
|
|
| 1 |
import os
|
|
|
|
| 2 |
import requests
|
| 3 |
+
import gradio as gr
|
| 4 |
+
from huggingface_hub import login
|
|
|
|
|
|
|
| 5 |
from smolagents import CodeAgent
|
| 6 |
+
from smolagents.models import HfApiModel
|
| 7 |
+
from duckduckgo_search import ddg_search # Importiert DuckDuckGo Search
|
| 8 |
|
| 9 |
+
# Tool: DuckDuckGoSearchTool
|
| 10 |
+
class DuckDuckGoTool:
|
| 11 |
+
def __init__(self):
|
| 12 |
+
self.name = "DuckDuckGoSearch"
|
| 13 |
+
self.description = "Tool to search DuckDuckGo for an answer."
|
| 14 |
+
|
| 15 |
+
def __call__(self, query: str) -> str:
|
| 16 |
+
"""Durchführt eine Suche mit DuckDuckGo und gibt die ersten 3 Ergebnisse zurück."""
|
|
|
|
|
|
|
|
|
|
| 17 |
try:
|
| 18 |
+
search_results = ddg_search(query)
|
| 19 |
+
results = [result["title"] + " - " + result["url"] for result in search_results[:3]]
|
| 20 |
+
return "\n".join(results)
|
|
|
|
|
|
|
| 21 |
except Exception as e:
|
| 22 |
+
return f"Fehler bei der DuckDuckGo-Suche: {e}"
|
| 23 |
|
| 24 |
+
# Agent: MySmolAgent
|
| 25 |
class MySmolAgent:
|
| 26 |
def __init__(self):
|
| 27 |
print("Initializing SmolAgent...")
|
|
|
|
| 28 |
|
| 29 |
+
# Sicherstellen, dass der Token korrekt gesetzt ist
|
| 30 |
+
token = os.getenv("HF_TOKEN")
|
| 31 |
+
if not token:
|
| 32 |
+
raise ValueError("HF_TOKEN environment variable is missing.")
|
| 33 |
+
|
| 34 |
+
# Anmeldung bei HuggingFace
|
| 35 |
+
login(token=token)
|
| 36 |
+
|
| 37 |
+
# Modell initialisieren
|
| 38 |
self.model = HfApiModel(model="mistralai/Mistral-7B-Instruct-v0.1")
|
| 39 |
|
| 40 |
+
# Agent mit Tools und Modell einrichten
|
| 41 |
self.agent = CodeAgent(
|
| 42 |
tools=[DuckDuckGoTool()],
|
| 43 |
model=self.model,
|
|
|
|
| 50 |
print(f"Agent running for question: {question[:60]}...")
|
| 51 |
return self.agent.run(question)
|
| 52 |
|
| 53 |
+
# Funktion, um Fragen zu beantworten und die Antworten zu senden
|
| 54 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 55 |
+
"""
|
| 56 |
+
Holt alle Fragen, lässt den Agenten sie beantworten, sendet alle Antworten,
|
| 57 |
+
und zeigt die Ergebnisse an.
|
| 58 |
+
"""
|
| 59 |
+
# --- Bestimmen der Hugging Face API-URLs ---
|
| 60 |
+
space_id = os.getenv("SPACE_ID")
|
| 61 |
+
|
| 62 |
+
if profile:
|
| 63 |
+
username = f"{profile.username}"
|
| 64 |
+
print(f"User logged in: {username}")
|
| 65 |
+
else:
|
| 66 |
+
print("User not logged in.")
|
| 67 |
+
return "Please Login to Hugging Face with the button.", None
|
| 68 |
+
|
| 69 |
api_url = "https://agents-course-unit4-scoring.hf.space"
|
| 70 |
questions_url = f"{api_url}/questions"
|
| 71 |
submit_url = f"{api_url}/submit"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
|
| 73 |
+
# 1. Instanziiere den Agenten
|
| 74 |
try:
|
| 75 |
agent = MySmolAgent()
|
| 76 |
except Exception as e:
|
| 77 |
+
print(f"Error instantiating agent: {e}")
|
| 78 |
+
return f"Error initializing agent: {e}", None
|
| 79 |
|
| 80 |
+
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 81 |
+
print(agent_code)
|
| 82 |
+
|
| 83 |
+
# 2. Frage abrufen
|
| 84 |
+
print(f"Fetching questions from: {questions_url}")
|
| 85 |
try:
|
| 86 |
response = requests.get(questions_url, timeout=15)
|
| 87 |
response.raise_for_status()
|
| 88 |
questions_data = response.json()
|
| 89 |
+
if not questions_data:
|
| 90 |
+
print("Fetched questions list is empty.")
|
| 91 |
+
return "Fetched questions list is empty or invalid format.", None
|
| 92 |
+
print(f"Fetched {len(questions_data)} questions.")
|
| 93 |
+
except requests.exceptions.RequestException as e:
|
| 94 |
+
print(f"Error fetching questions: {e}")
|
| 95 |
+
return f"Error fetching questions: {e}", None
|
| 96 |
+
except requests.exceptions.JSONDecodeError as e:
|
| 97 |
+
print(f"Error decoding JSON response from questions endpoint: {e}")
|
| 98 |
+
return f"Error decoding server response for questions: {e}", None
|
| 99 |
except Exception as e:
|
| 100 |
+
print(f"An unexpected error occurred fetching questions: {e}")
|
| 101 |
+
return f"An unexpected error occurred fetching questions: {e}", None
|
| 102 |
|
| 103 |
+
# 3. Agent ausführen
|
| 104 |
results_log = []
|
| 105 |
answers_payload = []
|
| 106 |
+
print(f"Running agent on {len(questions_data)} questions...")
|
| 107 |
for item in questions_data:
|
| 108 |
task_id = item.get("task_id")
|
| 109 |
question_text = item.get("question")
|
| 110 |
+
if not task_id or question_text is None:
|
| 111 |
+
print(f"Skipping item with missing task_id or question: {item}")
|
| 112 |
continue
|
| 113 |
try:
|
| 114 |
+
submitted_answer = agent(question_text)
|
| 115 |
+
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 116 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
| 117 |
except Exception as e:
|
| 118 |
+
print(f"Error running agent on task {task_id}: {e}")
|
| 119 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
| 120 |
|
| 121 |
if not answers_payload:
|
| 122 |
+
print("Agent did not produce any answers to submit.")
|
| 123 |
+
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 124 |
|
| 125 |
+
# 4. Bereite Submission vor
|
| 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 |
+
# 5. Einreichung
|
| 131 |
+
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
| 132 |
try:
|
| 133 |
+
response = requests.post(submit_url, json=submission_data, timeout=60)
|
| 134 |
+
response.raise_for_status()
|
| 135 |
+
result_data = response.json()
|
| 136 |
+
final_status = (
|
| 137 |
+
f"Submission Successful!\n"
|
| 138 |
+
f"User: {result_data.get('username')}\n"
|
| 139 |
+
f"Overall Score: {result_data.get('score', 'N/A')}% "
|
| 140 |
+
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
| 141 |
+
f"Message: {result_data.get('message', 'No message received.')}"
|
| 142 |
)
|
| 143 |
+
print("Submission successful.")
|
| 144 |
+
results_df = pd.DataFrame(results_log)
|
| 145 |
+
return final_status, results_df
|
| 146 |
+
except requests.exceptions.RequestException as e:
|
| 147 |
+
error_detail = f"Submission Failed: Network error - {e}"
|
| 148 |
+
print(error_detail)
|
| 149 |
+
results_df = pd.DataFrame(results_log)
|
| 150 |
+
return error_detail, results_df
|
| 151 |
except Exception as e:
|
| 152 |
+
status_message = f"An unexpected error occurred during submission: {e}"
|
| 153 |
+
print(status_message)
|
| 154 |
+
results_df = pd.DataFrame(results_log)
|
| 155 |
+
return status_message, results_df
|
| 156 |
|
| 157 |
+
# Gradio-Interface
|
| 158 |
with gr.Blocks() as demo:
|
| 159 |
+
gr.Markdown("# Basic Agent Evaluation Runner")
|
| 160 |
+
gr.Markdown(
|
| 161 |
+
"""
|
| 162 |
+
**Instructions:**
|
| 163 |
+
1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
|
| 164 |
+
2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
|
| 165 |
+
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
| 166 |
+
---
|
| 167 |
+
**Disclaimers:**
|
| 168 |
+
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).
|
| 169 |
+
This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution. For instance for the delay process of the submit button, a solution could be to cache the answers and submit in a seperate action or even to answer the questions in async.
|
| 170 |
+
"""
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
gr.LoginButton()
|
|
|
|
|
|
|
|
|
|
| 174 |
|
| 175 |
+
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 176 |
+
|
| 177 |
+
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
| 178 |
+
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 179 |
+
|
| 180 |
+
run_button.click(
|
| 181 |
+
fn=run_and_submit_all,
|
| 182 |
+
outputs=[status_output, results_table]
|
| 183 |
+
)
|
| 184 |
|
| 185 |
if __name__ == "__main__":
|
| 186 |
+
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
| 187 |
+
demo.launch(debug=True, share=False)
|