Spaces:
Sleeping
Sleeping
Download app.py from Aym4n3/Final_Assignment_Template: direct link, hf CLI and curl.
- Browser
- Download file 23.3 kB
-
https://huggingface.co/spaces/Aym4n3/Final_Assignment_Template/resolve/main/app.py
- Command line
-
hf download hf://spaces/Aym4n3/Final_Assignment_Template/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Aym4n3/Final_Assignment_Template/resolve/main/app.py
23.3 kB
| import os | |
| import json | |
| import ast | |
| import re | |
| import operator as op | |
| from pathlib import Path | |
| from typing import TypedDict, Annotated, Dict, List | |
| import gradio as gr | |
| import requests | |
| import pandas as pd | |
| from dotenv import load_dotenv | |
| from tavily import TavilyClient | |
| from langchain.tools import tool | |
| from langchain_openai import ChatOpenAI | |
| from langchain_core.messages import SystemMessage, HumanMessage, AnyMessage, RemoveMessage | |
| from langgraph.graph.message import add_messages, REMOVE_ALL_MESSAGES | |
| from langgraph.graph import START, END, StateGraph | |
| from langgraph.prebuilt import ToolNode | |
| DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space" | |
| load_dotenv() | |
| OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") | |
| TAVILY_API_KEY = os.getenv("TAVILY_API_KEY") | |
| if not OPENAI_API_KEY: | |
| raise ValueError("OPENAI_API_KEY is missing") | |
| if not TAVILY_API_KEY: | |
| raise ValueError("TAVILY_API_KEY is missing") | |
| tavily_client = TavilyClient(TAVILY_API_KEY) | |
| WORKSPACE_ROOT = Path(__file__).resolve().parent | |
| class GaiaState(TypedDict): | |
| original_question: str | |
| subquestions: List[str] | |
| current_subquestion_index: int | |
| subanswers: Dict[str, str] | |
| final_answer: str | |
| messages: Annotated[list[AnyMessage], add_messages] | |
| _ALLOWED_OPERATORS = { | |
| ast.Add: op.add, | |
| ast.Sub: op.sub, | |
| ast.Mult: op.mul, | |
| ast.Div: op.truediv, | |
| ast.USub: op.neg, | |
| ast.UAdd: op.pos, | |
| } | |
| def _safe_eval(node): | |
| if isinstance(node, ast.Expression): | |
| return _safe_eval(node.body) | |
| if isinstance(node, ast.Constant): | |
| if isinstance(node.value, (int, float)): | |
| return node.value | |
| raise ValueError("Only numeric constants are allowed") | |
| if isinstance(node, ast.Num): | |
| return node.n | |
| if isinstance(node, ast.BinOp): | |
| if type(node.op) not in _ALLOWED_OPERATORS: | |
| raise ValueError("Unsupported operation") | |
| left = _safe_eval(node.left) | |
| right = _safe_eval(node.right) | |
| if isinstance(node.op, ast.Div) and right == 0: | |
| raise ValueError("Division by zero") | |
| return _ALLOWED_OPERATORS[type(node.op)](left, right) | |
| if isinstance(node, ast.UnaryOp): | |
| if type(node.op) not in _ALLOWED_OPERATORS: | |
| raise ValueError("Unsupported unary operation") | |
| operand = _safe_eval(node.operand) | |
| return _ALLOWED_OPERATORS[type(node.op)](operand) | |
| raise ValueError("Invalid expression") | |
| def _truncate_text(value: str, max_chars: int = 6000) -> str: | |
| if len(value) <= max_chars: | |
| return value | |
| return value[:max_chars] + "\n...[truncated]..." | |
| def _extract_json_block(text: str): | |
| text = text.strip() | |
| if text.startswith("```"): | |
| text = re.sub(r"^```(?:json)?\s*", "", text) | |
| text = re.sub(r"\s*```$", "", text) | |
| match = re.search(r"\{.*\}", text, re.DOTALL) | |
| if match: | |
| return json.loads(match.group(0)) | |
| return json.loads(text) | |
| def _resolve_workspace_path(path_str: str) -> Path: | |
| candidate = Path(path_str).expanduser() | |
| if not candidate.is_absolute(): | |
| candidate = (WORKSPACE_ROOT / candidate).resolve() | |
| else: | |
| candidate = candidate.resolve() | |
| if WORKSPACE_ROOT not in candidate.parents and candidate != WORKSPACE_ROOT: | |
| raise ValueError("Path must be inside the workspace") | |
| return candidate | |
| def calculator(expression: str) -> str: | |
| """ | |
| Evaluate a mathematical expression safely. | |
| Supports numbers, parentheses, +, -, *, /, and unary +/-. | |
| Returns the result as a string. | |
| """ | |
| try: | |
| parsed = ast.parse(expression, mode="eval") | |
| result = _safe_eval(parsed) | |
| if isinstance(result, float) and result.is_integer(): | |
| result = int(result) | |
| return str(result) | |
| except Exception as e: | |
| return f"Error: {e}" | |
| def web_search(query: str) -> str: | |
| """ | |
| Search the web for up-to-date information relevant to a question. | |
| Returns top search results with titles, URLs, and snippets. | |
| """ | |
| try: | |
| search_response = tavily_client.search(query, max_results=5) | |
| results = search_response.get("results", []) | |
| if not results: | |
| return f"No search results found for query: {query}" | |
| formatted_results = [f"Search query: {query}", "", "Top results:"] | |
| for i, result in enumerate(results, start=1): | |
| title = result.get("title", "No title") | |
| url = result.get("url", "No URL") | |
| content = result.get("content", "No snippet available") | |
| formatted_results.append( | |
| f"{i}. {title}\nURL: {url}\nSnippet: {content}\n" | |
| ) | |
| return "\n".join(formatted_results) | |
| except Exception as e: | |
| return f"Web search error: {e}" | |
| def list_local_files() -> str: | |
| """ | |
| List local files in the workspace so you can inspect attachments such as Excel, CSV, JSON, or text files. | |
| """ | |
| allowed_suffixes = { | |
| ".xlsx", ".xls", ".csv", ".tsv", ".json", ".txt", ".md", | |
| ".pdf", ".png", ".jpg", ".jpeg", ".parquet" | |
| } | |
| files = [] | |
| for path in WORKSPACE_ROOT.rglob("*"): | |
| if path.is_file() and path.suffix.lower() in allowed_suffixes: | |
| try: | |
| relative_path = path.relative_to(WORKSPACE_ROOT) | |
| except ValueError: | |
| relative_path = path | |
| files.append(str(relative_path)) | |
| if not files: | |
| return "No supported local files found in the workspace." | |
| return "Local files:\n" + "\n".join(sorted(files)) | |
| def read_local_file(path: str) -> str: | |
| """ | |
| Read a local file from the workspace. Supports text, JSON, CSV/TSV, and Excel files. | |
| For spreadsheets, this returns sheet names, preview rows, column names, and numeric column sums when possible. | |
| """ | |
| try: | |
| resolved_path = _resolve_workspace_path(path) | |
| if not resolved_path.exists(): | |
| return f"File not found: {path}" | |
| suffix = resolved_path.suffix.lower() | |
| if suffix in {".txt", ".md", ".json"}: | |
| content = resolved_path.read_text(encoding="utf-8", errors="replace") | |
| if suffix == ".json": | |
| try: | |
| parsed = json.loads(content) | |
| content = json.dumps(parsed, indent=2, ensure_ascii=True) | |
| except Exception: | |
| pass | |
| return _truncate_text(content) | |
| if suffix in {".csv", ".tsv"}: | |
| sep = "\t" if suffix == ".tsv" else "," | |
| df = pd.read_csv(resolved_path, sep=sep) | |
| summary = [ | |
| f"File: {resolved_path.name}", | |
| f"Columns: {', '.join(str(col) for col in df.columns)}", | |
| f"Rows: {len(df)}", | |
| "", | |
| "Preview:", | |
| df.head(20).to_csv(index=False), | |
| ] | |
| numeric_df = df.select_dtypes(include="number") | |
| if not numeric_df.empty: | |
| summary.extend( | |
| [ | |
| "", | |
| "Numeric column sums:", | |
| numeric_df.sum(numeric_only=True).to_string(), | |
| ] | |
| ) | |
| return _truncate_text("\n".join(summary)) | |
| if suffix in {".xlsx", ".xls"}: | |
| excel_file = pd.ExcelFile(resolved_path) | |
| output_parts = [f"File: {resolved_path.name}", f"Sheets: {', '.join(excel_file.sheet_names)}"] | |
| for sheet_name in excel_file.sheet_names[:5]: | |
| df = excel_file.parse(sheet_name) | |
| output_parts.extend( | |
| [ | |
| "", | |
| f"Sheet: {sheet_name}", | |
| f"Columns: {', '.join(str(col) for col in df.columns)}", | |
| f"Rows: {len(df)}", | |
| "Preview:", | |
| df.head(20).to_csv(index=False), | |
| ] | |
| ) | |
| numeric_df = df.select_dtypes(include="number") | |
| if not numeric_df.empty: | |
| output_parts.extend( | |
| [ | |
| "Numeric column sums:", | |
| numeric_df.sum(numeric_only=True).to_string(), | |
| ] | |
| ) | |
| return _truncate_text("\n".join(output_parts)) | |
| return f"Unsupported file type for reading: {suffix}" | |
| except Exception as e: | |
| return f"File read error: {e}" | |
| tools = [web_search, calculator, list_local_files, read_local_file] | |
| tool_node = ToolNode(tools) | |
| def get_model(temperature: float = 0): | |
| return ChatOpenAI( | |
| model="gpt-4.1-mini", | |
| temperature=temperature, | |
| api_key=OPENAI_API_KEY, | |
| ) | |
| def planner(state: GaiaState): | |
| model = get_model() | |
| prompt = """You are an expert problem decomposition agent. | |
| Your job is to analyze a question and decide whether it should be decomposed into smaller subquestions. | |
| Rules: | |
| 1. If the question is simple and can be answered directly, return a single subquestion equal to the original question. | |
| 2. If the question requires multiple reasoning steps, break it into clear atomic subquestions. | |
| 3. Each subquestion should be answerable independently using tools such as web search or calculation. | |
| 4. Do NOT answer the question yourself. | |
| 5. Only produce subquestions needed to solve the problem. | |
| Output format (JSON only): | |
| { | |
| "subquestions": [ | |
| "subquestion 1", | |
| "subquestion 2" | |
| ] | |
| } | |
| Do not include explanations. | |
| Do not include text outside the JSON.""" | |
| messages = [ | |
| SystemMessage(content=prompt), | |
| HumanMessage(content=state["original_question"]), | |
| ] | |
| response = model.invoke(messages) | |
| subquestions = [] | |
| try: | |
| content = response.content if isinstance(response.content, str) else str(response.content) | |
| parsed = _extract_json_block(content) | |
| subquestions = parsed.get("subquestions", []) | |
| except Exception: | |
| subquestions = [] | |
| if not isinstance(subquestions, list) or not subquestions: | |
| subquestions = [state["original_question"]] | |
| subquestions = [str(q).strip() for q in subquestions if str(q).strip()] | |
| if not subquestions: | |
| subquestions = [state["original_question"]] | |
| return { | |
| "subquestions": subquestions, | |
| "current_subquestion_index": 0, | |
| } | |
| def answer_subquestion(state: GaiaState): | |
| current_index = state["current_subquestion_index"] | |
| current_subquestion = state["subquestions"][current_index] | |
| solver_model = get_model().bind_tools(tools) | |
| if not state["messages"]: | |
| prompt = """You are a research assistant solving a complex question. | |
| You may use tools when necessary to obtain information or perform calculations. | |
| Use tools when: | |
| - the answer requires up-to-date information | |
| - the answer requires external data | |
| - the answer requires arithmetic computation | |
| - the answer depends on a local attachment such as an Excel, CSV, JSON, or text file | |
| When local files may be relevant, first use list_local_files and then read_local_file. | |
| If you already know the answer with high confidence, answer directly. | |
| Be concise and accurate.""" | |
| messages = [ | |
| SystemMessage(content=prompt), | |
| HumanMessage(content=current_subquestion), | |
| ] | |
| else: | |
| messages = state["messages"] | |
| response = solver_model.invoke(messages) | |
| if not state["messages"]: | |
| return {"messages": messages + [response]} | |
| return {"messages": [response]} | |
| def route_after_llm(state: GaiaState): | |
| last_message = state["messages"][-1] | |
| if getattr(last_message, "tool_calls", None): | |
| return "tools" | |
| return "store_subanswer" | |
| def store_subanswer(state: GaiaState): | |
| current_index = state["current_subquestion_index"] | |
| next_index = current_index + 1 | |
| current_subquestion = state["subquestions"][current_index] | |
| last_message = state["messages"][-1] | |
| answer_text = last_message.content | |
| if isinstance(answer_text, list): | |
| answer_text = " ".join(str(x) for x in answer_text) | |
| else: | |
| answer_text = str(answer_text) | |
| updated_subanswers = dict(state["subanswers"]) | |
| updated_subanswers[current_subquestion] = answer_text.strip() | |
| return { | |
| "current_subquestion_index": next_index, | |
| "subanswers": updated_subanswers, | |
| "messages": [RemoveMessage(id=REMOVE_ALL_MESSAGES)], | |
| } | |
| def route_subquestion_loop(state: GaiaState): | |
| if state["current_subquestion_index"] < len(state["subquestions"]): | |
| return "answer_subquestion" | |
| return "final_answer" | |
| def final_answer(state: GaiaState): | |
| model = get_model() | |
| prompt = """You are a general AI assistant. I will give you an original question and a set of subquestions with their answers. You must formulate one final answer based only on that information. | |
| Finish your answer with the following template exactly: | |
| 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 | |
| Rules: | |
| - If asked for a number, do not use commas in the number and do not use units unless explicitly requested. | |
| - If asked for a string, do not use articles and do not use abbreviations unless explicitly requested. | |
| - If asked for a comma separated list, apply the same rules to each element. | |
| - Do not add anything after FINAL ANSWER.""" | |
| question_answer = "" | |
| for question, answer in state["subanswers"].items(): | |
| question_answer += f"Question: {question}\nAnswer: {answer}\n\n" | |
| user_content = ( | |
| f"Original question: {state['original_question']}\n\n" | |
| f"Subquestion answers:\n{question_answer}" | |
| ) | |
| messages = [ | |
| SystemMessage(content=prompt), | |
| HumanMessage(content=user_content), | |
| ] | |
| response = model.invoke(messages) | |
| content = response.content | |
| if isinstance(content, list): | |
| content = " ".join(str(x) for x in content) | |
| else: | |
| content = str(content) | |
| return {"final_answer": content.strip()} | |
| def build_graph(): | |
| builder = StateGraph(GaiaState) | |
| builder.add_node("planner", planner) | |
| builder.add_node("answer_subquestion", answer_subquestion) | |
| builder.add_node("tools", tool_node) | |
| builder.add_node("store_subanswer", store_subanswer) | |
| builder.add_node("final_answer", final_answer) | |
| builder.add_edge(START, "planner") | |
| builder.add_edge("planner", "answer_subquestion") | |
| builder.add_edge("tools", "answer_subquestion") | |
| builder.add_edge("final_answer", END) | |
| builder.add_conditional_edges( | |
| "answer_subquestion", | |
| route_after_llm, | |
| { | |
| "tools": "tools", | |
| "store_subanswer": "store_subanswer", | |
| }, | |
| ) | |
| builder.add_conditional_edges( | |
| "store_subanswer", | |
| route_subquestion_loop, | |
| { | |
| "answer_subquestion": "answer_subquestion", | |
| "final_answer": "final_answer", | |
| }, | |
| ) | |
| return builder.compile() | |
| class BasicAgent: | |
| def __init__(self): | |
| print("Initializing BasicAgent...") | |
| self.graph = build_graph() | |
| print("BasicAgent initialized.") | |
| def __call__(self, question: str) -> str: | |
| print(f"Agent received question (first 100 chars): {question[:100]}") | |
| initial_state: GaiaState = { | |
| "original_question": question, | |
| "subquestions": [], | |
| "current_subquestion_index": 0, | |
| "subanswers": {}, | |
| "final_answer": "", | |
| "messages": [], | |
| } | |
| result = self.graph.invoke(initial_state) | |
| answer = str(result.get("final_answer", "")).strip() | |
| if "FINAL ANSWER:" in answer: | |
| answer = answer.split("FINAL ANSWER:", 1)[1].strip() | |
| answer = answer.splitlines()[0].strip() | |
| answer = answer.strip().strip('"').strip("'") | |
| if not answer: | |
| answer = "Unable to determine answer" | |
| print(f"Agent returning answer: {answer}") | |
| return answer | |
| def run_and_submit_all(profile: gr.OAuthProfile | None): | |
| space_id = os.getenv("SPACE_ID") | |
| if profile: | |
| username = f"{profile.username}" | |
| print(f"User logged in: {username}") | |
| else: | |
| print("User not logged in.") | |
| return "Please Login to Hugging Face with the button.", None | |
| api_url = DEFAULT_API_URL | |
| questions_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}", None | |
| if space_id: | |
| agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main" | |
| else: | |
| agent_code = "" | |
| 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: | |
| print("Fetched questions list is empty.") | |
| return "Fetched questions list is empty or invalid format.", None | |
| print(f"Fetched {len(questions_data)} questions.") | |
| except requests.exceptions.RequestException as e: | |
| print(f"Error fetching questions: {e}") | |
| return f"Error fetching questions: {e}", None | |
| except ValueError as e: | |
| print(f"Error decoding JSON response from questions endpoint: {e}") | |
| return f"Error decoding server response for questions: {e}", None | |
| except Exception as e: | |
| print(f"An unexpected error occurred fetching questions: {e}") | |
| return f"An unexpected error occurred fetching questions: {e}", None | |
| results_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") | |
| if not task_id or question_text is None: | |
| print(f"Skipping item with missing task_id or question: {item}") | |
| continue | |
| try: | |
| submitted_answer = agent(question_text) | |
| 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) | |
| submission_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) | |
| print(f"Submitting {len(answers_payload)} answers to: {submit_url}") | |
| try: | |
| response = requests.post(submit_url, json=submission_data, timeout=60) | |
| response.raise_for_status() | |
| result_data = response.json() | |
| final_status = ( | |
| f"Submission Successful!\n" | |
| f"User: {result_data.get('username')}\n" | |
| f"Overall Score: {result_data.get('score', 'N/A')}% " | |
| f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n" | |
| f"Message: {result_data.get('message', 'No message received.')}" | |
| ) | |
| print("Submission successful.") | |
| results_df = pd.DataFrame(results_log) | |
| return final_status, results_df | |
| 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 ValueError: | |
| 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_df | |
| except requests.exceptions.Timeout: | |
| status_message = "Submission Failed: The request timed out." | |
| print(status_message) | |
| results_df = pd.DataFrame(results_log) | |
| return status_message, results_df | |
| except 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_df | |
| except 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 | |
| with gr.Blocks() as demo: | |
| gr.Markdown("# Basic Agent Evaluation Runner") | |
| gr.Markdown( | |
| """ | |
| **Instructions:** | |
| 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc. | |
| 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission. | |
| 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score. | |
| --- | |
| **Disclaimers:** | |
| Once clicking on the submit button, it can take quite some time. | |
| """ | |
| ) | |
| 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( | |
| fn=run_and_submit_all, | |
| outputs=[status_output, results_table], | |
| ) | |
| 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}") | |
| print(f" Runtime URL should be: https://{space_host_startup}.hf.space") | |
| else: | |
| 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?). 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) | |