DrekFretson commited on
Commit
a9e8d77
·
verified ·
1 Parent(s): b13c775

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +76 -60
app.py CHANGED
@@ -1,67 +1,28 @@
 
 
 
1
  import os
 
 
 
 
 
 
2
  import gradio as gr
3
  import requests
4
  import inspect
 
 
5
  import pandas as pd
6
- from langchain_core.messages import HumanMessage
7
- from agent import build_graph
8
-
9
- # (Keep Constants as is)
10
- # --- Constants ---
11
- DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
12
-
13
- # --- Basic Agent Definition ---
14
- # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
15
- class BasicAgent:
16
- def __init__(self):
17
- print("BasicAgent initialized.")
18
- self.graph = build_graph()
19
-
20
- def __call__(self, question: str) -> str:
21
- print(f"Agent received question (first 50 chars): {question[:50]}...")
22
- # Wrap the question in a HumanMessage from langchain_core
23
- messages = [HumanMessage(content=question)]
24
- messages = self.graph.invoke({"messages": messages})
25
- answer = messages['messages'][-1].content
26
- return answer[14:]
27
- # def __init__(self):
28
- # print("BasicAgent initialized.")
29
- # def __call__(self, question: str) -> str:
30
- # print(f"Agent received question (first 50 chars): {question[:50]}...")
31
- # fixed_answer = "This is a default answer."
32
- # print(f"Agent returning fixed answer: {fixed_answer}")
33
- # return fixed_answer
34
-
35
- def run_and_submit_all( profile: gr.OAuthProfile | None):
36
- """
37
- Fetches all questions, runs the BasicAgent on them, submits all answers,
38
- and displays the results.
39
- """
40
- # --- Determine HF Space Runtime URL and Repo URL ---
41
- space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
42
 
43
- if profile:
44
- username= f"{profile.username}"
45
- print(f"User logged in: {username}")
46
- else:
47
- print("User not logged in.")
48
- return "Please Login to Hugging Face with the button.", None
49
 
50
- api_url = DEFAULT_API_URL
51
- questions_url = f"{api_url}/questions"
52
- submit_url = f"{api_url}/submit"
53
 
54
- # 1. Instantiate Agent ( modify this part to create your agent)
55
- try:
56
- agent = BasicAgent()
57
- except Exception as e:
58
- print(f"Error instantiating agent: {e}")
59
- return f"Error initializing agent: {e}", None
60
- # 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)
61
- agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
62
- print(agent_code)
63
 
64
- # 2. Fetch Questions
65
  print(f"Fetching questions from: {questions_url}")
66
  try:
67
  response = requests.get(questions_url, timeout=15)
@@ -71,6 +32,7 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
71
  print("Fetched questions list is empty.")
72
  return "Fetched questions list is empty or invalid format.", None
73
  print(f"Fetched {len(questions_data)} questions.")
 
74
  except requests.exceptions.RequestException as e:
75
  print(f"Error fetching questions: {e}")
76
  return f"Error fetching questions: {e}", None
@@ -82,29 +44,83 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
82
  print(f"An unexpected error occurred fetching questions: {e}")
83
  return f"An unexpected error occurred fetching questions: {e}", None
84
 
85
- # 3. Run your Agent
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
  results_log = []
87
  answers_payload = []
88
  print(f"Running agent on {len(questions_data)} questions...")
89
  for item in questions_data:
90
  task_id = item.get("task_id")
 
91
  question_text = item.get("question")
92
  if not task_id or question_text is None:
93
  print(f"Skipping item with missing task_id or question: {item}")
94
  continue
95
  try:
96
- submitted_answer = agent(question_text)
97
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
98
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
99
  except Exception as e:
100
  print(f"Error running agent on task {task_id}: {e}")
101
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
102
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
  if not answers_payload:
104
  print("Agent did not produce any answers to submit.")
105
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
106
 
107
- # 4. Prepare Submission
108
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
109
  status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
110
  print(status_update)
@@ -179,7 +195,7 @@ with gr.Blocks() as demo:
179
 
180
  run_button.click(
181
  fn=run_and_submit_all,
182
- outputs=[status_output, results_table]
183
  )
184
 
185
  if __name__ == "__main__":
@@ -204,4 +220,4 @@ if __name__ == "__main__":
204
  print("-"*(60 + len(" App Starting ")) + "\n")
205
 
206
  print("Launching Gradio Interface for Basic Agent Evaluation...")
207
- demo.launch(debug=True, share=False)
 
1
+
2
+ from __future__ import unicode_literals
3
+ import subprocess
4
  import os
