Facelook commited on
Commit
d3ce64c
·
verified ·
1 Parent(s): a9b329d

Delete app.py.bak

Browse files
Files changed (1) hide show
  1. app.py.bak +0 -435
app.py.bak DELETED
@@ -1,435 +0,0 @@
1
- import os
2
- import gradio as gr
3
- import requests
4
- import json
5
- import pandas as pd
6
- import spacy
7
- from openai import OpenAI
8
- from agent_tools import duckduckgo_search, langsearch_search, TOOLS_MAPPING, TOOLS_DEFINITION
9
-
10
-
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
-
18
- class BasicAgent:
19
- def __init__(self):
20
- print("BasicAgent initialized.")
21
- self.client = OpenAI(base_url="https://openrouter.ai/api/v1", api_key=os.getenv("OR_TOKEN"))
22
-
23
- def __call__(self, question: str) -> str:
24
- print(f"Agent received question: {question}")
25
-
26
- try:
27
- count = 0
28
-
29
- # content = "You are an assistant that has access to the following set of tools. Read the question carefully and do not report your thoughts, explanations, reasoning, or conclusion. Always use RAG. If you know the answer, give only YOUR FINAL ANSWER. YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings. If you are asked for a number, don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise. If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise. If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string. On the other hand, if you really don't know the answer after your best efforts, break down the question and list all search queries in a string array."
30
- content = "You are a news researcher that has access to the following set of tools. Read the question carefully. Do do not report your thoughts, explanations, reasoning, or conclusion. Do not reason too long. Give only YOUR FINAL ANSWER. YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings. If you are asked for a number, don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise. If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise. If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string. If you don't have complete certainty, you must still provide your best answer based on the information available to you. Always provide an answer rather than no answer, use your best judgment to determine the most likely correct response."
31
-
32
- nlp = spacy.load("en_core_web_sm")
33
- doc = nlp(question)
34
- # Extract keywords: Nouns, Proper Nouns, Adjectives, and Verbs might be useful
35
- keywords = [token.lemma_ for token in doc if token.pos_ in ['NOUN', 'PROPN', 'ADJ', 'VERB'] and not token.is_stop]
36
- # Extract all recognized entities
37
- entities = [ent.text for ent in doc.ents]
38
- print("Keywords:", keywords)
39
- print("Entities:", entities)
40
-
41
- keywords.extend(entities) # Combine keywords and entities for search
42
-
43
- # Call langsearch_search function
44
- search_query = ""
45
- if keywords:
46
- search_query = " ".join(keywords)
47
- # print(f"No entities found, using keywords for search query: '{search_query}'")
48
- else:
49
- search_query = question
50
- # print("No entities or keywords found, using original question for search query.")
51
- search_results = langsearch_search(query=search_query, count=5)
52
- if len(search_results) > 0:
53
- # Convert search results to a readable text format
54
- search_results_text = ""
55
- for i, result in enumerate(search_results, 1):
56
- count += 1
57
- search_results_text += f"\n\n---SEARCH RESULT #{count}---\n"
58
- search_results_text += f"{search_results[i - 1]}"
59
- content += f"\n\nThe following are the results from the NLP wutg LangSearch, use it as reference along with your own knowledge base to provide the most accurate answer: {search_results_text}"
60
-
61
- search_results = langsearch_search(query=question, count=5)
62
- content += f"\n\nThe following are the results from the LangSearch, use it as reference along with your own knowledge base to provide the most accurate answer: {search_results}"
63
-
64
- # print(f"Content for system message: {content}")
65
-
66
- messages = [
67
- {
68
- "role": "system",
69
- "content": content
70
- },
71
- {
72
- "role": "user",
73
- "content": [
74
- {
75
- "type": "text",
76
- "text": question
77
- },
78
- # {
79
- # "type": "image_url",
80
- # "image_url": {
81
- # "url": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg"
82
- # }
83
- # }
84
- ]
85
- }
86
- ]
87
-
88
- for _ in range(3):
89
- # Generate response
90
- print("Using Inference API for generation...")
91
- completion = self.client.chat.completions.create(
92
- extra_headers={
93
- "HTTP-Referer": "<YOUR_SITE_URL>", # Optional. Site URL for rankings on openrouter.ai.
94
- "X-Title": "<YOUR_SITE_NAME>", # Optional. Site title for rankings on openrouter.ai.
95
- },
96
- extra_body={},
97
- # model="deepseek/deepseek-chat-v3-0324:free",
98
- # model="deepseek/deepseek-r1",
99
- # model="tngtech/deepseek-r1t-chimera:free",
100
- model="microsoft/mai-ds-r1:free",
101
- # tools=TOOLS_DEFINITION, # Use imported tools definition
102
- messages=messages,
103
- temperature=0.0,
104
- max_tokens=2048,
105
- )
106
- print(f"Completion: {completion}")
107
- messages.append(completion.choices[0].message)
108
-
109
- if completion.choices[0].message.tool_calls is None:
110
- answer = completion.choices[0].message.content
111
- if answer is None or answer == "":
112
- if completion.choices[0].message.reasoning is not None:
113
- answer = completion.choices[0].message.reasoning
114
- else:
115
- answer = "I apologize, but I encountered an error when trying to answer your question."
116
- print(f"Agent generated response: {answer}")
117
- return answer
118
-
119
- for tool_call in completion.choices[0].message.tool_calls:
120
- tool_name = tool_call.function.name
121
- tool_args = json.loads(tool_call.function.arguments)
122
- tool_response = TOOLS_MAPPING[tool_name](**tool_args) # Use imported tools mapping
123
- message = {
124
- "role": "tool",
125
- "tool_call_id": tool_call.id,
126
- "name": tool_name,
127
- "content": json.dumps(tool_response),
128
- }
129
- messages.append(message)
130
- print(f"Tool call: {message}")
131
- except Exception as e:
132
- print(f"Error generating response: {e}")
133
- fallback_answer = "I apologize, but I encountered an error when trying to answer your question."
134
- print(f"Agent returning fallback answer: {fallback_answer}")
135
- return fallback_answer
136
-
137
-
138
- def run_and_submit_all(profile: gr.OAuthProfile | None):
139
- """
140
- Fetches all questions, runs the BasicAgent on them, submits all answers,
141
- and displays the results.
142
- """
143
- # --- Determine HF Space Runtime URL and Repo URL ---
144
- space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
145
-
146
- if profile:
147
- username = f"{profile.username}"
148
- print(f"User logged in: {username}")
149
- else:
150
- print("User not logged in.")
151
- return "Please Login to Hugging Face with the button.", None
152
-
153
- api_url = DEFAULT_API_URL
154
- questions_url = f"{api_url}/questions"
155
- submit_url = f"{api_url}/submit"
156
-
157
- # 1. Instantiate Agent ( modify this part to create your agent)
158
- try:
159
- agent = BasicAgent()
160
- except Exception as e:
161
- print(f"Error instantiating agent: {e}")
162
- return f"Error initializing agent: {e}", None
163
- # 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)
164
- agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
165
- print(agent_code)
166
-
167
- # 2. Fetch Questions
168
- print(f"Fetching questions from: {questions_url}")
169
- # try:
170
- # response = requests.get(questions_url, timeout=15)
171
- # response.raise_for_status()
172
- # questions_data = response.json()
173
- # print(f"Questions: {questions_data}")
174
- # if not questions_data:
175
- # print("Fetched questions list is empty.")
176
- # return "Fetched questions list is empty or invalid format.", None
177
- # print(f"Fetched {len(questions_data)} questions.")
178
- # except requests.exceptions.RequestException as e:
179
- # print(f"Error fetching questions: {e}")
180
- # return f"Error fetching questions: {e}", None
181
- # except requests.exceptions.JSONDecodeError as e:
182
- # print(f"Error decoding JSON response from questions endpoint: {e}")
183
- # print(f"Response text: {response.text[:500]}")
184
- # return f"Error decoding server response for questions: {e}", None
185
- # except Exception as e:
186
- # print(f"An unexpected error occurred fetching questions: {e}")
187
- # return f"An unexpected error occurred fetching questions: {e}", None
188
- questions_data = [
189
- # {
190
- # 'task_id': '8e867cd7-cff9-4e6c-867a-ff5ddc2550be',
191
- # 'question': 'How many studio albums were published by Mercedes Sosa between 2000 and 2009 (included)? You can use the latest 2022 version of english wikipedia.',
192
- # 'Level': '1',
193
- # 'file_name': ''
194
- # },
195
- # {
196
- # 'task_id': 'a1e91b78-d3d8-4675-bb8d-62741b4b68a6',
197
- # 'question': 'In the video https:\\/\\/www.youtube.com/watch?v=L1vXCYZAYYM, what is the highest number of bird species to be on camera simultaneously?',
198
- # 'Level': '1',
199
- # 'file_name': ''
200
- # },
201
- # {
202
- # 'task_id': '2d83110e-a098-4ebb-9987-066c06fa42d0',
203
- # 'question': '.rewsna eht sa "tfel" drow eht fo etisoppo eht etirw ,ecnetnes siht dnatsrednu uoy fI',
204
- # 'Level': '1',
205
- # 'file_name': ''
206
- # },
207
- # {
208
- # 'task_id': 'cca530fc-4052-43b2-b130-b30968d8aa44',
209
- # 'question': "Review the chess position provided in the image. It is black's turn. Provide the correct next move for black which guarantees a win. Please provide your response in algebraic notation.",
210
- # 'Level': '1',
211
- # 'file_name': 'cca530fc-4052-43b2-b130-b30968d8aa44.png'
212
- # },
213
- {
214
- 'task_id': '4fc2f1ae-8625-45b5-ab34-ad4433bc21f8',
215
- 'question': 'Who nominated the only Featured Article on English Wikipedia about a dinosaur that was promoted in November 2016?',
216
- 'Level': '1',
217
- 'file_name': ''
218
- },
219
- # {
220
- # 'task_id': '6f37996b-2ac7-44b0-8e68-6d28256631b4',
221
- # 'question': 'Given this table defining * on the set S = {a, b, c, d, e}\n\n|*|a|b|c|d|e|\n|---|---|---|---|---|---|\n|a|a|b|c|b|d|\n|b|b|c|a|e|c|\n|c|c|a|b|b|a|\n|d|b|e|b|e|d|\n|e|d|b|a|d|c|\n\nprovide the subset of S involved in any possible counter-examples that prove * is not commutative. Provide your answer as a comma separated list of the elements in the set in alphabetical order.',
222
- # 'Level': '1',
223
- # 'file_name': ''
224
- # },
225
- # {
226
- # 'task_id': '9d191bce-651d-4746-be2d-7ef8ecadb9c2',
227
- # 'question': 'Examine the video at https:\\/\\/www.youtube.com/watch?v=1htKBjuUWec.\n\nWhat does Teal\'c say in response to the question "Isn\'t that hot?"',
228
- # 'Level': '1',
229
- # 'file_name': ''
230
- # },
231
- # {
232
- # 'task_id': 'cabe07ed-9eca-40ea-8ead-410ef5e83f91',
233
- # 'question': "What is the surname of the equine veterinarian mentioned in 1.E Exercises from the chemistry materials licensed by Marisa Alviar-Agnew & Henry Agnew under the CK-12 license in LibreText's Introductory Chemistry materials as compiled 08/21/2023?",
234
- # 'Level': '1',
235
- # 'file_name': ''
236
- # },
237
- # {
238
- # 'task_id': '3cef3a44-215e-4aed-8e3b-b1e3f08063b7',
239
- # 'question': "I'm making a grocery list for my mom, but she's a professor of botany and she's a real stickler when it comes to categorizing things. I need to add different foods to different categories on the grocery list, but if I make a mistake, she won't buy anything inserted in the wrong category. Here's the list I have so far:\n\nmilk, 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\n\nI need to make headings for the fruits and vegetables. Could you please create a list of just the vegetables from my list? If you could do that, then I can figure out how to categorize the rest of the list into the appropriate categories. But remember that my mom is a real stickler, so make sure that no botanical fruits end up on the vegetable list, or she won't get them when she's at the store. Please alphabetize the list of vegetables, and place each item in a comma separated list.",
240
- # 'Level': '1',
241
- # 'file_name': ''
242
- # },
243
- # {
244
- # 'task_id': '99c9cc74-fdc8-46c6-8f8d-3ce2d3bfeea3',
245
- # 'question': 'Hi, I\'m making a pie but I could use some help with my shopping list. I have everything I need for the crust, but I\'m not sure about the filling. I got the recipe from my friend Aditi, but she left it as a voice memo and the speaker on my phone is buzzing so I can\'t quite make out what she\'s saying. Could you please listen to the recipe and list all of the ingredients that my friend described? I only want the ingredients for the filling, as I have everything I need to make my favorite pie crust. I\'ve attached the recipe as Strawberry pie.mp3.\n\nIn your response, please only list the ingredients, not any measurements. So if the recipe calls for "a pinch of salt" or "two cups of ripe strawberries" the ingredients on the list would be "salt" and "ripe strawberries".\n\nPlease format your response as a comma separated list of ingredients. Also, please alphabetize the ingredients.",
246
- # 'Level': '1',
247
- # 'file_name': '99c9cc74-fdc8-46c6-8f8d-3ce2d3bfeea3.mp3'
248
- # },
249
- # {
250
- # 'task_id': '305ac316-eef6-4446-960a-92d80d542f82',
251
- # 'question': 'Who did the actor who played Ray in the Polish-language version of Everybody Loves Raymond play in Magda M.? Give only the first name.',
252
- # 'Level': '1',
253
- # 'file_name': ''
254
- # },
255
- # {
256
- # 'task_id': 'f918266a-b3e0-4914-865d-4faa564f1aef',
257
- # 'question': 'What is the final numeric output from the attached Python code?',
258
- # 'Level': '1',
259
- # 'file_name': 'f918266a-b3e0-4914-865d-4faa564f1aef.py'
260
- # },
261
- # {
262
- # 'task_id': '3f57289b-8c60-48be-bd80-01f8099ca449',
263
- # 'question': 'How many at bats did the Yankee with the most walks in the 1977 regular season have that same season?',
264
- # 'Level': '1',
265
- # 'file_name': ''
266
- # },
267
- # {
268
- # 'task_id': '1f975693-876d-457b-a649-393859e79bf3',
269
- # 'question': "Hi, I was out sick from my classes on Friday, so I'm trying to figure out what I need to study for my Calculus mid-term next week. My friend from class sent me an audio recording of Professor Willowbrook giving out the recommended reading for the test, but my headphones are broken :(\n\nCould you please listen to the recording for me and tell me the page numbers I'm supposed to go over? I've attached a file called Homework.mp3 that has the recording. Please provide just the page numbers as a comma-delimited list. And please provide the list in ascending order.",
270
- # 'Level': '1',
271
- # 'file_name': '1f975693-876d-457b-a649-393859e79bf3.mp3'
272
- # },
273
- # {
274
- # 'task_id': '840bfca7-4f7b-481a-8794-c560c340185d',
275
- # 'question': 'On June 6, 2023, an article by Carolyn Collins Petersen was published in Universe Today. This article mentions a team that produced a paper about their observations, linked at the bottom of the article. Find this paper. Under what NASA award number was the work performed by R. G. Arendt supported by?',
276
- # 'Level': '1',
277
- # 'file_name': ''
278
- # },
279
- # {
280
- # 'task_id': 'bda648d7-d618-4883-88f4-3466eabd860e',
281
- # 'question': "Where were the Vietnamese specimens described by Kuznetzov in Nedoshivina's 2010 paper eventually deposited? Just give me the city name without abbreviations.",
282
- # 'Level': '1',
283
- # 'file_name': ''
284
- # },
285
- # {
286
- # 'task_id': 'cf106601-ab4f-4af9-b045-5295fe67b37d',
287
- # 'question': "What country had the least number of athletes at the 1928 Summer Olympics? If there's a tie for a number of athletes, return the first in alphabetical order. Give the IOC country code as your answer.",
288
- # 'Level': '1',
289
- # 'file_name': ''
290
- # },
291
- # {
292
- # 'task_id': 'a0c07678-e491-4bbc-8f0b-07405144218f',
293
- # 'question': "Who are the pitchers with the number before and after Taishō Tamai's number as of July 2023? Give them to me in the form Pitcher Before, Pitcher After, use their last names only, in Roman characters.",
294
- # 'Level': '1',
295
- # 'file_name': ''
296
- # },
297
- # {
298
- # 'task_id': '7bd855d8-463d-4ed5-93ca-5fe35145f733',
299
- # 'question': 'The attached Excel file contains the sales of menu items for a local fast-food chain. What were the total sales that the chain made from food (not including drinks)? Express your answer in USD with two decimal places.',
300
- # 'Level': '1',
301
- # 'file_name': '7bd855d8-463d-4ed5-93ca-5fe35145f733.xlsx'
302
- # },
303
- # {
304
- # 'task_id': '5a0c1adf-205e-4841-a666-7c3ef95def9d',
305
- # 'question': 'What is the first name of the only Malko Competition recipient from the 20th Century (after 1977) whose nationality on record is a country that no longer exists?',
306
- # 'Level': '1',
307
- # 'file_name': ''
308
- # },
309
- ]
310
-
311
- # 3. Run your Agent
312
- results_log = []
313
- answers_payload = []
314
- print(f"Running agent on {len(questions_data)} questions")
315
- for item in questions_data:
316
- task_id = item.get("task_id")
317
- question_text = item.get("question")
318
- if not task_id or question_text is None:
319
- print(f"Skipping item with missing task_id or question: {item}")
320
- continue
321
- try:
322
- submitted_answer = agent(question_text)
323
- answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
324
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
325
- except Exception as e:
326
- print(f"Error running agent on task {task_id}: {e}")
327
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
328
-
329
- if not answers_payload:
330
- print("Agent did not produce any answers to submit.")
331
- return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
332
-
333
- # 4. Prepare Submission
334
- submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
335
- status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'"
336
- print(status_update)
337
-
338
- # 5. Submit
339
- print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
340
- try:
341
- response = requests.post(submit_url, json=submission_data, timeout=60)
342
- response.raise_for_status()
343
- result_data = response.json()
344
- final_status = (
345
- f"Submission Successful!\n"
346
- f"User: {result_data.get('username')}\n"
347
- f"Overall Score: {result_data.get('score', 'N/A')}% "
348
- f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
349
- f"Message: {result_data.get('message', 'No message received.')}"
350
- )
351
- print("Submission successful.")
352
- results_df = pd.DataFrame(results_log)
353
- return final_status, results_df
354
- except requests.exceptions.HTTPError as e:
355
- error_detail = f"Server responded with status {e.response.status_code}."
356
- try:
357
- error_json = e.response.json()
358
- error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
359
- except requests.exceptions.JSONDecodeError:
360
- error_detail += f" Response: {e.response.text[:500]}"
361
- status_message = f"Submission Failed: {error_detail}"
362
- print(status_message)
363
- results_df = pd.DataFrame(results_log)
364
- return status_message, results_df
365
- except requests.exceptions.Timeout:
366
- status_message = "Submission Failed: The request timed out."
367
- print(status_message)
368
- results_df = pd.DataFrame(results_log)
369
- return status_message, results_df
370
- except requests.exceptions.RequestException as e:
371
- status_message = f"Submission Failed: Network error - {e}"
372
- print(status_message)
373
- results_df = pd.DataFrame(results_log)
374
- return status_message, results_df
375
- except Exception as e:
376
- status_message = f"An unexpected error occurred during submission: {e}"
377
- print(status_message)
378
- results_df = pd.DataFrame(results_log)
379
- return status_message, results_df
380
-
381
-
382
- # --- Build Gradio Interface using Blocks ---
383
- with gr.Blocks() as demo:
384
- gr.Markdown("# Basic Agent Evaluation Runner")
385
- gr.Markdown(
386
- """
387
- **Instructions:**
388
-
389
- 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
390
- 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
391
- 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
392
-
393
- ---
394
- **Disclaimers:**
395
- 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).
396
- 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.
397
- """
398
- )
399
-
400
- gr.LoginButton()
401
-
402
- run_button = gr.Button("Run Evaluation & Submit All Answers")
403
-
404
- status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
405
- # Removed max_rows=10 from DataFrame constructor
406
- results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
407
-
408
- run_button.click(
409
- fn=run_and_submit_all,
410
- outputs=[status_output, results_table]
411
- )
412
-
413
- if __name__ == "__main__":
414
- print("\n" + "-" * 30 + " App Starting " + "-" * 30)
415
- # Check for SPACE_HOST and SPACE_ID at startup for information
416
- space_host_startup = os.getenv("SPACE_HOST")
417
- space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
418
-
419
- if space_host_startup:
420
- print(f"✅ SPACE_HOST found: {space_host_startup}")
421
- print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
422
- else:
423
- print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
424
-
425
- if space_id_startup: # Print repo URLs if SPACE_ID is found
426
- print(f"✅ SPACE_ID found: {space_id_startup}")
427
- print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
428
- print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
429
- else:
430
- print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
431
-
432
- print("-" * (60 + len(" App Starting ")) + "\n")
433
-
434
- print("Launching Gradio Interface for Basic Agent Evaluation...")
435
- demo.launch(debug=True, share=False)