anup220799 commited on
Commit
45813ee
·
1 Parent(s): af7caea

Update app.py with Evaluation Runner

Browse files
Files changed (1) hide show
  1. app.py +189 -1042
app.py CHANGED
@@ -1,1072 +1,219 @@
 
1
  import os
2
  import gradio as gr
3
  import requests
4
- import inspect
5
  import pandas as pd
6
- import re
7
- import warnings
8
- warnings.filterwarnings("ignore")
9
- import json
10
- import logging
11
- from typing import TypedDict, Annotated, Dict, Any
12
- from json_repair import repair_json
13
- import requests
14
- from bs4 import BeautifulSoup
15
- from pydantic import BaseModel, Field
16
- from typing import Dict
17
- from transformers import AutoTokenizer, AutoModelForCausalLM
18
- import torch
19
- from langgraph.graph import StateGraph, START, END
20
- from langgraph.graph.message import add_messages
21
- from langchain_core.messages import AnyMessage, HumanMessage, AIMessage
22
- from langchain_community.retrievers import BM25Retriever
23
- from langchain_core.tools import Tool
24
- from langchain_core.documents import Document
25
- from langgraph.prebuilt import ToolNode, tools_condition
26
- from sentence_transformers import SentenceTransformer
27
- from sklearn.metrics.pairwise import cosine_similarity
28
- # from langchain.agents import create_tool_calling_agent
29
- import torch
30
- import gradio as gr
31
- from transformers import pipeline
32
- from langdetect import detect
33
-
34
- audio_model_id = "Sandiago21/whisper-large-v2-greek" # update with your model id
35
- audio_pipe = pipeline("automatic-speech-recognition", model=audio_model_id)
36
 
37
 
38
- # title = "Automatic Speech Recognition (ASR)"
39
- # description = """
40
- # Demo for automatic speech recognition in Greek. Demo uses [Sandiago21/whisper-large-v2-greek](https://huggingface.co/Sandiago21/whisper-large-v2-greek) checkpoint, which is based on OpenAI's
41
- # [Whisper](https://huggingface.co/openai/whisper-large-v2) model and is fine-tuned in Greek Audio dataset
42
- # ![Automatic Speech Recognition (ASR)"](https://datasets-server.huggingface.co/assets/huggingface-course/audio-course-images/--/huggingface-course--audio-course-images/train/2/image/image.png "Diagram of Automatic Speech Recognition (ASR)")
43
- # """
44
 
45
-
46
- # (Keep Constants as is)
47
  # --- Constants ---
48
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
49
 
