Download misc.py from JPM34/final_assignment_agentic_course: direct link, hf CLI and curl.
- Browser
- Download file 5.68 kB
-
https://huggingface.co/spaces/JPM34/final_assignment_agentic_course/resolve/main/misc.py
- Command line
-
hf download hf://spaces/JPM34/final_assignment_agentic_course/misc.py
-
curl -L -o misc.py https://huggingface.co/spaces/JPM34/final_assignment_agentic_course/resolve/main/misc.py
5.68 kB
| import os | |
| import tempfile | |
| from typing import Optional | |
| def save_test_file(task_id: str, content: str) -> str: | |
| """Save a test file to a temporary location.""" | |
| temp_dir = tempfile.gettempdir() | |
| file_path = os.path.join(temp_dir, f"test_file_{task_id}.csv") | |
| with open(file_path, "w") as f: | |
| f.write(content) | |
| return file_path | |
| def answer_question( | |
| agent, verbose, question: str, task_file_path: Optional[str] = None | |
| ) -> str: | |
| """ | |
| Process a GAIA benchmark question and return the answer | |
| Args: | |
| question: The question to answer | |
| task_file_path: Optional path to a file associated with the question | |
| Returns: | |
| The answer to the question | |
| """ | |
| try: | |
| if verbose: | |
| print(f"Processing question: {question}") | |
| if task_file_path: | |
| print(f"With associated file: {task_file_path}") | |
| # Create a context with file information if available | |
| context = question | |
| file_content = None | |
| # If there's a file, read it and include its content in the context | |
| if task_file_path: | |
| try: | |
| with open(task_file_path, "r") as f: | |
| file_content = f.read() | |
| # Determine file type from extension | |
| file_ext = os.path.splitext(task_file_path)[1].lower() | |
| context = f""" Question: {question} This question has an associated file. Here is the file content: ```{file_ext} {file_content}```Analyze the file content above to answer the question.""" | |
| except Exception as file_e: | |
| context = f""" Question: {question} This question has an associated file at path: {task_file_path}. However, there was an error reading the file: {file_e}. You can still try to answer the question based on the information provided.""" | |
| # Check for special cases that need specific formatting | |
| # Reversed text questions | |
| if question.startswith(".") or ".rewsna eht sa" in question: | |
| context = f""" This question appears to be in reversed text. Here's the reversed version: {question[::-1]} Now answer the question above. Remember to format your answer exactly as requested. """ | |
| # Add a prompt to ensure precise answers | |
| rules = "When answering, your 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, do not include brackets and apply the above rules depending of whether the element to be put in the list is a number or a string." | |
| # full_prompt = f"""{context}. When answering, provide ONLY the precise answer requested. Do not include explanations, steps, reasoning, or additional text. Be direct and specific. GAIA benchmark requires exact matching answers. For example, if asked "What is the capital of France?", respond simply with "Paris".""" | |
| full_prompt = f"""{context}. {rules}""" | |
| # Run the agent with the question | |
| answer = agent.run(full_prompt) | |
| # Clean up the answer to ensure it's in the expected format | |
| # Remove common prefixes that models often add | |
| answer = _clean_answer(answer) | |
| if verbose: | |
| print(f"Generated answer: {answer}") | |
| return answer | |
| except Exception as e: | |
| error_msg = f"Error answering question: {e}" | |
| if verbose: | |
| print(error_msg) | |
| return error_msg | |
| def _clean_answer(answer: any) -> str: | |
| """ | |
| Clean up the answer to remove common prefixes and formatting | |
| that models often add but that can cause exact match failures. | |
| Args: | |
| answer: The raw answer from the model | |
| Returns: | |
| The cleaned answer as a string | |
| """ | |
| # Convert non-string types to strings | |
| if not isinstance(answer, str): | |
| # Handle numeric types (float, int) | |
| if isinstance(answer, float): | |
| # Format floating point numbers properly | |
| # Check if it's an integer value in float form (e.g., 12.0) | |
| if answer.is_integer(): | |
| formatted_answer = str(int(answer)) | |
| else: | |
| # For currency values that might need formatting | |
| if abs(answer) >= 1000: | |
| formatted_answer = f"${answer:,.2f}" | |
| else: | |
| formatted_answer = str(answer) | |
| return formatted_answer | |
| elif isinstance(answer, int): | |
| return str(answer) | |
| else: | |
| # For any other type | |
| return str(answer) | |
| # Now we know answer is a string, so we can safely use string methods | |
| # Normalize whitespace | |
| answer = answer.strip() | |
| # Remove common prefixes and formatting that models add | |
| prefixes_to_remove = [ | |
| "The answer is ", | |
| "Answer: ", | |
| "Final answer: ", | |
| "The result is ", | |
| "To answer this question: ", | |
| "Based on the information provided, ", | |
| "According to the information: ", | |
| ] | |
| for prefix in prefixes_to_remove: | |
| if answer.startswith(prefix): | |
| answer = answer[len(prefix) :].strip() | |
| # Remove quotes if they wrap the entire answer | |
| if (answer.startswith('"') and answer.endswith('"')) or ( | |
| answer.startswith("'") and answer.endswith("'") | |
| ): | |
| answer = answer[1:-1].strip() | |
| return answer | |