XeroDN commited on
Commit
579cbd3
·
verified ·
1 Parent(s): 200e7a7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +64 -82
app.py CHANGED
@@ -1,128 +1,110 @@
1
  import os
2
  import gradio as gr
3
- import requests
4
  import pandas as pd
5
- import openai
6
-
7
- # Load OpenAI API Key from environment
8
- openai.api_key = os.getenv("OPENAI_API_KEY")
9
 
10
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
11
 
12
- # --- Improved Smart Agent ---
13
- class SmartAgent:
14
  def __init__(self):
15
- print("SmartAgent initialized.")
 
 
 
 
 
 
16
 
17
  def __call__(self, question: str) -> str:
18
- print(f"[Agent] Processing question: {question[:60]}...")
19
  try:
20
- response = openai.ChatCompletion.create(
21
- model="gpt-4",
22
- messages=[
23
- {
24
- "role": "system",
25
- "content": (
26
- "You are a highly logical AI assistant specialized in answering "
27
- "knowledge and reasoning questions precisely and concisely. "
28
- "Provide only the final answer, with no extra commentary or labels."
29
- )
30
- },
31
- {"role": "user", "content": question}
32
- ],
33
- temperature=0.2, # Lower temp for more deterministic answers
34
- max_tokens=300,
35
- top_p=1,
36
- frequency_penalty=0,
37
- presence_penalty=0,
38
  )
39
- answer = response.choices[0].message["content"].strip()
40
- print(f"[Agent] Answer: {answer}")
41
- return answer
42
  except Exception as e:
43
- print(f"[Agent Error]: {e}")
44
  return "Error: Could not generate answer."
45
 
46
- # --- Submission Logic ---
 
 
 
 
 
47
  def run_and_submit_all(profile: gr.OAuthProfile | None):
48
  space_id = os.getenv("SPACE_ID", "your_username/your_space_name")
49
-
50
- if profile:
51
- username = profile.username
52
- print(f"User logged in: {username}")
53
- else:
54
  return "❌ Please log in to Hugging Face first.", None
55
 
 
56
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
57
- agent = SmartAgent()
58
 
 
 
 
 
 
 
 
 
59
  try:
60
  response = requests.get(f"{DEFAULT_API_URL}/questions", timeout=15)
61
  response.raise_for_status()
62
- questions = response.json()
63
  except Exception as e:
64
  return f"❌ Failed to fetch questions: {e}", None
65
 
66
- results_log = []
67
  answers_payload = []
68
-
69
- for item in questions:
70
- task_id = item.get("task_id")
71
- question_text = item.get("question")
72
- if not task_id or not question_text:
73
  continue
74
- try:
75
- answer = agent(question_text)
76
- answers_payload.append({"task_id": task_id, "submitted_answer": answer})
77
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": answer})
78
- except Exception as e:
79
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"Error: {e}"})
80
 
81
- submission = {
82
- "username": username,
83
- "agent_code": agent_code,
84
- "answers": answers_payload
85
- }
86
 
 
87
  try:
88
- resp = requests.post(f"{DEFAULT_API_URL}/submit", json=submission, timeout=60)
89
- resp.raise_for_status()
90
- result = resp.json()
91
- score = result.get("score", "N/A")
92
- correct = result.get("correct_count", "?")
93
- total = result.get("total_attempted", "?")
94
-
95
- msg = f"✅ Submission Successful!\nUser: {username}\nScore: {score}% ({correct}/{total} correct)"
 
 
 
 
 
 
 
96
  return msg, pd.DataFrame(results_log)
97
  except Exception as e:
98
  return f"❌ Submission failed: {e}", pd.DataFrame(results_log)
99
 
100
  # --- Gradio UI ---
101
  with gr.Blocks() as demo:
102
- gr.Markdown("## 🤖 GAIA Agent Submission Tool")
103
  gr.Markdown("Click below to log in and run your agent on the GAIA benchmark.")
104
  gr.LoginButton()
105
  run_btn = gr.Button("Run Evaluation & Submit All Answers")
106
  status = gr.Textbox(label="Status", lines=5)
107
- table = gr.DataFrame(label="Results")
108
 
109
  run_btn.click(fn=run_and_submit_all, outputs=[status, table])
110
 
111
- # --- Optional local test for debugging ---
112
- def local_test():
113
- print("Running local test...")
114
- agent = SmartAgent()
115
- test_questions = [
116
- "How many studio albums did Mercedes Sosa publish between 2000 and 2009?",
117
- "What is the capital city of France?",
118
- "List the vegetables in this list: milk, eggs, flour, whole bean coffee, Oreos, sweet potatoes, fresh basil, plums, green beans, rice, corn, bell pepper, whole allspice, acorns, broccoli, celery, zucchini, lettuce, peanuts."
119
- ]
120
- for q in test_questions:
121
- ans = agent(q)
122
- print(f"Q: {q}\nA: {ans}\n{'-'*40}")
123
-
124
  if __name__ == "__main__":