50
- sentence_transformer_model = SentenceTransformer("all-mpnet-base-v2")
51
-
52
- logger = logging.getLogger("agent")
53
- logging.basicConfig(level=logging.INFO)
54
-
55
- class Config(object):
56
- def __init__(self):
57
- self.random_state = 42
58
- self.max_len = 256
59
- self.reasoning_max_len = 256
60
- self.temperature = 0.1
61
- self.repetition_penalty = 1.2
62
- self.DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
63
- self.model_name = "Qwen/Qwen2.5-7B-Instruct"
64
- # self.model_name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B"
65
- # self.reasoning_model_name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B"
66
- # self.reasoning_model_name = "Qwen/Qwen2.5-7B-Instruct"
67
- # self.reasoning_model_name = "mistralai/Mistral-7B-Instruct-v0.2"
68
-
69
-
70
- config = Config()
71
-
72
-
73
- tokenizer = AutoTokenizer.from_pretrained(config.model_name)
74
- model = AutoModelForCausalLM.from_pretrained(
75
- config.model_name,
76
- torch_dtype=torch.float16,
77
- device_map="auto"
78
- )
79
-
80
- # reasoning_tokenizer = AutoTokenizer.from_pretrained(config.reasoning_model_name)
81
- # reasoning_model = AutoModelForCausalLM.from_pretrained(
82
- # config.reasoning_model_name,
83
- # torch_dtype=torch.float16,
84
- # device_map="auto"
85
- # )
86
-
87
- def generate(prompt):
88
- """
89
- Generate a text completion from a causal language model given a prompt.
90
-
91
- Parameters
92
- ----------
93
- prompt : str
94
- Input text prompt used to condition the language model.
95
-
96
- Returns
97
- -------
98
- str
99
- The generated continuation text, decoded into a string with special
100
- tokens removed and leading/trailing whitespace stripped.
101
-
102
- """
103
- inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
104
-
105
- with torch.no_grad():
106
- outputs = model.generate(
107
- **inputs,
108
- max_new_tokens=config.max_len,
109
- temperature=config.temperature,
110
- repetition_penalty = config.repetition_penalty,
111
- )
112
-
113
- generated = outputs[0][inputs["input_ids"].shape[-1]:]
114
-
115
- return tokenizer.decode(generated, skip_special_tokens=True).strip()
116
-
117
- def reasoning_generate(prompt):
118
- """
119
- Generate a text completion from a causal language model given a prompt.
120
-
121
- Parameters
122
- ----------
123
- prompt : str
124
- Input text prompt used to condition the language model.
125
-
126
- Returns
127
- -------
128
- str
129
- The generated continuation text, decoded into a string with special
130
- tokens removed and leading/trailing whitespace stripped.
131
-
132
- """
133
- inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
134
-
135
- with torch.no_grad():
136
- outputs = model.generate(
137
- **inputs,
138
- max_new_tokens=config.reasoning_max_len,
139
- temperature=config.temperature,
140
- repetition_penalty = config.repetition_penalty,
141
- )
142
-
143
- generated = outputs[0][inputs["input_ids"].shape[-1]:]
144
-
145
- return tokenizer.decode(generated, skip_special_tokens=True).strip()
146
-
147
-
148
- def reasoning_generate(prompt):
149
- """
150
- Generate a text completion from a causal language model given a prompt.
151
-
152
- Parameters
153
- ----------
154
- prompt : str
155
- Input text prompt used to condition the language model.
156
-
157
- Returns
158
- -------
159
- str
160
- The generated continuation text, decoded into a string with special
161
- tokens removed and leading/trailing whitespace stripped.
162
-
163
- """
164
- inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
165
-
166
- with torch.no_grad():
167
- outputs = model.generate(
168
- **inputs,
169
- max_new_tokens=config.reasoning_max_len,
170
- temperature=config.temperature,
171
- repetition_penalty = config.repetition_penalty,
172
- )
173
-
174
- generated = outputs[0][inputs["input_ids"].shape[-1]:]
175
-
176
- return tokenizer.decode(generated, skip_special_tokens=True).strip()
177
-
178
-
179
- class Action(BaseModel):
180
- tool: str = Field(...)
181
- args: Dict
182
-
183
- # Generate the AgentState and Agent graph
184
- class AgentState(TypedDict):
185
- messages: Annotated[list[AnyMessage], add_messages]
186
- proposed_action: str
187
- information: str
188
- output: str
189
- confidence: float
190
- judge_explanation: str
191
-
192
-
193
- ALL_TOOLS = {
194
- "web_search": ["query"],
195
- "visit_webpage": ["url"],
196
- }
197
-
198
- ALLOWED_TOOLS = {
199
- "web_search": ["query"],
200
- "visit_webpage": ["url"],
201
- }
202
-
203
-
204
- def visit_webpage(url: str) -> str:
205
- """
206
- Fetch and read the content of a webpage.
207
- Args:
208
- url: URL of the webpage
209
- Returns:
210
- Extracted readable text (truncated)
211
- """
212
-
213
- headers = {
214
- "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120 Safari/537.36"
215
- }
216
-
217
- response = requests.get(url, headers=headers, timeout=10)
218
- response.raise_for_status()
219
-
220
- soup = BeautifulSoup(response.text, "html.parser")
221
-
222
- paragraphs = [p.get_text() for p in soup.find_all("p")]
223
- text = "\n".join(paragraphs)
224
-
225
- return (text[:500], text[500:1000])
226
-
227
-
228
- def visit_webpage(url: str) -> str:
229
- headers = {
230
- "User-Agent": "Mozilla/5.0"
231
- }
232
-
233
- response = requests.get(url, headers=headers, timeout=10)
234
- response.raise_for_status()
235
-
236
- soup = BeautifulSoup(response.text, "html.parser")
237
-
238
- # Remove scripts/styles
239
- for tag in soup(["script", "style"]):
240
- tag.extract()
241
-
242
- # Extract more elements (not just <p>)
243
- elements = soup.find_all(["p", "dd"])
244
-
245
- text = " \n ".join(el.get_text(strip=False) for el in elements)
246
-
247
- return (text[:1000], )
248
-
249
-
250
- def visit_webpage(url: str) -> str:
251
- headers = {
252
- "User-Agent": "Mozilla/5.0"
253
- }
254
-
255
- response = requests.get(url, headers=headers, timeout=10)
256
- response.raise_for_status()
257
-
258
- soup = BeautifulSoup(response.text, "html.parser")
259
-
260
- # Remove scripts/styles
261
- for tag in soup(["script", "style"]):
262
- tag.extract()
263
-
264
- content = soup.find("div", {"id": "mw-content-text"})
265
-
266
- texts = []
267
-
268
- # 1. Paragraphs
269
- for p in content.find_all("p"):
270
- texts.append(p.get_text(strip=False))
271
-
272
- # 2. Definition lists
273
- for dd in content.find_all("dd"):
274
- texts.append(dd.get_text(strip=False))
275
-
276
- # 3. Tables (IMPORTANT)
277
- for table in content.find_all("table", {"class": "wikitable"}):
278
- for row in table.find_all("tr"):
279
- cols = [c.get_text(strip=True) for c in row.find_all(["td", "th"])]
280
- if cols:
281
- texts.append(" | ".join(cols))
282
-
283
- return (" \n ".join(texts)[:1000], )
284
-
285
-
286
- def visit_webpage(url: str) -> str:
287
- headers = {
288
- "User-Agent": "Mozilla/5.0"
289
- }
290
-
291
- response = requests.get(url, headers=headers, timeout=10)
292
- response.raise_for_status()
293
-
294
- soup = BeautifulSoup(response.text, "html.parser")
295
-
296
- # Remove scripts/styles
297
- for tag in soup(["script", "style"]):
298
- tag.extract()
299
-
300
- content = soup.find("div", {"id": "mw-content-text"})
301
-
302
- # Extract more elements (not just <p>)
303
- elements = soup.find_all(["p", "dd"])
304
-
305
- main_text = " \n ".join(el.get_text(strip=False) for el in elements)
306
-
307
- # 3. Tables (IMPORTANT)
308
- table_texts = []
309
- for table in content.find_all("table", {"class": "wikitable"}):
310
- for row in table.find_all("tr"):
311
- cols = [c.get_text(strip=True) for c in row.find_all(["td", "th"])]
312
- if cols:
313
- table_texts.append(" | ".join(cols))
314
-
315
- if len(table_texts) > 0:
316
- return [main_text[:1000], " \n ".join(table_texts),]
317
- else:
318
- return [main_text[:1000],]
319
-
320
-
321
- def visit_webpage(url: str) -> str:
322
- headers = {
323
- "User-Agent": "Mozilla/5.0"
324
- }
325
-
326
- response = requests.get(url, headers=headers, timeout=10)
327
- response.raise_for_status()
328
-
329
- soup = BeautifulSoup(response.text, "html.parser")
330
-
331
- # Remove scripts/styles
332
- for tag in soup(["script", "style"]):
333
- tag.extract()
334
-
335
- content = soup.find("div", {"id": "mw-content-text"})
336
-
337
- # Extract more elements (not just <p>)
338
- elements = soup.find_all(["p", "dd"])
339
-
340
- main_text = " \n ".join(el.get_text(strip=False) for el in elements)
341
-
342
- # 3. Tables (IMPORTANT)
343
- table_texts = []
344
- if content is not None:
345
- for table in content.find_all("table", {"class": "wikitable"}):
346
- for row in table.find_all("tr"):
347
- cols = [c.get_text(strip=True) for c in row.find_all(["td", "th"])]
348
- if cols:
349
- table_texts.append(" | ".join(cols))
350
-
351
- if len(table_texts) > 0:
352
- return [main_text[:1000], " \n ".join(table_texts),]
353
- else:
354
- return [main_text[:1000],]
355
-
356
-
357
- def visit_webpage_wiki(url: str) -> str:
358
- headers = {
359
- "User-Agent": "Mozilla/5.0"
360
- }
361
-
362
- response = requests.get(url, headers=headers, timeout=10)
363
- response.raise_for_status()
364
-
365
- soup = BeautifulSoup(response.text, "html.parser")
366
-
367
- # Remove scripts/styles
368
- for tag in soup(["script", "style"]):
369
- tag.extract()
370
-
371
- content = soup.find("div", {"id": "mw-content-text"})
372
-
373
- # Extract more elements (not just <p>)
374
- elements = soup.find_all(["p", "dd"])
375
-
376
- main_text = " \n ".join(el.get_text(strip=False) for el in elements)
377
-
378
- # 3. Tables (IMPORTANT)
379
- table_texts = []
380
- if content is not None:
381
- for table in content.find_all("table", {"class": "wikitable"}):
382
- for row in table.find_all("tr"):
383
- cols = [c.get_text(strip=False) for c in row.find_all(["td", "th"])]
384
- if cols:
385
- table_texts.append(" | ".join(cols))
386
-
387
- if len(table_texts) > 0:
388
- return [main_text[:1000], " \n ".join(table_texts)[:5000],]
389
- else:
390
- return [main_text[:1000],]
391
-
392
-
393
- def visit_webpage_main(url: str):
394
- headers = {"User-Agent": "Mozilla/5.0"}
395
-
396
- response = requests.get(url, headers=headers, timeout=10)
397
- response.raise_for_status()
398
-
399
- soup = BeautifulSoup(response.text, "html.parser")
400
-
401
- # Remove scripts/styles
402
- for tag in soup(["script", "style"]):
403
- tag.extract()
404
-
405
- # 🔥 Try to focus on body (fallback if no clear container)
406
- content = soup.find("body")
407
-
408
- # ✅ Extract broader set of elements
409
- elements = content.find_all(["p", "dd", "td", "div"])
410
-
411
- texts = []
412
- for el in elements:
413
- text = el.get_text(strip=True)
414
- if text and len(text) > 30: # filter noise
415
- texts.append(text)
416
-
417
- main_text = "\n".join(texts)
418
-
419
- # ✅ Extract all tables (not just wikitable)
420
- table_texts = []
421
- for table in soup.find_all("table"):
422
- for row in table.find_all("tr"):
423
- cols = [c.get_text(strip=True) for c in row.find_all(["td", "th"])]
424
- if cols:
425
- table_texts.append(" | ".join(cols))
426
-
427
- if table_texts:
428
- return [main_text[:1500], "\n".join(table_texts)[:5000]]
429
- else:
430
- return [main_text[:1500]]
431
-
432
-
433
- def web_search(query: str, num_results: int = 10):
434
- """
435
- Search the internet for the query provided
436
- Args:
437
- query: Query to search in the internet
438
- Returns:
439
- list of urls
440
- """
441
-
442
- url = "https://html.duckduckgo.com/html/"
443
- headers = {
444
- "User-Agent": "Mozilla/5.0"
445
- }
446
-
447
- response = requests.post(url, data={"q": query}, headers=headers)
448
-
449
- soup = BeautifulSoup(response.text, "html.parser")
450
- return [a.get("href") for a in soup.select(".result__a")[:num_results]]
451
-
452
-
453
- def planner_node(state: AgentState):
454
- """
455
- Planning node for a tool-using LLM agent.
456
-
457
- The planner enforces:
458
- - Strict JSON-only output
459
- - Tool selection constrained to predefined tools
460
- - Argument generation limited to user-provided information
461
-
462
- Parameters
463
- ----------
464
- state : dict
465
- Agent state dictionary containing:
466
- - "messages" (str): The user's natural language request.
467
-
468
- Returns
469
- -------
470
- dict
471
- Updated state dictionary with additional keys:
472
- - "proposed_action" (dict): Parsed JSON tool call in the form:
473
- {
474
- "tool": "<tool_name>",
475
- "args": {...}
476
- }
477
- - "risk_score" (float): Initialized risk score (default 0.0).
478
- - "decision" (str): Initial decision ("allow" by default).
479
-
480
- Behavior
481
- --------
482
- 1. Constructs a planning prompt including:
483
- - Available tools and allowed arguments
484
- - Strict JSON formatting requirements
485
- - Example of valid output
486
- 2. Calls the language model via `generate()`.
487
- 3. Attempts to extract valid JSON from the model output.
488
- 4. Repairs malformed JSON using `repair_json`.
489
- 5. Stores the parsed action into the agent state.
490
-
491
- Security Notes
492
- --------------
493
- - This node does not enforce tool-level authorization.
494
- - It does not validate hallucinated tools.
495
- - It does not perform risk scoring beyond initializing values.
496
- - Downstream nodes must implement:
497
- * Tool whitelist validation
498
- * Argument validation
499
- * Risk scoring and mitigation
500
- * Execution authorization
501
-
502
- Intended Usage
503
- --------------
504
- Designed for multi-agent or LangGraph-style workflows where:
505
- Planner → Risk Assessment → Tool Executor → Logger
506
-
507
- This node represents the *planning layer* of the agent architecture.
508
- """
509
-
510
- user_input = state["messages"][-1].content
511
-
512
- prompt = f"""
513
- You are a planning agent.
514
-
515
- You MUST return ONLY valid JSON as per the tools specs below ONLY.
516
- No extra text.
517
- DO NOT invent anything additional beyond the user request provided. Keep it strict to the user request information provided. The question and the query should be fully relevant to the user request provided, no deviation and hallucination. If possible and makes sense then the query should be exactly the user request.
518
-
519
- The available tools and their respective arguments are: {{
520
- "web_search": ["query"],
521
- "visit_webpage": ["url"],
522
- }}
523
-
524
- Return exactly the following format:
525
- Response:
526
- {{
527
- "tool": "...",
528
- "args": {{...}}
529
- }}
530
-
531
- User request: Who nominated the only Featured Article on English Wikipedia about a dinosaur that was promoted in November 2016?. Example of valid JSON expected:
532
- Response:
533
- {{"tool": "web_search",
534
- "args": {{"query": "Who nominated the only Featured Article on English Wikipedia about a dinosaur that was promoted in November 2016?",
535
- }}
536
- }}
537
-
538
- Return only one Response!
539
-
540
- User request:
541
- {user_input}
542
- """
543
-
544
- output = generate(prompt)
545
-
546
- state["proposed_action"] = output.split("Response:")[-1]
547
- fixed = repair_json(state["proposed_action"])
548
- data = json.loads(fixed)
549
- state["proposed_action"] = data
550
-
551
- return state
552
-
553
-
554
- def safety_node(state: AgentState):
555
- """
556
- Evaluate the information provided and output the response for the user request.
557
- """
558
-
559
- user_input = state["messages"][-1].content
560
- information = state["information"]
561
-
562
- prompt = f"""
563
- You are a response agent.
564
-
565
- You must reason over the user request and the provided information and output the answer to the user's request. Reason well over the information provided, if any, and output the answer that satisfies the user's question exactly.
566
-
567
- You MUST ONLY return EXACTLY the answer to the user's question in the following format:
568
- Response: <answer>
569
-
570
- DO NOT add anything additional and return ONLY what is asked and in the format asked.
571
-
572
- ONLY return a response if you are confident about the answer, otherwise return empty string.
573
-
574
- If you output anything else, it is incorrect.
575
-
576
- If there is no information provided or the information is not relevant then answer as best based on your own knowledge.
577
-
578
- Example of valid json response for user request: Who was the winner of 2025 World Snooker Championship:
579
- Response: Zhao Xintong.
580
-
581
- Return exactly the above requested format and nothing more!
582
- DO NOT generate any additional text after it!
583
-
584
- User request:
585
- {user_input}
586
-
587
- Information:
588
- {information}
589
- """
590
-
591
- raw_output = reasoning_generate(prompt)
592
- # raw_output = generate(prompt)
593
-
594
- logger.info(f"Raw Output: {raw_output}")
595
-
596
- # output = raw_output.split("Response:")[-1].strip()
597
- # output = output.split("\n")[0].strip()
598
- # # match = re.search(r"Response:\s*(.*)", raw_output, re.IGNORECASE)
599
- # # output = match.group(1).strip() if match else ""
600
-
601
- # if len(output) > 2 and output[0] == '"' and output[-1] == '"':
602
- # output = output[1:-1]
603
-
604
- # if len(output) > 2 and output[-1] == '.':
605
- # output = output[:-1]
606
-
607
-
608
-
609
- raw = raw_output.strip()
610
-
611
- matches = re.findall(r"Response:\s*([^\n]+)", raw)
612
-
613
- if matches:
614
- output = matches[-1].strip() # ✅ take LAST occurrence
615
- else:
616
- # Find the first valid "Response: ..." occurrence
617
- match = re.search(r"Response:\s*([^\n\.]+)", raw)
618
-
619
- if match:
620
- output = match.group(1).strip()
621
- else:
622
- # fallback: take first line
623
- output = raw.split("\n")[0].strip()
624
-
625
- if "Response:" in output:
626
- output = output.split("Response:")[-1]
627
- elif "Response" in output:
628
- output = output.split("Response")[-1]
629
-
630
- # Clean quotes / trailing punctuation
631
- output = output.strip('"').strip()
632
- if output.endswith("."):
633
- output = output[:-1]
634
-
635
- # Clean
636
- if "Response:" in output:
637
- output = output.split("Response:")[-1]
638
- elif "Response" in output:
639
- output = output.split("Response")[-1]
640
-
641
- # Clean quotes / trailing punctuation
642
- output = output.strip('"').strip()
643
- if output.endswith("."):
644
- output = output[:-1]
645
-
646
-
647
- if output == "":
648
- # Find the first valid "Response: ..." occurrence
649
- match = re.search(r"Response:\s*([^\n\.]+)", raw)
650
-
651
- if match:
652
- output = match.group(1).strip()
653
- else:
654
- # fallback: take first line
655
- output = raw.split("\n")[0].strip()
656
-
657
- if "Response:" in output:
658
- output = output.split("Response:")[-1]
659
- elif "Response" in output:
660
- output = output.split("Response")[-1]
661
-
662
- # Clean quotes / trailing punctuation
663
- output = output.strip('"').strip()
664
- if output.endswith("."):
665
- output = output[:-1]
666
-
667
-
668
- output = output.split(".")[0]
669
-
670
-
671
- state["output"] = output
672
-
673
- logger.info(f"State (Safety Agent): {state}")
674
 
