FD900 commited on
Commit
0b7542f
·
verified ·
1 Parent(s): 50918e4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +155 -115
app.py CHANGED
@@ -1,34 +1,149 @@
1
  import os
2
- import gradio as gr
3
  import requests
4
- import inspect
5
  import pandas as pd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
- # (Keep Constants as is)
8
  # --- Constants ---
9
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
10
 
11
- # --- Basic Agent Definition ---
12
- # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
13
- class BasicAgent:
14
- def __init__(self):
15
- print("BasicAgent initialized.")
16
- def __call__(self, question: str) -> str:
17
- print(f"Agent received question (first 50 chars): {question[:50]}...")
18
- fixed_answer = "This is a default answer."
19
- print(f"Agent returning fixed answer: {fixed_answer}")
20
- return fixed_answer
21
-
22
- def run_and_submit_all( profile: gr.OAuthProfile | None):
23
- """
24
- Fetches all questions, runs the BasicAgent on them, submits all answers,
25
- and displays the results.
26
- """
27
- # --- Determine HF Space Runtime URL and Repo URL ---
28
- space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
  if profile:
31
- username= f"{profile.username}"
32
  print(f"User logged in: {username}")
33
  else:
34
  print("User not logged in.")
@@ -38,66 +153,40 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
38
  questions_url = f"{api_url}/questions"
39
  submit_url = f"{api_url}/submit"
40
 
41
- # 1. Instantiate Agent ( modify this part to create your agent)
42
  try:
43
- agent = BasicAgent()
44
  except Exception as e:
45
- print(f"Error instantiating agent: {e}")
46
  return f"Error initializing agent: {e}", None
47
- # 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)
48
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
49
- print(agent_code)
50
 
51
- # 2. Fetch Questions
52
- print(f"Fetching questions from: {questions_url}")
53
  try:
54
  response = requests.get(questions_url, timeout=15)
55
  response.raise_for_status()
56
  questions_data = response.json()
57
- if not questions_data:
58
- print("Fetched questions list is empty.")
59
- return "Fetched questions list is empty or invalid format.", None
60
- print(f"Fetched {len(questions_data)} questions.")
61
- except requests.exceptions.RequestException as e:
62
- print(f"Error fetching questions: {e}")
63
- return f"Error fetching questions: {e}", None
64
- except requests.exceptions.JSONDecodeError as e:
65
- print(f"Error decoding JSON response from questions endpoint: {e}")
66
- print(f"Response text: {response.text[:500]}")
67
- return f"Error decoding server response for questions: {e}", None
68
  except Exception as e:
69
- print(f"An unexpected error occurred fetching questions: {e}")
70
- return f"An unexpected error occurred fetching questions: {e}", None
71
 
72
- # 3. Run your Agent
73
  results_log = []
74
  answers_payload = []
75
- print(f"Running agent on {len(questions_data)} questions...")
76
  for item in questions_data:
77
  task_id = item.get("task_id")
78
  question_text = item.get("question")
 
 
79
  if not task_id or question_text is None:
80
- print(f"Skipping item with missing task_id or question: {item}")
81
  continue
82
  try:
83
- submitted_answer = agent(question_text)
84
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
85
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
86
  except Exception as e:
87
- print(f"Error running agent on task {task_id}: {e}")
88
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
89
 
90
  if not answers_payload:
91
- print("Agent did not produce any answers to submit.")
92
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
93
 
94
- # 4. Prepare Submission
95
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
96
- status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
97
- print(status_update)
98
-
99
- # 5. Submit
100
- print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
101
  try:
102
  response = requests.post(submit_url, json=submission_data, timeout=60)
103
  response.raise_for_status()
@@ -109,61 +198,33 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
109
  f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
110
  f"Message: {result_data.get('message', 'No message received.')}"
111
  )
