Spaces:
Sleeping
Sleeping
Replace stub agent with LangGraph-based tool-using agent
Browse filesImplement a working GAIA benchmark agent using LangGraph instead of the
placeholder BasicAgent.
- Add tool-calling loop (agent -> tools -> agent) with web search,
Wikipedia, Python REPL, calculator, and file-reading tools
- Auto-download task-attached files via /files/{task_id} and expose
local path to the file reader tool
- Add a verification pass that strips model output down to a clean,
exact-match-ready final answer
- Wire task_id through to the agent so file-based questions can be
handled
- Update requirements.txt with langgraph/langchain deps
123456789101112131415161718192021222324252627282930313233343 unmodified lines38394041424344454647484950515253545556575859606162636465666768697071727374754 unmodified lines808182838485868788899091929394959697989910010110210310410534 unmodified lines1401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811 unmodified line183184185186187188189190191192193194195196import osimport gradio as grimport requestsimport inspectimport pandas as pd# (Keep Constants as is)# --- Constants ---DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"# --- Basic Agent Definition ---# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------class BasicAgent:def __init__(self):print("BasicAgent initialized.")def __call__(self, question: str) -> str:print(f"Agent received question (first 50 chars): {question[:50]}...")fixed_answer = "This is a default answer."print(f"Agent returning fixed answer: {fixed_answer}")return fixed_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...")4 unmodified linesprint(f"Skipping item with missing task_id or question: {item}")continuetry: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)# 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)response.raise_for_status()result_data = response.json()final_status = (34 unmodified linesreturn status_message, results_df# --- Build Gradio Interface using Blocks ---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 ( 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(fn=run_and_submit_all,outputs=[status_output, results_table])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)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412423 unmodified lines2462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792804 unmodified lines28528628728828929029129229329429529629729829930030130230330430530630730834 unmodified lines3433443453463473483493503513523533543553563573583593603613623633643653663673683693703711 unmodified line373374375376377378379380381382383384import osimport reimport jsonimport base64import operatorimport requestsimport pandas as pdimport gradio as grfrom typing import TypedDict, Annotatedfrom langgraph.graph import StateGraph, ENDfrom langgraph.prebuilt import ToolNodefrom langchain_core.messages import HumanMessage, SystemMessage, AIMessagefrom langchain_core.tools import toolfrom langchain_openai import ChatOpenAIfrom langchain_community.tools import DuckDuckGoSearchRun, WikipediaQueryRunfrom langchain_community.utilities import WikipediaAPIWrapperfrom langchain_experimental.tools import PythonREPLTool# --- Constants ---DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"# =========================================================# TOOLS# =========================================================@tooldef calculator(expression: str) -> str:"""Evaluate a basic arithmetic expression, e.g. "12 * (3 + 4)".Only use this for simple math; for anything more complex use thepython_repl tool instead."""try:allowed = {"__builtins__": {}}return str(eval(expression, allowed))except Exception as e:return f"Error evaluating expression: {e}"search_tool = DuckDuckGoSearchRun(name="web_search")search_tool.description = ("Search the web for current information, facts, names, dates, or anything ""you are not fully certain about. Input should be a search query string.")wiki_tool = WikipediaQueryRun(api_wrapper=WikipediaAPIWrapper(top_k_results=2, doc_content_chars_max=2000))wiki_tool.description = ("Look up a topic on Wikipedia. Good for factual/encyclopedic questions ""about people, places, events, and concepts. Input should be a search term.")python_tool = PythonREPLTool()python_tool.description = ("Execute Python code to do calculations, process data, parse files, or ""reason step by step. Any variable you want to see must be printed with print(). ""Use this for anything involving numbers, dates, sorting, counting, or file data.")@tooldef read_downloaded_file(file_path: str) -> str:"""Read the contents of a file that was downloaded for this task (csv, xlsx,txt, json, or pdf). Pass the local file path. Returns a text summary orthe raw content, truncated if very long."""if not os.path.exists(file_path):return f"Error: file not found at {file_path}"ext = file_path.lower().split(".")[-1]try:if ext == "csv":df = pd.read_csv(file_path)return f"CSV with shape {df.shape}. Columns: {list(df.columns)}\n\n{df.to_string(max_rows=50)}"elif ext in ("xlsx", "xls"):df = pd.read_excel(file_path)return f"Excel with shape {df.shape}. Columns: {list(df.columns)}\n\n{df.to_string(max_rows=50)}"elif ext == "json":with open(file_path, "r") as f:data = json.load(f)return json.dumps(data, indent=2)[:5000]elif ext == "pdf":try:from pypdf import PdfReaderreader = PdfReader(file_path)text = "\n".join(page.extract_text() or "" for page in reader.pages)return text[:8000] if text else "No extractable text found in PDF."except Exception as e:return f"Error reading PDF: {e}"else:with open(file_path, "r", errors="ignore") as f:content = f.read()return content[:8000]except Exception as e:return f"Error reading file: {e}"TOOLS = [calculator, search_tool, wiki_tool, python_tool, read_downloaded_file]# =========================================================# MODEL# =========================================================# Requires OPENAI_API_KEY set as a Space secret.# Swap model= for "gpt-4o" if you have budget for better accuracy.llm = ChatOpenAI(model="gpt-4o", temperature=0)llm_with_tools = llm.bind_tools(TOOLS)SYSTEM_PROMPT = """You are a general AI assistant answering benchmark questions that will begraded by EXACT STRING MATCH. Follow these rules strictly:1. Use tools (web_search, wikipedia, python_repl, calculator, read_downloaded_file) whenever youare not 100% certain of a fact, number, name, or date. Do not guess.2. If a file was provided for this task, use read_downloaded_file to inspect it before answering.3. Think step by step using tools, but your VERY LAST message must contain ONLY the final answer.4. Formatting rules for the final answer:- No explanations, no "the answer is", no "FINAL ANSWER:" prefix — just the answer itself.- If asked for a number, write only the number (no commas, no units, no $ sign) unless thequestion explicitly asks for units.- If asked for a string, use as few words as possible, no articles ("a", "the") unless thequestion requires them, and do not abbreviate unless asked.- If asked for a comma separated list, apply the above rules to each element.- Match the exact capitalization and spelling implied by the question when naming entities."""# =========================================================# GRAPH STATE# =========================================================class AgentState(TypedDict):messages: Annotated[list, operator.add]def call_model(state: AgentState):response = llm_with_tools.invoke(state["messages"])return {"messages": [response]}def should_continue(state: AgentState):last_message = state["messages"][-1]if getattr(last_message, "tool_calls", None):return "tools"return "verify"def verify_answer(state: AgentState):"""Second pass: force the model to strip any extra text and return a clean final answer."""draft = state["messages"][-1].contentverify_prompt = [SystemMessage(content=("Extract ONLY the final answer from the text below, with no extra words, ""no explanation, no punctuation unless part of the answer itself, and no ""'FINAL ANSWER:' prefix. Return just the answer.")),HumanMessage(content=str(draft)),]cleaned = llm.invoke(verify_prompt)return {"messages": [AIMessage(content=cleaned.content)]}tool_node = ToolNode(TOOLS)graph = StateGraph(AgentState)graph.add_node("agent", call_model)graph.add_node("tools", tool_node)graph.add_node("verify", verify_answer)graph.set_entry_point("agent")graph.add_conditional_edges("agent", should_continue, {"tools": "tools", "verify": "verify"})graph.add_edge("tools", "agent")graph.add_edge("verify", END)compiled_graph = graph.compile()# =========================================================# AGENT WRAPPER# =========================================================class BasicAgent:def __init__(self, api_url: str = DEFAULT_API_URL):self.graph = compiled_graphself.api_url = api_urlprint("BasicAgent initialized.")def _download_file_if_any(self, task_id: str) -> str | None:"""Try to download an attached file for this task. Returns local path or None."""url = f"{self.api_url}/files/{task_id}"try:resp = requests.get(url, timeout=15)if resp.status_code != 200 or not resp.content:return None# Try to infer filename/extension from headerscd = resp.headers.get("content-disposition", "")match = re.search(r'filename="?([^";]+)"?', cd)filename = match.group(1) if match else f"{task_id}_file"local_path = os.path.join("/tmp", filename)with open(local_path, "wb") as f:f.write(resp.content)return local_pathexcept Exception as e:print(f"No file downloaded for {task_id}: {e}")return Nonedef __call__(self, question: str, task_id: str | None = None) -> str:print(f"Agent received question (first 60 chars): {question[:60]}...")file_note = ""if task_id:local_path = self._download_file_if_any(task_id)if local_path:file_note = (f"\n\nA file has been downloaded for this task at local path: {local_path}\n"f"Use the read_downloaded_file tool with this exact path if the question requires it.")messages = [SystemMessage(content=SYSTEM_PROMPT),HumanMessage(content=question + file_note),]try:result = self.graph.invoke({"messages": messages}, config={"recursion_limit": 25})final_answer = str(result["messages"][-1].content).strip()except Exception as e:print(f"Agent error: {e}")final_answer = f"AGENT ERROR: {e}"print(f"Agent returning answer: {final_answer[:80]}")return final_answer# =========================================================# GRADIO APP (submission runner) — unchanged from template, wired to new agent# =========================================================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.")3 unmodified linesquestions_url = f"{api_url}/questions"submit_url = f"{api_url}/submit"try:agent = BasicAgent(api_url=api_url)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: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}", Noneresults_log = []answers_payload = []print(f"Running agent on {len(questions_data)} questions...")4 unmodified linesprint(f"Skipping item with missing task_id or question: {item}")continuetry:submitted_answer = agent(question_text, task_id=task_id)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=120)response.raise_for_status()result_data = response.json()final_status = (34 unmodified linesreturn status_message, results_dfwith gr.Blocks() as demo:gr.Markdown("# GAIA Agent Evaluation Runner (LangGraph)")gr.Markdown("""**Instructions:**1. Set `OPENAI_API_KEY` as a secret in your Space settings.2. Log in with the button below.3. Click 'Run Evaluation & Submit All Answers'.Note: this can take a while (multiple LLM + tool calls per question).""")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}")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}")else:print("ℹ️ SPACE_ID environment variable not found (running locally?).")print("-" * (60 + len(" App Starting ")) + "\n")print("Launching Gradio Interface for GAIA Agent Evaluation...")demo.launch(debug=True, share=False)
app.py+250-62