vtony commited on
Commit
f235500
·
verified ·
1 Parent(s): 0a72192

Delete app.py

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