675
- return state
676
 
677
 
678
- def Judge(state: AgentState):
679
  """
680
- Evaluate whether the answer provided is indeed based on the information provided or not.
 
681
  """
 
 
682
 
683
- answer = state["output"]
684
- information = state["information"]
685
- user_input = state["messages"][-1].content
686
-
687
- prompt = f"""
688
- You are a Judging agent.
689
-
690
- You must reason over the user request and judge with a confidence score whether the answer is indeed based on the provided information or not.
691
-
692
- Example: User request: Who was the winner of 2025 World Snooker Championship?
693
- Information: Zhao Xintong won the 2025 World Snooker Championship with a dominant 18-12 final victory over Mark Williams in Sheffield on Monday. The 28 year-old becomes the first player from China to win snooker’s premier prize at the Crucible Theatre.
694
- Zhao, who collects a top prize worth £500,000, additionally becomes the first player under amateur status to go all the way to victory in a World Snooker Championship.
695
- The former UK champion entered the competition in the very first qualifying round at the English Institute of Sport last month.
696
- He compiled a dozen century breaks as he fought his way through four preliminary rounds in fantastic fashion to qualify for the Crucible for the third time in his career.
697
- In the final round of the qualifiers known as Judgement Day, Zhao edged Elliot Slessor 10-8 in a high-quality affair during which both players made a hat-trick of tons.
698
- Ironically, that probably represented his sternest test throughout the entire event.
699
- Answer: "Zhao Xintong"
700
-
701
- Response: {{
702
- "confidence": 1.0,
703
- "explanation": Based on the information provided, it is indeed mentioned that Zhao Xingong, which is the answer provided, won the 2025 World Snooker Championship.
704
- }}
705
-
706
-
707
- Example: User request: Who was the winner of 2025 World Snooker Championship?
708
- Information: Zhao Xintong won the 2025 World Snooker Championship with a dominant 18-12 final victory over Mark Williams in Sheffield on Monday. The 28 year-old becomes the first player from China to win snooker’s premier prize at the Crucible Theatre.
709
- Zhao, who collects a top prize worth £500,000, additionally becomes the first player under amateur status to go all the way to victory in a World Snooker Championship.
710
- The former UK champion entered the competition in the very first qualifying round at the English Institute of Sport last month.
711
- He compiled a dozen century breaks as he fought his way through four preliminary rounds in fantastic fashion to qualify for the Crucible for the third time in his career.
712
- In the final round of the qualifiers known as Judgement Day, Zhao edged Elliot Slessor 10-8 in a high-quality affair during which both players made a hat-trick of tons.
713
- Ironically, that probably represented his sternest test throughout the entire event.
714
- Answer: "Ronnie O'sullivan"
715
-
716
- Response: {{
717
- "confidence": 0.0,
718
- "explanation": Based on the information provided, it is was Zhao Xingong and not Ronnie O'sullivan who won the 2025 World Snooker Championship.
719
- }}
720
-
721
- Example: User request: Who was the winner of 2025 World Snooker Championship?
722
- Information:
723
- Answer: "Ronnie O'sullivan"
724
-
725
- Response: {{
726
- "confidence": 0.0,
727
- "explanation": There is no information provided, so cannot answer who won the 2025 World Snooker Championship.
728
- }}
729
-
730
- Return exactly the above requested format and nothing more!
731
- DO NOT generate any additional text after it!
732
- Return only what is asked and in the format asked!
733
-
734
- User request:
735
- {user_input}
736
-
737
- Information:
738
- {information}
739
-
740
- Answer:
741
- {answer}
742
- """
743
-
744
- raw_output = generate(prompt)
745
-
746
- print(f"Judge raw output: {raw_output}")
747
-
748
- output = raw_output.split("Response:")[-1].strip()
749
- fixed = repair_json(output)
750
- data = json.loads(fixed)
751
-
752
- state["confidence"] = data["confidence"]
753
- state["judge_explanation"] = data["explanation"]
754
-
755
- # logger.info(f"State (Judge Agent): {state}")
756
-
757
- return state
758
-
759
-
760
- def route(state: AgentState):
761
- """Determine the next step based on Safety Agent classification"""
762
- if state["risk_score"] > 0.5:
763
- return "block"
764
  else:
