ncuxomun commited on
Commit
b383198
·
verified ·
1 Parent(s): 1b210c3

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +257 -0
app.py ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ import requests
4
+ import inspect
5
+ import pandas as pd
6
+ from dotenv import load_dotenv
7
+ load_dotenv()
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
+ def __call__(self, question: str) -> str:
19
+ print(f"Agent received question (first 50 chars): {question[:50]}...")
20
+ fixed_answer = "This is a default answer."
21
+ print(f"Agent returning fixed answer: {fixed_answer}")
22
+ return fixed_answer
23
+
24
+ from langgraph.graph import StateGraph
25
+ from langchain_core.runnables import RunnableLambda
26
+ from langchain_core.messages import HumanMessage, SystemMessage
27
+ from langchain_openai import ChatOpenAI
28
+
29
+ class LangGraphAgent:
30
+ def __init__(self):
31
+ print("LangGraphAgent initialized.")
32
+
33
+ # Fix: Use OPENAI_API_KEY as the standard environment variable name
34
+ openai_key = os.environ.get("OPENAI_API_KEY")
35
+ if not openai_key:
36
+ # Try alternative environment variable name as fallback
37
+ openai_key = os.environ.get("OPEN_AI_KEY")
38
+
39
+ if not openai_key:
40
+ raise ValueError("OpenAI API key not found in environment variables")
41
+
42
+ print(f"Loaded OpenAI Key: {openai_key[:3]}..." if openai_key else "No OpenAI Key found")
43
+
44
+ # Fix: Update the model name to a valid one
45
+ # "gpt-4.1" is not a valid model name, use "gpt-4" or "gpt-4-turbo" instead
46
+ self.llm = ChatOpenAI(model="gpt-4-turbo", temperature=0, api_key=openai_key)
47
+
48
+ self.sys_prompt = SystemMessage(
49
+ content="""You are a general AI assistant. I will ask you a question. Report your thoughts, and finish your answer with the following template: FINAL ANSWER: [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."""
50
+ )
51
+
52
+ def answer_fn(state):
53
+ question = state["question"]
54
+ print(f"[LangGraphAgent] Received: {question[:50]}...")
55
+ messages = [self.sys_prompt, HumanMessage(content=question)]
56
+ response = self.llm.invoke(messages).content
57
+
58
+ # Extract the "FINAL ANSWER:" line
59
+ final_answer = self._extract_final_answer(response)
60
+ return {"question": question, "answer": final_answer}
61
+
62
+ builder = StateGraph()
63
+ builder = builder.with_state_schema({"question": str, "answer": str})
64
+ builder.add_node("answer_question", RunnableLambda(answer_fn))
65
+ builder.set_entry_point("answer_question")
66
+ builder.set_finish_point("answer_question")
67
+ self.graph = builder.compile()
68
+
69
+ def __call__(self, question: str) -> str:
70
+ output = self.graph.invoke({"question": question})
71
+ return output["answer"]
72
+
73
+ def _extract_final_answer(self, response: str) -> str:
74
+ # Robustly find "FINAL ANSWER:" line
75
+ for line in response.strip().splitlines()[::-1]:
76
+ if line.strip().lower().startswith("final answer:"):
77
+ return line.split(":", 1)[1].strip()
78
+ print("Warning: FINAL ANSWER not found, returning full response.")
79
+ return response.strip()
80
+
81
+
82
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
83
+ """
84
+ Fetches all questions, runs the BasicAgent/LangGraphAgent on them, submits all answers,
85
+ and displays the results.
86
+ """
87
+ # --- Determine HF Space Runtime URL and Repo URL ---
88
+ space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
89
+
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
+
101
+ # 1. Instantiate Agent ( modify this part to create your agent)
102
+ try:
103
+ # agent = BasicAgent()
104
+ agent = LangGraphAgent()
105
+ except Exception as e:
106
+ print(f"Error instantiating agent: {e}")
107
+ return f"Error initializing agent: {e}", None
108
+ # 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)
109
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
110
+ print(agent_code)
111
+
112
+ # 2. Fetch Questions
113
+ print(f"Fetching questions from: {questions_url}")
114
+ try:
115
+ response = requests.get(questions_url, timeout=15)
116
+ response.raise_for_status()
117
+ questions_data = response.json()
118
+ if not questions_data:
119
+ print("Fetched questions list is empty.")
120
+ return "Fetched questions list is empty or invalid format.", None
121
+ print(f"Fetched {len(questions_data)} questions.")
122
+ except requests.exceptions.RequestException as e:
123
+ print(f"Error fetching questions: {e}")
124
+ return f"Error fetching questions: {e}", None
125
+ except requests.exceptions.JSONDecodeError as e:
126
+ print(f"Error decoding JSON response from questions endpoint: {e}")
127
+ print(f"Response text: {response.text[:500]}")
128
+ return f"Error decoding server response for questions: {e}", None
129
+ except Exception as e:
130
+ print(f"An unexpected error occurred fetching questions: {e}")
131
+ return f"An unexpected error occurred fetching questions: {e}", None
132
+
133
+ # 3. Run your Agent
134
+ results_log = []
135
+ answers_payload = []
136
+ print(f"Running agent on {len(questions_data)} questions...")
137
+ for item in questions_data:
138
+ task_id = item.get("task_id")
139
+ question_text = item.get("question")
140
+ if not task_id or question_text is None:
141
+ print(f"Skipping item with missing task_id or question: {item}")
142
+ continue
143
+ try:
144
+ submitted_answer = agent(question_text)
145
+ answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
146
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
147
+ except Exception as e:
148
+ print(f"Error running agent on task {task_id}: {e}")
149
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
150
+
151
+ if not answers_payload:
152
+ print("Agent did not produce any answers to submit.")
153
+ return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
154
+
155
+ # 4. Prepare Submission
156
+ submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
157
+ status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
158
+ print(status_update)
159
+
160
+ # 5. Submit
161
+ print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
162
+ try:
163
+ response = requests.post(submit_url, json=submission_data, timeout=60)
164
+ response.raise_for_status()
165
+ result_data = response.json()
166
+ final_status = (
167
+ f"Submission Successful!\n"
168
+ f"User: {result_data.get('username')}\n"
169
+ f"Overall Score: {result_data.get('score', 'N/A')}% "
170
+ f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
171
+ f"Message: {result_data.get('message', 'No message received.')}"
172
+ )
173
+ print("Submission successful.")
174
+ results_df = pd.DataFrame(results_log)
175
+ return final_status, results_df
176
+ except requests.exceptions.HTTPError as e:
177
+ error_detail = f"Server responded with status {e.response.status_code}."
178
+ try:
179
+ error_json = e.response.json()
180
+ error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
181
+ except requests.exceptions.JSONDecodeError:
182
+ error_detail += f" Response: {e.response.text[:500]}"
183
+ status_message = f"Submission Failed: {error_detail}"
184
+ print(status_message)
185
+ results_df = pd.DataFrame(results_log)
186
+ return status_message, results_df
187
+ except requests.exceptions.Timeout:
188
+ status_message = "Submission Failed: The request timed out."
189
+ print(status_message)
190
+ results_df = pd.DataFrame(results_log)
191
+ return status_message, results_df
192
+ except requests.exceptions.RequestException as e:
193
+ status_message = f"Submission Failed: Network error - {e}"
194
+ print(status_message)
195
+ results_df = pd.DataFrame(results_log)
196
+ return status_message, results_df
197
+ except Exception as e:
198
+ status_message = f"An unexpected error occurred during submission: {e}"
199
+ print(status_message)
200
+ results_df = pd.DataFrame(results_log)
201
+ return status_message, results_df
202
+
203
+
204
+ # --- Build Gradio Interface using Blocks ---
205
+ with gr.Blocks() as demo:
206
+ gr.Markdown("# Basic Agent Evaluation Runner")
207
+ gr.Markdown(
208
+ """
209
+ **Instructions:**
210
+
211
+ 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
212
+ 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
213
+ 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
214
+
215
+ ---
216
+ **Disclaimers:**
217
+ 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).
218
+ 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.
219
+ """
220
+ )
221
+
222
+ with gr.Row():
223
+ login_button = gr.LoginButton()
224
+
225
+ run_button = gr.Button("Run Evaluation & Submit All Answers")
226
+
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(
231
+ fn=run_and_submit_all,
232
+ outputs=[status_output, results_table]
233
+ )
234
+
235
+ if __name__ == "__main__":
236
+ print("\n" + "-"*30 + " App Starting " + "-"*30)
237
+ # Check for SPACE_HOST and SPACE_ID at startup for information
238
+ space_host_startup = os.getenv("SPACE_HOST")
239
+ space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
240
+
241
+ if space_host_startup:
242
+ print(f"✅ SPACE_HOST found: {space_host_startup}")
243
+ print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
244
+ else:
245
+ print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
246
+
247
+ if space_id_startup: # Print repo URLs if SPACE_ID is found
248
+ print(f"✅ SPACE_ID found: {space_id_startup}")
249
+ print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
250
+ print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
251
+ else:
252
+ print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
253
+
254
+ print("-"*(60 + len(" App Starting ")) + "\n")
255
+
256
+ print("Launching Gradio Interface for Basic Agent Evaluation...")
257
+ demo.launch(debug=True, share=True)