112
- print("Submission successful.")
113
- results_df = pd.DataFrame(results_log)
114
- return final_status, results_df
115
- except requests.exceptions.HTTPError as e:
116
- error_detail = f"Server responded with status {e.response.status_code}."
117
- try:
118
- error_json = e.response.json()
119
- error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
120
- except requests.exceptions.JSONDecodeError:
121
- error_detail += f" Response: {e.response.text[:500]}"
122
- status_message = f"Submission Failed: {error_detail}"
123
- print(status_message)
124
- results_df = pd.DataFrame(results_log)
125
- return status_message, results_df
126
- except requests.exceptions.Timeout:
127
- status_message = "Submission Failed: The request timed out."
128
- print(status_message)
129
- results_df = pd.DataFrame(results_log)
130
- return status_message, results_df
131
- except requests.exceptions.RequestException as e:
132
- status_message = f"Submission Failed: Network error - {e}"
133
- print(status_message)
134
- results_df = pd.DataFrame(results_log)
135
- return status_message, results_df
136
  except Exception as e:
137
- status_message = f"An unexpected error occurred during submission: {e}"
138
- print(status_message)
139
- results_df = pd.DataFrame(results_log)
140
- return status_message, results_df
141
-
142
 
143
- # --- Build Gradio Interface using Blocks ---
144
  with gr.Blocks() as demo:
145
  gr.Markdown("# Basic Agent Evaluation Runner")
146
  gr.Markdown(
147
  """
148
- **Instructions:**
149
-
150
  1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
151
  2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
152
  3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
153
 
154
- ---
155
- **Disclaimers:**
156
- 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).
157
- 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.
 
 
 
158
  """
159
  )
160
 
161
  gr.LoginButton()
162
 
163
  run_button = gr.Button("Run Evaluation & Submit All Answers")
164
-
165
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
166
- # Removed max_rows=10 from DataFrame constructor
167
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
168
 
169
  run_button.click(
@@ -171,26 +232,5 @@ with gr.Blocks() as demo:
171
  outputs=[status_output, results_table]
172
  )
173
 
174
- if __name__ == "__main__":
175
- print("\n" + "-"*30 + " App Starting " + "-"*30)
176
- # Check for SPACE_HOST and SPACE_ID at startup for information
177
- space_host_startup = os.getenv("SPACE_HOST")
178
- space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
179
-
180
- if space_host_startup:
181
- print(f"✅ SPACE_HOST found: {space_host_startup}")
182
- print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
183
- else:
184
- print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
185
-
186
- if space_id_startup: # Print repo URLs if SPACE_ID is found
187
- print(f"✅ SPACE_ID found: {space_id_startup}")
188
- print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
189
- print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
190
- else:
191
- print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
192
-
193
- print("-"*(60 + len(" App Starting ")) + "\n")
194
-
195
- print("Launching Gradio Interface for Basic Agent Evaluation...")
196
  demo.launch(debug=True, share=False)
 
1
  import os
 
2
  import requests
 
3
  import pandas as pd
4
+ import gradio as gr
5
+ import openai
6
+ from langchain.embeddings import OpenAIEmbeddings
7
+ from langchain.vectorstores import FAISS
8
+ from langchain.text_splitter import CharacterTextSplitter
9
+ from langchain.chains import RetrievalQA
10
+ from langchain.llms import OpenAI
11
+ from langchain.document_loaders import TextLoader, PyPDFLoader, CSVLoader
12
+ from langchain.tools import DuckDuckGoSearchRun
13
+ from langchain.agents import initialize_agent, Tool
14
+ from langchain.agents.agent_types import AgentType
15
+ from langchain.schema import Document
16
+ from PIL import Image
17
+ import pytesseract
18
 
 
19
  # --- Constants ---
20
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
21
 
