vaibhavi18092002 commited on
Commit
751db97
Β·
verified Β·
1 Parent(s): 6a70331

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +40 -205
app.py CHANGED
@@ -1,215 +1,50 @@
1
- import os
2
- import gradio as gr
3
- import requests
4
- import inspect
5
- import pandas as pd
6
-
7
- # Try to import Google GenAI SDK
8
- try:
9
- from google import genai
10
- except ImportError:
11
- raise ImportError("Please install the 'google-genai' package: pip install google-genai")
12
-
13
- # --- Constants ---
14
- DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
15
-
16
- # --- Gemini Agent Definition ---
17
- class GeminiAgent:
18
  def __init__(self):
19
- print("GeminiAgent initialized.")
20
- api_key = os.getenv("GEMINI_API_KEY")
21
- if not api_key:
22
- raise ValueError("GEMINI_API_KEY environment variable not set.")
23
- # Instantiate the Gemini API client
24
- self.client = genai.Client(api_key=api_key)
25
 
26
- def __call__(self, question: str) -> str:
27
- print(f"GeminiAgent received question (first 50 chars): {question[:50]}...")
28
- # Prompt the model to answer concisely without explanation
29
- prompt = f"Answer concisely without explanation: {question}"
30
- response = self.client.models.generate_content(
31
- model="gemini-2.0-flash", contents=prompt
32
- )
33
- answer = response.text.strip()
34
- # Remove trailing punctuation if any
35
- answer = answer.rstrip(".!?")
36
- print(f"GeminiAgent returning answer: {answer}")
37
- return answer
38
 
39
- def run_and_submit_all(profile: gr.OAuthProfile | None):
40
- """
41
- Fetches all questions, runs the GeminiAgent on them, submits all answers,
42
- and displays the results.
43
- """
44
- # --- Determine HF Space Runtime URL and Repo URL ---
45
- space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
46
 
47
- if profile:
48
- username = f"{profile.username}"
49
- print(f"User logged in: {username}")
50
- else:
51
- print("User not logged in.")
52
- return "Please Login to Hugging Face with the button.", None
53
 
54
- api_url = DEFAULT_API_URL
55
- questions_url = f"{api_url}/questions"
56
- submit_url = f"{api_url}/submit"
 
57
 
58
- # 1. Instantiate Agent
59
- try:
60
- agent = GeminiAgent()
61
- except Exception as e:
62
- print(f"Error instantiating agent: {e}")
63
- return f"Error initializing agent: {e}", None
64
- # In the case of an app running as a Hugging Face space, this link points
65
- # toward your codebase (useful for others so please keep it public)
66
- agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
67
- print(agent_code)
68
 
69
- # 2. Fetch Questions
70
- print(f"Fetching questions from: {questions_url}")
71
- try:
72
- response = requests.get(questions_url, timeout=15)
73
- response.raise_for_status()
74
- questions_data = response.json()
75
- if not questions_data:
76
- print("Fetched questions list is empty.")
77
- return "Fetched questions list is empty or invalid format.", None
78
- print(f"Fetched {len(questions_data)} questions.")
79
- except requests.exceptions.RequestException as e:
80
- print(f"Error fetching questions: {e}")
81
- return f"Error fetching questions: {e}", None
82
- except requests.exceptions.JSONDecodeError as e:
83
- print(f"Error decoding JSON response from questions endpoint: {e}")
84
- print(f"Response text: {response.text[:500]}")
85
- return f"Error decoding server response for questions: {e}", None
86
- except Exception as e:
87
- print(f"An unexpected error occurred fetching questions: {e}")
88
- return f"An unexpected error occurred fetching questions: {e}", None
89
 
90
- # 3. Run your Agent
91
- results_log = []
92
- answers_payload = []
93
- print(f"Running agent on {len(questions_data)} questions...")
94
- for item in questions_data:
95
- task_id = item.get("task_id")
96
- question_text = item.get("question")
97
- if not task_id or question_text is None:
98
- print(f"Skipping item with missing task_id or question: {item}")
99
- continue
100
  try:
101
- submitted_answer = agent(question_text)
102
- answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
103
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
104
  except Exception as e:
