rakesh-dvg commited on
Commit
7c59d10
·
verified ·
1 Parent(s): 38f7123

Delete app.py

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