Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -94,272 +94,3 @@ def run_and_submit_one():
|
|
| 94 |
|
| 95 |
run_and_submit_one()
|
| 96 |
|
| 97 |
-
|
| 98 |
-
#Client setup
|
| 99 |
-
#token = HF_TOKEN
|
| 100 |
-
#model_repo_id = chat_completion eller question_answering
|
| 101 |
-
|
| 102 |
-
# llm = LLMFunction.from_huggingface_inference_api(
|
| 103 |
-
# repo_id="google/flan-t5-base", #
|
| 104 |
-
# token="HF_TOKEN "
|
| 105 |
-
# )
|
| 106 |
-
|
| 107 |
-
# agent = CodeAgent(llm=llm)
|
| 108 |
-
# response = agent("Translate 'How are you?' to German.")
|
| 109 |
-
# print(response)
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
#----
|
| 115 |
-
# client = InferenceClient(
|
| 116 |
-
# provider="hf-inference",
|
| 117 |
-
# api_key=os.environ["HF_TOKEN"],
|
| 118 |
-
# )
|
| 119 |
-
|
| 120 |
-
# completion = client.chat.completions.create(
|
| 121 |
-
# model="tiiuae/falcon-rw-1b",
|
| 122 |
-
# messages=[
|
| 123 |
-
# {
|
| 124 |
-
# "role": "user",
|
| 125 |
-
# "content": "What is the capital of France?"
|
| 126 |
-
# }
|
| 127 |
-
# ],
|
| 128 |
-
# )
|
| 129 |
-
|
| 130 |
-
# completion = client.chat.completions.create(
|
| 131 |
-
# model="sarvamai/sarvam-m",
|
| 132 |
-
# messages=[
|
| 133 |
-
# {
|
| 134 |
-
# "role": "user",
|
| 135 |
-
# "content": "What is the capital of France?"
|
| 136 |
-
# }
|
| 137 |
-
# ],
|
| 138 |
-
# )
|
| 139 |
-
|
| 140 |
-
# (Keep Constants as is)
|
| 141 |
-
# --- Constants ---
|
| 142 |
-
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 143 |
-
|
| 144 |
-
# --- Basic Agent Definition ---
|
| 145 |
-
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
| 146 |
-
|
| 147 |
-
#Tools
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
#Model
|
| 151 |
-
model = InferenceClientModel() #Default
|
| 152 |
-
|
| 153 |
-
#Agent
|
| 154 |
-
code_agent = CodeAgent(tools=[], model=model)
|
| 155 |
-
#code_agent = CodeAgent(tools=[DuckDuckGoSearchTool()], model=model)
|
| 156 |
-
|
| 157 |
-
class BasicAgent:
|
| 158 |
-
def __init__(self):
|
| 159 |
-
print("BasicAgent initialized.")
|
| 160 |
-
def __call__(self, question: str) -> str:
|
| 161 |
-
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 162 |
-
|
| 163 |
-
fixed_answer = "This is a default answer."
|
| 164 |
-
print(f"Agent returning fixed answer: {fixed_answer}")
|
| 165 |
-
return fixed_answer
|
| 166 |
-
|
| 167 |
-
class BasicCodeAgent:
|
| 168 |
-
def __init__(self):
|
| 169 |
-
model = InferenceClientModel() #Cause of
|
| 170 |
-
|
| 171 |
-
# model = HfApiModel(
|
| 172 |
-
# max_tokens=2096,
|
| 173 |
-
# temperature=0.5,
|
| 174 |
-
# model_id='Qwen/Qwen2.5-Coder-32B-Instruct',# it is possible that this model may be overloaded
|
| 175 |
-
# custom_role_conversions=None,
|
| 176 |
-
# )
|
| 177 |
-
|
| 178 |
-
self.agent = CodeAgent(tools=[DuckDuckGoSearchTool()], model=model)
|
| 179 |
-
print("BasicCodeAgent initialized.")
|
| 180 |
-
|
| 181 |
-
def __call__(self, question: str) -> str:
|
| 182 |
-
print(f"BasicCodeAgent received question (first 50 chars): {question[:50]}...")
|
| 183 |
-
fixed_answer = "This is a default answer."
|
| 184 |
-
#answer = self.agent.run(question)
|
| 185 |
-
print(f"BasicCodeAgent returning fixed answer: {fixed_answer}")
|
| 186 |
-
return answer
|
| 187 |
-
|
| 188 |
-
# def run_and_submit_all( profile: gr.OAuthProfile | None):
|
| 189 |
-
# """
|
| 190 |
-
# Fetches all questions, runs the BasicAgent on them, submits all answers,
|
| 191 |
-
# and displays the results.
|
| 192 |
-
# """
|
| 193 |
-
# # --- Determine HF Space Runtime URL and Repo URL ---
|
| 194 |
-
# space_id = os.getenv("/Synnove/Final_Assignment_Template") # Get the SPACE_ID for sending link to the code
|
| 195 |
-
|
| 196 |
-
# if profile:
|
| 197 |
-
# username= f"{profile.username}"
|
| 198 |
-
# print(f"User logged in: {username}")
|
| 199 |
-
# else:
|
| 200 |
-
# print("User not logged in.")
|
| 201 |
-
# return "Please Login to Hugging Face with the button.", None
|
| 202 |
-
|
| 203 |
-
# api_url = "https://agents-course-unit4-scoring.hf.space"
|
| 204 |
-
# questions_url = f"{api_url}/questions"
|
| 205 |
-
# submit_url = f"{api_url}/submit"
|
| 206 |
-
|
| 207 |
-
# # 1. Instantiate Agent ( modify this part to create your agent)
|
| 208 |
-
# try:
|
| 209 |
-
# #agent = BasicAgent()
|
| 210 |
-
# agent = BasicCodeAgent()
|
| 211 |
-
|
| 212 |
-
# except Exception as e:
|
| 213 |
-
# print(f"Error instantiating agent: {e}")
|
| 214 |
-
# return f"Error initializing agent: {e}", None
|
| 215 |
-
# # 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)
|
| 216 |
-
# agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 217 |
-
# print(agent_code)
|
| 218 |
-
|
| 219 |
-
# # 2. Fetch Questions
|
| 220 |
-
# print(f"Fetching questions from: {questions_url}")
|
| 221 |
-
# try:
|
| 222 |
-
# response = requests.get(questions_url, timeout=15)
|
| 223 |
-
# response.raise_for_status()
|
| 224 |
-
# questions_data = response.json()
|
| 225 |
-
# if not questions_data:
|
| 226 |
-
# print("Fetched questions list is empty.")
|
| 227 |
-
# return "Fetched questions list is empty or invalid format.", None
|
| 228 |
-
# print(f"Fetched {len(questions_data)} questions.")
|
| 229 |
-
# except requests.exceptions.RequestException as e:
|
| 230 |
-
# print(f"Error fetching questions: {e}")
|
| 231 |
-
# return f"Error fetching questions: {e}", None
|
| 232 |
-
# except requests.exceptions.JSONDecodeError as e:
|
| 233 |
-
# print(f"Error decoding JSON response from questions endpoint: {e}")
|
| 234 |
-
# print(f"Response text: {response.text[:500]}")
|
| 235 |
-
# return f"Error decoding server response for questions: {e}", None
|
| 236 |
-
# except Exception as e:
|
| 237 |
-
# print(f"An unexpected error occurred fetching questions: {e}")
|
| 238 |
-
# return f"An unexpected error occurred fetching questions: {e}", None
|
| 239 |
-
|
| 240 |
-
# # 3. Run your Agent
|
| 241 |
-
# results_log = []
|
| 242 |
-
# answers_payload = []
|
| 243 |
-
# print(f"Running agent on {len(questions_data)} questions...")
|
| 244 |
-
# print(questions_data)
|
| 245 |
-
# for item in questions_data:
|
| 246 |
-
# task_id = item.get("task_id")
|
| 247 |
-
# question_text = item.get("question")
|
| 248 |
-
# if not task_id or question_text is None:
|
| 249 |
-
# print(f"Skipping item with missing task_id or question: {item}")
|
| 250 |
-
# continue
|
| 251 |
-
# try:
|
| 252 |
-
# submitted_answer = agent(question_text)
|
| 253 |
-
# answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 254 |
-
# results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
| 255 |
-
# except Exception as e:
|
| 256 |
-
# print(f"Error running agent on task {task_id}: {e}")
|
| 257 |
-
# results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
| 258 |
-
|
| 259 |
-
# if not answers_payload:
|
| 260 |
-
# print("Agent did not produce any answers to submit.")
|
| 261 |
-
# return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 262 |
-
|
| 263 |
-
# # 4. Prepare Submission
|
| 264 |
-
# submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 265 |
-
# status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
| 266 |
-
# print(status_update)
|
| 267 |
-
|
| 268 |
-
# # 5. Submit
|
| 269 |
-
# print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
| 270 |
-
# try:
|
| 271 |
-
# response = requests.post(submit_url, json=submission_data, timeout=60)
|
| 272 |
-
# response.raise_for_status()
|
| 273 |
-
# result_data = response.json()
|
| 274 |
-
# final_status = (
|
| 275 |
-
# f"Submission Successful!\n"
|
| 276 |
-
# f"User: {result_data.get('username')}\n"
|
| 277 |
-
# f"Overall Score: {result_data.get('score', 'N/A')}% "
|
| 278 |
-
# f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
| 279 |
-
# f"Message: {result_data.get('message', 'No message received.')}"
|
| 280 |
-
# )
|
| 281 |
-
# print("Submission successful.")
|
| 282 |
-
# results_df = pd.DataFrame(results_log)
|
| 283 |
-
# return final_status, results_df
|
| 284 |
-
# except requests.exceptions.HTTPError as e:
|
| 285 |
-
# error_detail = f"Server responded with status {e.response.status_code}."
|
| 286 |
-
# try:
|
| 287 |
-
# error_json = e.response.json()
|
| 288 |
-
# error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
| 289 |
-
# except requests.exceptions.JSONDecodeError:
|
| 290 |
-
# error_detail += f" Response: {e.response.text[:500]}"
|
| 291 |
-
# status_message = f"Submission Failed: {error_detail}"
|
| 292 |
-
# print(status_message)
|
| 293 |
-
# results_df = pd.DataFrame(results_log)
|
| 294 |
-
# return status_message, results_df
|
| 295 |
-
# except requests.exceptions.Timeout:
|
| 296 |
-
# status_message = "Submission Failed: The request timed out."
|
| 297 |
-
# print(status_message)
|
| 298 |
-
# results_df = pd.DataFrame(results_log)
|
| 299 |
-
# return status_message, results_df
|
| 300 |
-
# except requests.exceptions.RequestException as e:
|
| 301 |
-
# status_message = f"Submission Failed: Network error - {e}"
|
| 302 |
-
# print(status_message)
|
| 303 |
-
# results_df = pd.DataFrame(results_log)
|
| 304 |
-
# return status_message, results_df
|
| 305 |
-
# except run_and_submit_allxception as e:
|
| 306 |
-
# status_message = f"An unexpected error occurred during submission: {e}"
|
| 307 |
-
# print(status_message)
|
| 308 |
-
# results_df = pd.DataFrame(results_log)
|
| 309 |
-
# return status_message, results_df
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
# # --- Build Gradio Interface using Blocks ---
|
| 313 |
-
# with gr.Blocks() as demo:
|
| 314 |
-
# gr.Markdown("# Basic Agent Evaluation Runner")
|
| 315 |
-
# gr.Markdown(
|
| 316 |
-
# """
|
| 317 |
-
# **Instructions:**
|
| 318 |
-
|
| 319 |
-
# 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
|
| 320 |
-
# 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
|
| 321 |
-
# 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
| 322 |
-
|
| 323 |
-
# ---
|
| 324 |
-
# **Disclaimers:**
|
| 325 |
-
# 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).
|
| 326 |
-
# 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.
|
| 327 |
-
# """
|
| 328 |
-
# )
|
| 329 |
-
|
| 330 |
-
# gr.LoginButton()
|
| 331 |
-
|
| 332 |
-
# run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 333 |
-
|
| 334 |
-
# status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
| 335 |
-
# # Removed max_rows=10 from DataFrame constructor
|
| 336 |
-
# results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 337 |
-
|
| 338 |
-
# run_button.click(
|
| 339 |
-
# fn=run_and_submit_all,
|
| 340 |
-
# outputs=[status_output, results_table]
|
| 341 |
-
# )
|
| 342 |
-
|
| 343 |
-
# if __name__ == "__main__":
|
| 344 |
-
# print("\n" + "-"*30 + " App Starting " + "-"*30)
|
| 345 |
-
# # Check for SPACE_HOST and SPACE_ID at startup for information
|
| 346 |
-
# space_host_startup = os.getenv("SPACE_HOST")
|
| 347 |
-
# space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
|
| 348 |
-
|
| 349 |
-
# if space_host_startup:
|
| 350 |
-
# print(f"✅ SPACE_HOST found: {space_host_startup}")
|
| 351 |
-
# print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
|
| 352 |
-
# else:
|
| 353 |
-
# print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
| 354 |
-
|
| 355 |
-
# if space_id_startup: # Print repo URLs if SPACE_ID is found
|
| 356 |
-
# print(f"✅ SPACE_ID found: {space_id_startup}")
|
| 357 |
-
# print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
| 358 |
-
# print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
| 359 |
-
# else:
|
| 360 |
-
# print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
| 361 |
-
|
| 362 |
-
# print("-"*(60 + len(" App Starting ")) + "\n")
|
| 363 |
-
|
| 364 |
-
# print("Launching Gradio Interface for Basic Agent Evaluation...")
|
| 365 |
-
# demo.launch(debug=True, share=False)
|
|
|
|
| 94 |
|
| 95 |
run_and_submit_one()
|
| 96 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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