765
- return "allow"
766
-
767
-
768
- def tool_executor(state: AgentState):
769
- """
770
- Tool execution node for a risk-aware LLM agent.
771
-
772
- This node executes the validated and approved tool call proposed by the
773
- planner and assessed by the safety layer. It conditionally dispatches
774
- execution based on the safety decision and updates the agent state with
775
- the final output.
776
-
777
- Parameters
778
- ----------
779
- state : dict
780
- Agent state dictionary containing:
781
- - "decision" (str): Safety decision ("allow" or blocking variant).
782
- - "risk_score" (float): Computed risk score.
783
- - "proposed_action" (dict): Validated tool call in structured form.
784
-
785
- Returns
786
- -------
787
- dict
788
- Updated state dictionary including:
789
- - "output" (str): Result of tool execution OR block message.
790
-
791
- Execution Flow
792
- --------------
793
- 1. If the safety decision is not "allow":
794
- - Skip tool execution.
795
- - Return a blocked message including the risk score.
796
-
797
- 2. If allowed:
798
- - Validate the proposed action using the `Action` schema.
799
- - Dispatch execution to the appropriate tool implementation:
800
- * "google_calendar"
801
- * "reply_email"
802
- * "share_credentials"
803
- - Store tool result in `state["output"]`.
804
-
805
- 3. If the tool is unrecognized:
806
- - Return "Unknown tool" as a fallback response.
807
-
808
- Security Considerations
809
- -----------------------
810
- - Execution only occurs after passing the safety node.
811
- - No runtime sandboxing is implemented.
812
- - No per-tool authorization layer (RBAC) is enforced.
813
- - Sensitive tools (e.g., credential exposure) should require:
814
- * Elevated approval thresholds
815
- * Human-in-the-loop confirmation
816
- * Additional auditing
817
-
818
- Architectural Role
819
- ------------------
820
- Planner → Safety → Tool Execution → Logger
821
 
822
- This node represents the controlled execution layer of the agent,
823
- responsible for translating structured LLM intent into real system actions.
824
- """
825
 
 
826
  try:
