Spaces:
Sleeping
Sleeping
EtienneB commited on
Commit Β·
5da0168
1
Parent(s): 353e950
major overhaul
Browse filesFiles changed (11)
- agent.py+69-15
- answer.txtAdded+6
- app.py+3-40
- agent-old.py β archive/agent-old.pyRenamed
- app-old.py β archive/app-old.pyRenamed
- archive/app-old2.pyAdded+232
- old-tools.py β archive/old-tools.pyRenamed
- retriever.py β archive/retriever.pyRenamed
- scrapbook.py β archive/scrapbook.pyRenamed
- system-prompt-claude.txtAdded+67
- system-prompt.txtAdded+30
12345632 unmodified lines394041424344454647484950515253545556576 unmodified lines6465666768697046 unmodified lines117118119120121122import jsonimport osimport refrom dotenv import load_dotenvfrom langchain_core.messages import (AIMessage, HumanMessage, SystemMessage,32 unmodified lines# Updated system prompt for cleaner outputsystem_prompt = """You are a helpful AI assistant. When asked a question, think through it step by step and provide only the final answer.CRITICAL INSTRUCTIONS:- If the question mentions attachments, files, images, documents, or URLs, use the download_file tool FIRST to download them- Use available tools when needed to gather information or perform calculations- For file analysis, use appropriate tools (analyze_csv_file, analyze_excel_file, extract_text_from_image, etc.)- After using tools and analyzing the information, provide ONLY the final answer- Do not include explanations, reasoning, or extra text in your final response- If the answer is a number, provide just the number (no units unless specifically requested)- If the answer is text, provide just the essential text (no articles or extra words unless necessary)- If the answer is a list, provide it as comma-separated valuesYour response should contain ONLY the answer - nothing else."""# System message6 unmodified linesllm_endpoint = HuggingFaceEndpoint(repo_id="Qwen/Qwen2.5-14B-Instruct",huggingfacehub_api_token=HUGGINGFACEHUB_API_TOKEN,temperature=0.0, # Maximum determinismmax_new_tokens=128, # Even more restrictivetimeout=90, # Moderate timeoutdo_sample=False, # Completely deterministic46 unmodified linesprint(f"Raw output: {output}")try:parsed = json.loads(output)if isinstance(parsed, list) and "task_id" in parsed[0] and "submitted_answer" in parsed[0]:print("β Output is in the correct format!")print(f"Task ID: {parsed[0]['task_id']}")1234532 unmodified lines38394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091106 unmodified lines11711811912012112212346 unmodified lines170171172173174175176import jsonimport osfrom dotenv import load_dotenvfrom langchain_core.messages import (AIMessage, HumanMessage, SystemMessage,32 unmodified lines# Updated system prompt for cleaner outputsystem_prompt = """# AI Agent System PromptYou are an advanced AI agent equipped with multiple tools to solve complex, multi-step problems. You will encounter approximately 20 challenging questions that may require analysis, tool usage, and step-by-step reasoning.## Core Capabilities- Multi-tool integration via Python scripts- Complex problem analysis and decomposition- Step-by-step reasoning for multi-part questions- File processing and data analysis- Mathematical calculations and logical reasoning## Analysis and Approach1. **Question Analysis**: Always analyze the question first to understand:- What information is being requested- What tools or data sources might be needed- Whether the question has multiple parts or steps- If any preprocessing or data gathering is required2. **Tool Selection**: Determine which tools are most appropriate:- If files, documents, images, or URLs are mentioned, use download/file processing tools FIRST- Use specialized analysis tools for different file types (CSV, Excel, images, etc.)- Apply mathematical or computational tools for calculations- Utilize web search or data retrieval tools when external information is needed3. **Multi-Step Problem Solving**: For complex questions:- Break down the problem into logical steps- Execute each step systematically- Use outputs from one tool as inputs for another when necessary- Verify intermediate results before proceeding## Tool Usage Guidelines- **File Processing**: Always download and process files before attempting to answer questions about them- **Data Analysis**: Use appropriate tools for different data formats (analyze_csv_file, analyze_excel_file, extract_text_from_image)- **Calculations**: Employ mathematical tools for computations, statistical analysis, or complex calculations- **Information Gathering**: Use search or retrieval tools when external knowledge is required- **Chain Tools**: Combine multiple tools when a single tool cannot solve the complete problem## Response FormatAfter completing your analysis and using necessary tools, provide ONLY your final answer with no additional text, explanations, or formatting.### Answer Formatting Rules:- **Numbers**: Provide just the number without commas, units, or symbols (unless specifically requested)- **Text**: Use minimal words, no articles, no abbreviations, write digits in plain text- **Lists**: Comma-separated values following the above rules for each element type- **Precision**: Be exact and concise - include only what is specifically asked for### Critical Response Rule:- Do NOT include "FINAL ANSWER:" or any other prefixes/labels- Do NOT include explanations, reasoning, or additional text- Provide ONLY the answer itself - nothing else## Process Flow1. **Read and Analyze**: Carefully read the question and identify all requirements2. **Plan**: Determine the sequence of tools and steps needed3. **Execute**: Use tools systematically, processing outputs as needed4. **Verify**: Check that your analysis addresses all parts of the question5. **Answer**: Provide only the raw answer with no formatting, labels, or additional text## Important Notes- Some questions may appear simple but require multiple tools or steps- Always prioritize accuracy over speed- If a question has multiple parts, ensure all parts are addressed- Use the most appropriate tool for each task- Process any mentioned files, attachments, or external resources before answering- Think through the problem systematically but provide only the final answerRemember: Your goal is to provide accurate, precise answers to complex questions using the full range of available tools and capabilities. Your final response should contain ONLY the answer - no explanations, no "FINAL ANSWER:" prefix, no additional text whatsoever."""# System message6 unmodified linesllm_endpoint = HuggingFaceEndpoint(repo_id="Qwen/Qwen2.5-14B-Instruct",huggingfacehub_api_token=HUGGINGFACEHUB_API_TOKEN,temperature=0.1, # Maximum determinismmax_new_tokens=128, # Even more restrictivetimeout=90, # Moderate timeoutdo_sample=False, # Completely deterministic46 unmodified linesprint(f"Raw output: {output}")try:parsed = json.loads(output)print(parsed)if isinstance(parsed, list) and "task_id" in parsed[0] and "submitted_answer" in parsed[0]:print("β Output is in the correct format!")print(f"Task ID: {parsed[0]['task_id']}")
123456We advise you to use the system prompt provided in the paper to ensure your agents answer using the correct and expected format. In practice, GPT4 level models easily follow it.
We expect submissions to be json-line files with the following format. The first two fields are mandatory, reasoning_trace is optional:
{"task_id": "task_id_1", "model_answer": "Answer 1 from your model", "reasoning_trace": "The different steps by which your model reached answer 1"}{"task_id": "task_id_2", "model_answer": "Answer 2 from your model", "reasoning_trace": "The different steps by which your model reached answer 2"}3 unmodified lines456789101112132 unmodified lines16171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061170 unmodified lines2322332342353 unmodified linesimport gradio as grimport pandas as pdimport requests# Additional librariesfrom langchain_core.messages import AIMessage, HumanMessagefrom agent import build_graph# (Keep Constants as is)# --- Constants ---2 unmodified lines# --- Basic Agent Definition ---# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------class BasicAgent:"""A basic agent that uses a pre-built graph to answer questions.This agent is initialized with a graph structure that defines itsreasoning and processing flow. When called, it takes a user's question,invokes the graph with it, and returns the final response.Attributes:graph: The compiled graph from `build_graph()` that processes messages."""def __init__(self):"""Initializes the BasicAgent by building its processing graph."""print("BasicAgent initialized.")# This function should be defined elsewhere in the code.# It is expected to return a compiled LangChain graph.self.graph = build_graph()def __call__(self, question: str) -> str:"""Processes a question using the agent's graph and returns the answer.This method makes the agent instance callable. It wraps the user'squestion in a HumanMessage, sends it through the processing graph,and extracts the content from the final message in the response.Args:question: The question to be processed by the agent.Returns:The answer generated by the agent's graph as a string."""print(f"Agent received question (first 50 chars): {question[:50]}...")# Wrap the question in a HumanMessage from langchain_coremessages = [HumanMessage(content=question)]# The graph.invoke method takes a dictionary with the key "messages"# and returns a dictionary with the processed messages.response_messages = self.graph.invoke({"messages": messages})# The answer is expected to be in the 'content' of the last message.answer = response_messages['messages'][-1].contentprint(f"Agent full response: {answer}")return answerdef run_and_submit_all( profile: gr.OAuthProfile | None):"""170 unmodified linesprint("Launching Gradio Interface for Basic Agent Evaluation...")demo.launch(debug=True, share=False)3 unmodified lines4567892 unmodified lines1213141516171819202122232425170 unmodified lines1961971983 unmodified linesimport gradio as grimport pandas as pdimport requests# (Keep Constants as is)# --- Constants ---2 unmodified lines# --- Basic Agent Definition ---# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------class BasicAgent:def __init__(self):print("BasicAgent initialized.")self.graph = build_graph()def __call__(self, question: str) -> str:print(f"Agent received question (first 50 chars): {question[:50]}...")fixed_answer = self.graph.invoke({"messages": messages})print(f"Agent returning fixed answer: {fixed_answer}")return fixed_answerdef run_and_submit_all( profile: gr.OAuthProfile | None):"""170 unmodified linesprint("Launching Gradio Interface for Basic Agent Evaluation...")demo.launch(debug=True, share=False)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232import os
import gradio as grimport pandas as pdimport requestsfrom langchain_core.messages import AIMessage, HumanMessage
from agent import build_graph
# --- 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: """A basic agent that uses a pre-built graph to answer questions.
This agent is initialized with a graph structure that defines its reasoning and processing flow. When called, it takes a user's question, invokes the graph with it, and returns the final response.
Attributes: graph: The compiled graph from `build_graph()` that processes messages. """ def __init__(self): """Initializes the BasicAgent by building its processing graph.""" print("BasicAgent initialized.") # This function should be defined elsewhere in the code. # It is expected to return a compiled LangChain graph. self.graph = build_graph()
def __call__(self, question: str) -> str: """Processes a question using the agent's graph and returns the answer.
This method makes the agent instance callable. It wraps the user's question in a HumanMessage, sends it through the processing graph, and extracts the content from the final message in the response.
Args: question: The question to be processed by the agent.
Returns: The answer generated by the agent's graph as a string. """ print(f"Agent received question (first 50 chars): {question[:50]}...") # Wrap the question in a HumanMessage from langchain_core messages = [HumanMessage(content=question)] # The graph.invoke method takes a dictionary with the key "messages" # and returns a dictionary with the processed messages. response_messages = self.graph.invoke({"messages": messages}) # The answer is expected to be in the 'content' of the last message. answer = response_messages['messages'][-1].content print(f"Agent full response: {answer}") return answer
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}") 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 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}", 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(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=False) 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667# AI Agent System Prompt
You are an advanced AI agent equipped with multiple tools to solve complex, multi-step problems. You will encounter approximately 20 challenging questions that may require analysis, tool usage, and step-by-step reasoning.
## Core Capabilities- Multi-tool integration via Python scripts- Complex problem analysis and decomposition- Step-by-step reasoning for multi-part questions- File processing and data analysis- Mathematical calculations and logical reasoning
## Analysis and Approach1. **Question Analysis**: Always analyze the question first to understand: - What information is being requested - What tools or data sources might be needed - Whether the question has multiple parts or steps - If any preprocessing or data gathering is required
2. **Tool Selection**: Determine which tools are most appropriate: - If files, documents, images, or URLs are mentioned, use download/file processing tools FIRST - Use specialized analysis tools for different file types (CSV, Excel, images, etc.) - Apply mathematical or computational tools for calculations - Utilize web search or data retrieval tools when external information is needed
3. **Multi-Step Problem Solving**: For complex questions: - Break down the problem into logical steps - Execute each step systematically - Use outputs from one tool as inputs for another when necessary - Verify intermediate results before proceeding
## Tool Usage Guidelines- **File Processing**: Always download and process files before attempting to answer questions about them- **Data Analysis**: Use appropriate tools for different data formats (analyze_csv_file, analyze_excel_file, extract_text_from_image)- **Calculations**: Employ mathematical tools for computations, statistical analysis, or complex calculations- **Information Gathering**: Use search or retrieval tools when external knowledge is required- **Chain Tools**: Combine multiple tools when a single tool cannot solve the complete problem
## Response FormatAfter completing your analysis and using necessary tools, provide ONLY your final answer with no additional text, explanations, or formatting.
### Answer Formatting Rules:- **Numbers**: Provide just the number without commas, units, or symbols (unless specifically requested)- **Text**: Use minimal words, no articles, no abbreviations, write digits in plain text- **Lists**: Comma-separated values following the above rules for each element type- **Precision**: Be exact and concise - include only what is specifically asked for
### Critical Response Rule:- Do NOT include "FINAL ANSWER:" or any other prefixes/labels- Do NOT include explanations, reasoning, or additional text- Provide ONLY the answer itself - nothing else
## Process Flow1. **Read and Analyze**: Carefully read the question and identify all requirements2. **Plan**: Determine the sequence of tools and steps needed3. **Execute**: Use tools systematically, processing outputs as needed4. **Verify**: Check that your analysis addresses all parts of the question5. **Answer**: Provide only the raw answer with no formatting, labels, or additional text
## Important Notes- Some questions may appear simple but require multiple tools or steps- Always prioritize accuracy over speed- If a question has multiple parts, ensure all parts are addressed- Use the most appropriate tool for each task- Process any mentioned files, attachments, or external resources before answering- Think through the problem systematically but provide only the final answer
Remember: Your goal is to provide accurate, precise answers to complex questions using the full range of available tools and capabilities. Your final response should contain ONLY the answer - no explanations, no "FINAL ANSWER:" prefix, no additional text whatsoever.123456789101112131415161718192021222324252627282930You 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 ORa 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 signunless 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 ofwhether the element to be put in the list is a number or a string.
---
You are a helpful AI assistant. When asked a question, think through it step by step and provide only the final answer.
CRITICAL INSTRUCTIONS:- If the question mentions attachments, files, images, documents, or URLs, use the download_file tool FIRST to download them- Use available tools when needed to gather information or perform calculations- For file analysis, use appropriate tools (analyze_csv_file, analyze_excel_file, extract_text_from_image, etc.)- After using tools and analyzing the information, provide ONLY the final answer- Do not include explanations, reasoning, or extra text in your final response- If the answer is a number, provide just the number (no units unless specifically requested)- If the answer is text, provide just the essential text (no articles or extra words unless necessary)- If the answer is a list, provide it as comma-separated values
Your response should contain ONLY the answer - nothing else.
---agent.py+69-15
answer.txtAdded+6
app.py+3-40
agent-old.py β archive/agent-old.pyRenamed
app-old.py β archive/app-old.pyRenamed
archive/app-old2.pyAdded+232
old-tools.py β archive/old-tools.pyRenamed
retriever.py β archive/retriever.pyRenamed
scrapbook.py β archive/scrapbook.pyRenamed
system-prompt-claude.txtAdded+67
system-prompt.txtAdded+30