22
+ # --- Basic Agent Definition with RAG + Tools ---
23
+ class RAGAgent:
24
+ def _init_(self):
25
+ self.api_key = os.getenv("OPENAI_API_KEY")
26
+ if not self.api_key:
27
+ raise ValueError("OPENAI_API_KEY is not set in environment variables.")
28
+ openai.api_key = self.api_key
29
+ print("GPT-4o RAG Agent with tools initialized.")
30
+ self.vectorstore = None
31
+ self.tools = [
32
+ Tool(
33
+ name="Search News",
34
+ func=DuckDuckGoSearchRun().run,
35
+ description="Useful for finding recent news articles about a topic."
36
+ ),
37
+ Tool(
38
+ name="Company Profile",
39
+ func=DuckDuckGoSearchRun().run,
40
+ description="Retrieve basic profile information about a company."
41
+ ),
42
+ Tool(
43
+ name="Search Wikipedia",
44
+ func=DuckDuckGoSearchRun().run,
45
+ description="Good for general encyclopedic knowledge."
46
+ )
47
+ ]
48
+
49
+ def build_vectorstore(self, file_path):
50
+ print(f"Building vectorstore from file: {file_path}")
51
+ ext = os.path.splitext(file_path)[-1].lower()
52
+ if ext == ".txt":
53
+ loader = TextLoader(file_path)
54
+ elif ext == ".pdf":
55
+ loader = PyPDFLoader(file_path)
56
+ elif ext == ".csv":
57
+ loader = CSVLoader(file_path)
58
+ elif ext in [".png", ".jpg", ".jpeg"]:
59
+ def ocr_image(file_path):
60
+ text = pytesseract.image_to_string(Image.open(file_path))
61
+ return [Document(page_content=text)]
62
+
63
+ class OCRImageLoader:
64
+ def _init_(self, path):
65
+ self.path = path
66
+
67
+ def load(self):
68
+ return ocr_image(self.path)
69
+
70
+ loader = OCRImageLoader(file_path)
71
+ else:
72
+ raise ValueError(f"Unsupported file type: {ext}")
73
+
74
+ documents = loader.load()
75
+ text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=100)
76
+ texts = text_splitter.split_documents(documents)
77
+ embeddings = OpenAIEmbeddings()
78
+ self.vectorstore = FAISS.from_documents(texts, embeddings)
79
+
80
+ def classify_task_level(self, question: str) -> int:
81
+ if any(kw in question.lower() for kw in ["in the image", "clockwise", "based on", "served in", "multi-step"]):
82
+ return 3
83
+ elif len(question.split()) > 40 or any(kw in question.lower() for kw in ["using the tool", "summarize and compare"]):
84
+ return 2
85
+ else:
86
+ return 1
87
+
88
+ def simple_answer(self, question, file_path):
89
+ if file_path and os.path.isfile(file_path):
90
+ self.build_vectorstore(file_path)
91
+ retriever = self.vectorstore.as_retriever()
92
+ qa_chain = RetrievalQA.from_chain_type(llm=OpenAI(model_name="gpt-4o", temperature=0.3), retriever=retriever)
93
+ return qa_chain.run(question)
94
+ else:
95
+ return OpenAI(model_name="gpt-4o", temperature=0.3)(question)
96
+
97
+ def coordinated_tool_reasoning(self, question, file_path):
98
+ if file_path and os.path.isfile(file_path):
99
+ self.build_vectorstore(file_path)
100
+ retriever = self.vectorstore.as_retriever()
101
+ else:
102
+ retriever = None
103
+
104
+ agent_executor = initialize_agent(
105
+ self.tools,
106
+ OpenAI(model_name="gpt-4o", temperature=0.3),
107
+ agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
108
+ verbose=True
109
+ )
110
+
111
+ context = retriever.get_relevant_documents(question) if retriever else []
112
+ augmented_question = f"{question}\n\nContext:\n{''.join([doc.page_content for doc in context])}" if context else question
113
+ return agent_executor.run(augmented_question)
114
+
115
+ def complex_multihop_chain(self, question, file_path):
116
+ return self.coordinated_tool_reasoning(question, file_path)
117
+
118
+ def solve_question(self, question: str, file_path: str = None, level: int = None) -> str:
119
+ print(f"Received question (first 50 chars): {question[:50]}...")
120
+ if level is None:
121
+ level = self.classify_task_level(question)
122
+ print(f"Classified task as Level {level}")
123
+
124
+ try:
125
+ if level == 1:
126
+ return self.simple_answer(question, file_path)
127
+ elif level == 2:
128
+ return self.coordinated_tool_reasoning(question, file_path)
129
+ elif level == 3:
130
+ return self.complex_multihop_chain(question, file_path)
131
+ else:
132
+ raise ValueError("Unsupported level.")
133
+ except Exception as e:
134
+ print(f"Error during reasoning: {e}")
135
+ return f"Error: {e}"
136
+
137
+ def _call_(self, question: str, file_path: str = None, level: int = None) -> str:
138
+ return self.solve_question(question, file_path, level)
139
+
140
+ # --- Evaluation & Submission Code ---
141
+
142
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
143
+ space_id = os.getenv("SPACE_ID")
144
 