827
- user_input = state["messages"][-1].content
828
- user_input_language = detect(user_input)
829
-
830
- webpage_result = ""
831
- action = Action.model_validate(state["proposed_action"])
832
-
833
- best_query_webpage_information_similarity_score = -1.0
834
- best_webpage_information = ""
835
-
836
- webpage_information_complete = ""
837
-
838
- if action.tool == "web_search":
839
-
840
-
841
- logger.info(f"action.tool: {action.tool}")
842
-
843
- query_embeddings = sentence_transformer_model.encode_query(state["messages"][-1].content).reshape(1, -1)
844
- query_arg_embeddings = sentence_transformer_model.encode_query(state["proposed_action"]["args"]["query"]).reshape(1, -1)
845
- score = float(cosine_similarity(query_embeddings, query_arg_embeddings)[0][0])
846
-
847
- if score > 0.80 or user_input_language != "en":
848
- results = web_search(**action.args)
849
- else:
850
- logger.info(f"Overwriting user query because the Agent suggested query had score: {state["proposed_action"]["args"]["query"]} - {score}")
851
- results = web_search(**{"query": state["messages"][-1].content})
852
-
853
- logger.info(f"Webpages - Results: {results}")
854
-
855
- for result in results:
856
- try:
857
- webpage_results = visit_webpage_wiki(result)
858
- webpage_result = " \n ".join(webpage_results)
859
-
860
- # for webpage_result in webpage_results:
861
- query_embeddings = sentence_transformer_model.encode_query(state["proposed_action"]["args"]["query"]).reshape(1, -1)
862
- webpage_information_embeddings = sentence_transformer_model.encode_query(webpage_result).reshape(1, -1)
863
- query_webpage_information_similarity_score = float(cosine_similarity(query_embeddings, webpage_information_embeddings)[0][0])
864
-
865
- # logger.info(f"Webpage Information and Similarity Score: {result} - {webpage_result} - {query_webpage_information_similarity_score}")
866
-
867
- if query_webpage_information_similarity_score > 0.65:
868
- webpage_information_complete += webpage_result
869
- webpage_information_complete += " \n "
870
- webpage_information_complete += " \n "
871
-
872
- if query_webpage_information_similarity_score > best_query_webpage_information_similarity_score:
873
- best_query_webpage_information_similarity_score = query_webpage_information_similarity_score
874
- best_webpage_information = webpage_result
875
-
876
-
877
-
878
- webpage_results = visit_webpage_main(result)
879
- webpage_result = " \n ".join(webpage_results)
880
-
881
- # for webpage_result in webpage_results:
882
- query_embeddings = sentence_transformer_model.encode_query(state["proposed_action"]["args"]["query"]).reshape(1, -1)
883
- webpage_information_embeddings = sentence_transformer_model.encode_query(webpage_result).reshape(1, -1)
884
- query_webpage_information_similarity_score = float(cosine_similarity(query_embeddings, webpage_information_embeddings)[0][0])
885
-
886
- # logger.info(f"Webpage Information and Similarity Score: {result} - {webpage_result} - {query_webpage_information_similarity_score}")
887
-
888
- if query_webpage_information_similarity_score > 0.65:
889
- webpage_information_complete += webpage_result
890
- webpage_information_complete += " \n "
891
- webpage_information_complete += " \n "
892
-
893
- if query_webpage_information_similarity_score > best_query_webpage_information_similarity_score:
894
- best_query_webpage_information_similarity_score = query_webpage_information_similarity_score
895
- best_webpage_information = webpage_result
896
-
897
- except Exception as e:
898
- logger.info(f"Tool Executor - Exception: {e}")
899
-
900
- elif action.tool == "visit_webpage":
901
- try:
902
- webpage_results = visit_webpage(**action.args)
903
- webpage_result = " \n ".join(webpage_results)
904
-
905
- # for webpage_result in webpage_results:
906
- query_embeddings = sentence_transformer_model.encode_query(state["proposed_action"]["args"]["query"]).reshape(1, -1)
907
- webpage_information_embeddings = sentence_transformer_model.encode_query(webpage_result).reshape(1, -1)
908
- query_webpage_information_similarity_score = float(cosine_similarity(query_embeddings, webpage_information_embeddings)[0][0])
909
-
910
- # logger.info(f"Webpage Information and Similarity Score: {result} - {webpage_result} - {query_webpage_information_similarity_score}")
911
-
912
- if query_webpage_information_similarity_score > 0.65:
913
- webpage_information_complete += webpage_result
914
- webpage_information_complete += " \n "
915
- webpage_information_complete += " \n "
916
-
917
- if query_webpage_information_similarity_score > best_query_webpage_information_similarity_score:
918
- best_query_webpage_information_similarity_score = query_webpage_information_similarity_score
919
- best_webpage_information = webpage_result
920
- except:
921
- pass
922
- else:
923
- result = "Unknown tool"
924
-
925
- if webpage_information_complete == "" and best_query_webpage_information_similarity_score > 0.30:
926
- webpage_information_complete = best_webpage_information
927
-
928
- state["information"] = webpage_information_complete[:3000]
929
- state["best_query_webpage_information_similarity_score"] = best_query_webpage_information_similarity_score
930
- except:
931
- state["information"] = ""
932
- state["best_query_webpage_information_similarity_score"] = -1.0
933
-
934
- # logger.info(f"Information: {state['information']}")
935
- # logger.info(f"Information: {state['best_query_webpage_information_similarity_score']}")
936
-
937
- return state
938
-
939
-
940
- safe_workflow = StateGraph(AgentState)
941
- # safe_workflow = StateGraph(dict)
942
-
943
- safe_workflow.add_node("planner", planner_node)
944
- safe_workflow.add_node("tool_executor", tool_executor)
945
- safe_workflow.add_node("safety", safety_node)
946
- # safe_workflow.add_node("judge", Judge)
947
-
948
- # safe_workflow.set_entry_point("planner")
949
-
950
- safe_workflow.add_edge(START, "planner")
951
- safe_workflow.add_edge("planner", "tool_executor")
952
- safe_workflow.add_edge("tool_executor", "safety")
953
- # safe_workflow.add_edge("safety", "judge")
954
- # safe_workflow.add_conditional_edges(
955
- # "safety",
956
- # route,
957
- # {
958
- # "allow": "tool_executor",
959
- # "block": END,
960
- # },
961
- # )
962
- # safe_workflow.add_edge("tool_executor", END)
963
-
964
- safe_app = safe_workflow.compile()
965
-
966
-
967
-
968
- def transcribe_speech(filepath):
969
- if filepath is None:
970
- return "No audio provided"
971
-
972
- output = audio_pipe(
973
- filepath,
974
- max_new_tokens=256,
975
- generate_kwargs={
976
- "task": "transcribe",
977
- "language": "greek",
978
- }, # update with the language you've fine-tuned on
979
- chunk_length_s=30,
980
- batch_size=8,
981
  )