125
- print("Launching GAIA Agent App")
126
- local_test()
127
  demo.launch()
128
-
 
1
  import os
2
  import gradio as gr
 
3
  import pandas as pd
4
+ import requests
 
 
 
5
 
6
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
7
 
8
+ # --- OpenAI-based Agent ---
9
+ class OpenAIAgent:
10
  def __init__(self):
11
+ import openai
12
+ self.openai = openai
13
+ self.api_key = os.getenv("OPENAI_API_KEY")
14
+ if not self.api_key:
15
+ raise ValueError("OPENAI_API_KEY environment variable is not set.")
16
+ self.openai.api_key = self.api_key
17
+ self.model = "gpt-3.5-turbo" # Use free-accessible model
18
 
19
  def __call__(self, question: str) -> str:
 
20
  try:
21
+ prompt = f"""You are a helpful, knowledgeable AI answering a challenging question. Only return the answer, no explanation or preamble.\n\nQuestion:\n{question}"""
22
+ response = self.openai.ChatCompletion.create(
23
+ model=self.model,
24
+ messages=[{"role": "user", "content": prompt}],
25
+ temperature=0.2,
26
+ max_tokens=400
 
 
 
 
 
 
 
 
 
 
 
 
27
  )
28
+ return response.choices[0].message["content"].strip()
 
 
29
  except Exception as e:
30
+ print("[OpenAI Error]:", e)
31
  return "Error: Could not generate answer."
32
 
33
+ # --- Dummy Agent for Broken Envs ---
34
+ class DummyAgent:
35
+ def __call__(self, question: str) -> str:
36
+ return "Error: Could not generate answer."
37
+
38
+ # --- Main Evaluation Function ---
39
  def run_and_submit_all(profile: gr.OAuthProfile | None):
40
  space_id = os.getenv("SPACE_ID", "your_username/your_space_name")
41
+ if not profile:
 
 
 
 
42
  return "❌ Please log in to Hugging Face first.", None
43
 
44
+ username = profile.username
45
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
 
46
 
47
+ # Choose agent
48
+ try:
49
+ agent = OpenAIAgent()
50
+ except Exception as e:
51
+ print("Using dummy agent due to error:", e)
52
+ agent = DummyAgent()
53
+
54
+ # Fetch questions
55
  try:
56
  response = requests.get(f"{DEFAULT_API_URL}/questions", timeout=15)
57
  response.raise_for_status()
58
+ questions_data = response.json()
59
  except Exception as e:
60
  return f"❌ Failed to fetch questions: {e}", None
61
 
62
+ # Generate answers
63
  answers_payload = []
64
+ results_log = []
65
+ for q in questions_data:
66
+ task_id = q.get("task_id")
67
+ question = q.get("question")
68
+ if not task_id or not question:
69
  continue
70
+ answer = agent(question)
71
+ answers_payload.append({"task_id": task_id, "submitted_answer": answer})
72
+ results_log.append({"Task ID": task_id, "Question": question, "Submitted Answer": answer})
 
 
 
73
 
74
+ if not answers_payload:
75
+ return "❌ No answers were generated by the agent.", pd.DataFrame(results_log)
 
 
 
76
 
77
+ # Submit answers
78
  try:
79
+ submission = {
80
+ "username": username,
81
+ "agent_code": agent_code,
82
+ "answers": answers_payload
83
+ }
84
+ post_resp = requests.post(f"{DEFAULT_API_URL}/submit", json=submission, timeout=60)
85
+ post_resp.raise_for_status()
86
+ result = post_resp.json()
87
+
88
+ msg = (
89
+ f"✅ Submission Successful!\n"
90
+ f"User: {username}\n"
91
+ f"Score: {result.get('score', 'N/A')}% "
92
+ f"({result.get('correct_count', '?')}/{result.get('total_attempted', '?')} correct)"
93
+ )
94
  return msg, pd.DataFrame(results_log)
95
  except Exception as e:
96
  return f"❌ Submission failed: {e}", pd.DataFrame(results_log)
97
 
98
  # --- Gradio UI ---
99
  with gr.Blocks() as demo:
100
+ gr.Markdown("## 🤖 GAIA Benchmark Agent Submission")
101
  gr.Markdown("Click below to log in and run your agent on the GAIA benchmark.")
102
  gr.LoginButton()
103
  run_btn = gr.Button("Run Evaluation & Submit All Answers")
104
  status = gr.Textbox(label="Status", lines=5)
105
+ table = gr.DataFrame(label="Agent Answers")
106
 
107
  run_btn.click(fn=run_and_submit_all, outputs=[status, table])
108
 
 
 
 
 
 
 
 
 
 
 
 
 
 
109
  if __name__ == "__main__":
 
 
110
  demo.launch()