145
  if profile:
146
+ username = f"{profile.username}"
147
  print(f"User logged in: {username}")
148
  else:
149
  print("User not logged in.")
 
153
  questions_url = f"{api_url}/questions"
154
  submit_url = f"{api_url}/submit"
155
 
 
156
  try:
157
+ agent = RAGAgent()
158
  except Exception as e:
 
159
  return f"Error initializing agent: {e}", None
160
+
161
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
 
162
 
 
 
163
  try:
164
  response = requests.get(questions_url, timeout=15)
165
  response.raise_for_status()
166
  questions_data = response.json()
 
 
 
 
 
 
 
 
 
 
 
167
  except Exception as e:
168
+ return f"Error fetching questions: {e}", None
 
169
 
 
170
  results_log = []
171
  answers_payload = []
 
172
  for item in questions_data:
173
  task_id = item.get("task_id")
174
  question_text = item.get("question")
175
+ file_path = item.get("file_path")
176
+ level = item.get("level")
177
  if not task_id or question_text is None:
 
178
  continue
179
  try:
180
+ submitted_answer = agent(question_text, file_path, level)
181
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
182
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
183
  except Exception as e:
184
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
 
185
 
186
  if not answers_payload:
 
187
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
188
 
 
189
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
 
 
 
 
 
190
  try:
191
  response = requests.post(submit_url, json=submission_data, timeout=60)
192
  response.raise_for_status()
 
198
  f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
199
  f"Message: {result_data.get('message', 'No message received.')}"
200
  )
201
+ return final_status, pd.DataFrame(results_log)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
202
  except Exception as e:
203
+ return f"Submission Failed: {e}", pd.DataFrame(results_log)
 
 
 
 
204
 
 
205
  with gr.Blocks() as demo:
206
  gr.Markdown("# Basic Agent Evaluation Runner")
207
  gr.Markdown(
208
  """
209
+ *Instructions:*
 
210
  1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
211
  2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
212
  3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
213
 
214
+ This agent is designed for tasks that require:
215
+ - Structured responses
216
+ - Multimodal reasoning (e.g., analyzing images)
217
+ - Multi-hop retrieval of interdependent facts (e.g., identify fruit in an image, lookup ship history, fetch historical menus)
218
+ - Correct sequencing and planning over multiple steps
219
+
220
+ These capabilities are critical to solving complex GAIA tasks that go beyond what standalone LLMs can handle.
221
  """
222
  )
223
 
224
  gr.LoginButton()
225
 
226
  run_button = gr.Button("Run Evaluation & Submit All Answers")
 
227
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
 
228
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
229
 
230
  run_button.click(
 
232
  outputs=[status_output, results_table]
233
  )
234
 
235
+ if _name_ == "_main_":
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
236
  demo.launch(debug=True, share=False)