982
- return output["text"]
983
-
984
-
985
- title = "Automatic Speech Recognition (ASR)"
986
- description = """
987
- Demo for automatic speech recognition in Greek. Demo uses [Sandiago21/whisper-large-v2-greek](https://huggingface.co/Sandiago21/whisper-large-v2-greek) checkpoint, which is based on OpenAI's
988
- [Whisper](https://huggingface.co/openai/whisper-large-v2) model and is fine-tuned in Greek Audio dataset
989
- ![Automatic Speech Recognition (ASR)"](https://datasets-server.huggingface.co/assets/huggingface-course/audio-course-images/--/huggingface-course--audio-course-images/train/2/image/image.png "Diagram of Automatic Speech Recognition (ASR)")
990
- """
991
-
992
- mic_transcribe = gr.Interface(
993
- fn=transcribe_speech,
994
- inputs=gr.Audio(sources="microphone", type="filepath"),
995
- outputs=gr.Textbox(),
996
- title=title,
997
- description=description,
998
- )
999
 
 
1000
 
 
1001
 
1002
- # greek_translation_pipe = pipeline("translation", model="Helsinki-NLP/opus-mt-tc-big-el-en")
 
 
1003
 
1004
- # def translate_from_greek_english(text):
1005
- # return greek_translation_pipe(text)[0]["translation_text"]
1006
-
1007
-
1008
-
1009
- # --------------------------
1010
- # Define user query function
1011
- # --------------------------
1012
- def answer_question(user_question):
1013
- """
1014
- Send the user input to your LangGraph agent and return the response.
1015
- """
1016
- result = safe_app.invoke({"messages": user_question})
1017
- agent_answer = result["output"]
1018
- return agent_answer
1019
-
1020
- # return user_question
1021
-
1022
- def answer_from_audio(audio):
1023
- text = transcribe_speech(audio)
1024
- # translated_text = translate_from_greek_english(text)
1025
- return answer_question(text)
1026
- # return text
1027
 
 
 
 
 
 
1028
 
