Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -1,57 +1,127 @@
|
|
1 |
-
import
|
|
|
|
|
|
|
|
|
|
|
2 |
from langchain_groq import ChatGroq
|
3 |
from langchain_community.utilities import ArxivAPIWrapper, WikipediaAPIWrapper
|
4 |
from langchain_community.tools import ArxivQueryRun, WikipediaQueryRun, DuckDuckGoSearchRun
|
5 |
from langchain.agents import initialize_agent, AgentType
|
6 |
-
from langchain.callbacks import StreamlitCallbackHandler
|
7 |
-
import os
|
8 |
-
from dotenv import load_dotenv
|
9 |
|
10 |
-
# ---
|
11 |
-
|
12 |
|
13 |
-
|
14 |
-
api_wrapper_arxiv = ArxivAPIWrapper(top_k_results=1, doc_content_chars_max=250)
|
15 |
-
arxiv = ArxivQueryRun(api_wrapper=api_wrapper_arxiv)
|
16 |
|
17 |
-
|
18 |
-
|
|
|
|
|
|
|
|
|
19 |
|
20 |
-
|
21 |
-
tools = [
|
|
|
|
|
|
|
|
|
22 |
|
23 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
24 |
|
25 |
-
|
26 |
-
|
27 |
-
|
|
|
|
|
|
|
28 |
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
33 |
|
34 |
-
|
35 |
-
|
36 |
|
37 |
-
|
38 |
-
|
39 |
-
if user_api_key:
|
40 |
-
llm.groq_api_key = user_api_key
|
41 |
|
42 |
-
|
43 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
44 |
|
45 |
-
|
46 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
47 |
|
48 |
-
|
49 |
-
|
50 |
-
|
|
|
51 |
|
52 |
-
|
53 |
-
st_cb = StreamlitCallbackHandler(st.container(), expand_new_thoughts=False)
|
54 |
-
response = run_agent(prompt)
|
55 |
-
st.session_state.messages.append({"role": "assistant", "content": response})
|
56 |
-
st.write(response)
|
57 |
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import gradio as gr
|
3 |
+
import requests
|
4 |
+
import pandas as pd
|
5 |
+
from dotenv import load_dotenv
|
6 |
+
|
7 |
from langchain_groq import ChatGroq
|
8 |
from langchain_community.utilities import ArxivAPIWrapper, WikipediaAPIWrapper
|
9 |
from langchain_community.tools import ArxivQueryRun, WikipediaQueryRun, DuckDuckGoSearchRun
|
10 |
from langchain.agents import initialize_agent, AgentType
|
|
|
|
|
|
|
11 |
|
12 |
+
# --- Constants ---
|
13 |
+
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
14 |
|
15 |
+
api_key = "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"
|
|
|
|
|
16 |
|
17 |
+
# --- GAIA-compatible Agent Definition ---
|
18 |
+
class GaiaAgent:
|
19 |
+
def __init__(self):
|
20 |
+
load_dotenv()
|
21 |
+
self.api_key = os.getenv("GROQ_API_KEY") or "your_fallback_key"
|
22 |
+
self.llm = ChatGroq(groq_api_key=self.api_key, model_name="Llama3-8b-8192")
|
23 |
|
24 |
+
# Define tools
|
25 |
+
self.tools = [
|
26 |
+
DuckDuckGoSearchRun(name="Search"),
|
27 |
+
ArxivQueryRun(api_wrapper=ArxivAPIWrapper(top_k_results=1, doc_content_chars_max=250)),
|
28 |
+
WikipediaQueryRun(api_wrapper=WikipediaAPIWrapper(top_k_results=1, doc_content_chars_max=250))
|
29 |
+
]
|
30 |
|
31 |
+
self.agent = initialize_agent(
|
32 |
+
self.tools,
|
33 |
+
self.llm,
|
34 |
+
agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
|
35 |
+
handle_parsing_errors=True
|
36 |
+
)
|
37 |
+
|
38 |
+
def __call__(self, question: str) -> str:
|
39 |
+
try:
|
40 |
+
return self.agent.run(question)
|
41 |
+
except Exception as e:
|
42 |
+
return f"[ERROR] {str(e)}"
|
43 |
+
|
44 |
+
# --- Evaluation Logic ---
|
45 |
+
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
46 |
+
space_id = os.getenv("SPACE_ID")
|
47 |
+
|
48 |
+
if profile:
|
49 |
+
username = f"{profile.username}"
|
50 |
+
print(f"User logged in: {username}")
|
51 |
+
else:
|
52 |
+
print("User not logged in.")
|
53 |
+
return "Please Login to Hugging Face with the button.", None
|
54 |
+
|
55 |
+
questions_url = f"{DEFAULT_API_URL}/questions"
|
56 |
+
submit_url = f"{DEFAULT_API_URL}/submit"
|
57 |
+
|
58 |
+
try:
|
59 |
+
agent = GaiaAgent()
|
60 |
+
except Exception as e:
|
61 |
+
return f"Error initializing agent: {e}", None
|
62 |
+
|
63 |
+
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
64 |
+
print(f"Fetching questions from: {questions_url}")
|
65 |
|
66 |
+
try:
|
67 |
+
response = requests.get(questions_url, timeout=15)
|
68 |
+
response.raise_for_status()
|
69 |
+
questions_data = response.json()
|
70 |
+
except Exception as e:
|
71 |
+
return f"Error fetching questions: {e}", None
|
72 |
|
73 |
+
results_log = []
|
74 |
+
answers_payload = []
|
75 |
+
for item in questions_data:
|
76 |
+
task_id = item.get("task_id")
|
77 |
+
question_text = item.get("question")
|
78 |
+
if not task_id or question_text is None:
|
79 |
+
continue
|
80 |
+
try:
|
81 |
+
submitted_answer = agent(question_text)
|
82 |
+
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
83 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
84 |
+
except Exception as e:
|
85 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
86 |
|
87 |
+
if not answers_payload:
|
88 |
+
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
89 |
|
90 |
+
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
91 |
+
print(f"Submitting answers to: {submit_url}")
|
|
|
|
|
92 |
|
93 |
+
try:
|
94 |
+
response = requests.post(submit_url, json=submission_data, timeout=60)
|
95 |
+
response.raise_for_status()
|
96 |
+
result_data = response.json()
|
97 |
+
final_status = (
|
98 |
+
f"Submission Successful!\n"
|
99 |
+
f"User: {result_data.get('username')}\n"
|
100 |
+
f"Overall Score: {result_data.get('score', 'N/A')}% "
|
101 |
+
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
102 |
+
f"Message: {result_data.get('message', 'No message received.')}"
|
103 |
+
)
|
104 |
+
return final_status, pd.DataFrame(results_log)
|
105 |
+
except Exception as e:
|
106 |
+
return f"Submission Failed: {e}", pd.DataFrame(results_log)
|
107 |
|
108 |
+
# --- Gradio UI ---
|
109 |
+
with gr.Blocks() as demo:
|
110 |
+
gr.Markdown("# Basic Agent Evaluation Runner")
|
111 |
+
gr.Markdown("""
|
112 |
+
**Instructions:**
|
113 |
+
1. Modify `GaiaAgent` to implement your logic.
|
114 |
+
2. Log in to your Hugging Face account below.
|
115 |
+
3. Click 'Run Evaluation & Submit All Answers'.
|
116 |
+
""")
|
117 |
|
118 |
+
gr.LoginButton()
|
119 |
+
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
120 |
+
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
121 |
+
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
122 |
|
123 |
+
run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
|
|
|
|
|
|
|
|
|
124 |
|
125 |
+
if __name__ == "__main__":
|
126 |
+
print("Launching GAIA-compatible agent...")
|
127 |
+
demo.launch(debug=True, share=False)
|