105
- print(f"Error running agent on task {task_id}: {e}")
106
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
107
-
108
- if not answers_payload:
109
- print("Agent did not produce any answers to submit.")
110
- return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
111
-
112
- # 4. Prepare Submission
113
- submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
114
- status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
115
- print(status_update)
116
-
117
- # 5. Submit
118
- print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
119
- try:
120
- response = requests.post(submit_url, json=submission_data, timeout=60)
121
- response.raise_for_status()
122
- result_data = response.json()
123
- final_status = (
124
- f"Submission Successful!\n"
125
- f"User: {result_data.get('username')}\n"
126
- f"Overall Score: {result_data.get('score', 'N/A')}% "
127
- f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
128
- f"Message: {result_data.get('message', 'No message received.')}"
129
- )
130
- print("Submission successful.")
131
- results_df = pd.DataFrame(results_log)
132
- return final_status, results_df
133
- except requests.exceptions.HTTPError as e:
134
- error_detail = f"Server responded with status {e.response.status_code}."
135
- try:
136
- error_json = e.response.json()
137
- error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
138
- except requests.exceptions.JSONDecodeError:
139
- error_detail += f" Response: {e.response.text[:500]}"
140
- status_message = f"Submission Failed: {error_detail}"
141
- print(status_message)
142
- results_df = pd.DataFrame(results_log)
143
- return status_message, results_df
144
- except requests.exceptions.Timeout:
145
- status_message = "Submission Failed: The request timed out."
146
- print(status_message)
147
- results_df = pd.DataFrame(results_log)
148
- return status_message, results_df
149
- except requests.exceptions.RequestException as e:
150
- status_message = f"Submission Failed: Network error - {e}"
151
- print(status_message)
152
- results_df = pd.DataFrame(results_log)
153
- return status_message, results_df
154
- except Exception as e:
155
- status_message = f"An unexpected error occurred during submission: {e}"
156
- print(status_message)
157
- results_df = pd.DataFrame(results_log)
158
- return status_message, results_df
159
-
160
- # --- Build Gradio Interface using Blocks ---
161
- with gr.Blocks() as demo:
162
- gr.Markdown("# Gemini Agent Evaluation Runner")
163
- gr.Markdown(
164
- """
165
- **Instructions:**
166
- 1. Please clone this space, then modify the code to define your agent's logic,
167
- the tools, the necessary packages, etc ...
168
- 2. Log in to your Hugging Face account using the button below. This uses your
169
- HF username for submission.
170
- 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your
171
- agent, submit answers, and see the score.
172
-
173
- ---
174
- **Disclaimers:**
175
- Once clicking on the "submit" button, it can take quite some time (this is the
176
- time for the agent to go through all the questions).
177
- This space provides a basic setup and is intentionally sub-optimal to
178
- encourage you to develop your own, more robust solution. For instance, for the
179
- delay process of the submit button, a solution could be to cache the answers and
180
- submit in a separate action or even to answer the questions asynchronously.
181
- """
182
- )
183
- gr.LoginButton()
184
- run_button = gr.Button("Run Evaluation & Submit All Answers")
185
- status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
186
- results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
187
-
188
- run_button.click(
189
- fn=run_and_submit_all,
190
- outputs=[status_output, results_table]
191
- )
192
-
193
- if __name__ == "__main__":
194
- print("\n" + "-"*30 + " App Starting " + "-"*30)
195
- # Check for SPACE_HOST and SPACE_ID at startup for information
196
- space_host_startup = os.getenv("SPACE_HOST")
197
- space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
198
-
199
- if space_host_startup:
200
- print(f"βœ… SPACE_HOST found: {space_host_startup}")
201
- print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
202
- else:
203
- print("��️ SPACE_HOST environment variable not found (running locally?).")
204
-
205
- if space_id_startup: # Print repo URLs if SPACE_ID is found
206
- print(f"βœ… SPACE_ID found: {space_id_startup}")
207
- print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
208
- print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
209
- else:
210
- print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
211
-
212
- print("-"*(60 + len(" App Starting ")) + "\n")
213
-
214
- print("Launching Gradio Interface for Gemini Agent Evaluation...")
215
- demo.launch(debug=True, share=False)
 
1
+ # Add this class replacing the current GeminiAgent
2
+ class MultiAgent:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  def __init__(self):
4
+ print("MultiAgent initialized with Gemini fallback.")
 
 
 
 
 
5
 
6
+ # Load primary Gemini key
7
+ self.gemini_key = os.getenv("GEMINI_API_KEY")
8
+ self.alt_key = os.getenv("GEMINI_API_KEY_2") # Second key (optional)
 
 
 
 
 
 
 
 
 
9
 
10
+ if not self.gemini_key:
11
+ raise ValueError("GEMINI_API_KEY environment variable not set.")
 
 
 
 
 
12
 
13
+ import google.generativeai as genai
14
+ self.genai = genai
 
 
 
 
15
 
16
+ # Primary client
17
+ self.client_primary = genai.Client(api_key=self.gemini_key)
18
+ # Secondary client (fallback)
19
+ self.client_secondary = genai.Client(api_key=self.alt_key) if self.alt_key else None
20
 
21
+ self.model_name = "gemini-2.5-flash-preview-04-17"
 
 
 
 
 
 
 
 
 
22
 
23
+ def _query_model(self, client, question):
24
+ prompt = f"Answer concisely without explanation: {question}"
25
+ response = client.models.generate_content(
26
+ model=self.model_name,
27
+ contents=prompt
28
+ )
29
+ return response.text.strip().rstrip(".!?")
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
+ def __call__(self, question: str) -> str:
32
+ print(f"MultiAgent received question: {question[:50]}...")
 
 
 
 
 
 
 
 
33
  try:
34
+ return self._query_model(self.client_primary, question)
 
 
35
  except Exception as e:
36
+ print(f"⚠️ Primary Gemini failed: {e}")
37
+ if self.client_secondary:
38
+ try:
39
+ print("Attempting fallback Gemini key...")
40
+ return self._query_model(self.client_secondary, question)
41
+ except Exception as e2:
42
+ print(f"❌ Secondary Gemini failed: {e2}")
43
+ return "AGENT ERROR"
44
+ else:
45
+ return "AGENT ERROR"
46
+
47
+ # Then replace:
48
+ # agent = GeminiAgent()
49
+ # with:
50
+ # agent = MultiAgent()