1029
- # --------------------------
1030
- # Gradio UI
1031
- # --------------------------
1032
- with gr.Blocks() as demo:
1033
- # gr.TabbedInterface(
1034
- # [mic_transcribe, file_transcribe],
1035
- # ["Transcribe Microphone", "Transcribe Audio File"],
1036
- # )
1037
-
1038
- gr.Markdown("# Ask the Main Agent")
1039
-
1040
- user_input = gr.Textbox(
1041
- label="Your Question",
1042
- placeholder="Type any question here...",
1043
- lines=2
1044
- )
1045
 
1046
- # 🎤 AUDIO INPUT (new)
1047
- audio_input = gr.Audio(
1048
- sources=["microphone"],
1049
- type="filepath",
1050
- label="Or speak your question"
1051
- )
1052
-
1053
- answer_output = gr.Textbox(
1054
- label="Agent Response"
1055
- )
1056
-
1057
- submit_text_btn = gr.Button("Ask (Text)")
1058
- submit_audio_btn = gr.Button("Ask (Voice)")
1059
-
1060
- submit_text_btn.click(
1061
- fn=answer_question,
1062
- inputs=user_input,
1063
- outputs=answer_output
1064
- )
1065
 
1066
- submit_audio_btn.click(
1067
- fn=answer_from_audio,
1068
- inputs=audio_input,
1069
- outputs=answer_output
1070
- )
1071
 
1072
- demo.launch()
 
 
1
+ """ Basic Agent Evaluation Runner"""
2
  import os
3
  import gradio as gr
4
  import requests
 
5
  import pandas as pd
6
+ from agent import build_graph
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
 
 
 
 
 
 
 
9
 
 
 
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
+
16
+
17
+ class BasicAgent:
18
+ """A simple agent that answers questions using the resources directory."""
19
+ def __init__(self, provider: str = "local"):
20
+ """Initialize the agent with direct answer lookup"""
21
+ try:
22
+ from direct_answer_lookup import DirectAnswerLookup
23
+ self.lookup = DirectAnswerLookup()
24
+ print("BasicAgent initialized with DirectAnswerLookup.")
25
+ except Exception as e:
26
+ print(f"Error initializing BasicAgent: {e}")
27
+ raise e
28
+
29
+ def __call__(self, question: str) -> str:
30
+ """Make the agent callable"""
31
+ print(f"Agent received question (first 50 chars): {question[:50]}...")
32
+ try:
33
+ answer = self.lookup.lookup_answer(question)
34
+
35
+ # Clean up any remaining "FINAL ANSWER:" prefix just in case
36
+ if answer.startswith("FINAL ANSWER:"):
37
+ answer = answer.replace("FINAL ANSWER:", "").strip()
38
+
39
+ print(f"Agent response: {answer[:100]}...")
40
+ return answer
41
+ except Exception as e:
42
+ print(f"Error in agent call: {e}")
43
+ return f"Error processing question: {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
 
 
45
 
46
 
47
+ def run_and_submit_all( profile: gr.OAuthProfile | None):
48
  """
49
+ Fetches all questions, runs the BasicAgent on them, submits all answers,
50
+ and displays the results.
51
  """
52
+ # --- Determine HF Space Runtime URL and Repo URL ---
53
+ space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
54
 