5
+ #from dotenv import load_dotenv
6
+
7
+ #load_dotenv()
8
+
9
+ os.environ['USER_AGENT'] = 'myagent'
10
+
11
  import gradio as gr
12
  import requests
13
  import inspect
14
+ import tempfile
15
+ import nest_asyncio
16
  import pandas as pd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
+ from agent import MyAgent
19
+ from tools import initialize_web_tools
 
 
 
 
20
 
21
+ nest_asyncio.apply()
 
 
22
 
23
+ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
 
 
 
 
 
 
 
 
24
 
25
+ def fetch_questions(questions_url):
26
  print(f"Fetching questions from: {questions_url}")
27
  try:
28
  response = requests.get(questions_url, timeout=15)
 
32
  print("Fetched questions list is empty.")
33
  return "Fetched questions list is empty or invalid format.", None
34
  print(f"Fetched {len(questions_data)} questions.")
35
+ return questions_data
36
  except requests.exceptions.RequestException as e:
37
  print(f"Error fetching questions: {e}")
38
  return f"Error fetching questions: {e}", None
 
44
  print(f"An unexpected error occurred fetching questions: {e}")
45
  return f"An unexpected error occurred fetching questions: {e}", None
46
 
47
+ def download_file(files_url, task_id):
48
+ try:
49
+ filename = task_id
50
+ response = requests.get(files_url+'/'+filename)
51
+ response.raise_for_status()
52
+
53
+ filename = response.headers['content-disposition'].split('"')[1]
54
+ temp_dir = tempfile.gettempdir()
55
+ file_path = os.path.join(temp_dir, filename)
56
+ with open(file_path, 'wb') as f:
57
+ f.write(response.content)
58
+
59
+ return file_path
60
+ except Exception as file_e:
61
+ print(f"No file found for task {task_id} or error: {file_e}")
62
+ return None
63
+
64
+ async def run_my_agent(agent, questions_data, files_url):
65
  results_log = []
66
  answers_payload = []
67
  print(f"Running agent on {len(questions_data)} questions...")
68
  for item in questions_data:
69
  task_id = item.get("task_id")
70
+ file_path = download_file(files_url, task_id)
71
  question_text = item.get("question")
72
  if not task_id or question_text is None:
73
  print(f"Skipping item with missing task_id or question: {item}")
74
  continue
75
  try:
76
+ submitted_answer = await agent(question_text, file_path, task_id)
77
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
78
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
79
  except Exception as e:
80
  print(f"Error running agent on task {task_id}: {e}")
81
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
82
+ return results_log, answers_payload
83
+
84
+ async def run_and_submit_all( profile: gr.OAuthProfile | None):
85
+ """
86
+ Fetches all questions, runs the BasicAgent on them, submits all answers,
87
+ and displays the results.
88
+ """
89
+ # --- Determine HF Space Runtime URL and Repo URL ---
90
+ if profile:
91
+ username= f"{profile.username}"
92
+ print(f"User logged in: {username}")
93
+ else:
94
+ print("User not logged in.")
95
+ return "Please Login to Hugging Face with the button.", None
96
 
97
+ api_url = DEFAULT_API_URL
98
+ questions_url = f"{api_url}/questions"
99
+ submit_url = f"{api_url}/submit"
100
+ files_url = f"{api_url}/files"
101
+
102
+ # 1. Instantiate Agent ( modify this part to create your agent)
103
+ try:
104
+ web_tools = initialize_web_tools()
105
+ agent = MyAgent(web_tools=web_tools)
106
+ except Exception as e:
107
+ print(f"Error instantiating agent: {e}")
108
+ return f"Error initializing agent: {e}", None
109
+ # 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)
110
+ agent_code = f"https://huggingface.co/spaces/{space_id_startup}/tree/main"
111
+ print(agent_code)
112
+
113
+ # 2. Fetch Questions
114
+ questions_data = fetch_questions(questions_url)
115
+
116
+ # 3. Run your Agent
117
+ results_log, answers_payload = await run_my_agent(agent, questions_data, files_url)
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 = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
125
  status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
126
  print(status_update)
 
195
 
196
  run_button.click(
197
  fn=run_and_submit_all,
198
+ outputs=[status_output, results_table],
199
  )
200
 
201
  if __name__ == "__main__":
 
220
  print("-"*(60 + len(" App Starting ")) + "\n")
221
 
222
  print("Launching Gradio Interface for Basic Agent Evaluation...")
223
+ demo.launch(debug=True, share=False)