import inspect import os import re from typing import Any, Dict, List, Optional, TypedDict import gradio as gr import pandas as pd import requests import wikipedia import wikipediaapi from bs4 import BeautifulSoup from langchain_community.retrievers import WikipediaRetriever from langchain_community.tools import DuckDuckGoSearchRun, WikipediaQueryRun from langchain_community.utilities import WikipediaAPIWrapper from langchain_core import messages from langchain_core.messages import ( BaseMessage, ChatMessage, HumanMessage, SystemMessage, ToolCall, ToolMessage, ) from langchain_google_community.search import GoogleSearchAPIWrapper from langchain_openai import ChatOpenAI from langgraph.graph import END, START, StateGraph hf_token = os.getenv("OPENAI_API_KEY") # (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 ------ PROMPT = """ You are a general AI assistant. I will ask you a question. Report your thoughts,always use at least 2 sources to double check your answer, 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. Use the following process to answer the question: 1. Analyze and Plan: Extract ALL Parameters Identify search terms, URLs, code, file paths Plan Steps: Break down the problem into logical steps required to reach the final answer 2. Delegate Strategically For each step, choose the best Agent Tool. Call the tool with a single string argument `request` containing ALL information the specialist needs Available Tools: `DuckDuckGoSearchAgent`, `CodeExecutorAgent`, `WikipediaAgent` - For wikipedia searches, **strongly prefer** `WikipediaAgent` formatting the query like WikipediaAgent(`request`='search query'), if duckduckgosearchagent is not providing the exact information but its response can be used to refine a wikipedia query, try doing that as well - For general web searches, **strongly prefer** `DuckDuckGoSearchAgent` formatting the query like DuckDuckGoSearchAgent(`request`='search query') where search query is very specific - For standard Python code execution, **strongly prefer** `CodeExecutorAgent` formatting the query like CodeExecutorAgent(`request`='python code') 3. Synthesize Results: Combine the information obtained from the specialist agents Perform any final reasoning or calculation steps needed based on the collected data Double-check that the synthesized answer directly addresses the original question and respects ALL specific formatting or content details requested (e.g., rounding, order, units IF asked for).\n" 4. Format Output: Last sentence should of your response shoule either: - start **EXACTLY** with `FINAL ANSWER: ` followed by the answer. - OR start **EXACTLY** with `TOOL: ` followed by the tool name and the request to the tool, example `TOOL: DuckDuckGoSearchAgent(request='search query')` Before answering reread the question and make sure you are answering the exact question asked. """ class AnswerState(TypedDict): question: str task_id: str attempt: int answer: Optional[str] messages: List[BaseMessage] is_final_answer: bool search_request: Optional[str] wiki_request: Optional[str] python_request: Optional[str] class BasicAgent: def __init__(self): self.model = ChatOpenAI(model="gpt-4o", temperature=0.0) self.graph = StateGraph(AnswerState) self.graph.add_node("log_question", self.log_question) self.graph.add_node("get_attachment", self.get_attachment) self.graph.add_node("invoke_model", self.invoke_model) self.graph.add_node("web_search", self.web_search) self.graph.add_node("wiki_search", self.wiki_search) self.graph.add_node("python_exec", self.python_exec) self.graph.add_node("decide", self.decide) self.graph.add_node("final_answer", self.final_answer) self.graph.add_node("exceeded_attempts", self.exceeded_attempts) self.graph.add_edge(START, "log_question") self.graph.add_edge("log_question", "get_attachment") self.graph.add_edge("get_attachment", "invoke_model") self.graph.add_edge("web_search", "invoke_model") self.graph.add_edge("wiki_search", "invoke_model") self.graph.add_edge("python_exec", "invoke_model") # Add conditional edges self.graph.add_conditional_edges( "invoke_model", self.decide, { "FINAL_ANSWER": "final_answer", "EXCEEDED_ATTEMPTS": "exceeded_attempts", "WEB_SEARCH": "web_search", "WIKI_SEARCH": "wiki_search", "PYTHON_EXEC": "python_exec", }, ) self.graph.add_edge("final_answer", END) self.graph.add_edge("exceeded_attempts", END) self.compiled_graph = self.graph.compile() def __call__(self, task_id: str, question: str) -> str: print(f"Agent received question (first 50 chars) {task_id}: {question[:50]}...") res = self.compiled_graph.invoke( { "question": question, "task_id": task_id, "attempt": 0, "answer": None, "messages": [], "is_final_answer": False, "search_request": None, "wiki_request": None, "python_request": None, } ) return res.get("answer", "N/A") def log_question(self, state: AnswerState) -> Dict[str, Any]: print( f"[log_question] Agent received question {state['task_id']}: {state['question']}..." ) state["messages"] = [SystemMessage(content=PROMPT)] state["messages"].append(HumanMessage(content="Question: " + state["question"])) return { "messages": state["messages"], } def get_attachment(self, state: AnswerState) -> Dict[str, Any]: print(f"[get_attachment] getting attachment for: {state['task_id']}...") api_url = DEFAULT_API_URL file_url = f"{api_url}/files/{state['task_id']}" try: response = requests.get(file_url, timeout=15) response.raise_for_status() data = response.text state["messages"].append(HumanMessage(content="Attachment: " + data)) return { "messages": state["messages"], } except Exception as e: print(f"An unexpected error occurred fetching attachment: {e}") return {} def final_answer(self, state: AnswerState) -> Dict[str, Any]: print(f"[final_answer] Agent returning answer: {state['answer']}") answer = state["answer"] if state["answer"] else "I don't know" return { "answer": answer, "is_final_answer": True, } def wiki_search(self, state: AnswerState) -> Dict[str, Any]: print("[wiki_search] Searching for: " + str(state["wiki_request"])) # wikipedia.set_lang("en") # page_titles = wikipedia.search(state["wiki_request"], results=1) # print("[wiki_search] Fetching the whole page") # wiki = wikipediaapi.Wikipedia(language="en", user_agent="gaia_example") # page = wiki.page(page_titles[0]) # if page.exists(): # html_url = f"https://en.wikipedia.org/wiki/{page.title.replace(' ', '_')}" # html = requests.get(html_url).text # soup = BeautifulSoup(html, "html.parser") # state["messages"].append( # ChatMessage( # role="user", content="WikipediaAgent tool results are: " + str(html) # ) # ) # return {"messages": state["messages"]} print("[wiki_search] Fetching the page via wikiRetriever") wiki_tool = WikipediaRetriever( wiki_client=wikipedia, top_k_results=1, doc_content_chars_max=50000, load_all_available_meta=True, ) results = wiki_tool.invoke(str(state["wiki_request"])) if results: print(f"Wiki results: {results[0].page_content}") state["messages"].append( ChatMessage( role="user", content="WikipediaAgent tool results are: " + results[0].page_content, ) ) return {"messages": state["messages"]} print("[wiki_search] Fetching the page via WikipediaAPIWrapper") wiki_tool = WikipediaAPIWrapper( wiki_client=wikipedia, top_k_results=1, doc_content_chars_max=50000, load_all_available_meta=True, ) results = wiki_tool.run(str(state["wiki_request"])) print(f"Wiki results: {results}") state["messages"].append( ChatMessage( role="user", content="WikipediaAgent tool results are: " + results, ) ) return {"messages": state["messages"]} def python_exec(self, state: AnswerState) -> Dict[str, Any]: print("[python_exec] Executing: " + str(state["python_request"])) import contextlib import io # Redirect stdout to capture output output = io.StringIO() sandbox_globals = {} sandbox_locals = {} with contextlib.redirect_stdout(output): exec(str(state["python_request"]), sandbox_globals, sandbox_locals) res = output.getvalue() print(f"Python results: {res}") state["messages"].append( ChatMessage( role="user", content="CodeExecutorAgent tool results are: " + res, ) ) return {"messages": state["messages"]} def web_search(self, state: AnswerState) -> Dict[str, Any]: print("[web_search] Searching for: " + str(state["search_request"])) search_tool = GoogleSearchAPIWrapper() results = search_tool.run(str(state["search_request"])) print(f"Search results: {results}") state["messages"].append( ChatMessage( role="user", content="DuckDuckGoSearchAgent tool results are: " + results, ) ) return {"messages": state["messages"]} def exceeded_attempts(self, state: AnswerState) -> Dict[str, Any]: print( f"[exceeded_attempts] Exceeded max number of attempts ({state['attempt']})." ) state["messages"].append( ChatMessage( role="user", content="Based on the information provided and your internal knowledge, please provide a final answer, no tool calls allowed.", ) ) response = self.model.invoke(state["messages"]) if "FINAL ANSWER:" in response.content: answer = response.text().split("FINAL ANSWER:")[-1].strip() print(f"Agent final answer: {answer}") return { "answer": answer, "is_final_answer": True, } return { "answer": "Exceeded max number of attempts.", "is_final_answer": False, } def decide(self, state: AnswerState) -> str: print("[parse_response] parsing last chat response") if state["is_final_answer"]: return "FINAL_ANSWER" elif state["attempt"] > 4: return "EXCEEDED_ATTEMPTS" elif state["search_request"]: return "WEB_SEARCH" elif state["wiki_request"]: return "WIKI_SEARCH" elif state["python_request"]: return "PYTHON_EXEC" return "FINAL_ANSWER" def invoke_model(self, state: AnswerState) -> Dict[str, Any]: print("[invoke_model] Agent trying to answer") state["search_request"] = None state["wiki_request"] = None state["python_request"] = None response = self.model.invoke(state["messages"]) print(f"Agent response: {response.content}") state["messages"].append( ChatMessage( role="assistant", content=response.content, ) ) if "FINAL ANSWER:" in response.content: answer = response.text().split("FINAL ANSWER:")[-1].strip() print(f"Agent final answer: {answer}") print(f"Agent returning answer: {state['answer']}") state["answer"] = answer state["is_final_answer"] = True elif "TOOL: DuckDuckGoSearchAgent" in response.content: request_full = ( response.text().split("TOOL: DuckDuckGoSearchAgent(")[-1].strip(")") ) print(f"Tool invocation request: {request_full}") request = request_full.split("request=")[-1].strip("'") print(f"Search request: {request}") state["search_request"] = request elif "TOOL: WikipediaAgent" in response.content: request_full = response.text().split("TOOL: WikipediaAgent(")[-1].strip(")") print(f"Tool invocation request: {request_full}") request = request_full.split("request=")[-1].strip("'") print(f"Wiki request: {request}") state["wiki_request"] = request elif "TOOL: CodeExecutorAgent" in response.content: request_full = response.text().split("TOOL: WikipediaAgent(")[-1].strip(")") print(f"Tool invocation request: {request_full}") request = request_full.split("request=")[-1].strip("'") print(f"Python request: {request}") state["python_request"] = request return { "messages": state["messages"], "attempt": state.get("attempt", 0) + 1, "answer": state["answer"], "is_final_answer": state["is_final_answer"], "search_request": state["search_request"], "wiki_request": state["wiki_request"], } def 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 code 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" # 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 Questions print(f"Fetching questions from: {questions_url}") response = None 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.JSONDecodeError as e: print(f"Error decoding JSON response from questions endpoint: {e}") if response: print(f"Response text: {response.text[:500]}") return f"Error decoding server response for questions: {e}", None except requests.exceptions.RequestException as e: print(f"Error fetching questions: {e}") return f"Error fetching 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 # 3. Run your Agent 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(task_id, 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 Submission 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) # 5. Submit 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 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_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 # --- 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 constructor 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) # Check for SPACE_HOST and SPACE_ID at startup for information space_host_startup = os.getenv("SPACE_HOST") space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup 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 repo URLs if SPACE_ID is found 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=True)