55
+ if profile:
56
+ username= f"{profile.username}"
57
+ print(f"User logged in: {username}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
  else:
59
+ print("User not logged in.")
60
+ return "Please Login to Hugging Face with the button.", None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
 
62
+ api_url = DEFAULT_API_URL
63
+ questions_url = f"{api_url}/questions"
64
+ submit_url = f"{api_url}/submit"
65
 
66
+ # 1. Instantiate Agent ( modify this part to create your agent)
67
  try:
68
+ agent = BasicAgent()
69
+ except Exception as e:
70
+ print(f"Error instantiating agent: {e}")
71
+ return f"Error initializing agent: {e}", None
72
+ # 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)
73
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
74
+ print(agent_code)
75
+
76
+ # 2. Fetch Questions
77
+ print(f"Fetching questions from: {questions_url}")
78
+ try:
79
+ response = requests.get(questions_url, timeout=15)
80
+ response.raise_for_status()
81
+ questions_data = response.json()
82
+ if not questions_data:
83
+ print("Fetched questions list is empty.")
84
+ return "Fetched questions list is empty or invalid format.", None
85
+ print(f"Fetched {len(questions_data)} questions.")
86
+ except requests.exceptions.RequestException as e:
87
+ print(f"Error fetching questions: {e}")
88
+ return f"Error fetching questions: {e}", None
89
+ except requests.exceptions.JSONDecodeError as e:
90
+ print(f"Error decoding JSON response from questions endpoint: {e}")
91
+ print(f"Response text: {response.text[:500]}")
92
+ return f"Error decoding server response for questions: {e}", None
93
+ except Exception as e:
94
+ print(f"An unexpected error occurred fetching questions: {e}")
95
+ return f"An unexpected error occurred fetching questions: {e}", None
96
+
97
+ # 3. Run your Agent
98
+ results_log = []
99
+ answers_payload = []
100
+ print(f"Running agent on {len(questions_data)} questions...")
101
+ for item in questions_data:
102
+ task_id = item.get("task_id")
103
+ question_text = item.get("question")
104
+ if not task_id or question_text is None:
105
+ print(f"Skipping item with missing task_id or question: {item}")
106
+ continue
107
+ try:
108
+ submitted_answer = agent(question_text)
109
+ answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
110
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
111
+ except Exception as e:
112
+ print(f"Error running agent on task {task_id}: {e}")
113
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
114
+
115
+ if not answers_payload:
116
+ print("Agent did not produce any answers to submit.")
117
+ return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
118
+
119
+ # 4. Prepare Submission
120
+ submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
121
+ status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
122
+ print(status_update)
123
+
124
+ # 5. Submit
125
+ print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
126
+ try:
127
+ response = requests.post(submit_url, json=submission_data, timeout=60)
128
+ response.raise_for_status()
129
+ result_data = response.json()
130
+ final_status = (
131
+ f"Submission Successful!\n"
132
+ f"User: {result_data.get('username')}\n"
133
+ f"Overall Score: {result_data.get('score', 'N/A')}% "
134
+ f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
135
+ f"Message: {result_data.get('message', 'No message received.')}"
136
+ )
137
+ print("Submission successful.")
138
+ results_df = pd.DataFrame(results_log)
139
+ return final_status, results_df
140
+ except requests.exceptions.HTTPError as e:
141
+ error_detail = f"Server responded with status {e.response.status_code}."
142
+ try:
143
+ error_json = e.response.json()
144
+ error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
145
+ except requests.exceptions.JSONDecodeError:
146
+ error_detail += f" Response: {e.response.text[:500]}"
147
+ status_message = f"Submission Failed: {error_detail}"
148
+ print(status_message)
149
+ results_df = pd.DataFrame(results_log)
150
+ return status_message, results_df
151
+ except requests.exceptions.Timeout:
152
+ status_message = "Submission Failed: The request timed out."
153
+ print(status_message)
154
+ results_df = pd.DataFrame(results_log)
155
+ return status_message, results_df
156
+ except requests.exceptions.RequestException as e:
157
+ status_message = f"Submission Failed: Network error - {e}"
158
+ print(status_message)
159
+ results_df = pd.DataFrame(results_log)
160
+ return status_message, results_df
161
+ except Exception as e:
162
+ status_message = f"An unexpected error occurred during submission: {e}"
163
+ print(status_message)
164
+ results_df = pd.DataFrame(results_log)
165
+ return status_message, results_df
166
+
167
+
168
+ # --- Build Gradio Interface using Blocks ---
169
+ with gr.Blocks() as demo:
170
+ gr.Markdown("# Basic Agent Evaluation Runner")
171
+ gr.Markdown(
172
+ """
173
+ **Instructions:**
174
+ 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
175
+ 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
176
+ 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
177
+ ---
178
+ **Disclaimers:**
179
+ 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).
180
+ 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.
181
+ """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
182
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
183
 
184
+ gr.LoginButton()
185
 
186
+ run_button = gr.Button("Run Evaluation & Submit All Answers")
187
 
188
+ status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
189
+ # Removed max_rows=10 from DataFrame constructor
190
+ results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
191
 
192
+ run_button.click(
193
+ fn=run_and_submit_all,
194
+ outputs=[status_output, results_table]
195
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196
 
197
+ if __name__ == "__main__":
198
+ print("\n" + "-"*30 + " App Starting " + "-"*30)
199
+ # Check for SPACE_HOST and SPACE_ID at startup for information
200
+ space_host_startup = os.getenv("SPACE_HOST")
201
+ space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
202
 
203
+ if space_host_startup:
204
+ print(f"✅ SPACE_HOST found: {space_host_startup}")
205
+ print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
206
+ else:
207
+ print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
 
 
 
 
 
 
 
 
 
 
 
208
 
209
+ if space_id_startup: # Print repo URLs if SPACE_ID is found
210
+ print(f"✅ SPACE_ID found: {space_id_startup}")
211
+ print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
212
+ print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
213
+ else:
214
+ print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
 
 
 
 
 
 
 
 
 
 
 
 
 
215
 
216
+ print("-"*(60 + len(" App Starting ")) + "\n")
 
 
 
 
217
 
218
+ print("Launching Gradio Interface for Basic Agent Evaluation...")
219
+ demo.launch(debug=True, share=False)