DeekshithN05 commited on
Commit
3da32fa
·
verified ·
1 Parent(s): 8702fd0

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -232
app.py DELETED
@@ -1,232 +0,0 @@
1
- import os
2
- import gradio as gr
3
- import re
4
- import requests
5
- import pandas as pd
6
- from agent import build_graph
7
- from langchain_core.messages import HumanMessage
8
-
9
-
10
- # (Keep Constants as is)
11
- # --- Constants ---
12
- DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
13
-
14
-
15
- # --- Basic Agent Definition ---
16
- class BasicAgent:
17
- def __init__(self):
18
- print("BasicAgent initialized.")
19
- self.graph = build_graph()
20
-
21
- def __call__(self, question: str) -> str:
22
- print(f"Agent received question (first 50 chars): {question[:50]}...")
23
- # Wrap the question in a HumanMessage from langchain_core
24
- messages = [HumanMessage(content=question)]
25
- messages = self.graph.invoke({"messages": messages})
26
- answer = messages["messages"][-1].content
27
- # Use regex to extract the answer after FINAL ANSWER:
28
- match = re.search(r"FINAL ANSWER:\s*(.+)", answer, re.IGNORECASE)
29
- if match:
30
- final_answer = match.group(1).strip()
31
- # Optionally: strip trailing explanations (e.g., if comma-separated and extra stuff is appended)
32
- final_answer = (
33
- final_answer.split("\n")[0].split(",")[0] if final_answer else ""
34
- )
35
- return final_answer
36
- return answer
37
-
38
-
39
- def run_and_submit_all(profile: gr.OAuthProfile | None):
40
- """
41
- Fetches all questions, runs the BasicAgent on them, submits all answers,
42
- and displays the results.
43
- """
44
- space_id = os.getenv("SPACE_ID")
45
-
46
- if profile:
47
- username = f"{profile.username}"
48
- print(f"User logged in: {username}")
49
- else:
50
- print("User not logged in.")
51
- return "Please Login to Hugging Face with the button.", None
52
-
53
- api_url = DEFAULT_API_URL
54
- questions_url = f"{api_url}/questions"
55
- submit_url = f"{api_url}/submit"
56
-
57
- # 1. Instantiate Agent ( modify this part to create your agent)
58
- try:
59
- agent = BasicAgent()
60
- except Exception as e:
61
- print(f"Error instantiating agent: {e}")
62
- return f"Error initializing agent: {e}", None
63
- # In the case of an app running as a hugging Face space, this link points toward your codebase ( usefull for others so please keep it public)
64
- agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
65
-
66
- # 2. Fetch Questions
67
- print(f"Fetching questions from: {questions_url}")
68
- try:
69
- response = requests.get(questions_url, timeout=15)
70
- response.raise_for_status()
71
- questions_data = response.json()
72
- if not questions_data:
73
- print("Fetched questions list is empty.")
74
- return "Fetched questions list is empty or invalid format.", None
75
- print(f"Fetched {len(questions_data)} questions.")
76
- except requests.exceptions.RequestException as e:
77
- print(f"Error fetching questions: {e}")
78
- return f"Error fetching questions: {e}", None
79
- except requests.exceptions.JSONDecodeError as e:
80
- print(f"Error decoding JSON response from questions endpoint: {e}")
81
- print(f"Response text: {response.text[:500]}")
82
- return f"Error decoding server response for questions: {e}", None
83
- except Exception as e:
84
- print(f"An unexpected error occurred fetching questions: {e}")
85
- return f"An unexpected error occurred fetching questions: {e}", None
86
-
87
- # 3. Run your Agent
88
- results_log = []
89
- answers_payload = []
90
- print(f"Running agent on {len(questions_data)} questions...")
91
- for item in questions_data:
92
- task_id = item.get("task_id")
93
- question_text = item.get("question")
94
- if not task_id or question_text is None:
95
- print(f"Skipping item with missing task_id or question: {item}")
96
- continue
97
- try:
98
- submitted_answer = agent(question_text)
99
- answers_payload.append(
100
- {"task_id": task_id, "submitted_answer": submitted_answer}
101
- )
102
- results_log.append(
103
- {
104
- "Task ID": task_id,
105
- "Question": question_text,
106
- "Submitted Answer": submitted_answer,
107
- }
108
- )
109
- except Exception as e:
110
- print(f"Error running agent on task {task_id}: {e}")
111
- results_log.append(
112
- {
113
- "Task ID": task_id,
114
- "Question": question_text,
115
- "Submitted Answer": f"AGENT ERROR: {e}",
116
- }
117
- )
118
-
119
- if not answers_payload:
120
- print("Agent did not produce any answers to submit.")
121
- return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
122
-
123
- # 4. Prepare Submission
124
- submission_data = {
125
- "username": username.strip(),
126
- "agent_code": agent_code,
127
- "answers": answers_payload,
128
- }
129
- status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
130
- print(status_update)
131
-
132
- # 5. Submit
133
- print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
134
- try:
135
- response = requests.post(submit_url, json=submission_data, timeout=60)
136
- response.raise_for_status()
137
- result_data = response.json()
138
- final_status = (
139
- f"Submission Successful!\n"
140
- f"User: {result_data.get('username')}\n"
141
- f"Overall Score: {result_data.get('score', 'N/A')}% "
142
- f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
143
- f"Message: {result_data.get('message', 'No message received.')}"
144
- )
145
- print("Submission successful.")
146
- results_df = pd.DataFrame(results_log)
147
- return final_status, results_df
148
- except requests.exceptions.HTTPError as e:
149
- error_detail = f"Server responded with status {e.response.status_code}."
150
- try:
151
- error_json = e.response.json()
152
- error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
153
- except requests.exceptions.JSONDecodeError:
154
- error_detail += f" Response: {e.response.text[:500]}"
155
- status_message = f"Submission Failed: {error_detail}"
156
- print(status_message)
157
- results_df = pd.DataFrame(results_log)
158
- return status_message, results_df
159
- except requests.exceptions.Timeout:
160
- status_message = "Submission Failed: The request timed out."
161
- print(status_message)
162
- results_df = pd.DataFrame(results_log)
163
- return status_message, results_df
164
- except requests.exceptions.RequestException as e:
165
- status_message = f"Submission Failed: Network error - {e}"
166
- print(status_message)
167
- results_df = pd.DataFrame(results_log)
168
- return status_message, results_df
169
- except Exception as e:
170
- status_message = f"An unexpected error occurred during submission: {e}"
171
- print(status_message)
172
- results_df = pd.DataFrame(results_log)
173
- return status_message, results_df
174
-
175
-
176
- # --- Build Gradio Interface using Blocks ---
177
- with gr.Blocks() as demo:
178
- gr.Markdown("# Basic Agent Evaluation Runner")
179
- gr.Markdown(
180
- """
181
- **Instructions:**
182
-
183
- 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
184
- 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
185
- 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
186
-
187
- ---
188
- **Disclaimers:**
189
- 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).
190
- 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.
191
- """
192
- )
193
-
194
- gr.LoginButton()
195
-
196
- run_button = gr.Button("Run Evaluation & Submit All Answers")
197
-
198
- status_output = gr.Textbox(
199
- label="Run Status / Submission Result", lines=5, interactive=False
200
- )
201
- # Removed max_rows=10 from DataFrame constructor
202
- results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
203
-
204
- run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
205
-
206
- if __name__ == "__main__":
207
- print("\n" + "-" * 30 + " App Starting " + "-" * 30)
208
- # Check for SPACE_HOST and SPACE_ID at startup for information
209
- space_host_startup = os.getenv("SPACE_HOST")
210
- space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
211
-
212
- if space_host_startup:
213
- print(f"✅ SPACE_HOST found: {space_host_startup}")
214
- print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
215
- else:
216
- print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
217
-
218
- if space_id_startup: # Print repo URLs if SPACE_ID is found
219
- print(f"✅ SPACE_ID found: {space_id_startup}")
220
- print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
221
- print(
222
- f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main"
223
- )
224
- else:
225
- print(
226
- "ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined."
227
- )
228
-
229
- print("-" * (60 + len(" App Starting ")) + "\n")
230
-
231
- print("Launching Gradio Interface for Basic Agent Evaluation...")
232
- demo.launch(debug=True, share=False)