Spaces:
Sleeping
Sleeping
Update app.py
Browse files1 unmodified line2345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747512 unmodified lines888990919293942 unmodified lines9798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321332 unmodified lines1361371381391401411421431441451461471481491501511521531541551561571581591601611621632 unmodified lines1661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013021 unmodified line3043053063073083093103113123133143153163174 unmodified lines3223233243253263273283293303313323331 unmodified line3353363373383393403413423433443453463473483493503513523533543553563573583593604 unmodified lines3653663673683693703713723733743753763773783793803813823833843853863 unmodified lines3903913923933943953965 unmodified lines4024034044054064074082 unmodified lines4114124134144154164172 unmodified lines4204214224234244254264274284294306 unmodified lines4374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754 unmodified lines4804814824834844854864874884894904914924934944954964974984995005015025033 unmodified lines5075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775787 unmodified lines5865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216227 unmodified lines6306316326336346356366376386396406416426436446452 unmodified lines6486496506516526536546556566571 unmodified line6596606616626636646656666676686696706716721 unmodified lineimport base64from io import BytesIOimport gradio as grfrom gradio_client import fileimport requestsimport inspectimport pandas as pdimport toolsfrom smolagents import CodeAgent# Resolve the correct LLM model class across smolagents versionstry:from smolagents import InferenceClientModel as _HFModel # smolagents >= 1.0except ImportError:try:from smolagents.models import HfApiModel as _HFModelexcept ImportError:from smolagents import HfApiModel as _HFModelfrom typing import TypedDict, List, Dict, Any, Optionalfrom langgraph.graph import StateGraph, START, ENDfrom langchain_core.messages import HumanMessage # kept for LangGraph compatibility# Helper to build a smolagents-compatible message listdef _msg(content: str) -> list:return [{"role": "user", "content": content}]# (Keep Constants as is)# --- Constants ---DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"# --- Models ---def _build_hf_model(model_name: str):"""Build a text model across smolagents versions."""for kwargs in ({"model_id": model_name, "max_tokens": 2048, "temperature": 0.3},{"model_id": model_name, "max_new_tokens": 2048, "temperature": 0.3},{"repo_id": model_name, "max_tokens": 2048, "temperature": 0.3},{"repo_id": model_name, "max_new_tokens": 2048, "temperature": 0.3},):try:return _HFModel(**kwargs)except TypeError:continueraise RuntimeError(f"Cannot instantiate model {model_name} with available smolagents version")# Text/math models via smolagentsmodel = _build_hf_model("meta-llama/Llama-3.2-3B-Instruct") # General model for classification and final answer synthesismath_model = _build_hf_model("deepseek-ai/deepseek-math-7b-instruct")# FireRed OCR (Transformers) loaded lazily to avoid startup crashes_fire_red_model = None_fire_red_processor = Nonedef _load_fire_red_ocr():"""Lazy-load FireRed OCR model and processor using Transformers."""global _fire_red_model, _fire_red_processorif _fire_red_model is not None and _fire_red_processor is not None:return _fire_red_model, _fire_red_processorimport torchfrom transformers import AutoProcessor, Qwen3VLForConditionalGeneration_fire_red_model = Qwen3VLForConditionalGeneration.from_pretrained("FireRedTeam/FireRed-OCR",torch_dtype=torch.bfloat16 if torch.cuda.is_available() else torch.float32,device_map="auto",)_fire_red_processor = AutoProcessor.from_pretrained("FireRedTeam/FireRed-OCR")return _fire_red_model, _fire_red_processordef _extract_text_from_response(response: Any) -> str:12 unmodified linesreturn str(content)return str(response)#define the stateclass AgentState(TypedDict):question: strtask_id: Optional[str]2 unmodified lineshave_file: Optional[bool]is_math: Optional[bool]have_image: Optional[bool]final_answer: Optional[str] # The final answer produced by the agentretry_count: Optional[int] # Number of retries so farmessages: List[Dict[str, Any]] # Track conversation with LLM for analysis#define nodesdef read(state: AgentState) -> str:"""Agent reads and logs the incoming question."""question = state["question"]print(f"Agent is reading the question: {question[:50]}...")return {}def classify(state: AgentState) -> str:"""Agent classifies the question to determine which tools to use."""question = state["question"].lower()#prompt for LLM to classify the questionprompt = f"""You are an agent that classifies questions to determine which tools to use.Classify the following question into the categories: 'need to be searched on web/wikipidia', 'has a file in the question', 'is a math problem', 'has an image in the question'.Question: {question}Return a JSON object with boolean fields for each category, for example:{{"is_searching": true,"have_file": false,"is_math": false,"have_image": false}}"""messages = _msg(prompt)response = model(messages)raw = _extract_text_from_response(response)# Parse JSON from the model's responseimport json, rematch = re.search(r'\{.*?\}', raw, re.DOTALL)data = {}2 unmodified linesdata = json.loads(match.group())except json.JSONDecodeError:passis_searching = bool(data.get("is_searching", False))have_file = bool(data.get("have_file", False))is_math = bool(data.get("is_math", False))have_image = bool(data.get("have_image", False))print(f"Classification result: is_searching={is_searching}, have_file={have_file}, is_math={is_math}, have_image={have_image}")mew_messages = state.get("messages", []) + [{"role": "system", "content": "Classify the question to determine which tools to use."},{"role": "user", "content": question},{"role": "assistant", "content": f"Classification result: is_searching={is_searching}, have_file={have_file}, is_math={is_math}, have_image={have_image}"}]return {"is_searching": is_searching,"have_file": have_file,"is_math": is_math,"have_image": have_image,"messages": mew_messages}def handele_search(state: AgentState) -> str:"""Agent performs a web search if classified as needing search."""question = state["question"]print(f"Agent is performing a web search for: {question[:50]}...")2 unmodified linesnew_messages = state.get("messages", []) + [{"role": "system", "content": "Perform a web search if classified as needing search."},{"role": "user", "content": question},{"role": "assistant", "content": f"Search results: {search_results[:100]}..."}]return {"search_results": search_results,"messages": new_messages}def handle_image(state: AgentState) -> str:"""Agent handles an image if classified as having an image.Downloads the image as base64 and sends it to a vision-capable modelusing a multimodal message format."""question = state["question"]task_id = state.get("task_id", "")file_name = state.get("file_name", "")# Use ImageReaderTool to download the image as base64image_reader = tools.ImageReaderTool()image_data_uri = image_reader(task_id, file_name) if task_id and file_name else ""if not image_data_uri or image_data_uri.startswith("Failed"):print(f"Could not download image for task {task_id}")new_messages = state.get("messages", []) + [{"role": "assistant", "content": f"[Could not download image '{file_name}' for analysis.]"}]return {"image_description": "","transcribed_text": "","messages": new_messages}# Build multimodal message with image for a vision-capable modelprompt_text = f"""Analyze the attached image in detail.Describe the content of the image and transcribe all text visible in it.Question: {question}Return a JSON object with the following fields:{{"image_description": "A detailed description of the image content.","transcribed_text": "All text visible in the image transcribed here."}}"""# Run OCR through FireRed-OCR using Transformerstry:# Decode base64 data URI into bytes/PIL image_, b64_data = image_data_uri.split(",", 1)image_bytes = base64.b64decode(b64_data)from PIL import Imageimage = Image.open(BytesIO(image_bytes)).convert("RGB")ocr_model, ocr_processor = _load_fire_red_ocr()messages = [{"role": "user","content": [{"type": "image", "image": image},{"type": "text", "text": prompt_text},],}]text = ocr_processor.apply_chat_template(messages,tokenize=False,add_generation_prompt=True,)inputs = ocr_processor(text=[text],images=[image],return_tensors="pt",padding=True,)inputs = {k: v.to(ocr_model.device) for k, v in inputs.items()}generated_ids = ocr_model.generate(**inputs, max_new_tokens=2048)prompt_len = inputs["input_ids"].shape[1]generated_trimmed = generated_ids[:, prompt_len:]output_text = ocr_processor.batch_decode(generated_trimmed,skip_special_tokens=True,clean_up_tokenization_spaces=False,)ocr_text = output_text[0].strip() if output_text else ""except Exception as e:ocr_text = f"OCR error: {e}"image_description = ocr_texttranscribed_text = ocr_textprint(f"Image description: {image_description[:100]}...")print(f"Transcribed text: {transcribed_text[:100]}...")new_messages = state.get("messages", []) + [{"role": "system", "content": "Analyze and describe the image if classified as having an image."},{"role": "user", "content": question},{"role": "assistant", "content": f"Image description: {image_description[:100]}..., Transcribed text: {transcribed_text[:100]}..."}]return {"image_description": image_description,"transcribed_text": transcribed_text,"messages": new_messages}def handle_file(state: AgentState) -> str:"""Agent processes the file if classified as having a file.Uses the FileReaderTool to download and read the file from the API."""question = state["question"]task_id = state.get("task_id", "")file_name = state.get("file_name", "")# Use the file_reader tool to fetch the file contentfile_reader = tools.FileReaderTool()file_content = file_reader(task_id, file_name) if task_id and file_name else ""# Build prompt with the retrieved file contentfile_context = ""if file_content:file_context = f"\n\n--- Attached file: {file_name} ---\n{file_content}\n--- End of file ---"elif file_name:file_context = f"\n\n[Note: A file '{file_name}' was referenced but could not be retrieved.]"prompt = f"""You are an agent that can read and extract information from files.Below is the content of the attached file retrieved from the API. Read it carefully and extract any relevant information that could help answer the question.Question: {question}{file_context}Return a JSON object with the following field:{{"extracted_info": "The relevant extracted information from the file."}}"""messages = _msg(prompt)response = model(messages)extracted_info = _extract_text_from_response(response)1 unmodified linenew_messages = state.get("messages", []) + [{"role": "system", "content": "Read and extract information from the attached file."},{"role": "user", "content": question},{"role": "assistant", "content": f"Extracted info: {extracted_info[:100]}..."}]return {"extracted_info": extracted_info,"messages": new_messages}def handle_math(state: AgentState) -> str:"""Agent handles a math problem if classified as a math problem."""question = state["question"]print(f"Agent is handling a math problem: {question[:50]}...")4 unmodified linesnew_messages = state.get("messages", []) + [{"role": "system", "content": "Handle the question if classified as a math problem."},{"role": "user", "content": question},{"role": "assistant", "content": f"Math solution: {solution[:100]}..."}]return {"math_solution": solution,"messages": new_messages}def answer(state: AgentState) -> dict:1 unmodified linequestion = state["question"]messages_history = state.get("messages", [])# Build context summary from all assistant messagescontext_parts = []for msg in messages_history:if msg.get("role") == "assistant":context_parts.append(msg["content"])context = "\n".join(context_parts) if context_parts else "No additional context gathered."prompt = f"""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.Question: {question}Context gathered:{context}"""messages = _msg(prompt)# Use the general model for final answer synthesisresponse = model(messages)raw_response = _extract_text_from_response(response)# Extract the final answer after "FINAL ANSWER:" if presentif "FINAL ANSWER:" in raw_response:final_answer = raw_response.split("FINAL ANSWER:")[-1].strip()else:4 unmodified linesdef evaluate(state: AgentState) -> dict:"""LLM evaluates whether the current final_answer is adequate.If not, increments retry_count so the graph can loop back."""import json, requestion = state["question"]current_answer = state.get("final_answer", "")retry_count = state.get("retry_count", 0) or 0prompt = f"""You are a strict evaluator. Given the question and a candidate answer, decide if the answer is complete, relevant, and not an error message.Question: {question}Candidate answer: {current_answer}Return ONLY a JSON object:{{"is_adequate": true}} if the answer looks correct and complete,{{"is_adequate": false}} if the answer is wrong, incomplete, an error, or just says it could not find information."""response = model(_msg(prompt))raw = _extract_text_from_response(response)match = re.search(r'\{.*?\}', raw, re.DOTALL)3 unmodified linesdata = json.loads(match.group())except json.JSONDecodeError:passis_adequate = bool(data.get("is_adequate", True)) # default: acceptprint(f"Evaluation: is_adequate={is_adequate}, retry_count={retry_count}")return {"retry_count": retry_count + (0 if is_adequate else 1),5 unmodified linesdef route_after_evaluate(state: AgentState) -> str:"""If answer was inadequate and retries remain, search web for more context."""retry_count = state.get("retry_count", 0) or 0if retry_count > 0 and retry_count <= 2:print(f"Answer inadequate — retry {retry_count}/2, routing to web search")2 unmodified linesdef route_after_classify(state: AgentState) -> str:"""Routing function: decide which handler to invoke based on classification."""if state.get("have_image"):return "handle_image"if state.get("have_file"):2 unmodified linesreturn "handle_math"if state.get("is_searching"):return "handle_search"# Default: go straight to answerreturn "answer"#create the graphagent_graph = StateGraph(AgentState)agent_graph.add_node("read", read)agent_graph.add_node("classify", classify)6 unmodified linesagent_graph.add_edge(START, "read")agent_graph.add_edge("read", "classify")agent_graph.add_conditional_edges("classify",route_after_classify,)agent_graph.add_edge("handle_search", "answer")agent_graph.add_edge("handle_image", "answer")agent_graph.add_edge("handle_file", "answer")agent_graph.add_edge("handle_math", "answer")agent_graph.add_edge("answer", "evaluate")agent_graph.add_conditional_edges("evaluate",route_after_evaluate,)compiled_agent = agent_graph.compile()# --- Basic Agent Definition ---# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------class BasicAgent:def __init__(self):self.file_reader = tools.FileReaderTool()self.image_reader = tools.ImageReaderTool()self.web_search = tools.WebSearchTool()self.tools = [self.file_reader, self.image_reader, self.web_search]print("Agent initialized.")def __call__(self, question: str, task_id: str = "", file_name: str = "") -> str:print(f"Agent received question (first 50 chars): {question[:50]}...")# Run the LangGraph workflowresult_state = compiled_agent.invoke({"question": question,"task_id": task_id,4 unmodified lines"is_math": False,"have_image": False,"final_answer": "","retry_count": 0})# Extract the final answer from the statefinal_answer = result_state.get("final_answer", "No answer produced.")print(f"Agent returning answer: {final_answer[:100]}...")return final_answerdef run_and_submit_all( profile: gr.OAuthProfile | None):"""Fetches all questions, runs the BasicAgent on them, submits all answers,and displays the results."""# --- Determine HF Space Runtime URL and Repo URL ---space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the codeif profile:username= f"{profile.username}"print(f"User logged in: {username}")else:print("User not logged in.")3 unmodified linesquestions_url = f"{api_url}/questions"submit_url = f"{api_url}/submit"# 1. Instantiate Agent ( modify this part to create your agent)try:agent = BasicAgent()except Exception as e:print(f"Error instantiating agent: {e}")return f"Error initializing agent: {e}", None# 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)agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"print(agent_code)# 2. Fetch Questionsprint(f"Fetching questions from: {questions_url}")try:response = requests.get(questions_url, timeout=15)response.raise_for_status()questions_data = response.json()if not questions_data:print("Fetched questions list is empty.")return "Fetched questions list is empty or invalid format.", Noneprint(f"Fetched {len(questions_data)} questions.")except requests.exceptions.RequestException as e:print(f"Error fetching questions: {e}")return f"Error fetching questions: {e}", Noneexcept requests.exceptions.JSONDecodeError as e:print(f"Error decoding JSON response from questions endpoint: {e}")print(f"Response text: {response.text[:500]}")return f"Error decoding server response for questions: {e}", Noneexcept Exception as e:print(f"An unexpected error occurred fetching questions: {e}")return f"An unexpected error occurred fetching questions: {e}", None# 3. Run your Agentresults_log = []answers_payload = []print(f"Running agent on {len(questions_data)} questions...")for item in questions_data:task_id = item.get("task_id")# Handle both "Question" (dataset format) and "question" (API format)question_text = item.get("question") or item.get("Question")if not task_id or question_text is None:print(f"Skipping item with missing task_id or question: {item}")continue# Check for attached filefile_name = item.get("file_name", "")if file_name:print(f"Task {task_id} has attached file: {file_name}")try:submitted_answer = agent(question_text, task_id=task_id, file_name=file_name)answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})except Exception as e:print(f"Error running agent on task {task_id}: {e}")results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})if not answers_payload:print("Agent did not produce any answers to submit.")return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)# 4. Prepare Submissionsubmission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."print(status_update)# 5. Submitprint(f"Submitting {len(answers_payload)} answers to: {submit_url}")try:response = requests.post(submit_url, json=submission_data, timeout=60)7 unmodified linesf"Message: {result_data.get('message', 'No message received.')}")print("Submission successful.")results_df = pd.DataFrame(results_log)return final_status, results_dfexcept requests.exceptions.HTTPError as e:error_detail = f"Server responded with status {e.response.status_code}."try:error_json = e.response.json()error_detail += f" Detail: {error_json.get('detail', e.response.text)}"except requests.exceptions.JSONDecodeError:error_detail += f" Response: {e.response.text[:500]}"status_message = f"Submission Failed: {error_detail}"print(status_message)results_df = pd.DataFrame(results_log)return status_message, results_dfexcept requests.exceptions.Timeout:status_message = "Submission Failed: The request timed out."print(status_message)results_df = pd.DataFrame(results_log)return status_message, results_dfexcept requests.exceptions.RequestException as e:status_message = f"Submission Failed: Network error - {e}"print(status_message)results_df = pd.DataFrame(results_log)return status_message, results_dfexcept Exception as e:status_message = f"An unexpected error occurred during submission: {e}"print(status_message)results_df = pd.DataFrame(results_log)return status_message, results_df# --- Build Gradio Interface using Blocks ---with gr.Blocks() as demo:gr.Markdown("# Basic Agent Evaluation Runner")gr.Markdown(7 unmodified lines---**Disclaimers:**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).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.""")gr.LoginButton()run_button = gr.Button("Run Evaluation & Submit All Answers")status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)# Removed max_rows=10 from DataFrame constructorresults_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)run_button.click(2 unmodified lines)if __name__ == "__main__":print("\n" + "-"*30 + " App Starting " + "-"*30)# Check for SPACE_HOST and SPACE_ID at startup for informationspace_host_startup = os.getenv("SPACE_HOST")space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startupif space_host_startup:print(f"✅ SPACE_HOST found: {space_host_startup}")1 unmodified lineelse:print("ℹ️ SPACE_HOST environment variable not found (running locally?).")if space_id_startup: # Print repo URLs if SPACE_ID is foundprint(f"✅ SPACE_ID found: {space_id_startup}")print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")else:print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")print("-"*(60 + len(" App Starting ")) + "\n")print("Launching Gradio Interface for Basic Agent Evaluation...")demo.launch(debug=True, share=False)1 unmodified line2345678910111213141516171819202122232425262728293031323334353637383940414212 unmodified lines55565758596061622 unmodified lines65666768697071727374757677787980818283848586878889909192939495969798991001011021031042 unmodified lines1071081091101111121131141151161171181191201211221231241251261271281291301311321331342 unmodified lines1371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362371 unmodified line2392402412422432442452462472482492504 unmodified lines2552562572582592602612622631 unmodified line2652662672682692702712722732742752762772782792802812822832842852862872882892902912922932944 unmodified lines2993003013023033043053063073083093103113123133143153163173183 unmodified lines3223233243253263273285 unmodified lines3343353363373383392 unmodified lines3423433443453463472 unmodified lines3503513523533543553563573583596 unmodified lines3663673683693703713723733743753763773783793803813823833843853863873883893903913924 unmodified lines3973983994004014024034044054064074084094104114124134144153 unmodified lines4194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694707 unmodified lines4784794804814824834844854864874884894904914924934944954964974984995005017 unmodified lines5095105115125135145155165175185195205215222 unmodified lines5255265275285295305315325331 unmodified line5355365375385395405415425435445455465471 unmodified lineimport base64from io import BytesIOimport gradio as grimport requestsimport pandas as pdimport toolsfrom smolagents import InferenceClientModelfrom typing import TypedDict, List, Dict, Any, Optionalfrom langgraph.graph import StateGraph, START, END# Helper to build a smolagents-compatible message listdef _msg(content: str) -> list:return [{"role": "user", "content": content}]# --- Constants ---DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"# --- Models via HF Inference API (correct method for HF Spaces) ---# InferenceClientModel routes all calls through the HF Serverless Inference API.# No GPU or local model weights are required in the Space container.model = InferenceClientModel(model_id="meta-llama/Llama-3.2-3B-Instruct",max_tokens=2048,temperature=0.3,)math_model = InferenceClientModel(model_id="deepseek-ai/deepseek-math-7b-instruct",max_tokens=2048,temperature=0.3,)# Vision model for image / OCR tasks — also served via Inference APIvision_model = InferenceClientModel(model_id="Qwen/Qwen2.5-VL-7B-Instruct",max_tokens=2048,)def _extract_text_from_response(response: Any) -> str:12 unmodified linesreturn str(content)return str(response)# --- State ---class AgentState(TypedDict):question: strtask_id: Optional[str]2 unmodified lineshave_file: Optional[bool]is_math: Optional[bool]have_image: Optional[bool]final_answer: Optional[str]retry_count: Optional[int]messages: List[Dict[str, Any]]# --- Nodes ---def read(state: AgentState) -> dict:"""Agent reads and logs the incoming question."""question = state["question"]print(f"Agent is reading the question: {question[:50]}...")return {}def classify(state: AgentState) -> dict:"""Agent classifies the question to determine which tools to use."""question = state["question"].lower()prompt = f"""You are an agent that classifies questions to determine which tools to use.Classify the following question into the categories: 'need to be searched on web/wikipedia', 'has a file in the question', 'is a math problem', 'has an image in the question'.Question: {question}Return a JSON object with boolean fields for each category, for example:{{"is_searching": true,"have_file": false,"is_math": false,"have_image": false}}"""messages = _msg(prompt)response = model(messages)raw = _extract_text_from_response(response)import json, rematch = re.search(r'\{.*?\}', raw, re.DOTALL)data = {}2 unmodified linesdata = json.loads(match.group())except json.JSONDecodeError:passis_searching = bool(data.get("is_searching", False))have_file = bool(data.get("have_file", False))is_math = bool(data.get("is_math", False))have_image = bool(data.get("have_image", False))print(f"Classification: is_searching={is_searching}, have_file={have_file}, is_math={is_math}, have_image={have_image}")new_messages = state.get("messages", []) + [{"role": "system", "content": "Classify the question to determine which tools to use."},{"role": "user", "content": question},{"role": "assistant", "content": f"is_searching={is_searching}, have_file={have_file}, is_math={is_math}, have_image={have_image}"},]return {"is_searching": is_searching,"have_file": have_file,"is_math": is_math,"have_image": have_image,"messages": new_messages,}def handele_search(state: AgentState) -> dict:"""Agent performs a web search if classified as needing search."""question = state["question"]print(f"Agent is performing a web search for: {question[:50]}...")2 unmodified linesnew_messages = state.get("messages", []) + [{"role": "system", "content": "Perform a web search if classified as needing search."},{"role": "user", "content": question},{"role": "assistant", "content": f"Search results: {search_results[:100]}..."},]return {"search_results": search_results, "messages": new_messages}def handle_image(state: AgentState) -> dict:"""Agent handles an image using a vision model via the HF Inference API.Instead of loading a local transformer model (which would be too heavy fora standard Space), the image is forwarded to a vision-capableInferenceClientModel (Qwen2.5-VL) through the HF Serverless Inference API."""question = state["question"]task_id = state.get("task_id", "")file_name = state.get("file_name", "")image_reader = tools.ImageReaderTool()image_data_uri = image_reader(task_id, file_name) if task_id and file_name else ""if not image_data_uri or image_data_uri.startswith("Failed"):print(f"Could not download image for task {task_id}")new_messages = state.get("messages", []) + [{"role": "assistant", "content": f"[Could not download image '{file_name}' for analysis.]"},]return {"image_description": "", "transcribed_text": "", "messages": new_messages}prompt_text = (f"Analyze the attached image in detail.\n"f"Describe its content and transcribe all text visible in it.\n\n"f"Question: {question}\n\n"f"Return a JSON object: "f'{{ "image_description": "...", "transcribed_text": "..." }}')# Send image + text to the vision model via the HF Inference API.# InferenceClientModel accepts OpenAI-style multimodal message format.vision_messages = [{"role": "user","content": [{"type": "image_url", "image_url": {"url": image_data_uri}},{"type": "text", "text": prompt_text},],}]try:response = vision_model(vision_messages)ocr_text = _extract_text_from_response(response)except Exception as e:ocr_text = f"Vision model error: {e}"import json, rematch = re.search(r'\{.*?\}', ocr_text, re.DOTALL)image_description = ocr_texttranscribed_text = ocr_textif match:try:data = json.loads(match.group())image_description = data.get("image_description", ocr_text)transcribed_text = data.get("transcribed_text", ocr_text)except json.JSONDecodeError:passprint(f"Image description: {image_description[:100]}...")print(f"Transcribed text: {transcribed_text[:100]}...")new_messages = state.get("messages", []) + [{"role": "system", "content": "Analyze and describe the image if classified as having an image."},{"role": "user", "content": question},{"role": "assistant", "content": f"Image description: {image_description[:100]}..., Transcribed text: {transcribed_text[:100]}..."},]return {"image_description": image_description, "transcribed_text": transcribed_text, "messages": new_messages}def handle_file(state: AgentState) -> dict:"""Agent processes the file if classified as having a file."""question = state["question"]task_id = state.get("task_id", "")file_name = state.get("file_name", "")file_reader = tools.FileReaderTool()file_content = file_reader(task_id, file_name) if task_id and file_name else ""file_context = ""if file_content:file_context = f"\n\n--- Attached file: {file_name} ---\n{file_content}\n--- End of file ---"elif file_name:file_context = f"\n\n[Note: A file '{file_name}' was referenced but could not be retrieved.]"prompt = (f"You are an agent that can read and extract information from files.\n"f"Read the attached file content carefully and extract any relevant information "f"that could help answer the question.\n\n"f"Question: {question}{file_context}\n\n"f'Return a JSON object: {{ "extracted_info": "..." }}')messages = _msg(prompt)response = model(messages)extracted_info = _extract_text_from_response(response)1 unmodified linenew_messages = state.get("messages", []) + [{"role": "system", "content": "Read and extract information from the attached file."},{"role": "user", "content": question},{"role": "assistant", "content": f"Extracted info: {extracted_info[:100]}..."},]return {"extracted_info": extracted_info, "messages": new_messages}def handle_math(state: AgentState) -> dict:"""Agent handles a math problem if classified as a math problem."""question = state["question"]print(f"Agent is handling a math problem: {question[:50]}...")4 unmodified linesnew_messages = state.get("messages", []) + [{"role": "system", "content": "Handle the question if classified as a math problem."},{"role": "user", "content": question},{"role": "assistant", "content": f"Math solution: {solution[:100]}..."},]return {"math_solution": solution, "messages": new_messages}def answer(state: AgentState) -> dict:1 unmodified linequestion = state["question"]messages_history = state.get("messages", [])context_parts = [msg["content"]for msg in messages_historyif msg.get("role") == "assistant"]context = "\n".join(context_parts) if context_parts else "No additional context gathered."prompt = ("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.\n\n"f"Question: {question}\n\n"f"Context gathered:\n{context}\n")messages = _msg(prompt)response = model(messages)raw_response = _extract_text_from_response(response)if "FINAL ANSWER:" in raw_response:final_answer = raw_response.split("FINAL ANSWER:")[-1].strip()else:4 unmodified linesdef evaluate(state: AgentState) -> dict:"""LLM evaluates whether the current final_answer is adequate."""import json, requestion = state["question"]current_answer = state.get("final_answer", "")retry_count = state.get("retry_count", 0) or 0prompt = (f"You are a strict evaluator. Given the question and a candidate answer, decide if the "f"answer is complete, relevant, and not an error message.\n\n"f"Question: {question}\nCandidate answer: {current_answer}\n\n"f'Return ONLY a JSON object:\n'f'{{"is_adequate": true}} if the answer looks correct and complete,\n'f'{{"is_adequate": false}} if the answer is wrong, incomplete, an error, or says it could not find information.')response = model(_msg(prompt))raw = _extract_text_from_response(response)match = re.search(r'\{.*?\}', raw, re.DOTALL)3 unmodified linesdata = json.loads(match.group())except json.JSONDecodeError:passis_adequate = bool(data.get("is_adequate", True))print(f"Evaluation: is_adequate={is_adequate}, retry_count={retry_count}")return {"retry_count": retry_count + (0 if is_adequate else 1),5 unmodified linesdef route_after_evaluate(state: AgentState) -> str:retry_count = state.get("retry_count", 0) or 0if retry_count > 0 and retry_count <= 2:print(f"Answer inadequate — retry {retry_count}/2, routing to web search")2 unmodified linesdef route_after_classify(state: AgentState) -> str:if state.get("have_image"):return "handle_image"if state.get("have_file"):2 unmodified linesreturn "handle_math"if state.get("is_searching"):return "handle_search"return "answer"# --- Build LangGraph ---agent_graph = StateGraph(AgentState)agent_graph.add_node("read", read)agent_graph.add_node("classify", classify)6 unmodified linesagent_graph.add_edge(START, "read")agent_graph.add_edge("read", "classify")agent_graph.add_conditional_edges("classify", route_after_classify)agent_graph.add_edge("handle_search", "answer")agent_graph.add_edge("handle_image", "answer")agent_graph.add_edge("handle_file", "answer")agent_graph.add_edge("handle_math", "answer")agent_graph.add_edge("answer", "evaluate")agent_graph.add_conditional_edges("evaluate", route_after_evaluate)compiled_agent = agent_graph.compile()# --- Agent ---class BasicAgent:def __init__(self):self.file_reader = tools.FileReaderTool()self.image_reader = tools.ImageReaderTool()self.web_search = tools.WebSearchTool()print("Agent initialized.")def __call__(self, question: str, task_id: str = "", file_name: str = "") -> str:print(f"Agent received question (first 50 chars): {question[:50]}...")result_state = compiled_agent.invoke({"question": question,"task_id": task_id,4 unmodified lines"is_math": False,"have_image": False,"final_answer": "","retry_count": 0,})final_answer = result_state.get("final_answer", "No answer produced.")print(f"Agent returning answer: {final_answer[:100]}...")return final_answerdef run_and_submit_all(profile: gr.OAuthProfile | None):"""Fetches all questions, runs the BasicAgent on them, submits all answers."""space_id = os.getenv("SPACE_ID")if profile:username = f"{profile.username}"print(f"User logged in: {username}")else:print("User not logged in.")3 unmodified linesquestions_url = f"{api_url}/questions"submit_url = f"{api_url}/submit"try:agent = BasicAgent()except Exception as e:print(f"Error instantiating agent: {e}")return f"Error initializing agent: {e}", Noneagent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"print(agent_code)print(f"Fetching questions from: {questions_url}")try:response = requests.get(questions_url, timeout=15)response.raise_for_status()questions_data = response.json()if not questions_data:return "Fetched questions list is empty or invalid format.", Noneprint(f"Fetched {len(questions_data)} questions.")except requests.exceptions.RequestException as e:return f"Error fetching questions: {e}", Noneexcept Exception as e:return f"An unexpected error occurred fetching questions: {e}", Noneresults_log = []answers_payload = []print(f"Running agent on {len(questions_data)} questions...")for item in questions_data:task_id = item.get("task_id")question_text = item.get("question") or item.get("Question")if not task_id or question_text is None:print(f"Skipping item with missing task_id or question: {item}")continuefile_name = item.get("file_name", "")if file_name:print(f"Task {task_id} has attached file: {file_name}")try:submitted_answer = agent(question_text, task_id=task_id, file_name=file_name)answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})except Exception as e:print(f"Error running agent on task {task_id}: {e}")results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})if not answers_payload:return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}print(f"Submitting {len(answers_payload)} answers to: {submit_url}")try:response = requests.post(submit_url, json=submission_data, timeout=60)7 unmodified linesf"Message: {result_data.get('message', 'No message received.')}")print("Submission successful.")return final_status, pd.DataFrame(results_log)except requests.exceptions.HTTPError as e:error_detail = f"Server responded with status {e.response.status_code}."try:error_json = e.response.json()error_detail += f" Detail: {error_json.get('detail', e.response.text)}"except Exception:error_detail += f" Response: {e.response.text[:500]}"return f"Submission Failed: {error_detail}", pd.DataFrame(results_log)except requests.exceptions.Timeout:return "Submission Failed: The request timed out.", pd.DataFrame(results_log)except requests.exceptions.RequestException as e:return f"Submission Failed: Network error - {e}", pd.DataFrame(results_log)except Exception as e:return f"An unexpected error occurred during submission: {e}", pd.DataFrame(results_log)# --- Gradio Interface ---with gr.Blocks() as demo:gr.Markdown("# Basic Agent Evaluation Runner")gr.Markdown(7 unmodified lines---**Disclaimers:**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).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 separate action or even to answer the questions in async.""")gr.LoginButton()run_button = gr.Button("Run Evaluation & Submit All Answers")status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)run_button.click(2 unmodified lines)if __name__ == "__main__":print("\n" + "-" * 30 + " App Starting " + "-" * 30)space_host_startup = os.getenv("SPACE_HOST")space_id_startup = os.getenv("SPACE_ID")if space_host_startup:print(f"✅ SPACE_HOST found: {space_host_startup}")1 unmodified lineelse:print("ℹ️ SPACE_HOST environment variable not found (running locally?).")if space_id_startup:print(f"✅ SPACE_ID found: {space_id_startup}")print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")else:print("ℹ️ SPACE_ID environment variable not found (running locally?).")print("-" * (60 + len(" App Starting ")) + "\n")print("Launching Gradio Interface for Basic Agent Evaluation...")demo.launch(debug=True, share=False)
app.py+172-297