Spaces:
Sleeping
Sleeping
Update app.py
Browse files13 unmodified lines141516171819202124 unmodified lines46474849505143 unmodified lines959697989910010115 unmodified lines11711811912012112212322 unmodified lines1461471481491501511521531541551565 unmodified lines16216316416516616716814 unmodified lines1831841851861871881891901911921931941951961971981993 unmodified lines2032042052062072082092105 unmodified lines21621721821922022122210 unmodified lines2332342352362372382397 unmodified lines2472482492502512522536 unmodified lines26026126226326426526617 unmodified lines28428528628728828929020 unmodified lines3113123133143153163173183197 unmodified lines32732832933033133233313 unmodified linesfrom tenacity import retry, stop_after_attempt, wait_exponentialimport ioimport sys# Set recursion limit for Python and LangGraphsys.setrecursionlimit(1500)# --- Setup Logging ---24 unmodified lineslogging.warning(f"All retries failed for query '{query}'. Falling back to reasoning.")return "Web search failed; using reasoning."# --- Answer Formatting ---def format_answer(answer: str, question: str) -> str:"""Post-process answers to match GAIA's exact-match requirements."""43 unmodified linesmessages: Annotated[List, add_messages]question: strtask_id: strfile_data: pd.DataFrame | Nonesearch_result: stranswer: strattempts: int15 unmodified linesAnalyze the question to determine the required action:- List tasks (keywords: "list," "comma-separated," "categorize"): Action: reason, Input: none- File tasks (keywords: "attached," "Excel," "spreadsheet", ".mp3"): Action: fetch_file, Input: none- Search tasks (keywords: "who," "when," "historical," "competition", "wikipedia"): Action: search, Input: specific query- Number tasks (keywords: "how many," "count"): Action: search, Input: specific query- Fallback: Action: reason, Input: none22 unmodified linesSteps:1. Analyze question format (list, USD, name, number).2. Use data:- File: Analyze DataFrame (e.g., sum sales where 'Category' != 'Drink').- Search: Extract names, numbers, codes.3. Reason:- Lists: Filter, alphabetize.- Files: Sum columns, handle missing data.- Search: Parse for key info.4. Format:- Lists: 'item1, item2' (alphabetized).5 unmodified linesSpecific instructions:- Mercedes Sosa studio albums (2000-2009): Misa Criolla (2000), Acústico (2002), Corazón Libre (2005), Cantora 1 (2009), Cantora 2 (2009). Answer: 5- Vegetable lists: Only non-botanical fruits (broccoli, celery, fresh basil, green beans, lettuce, sweet potatoes).- .mp3 files: Return 'ERROR: Audio transcription not supported'.Examples:- Q: List of vegetables...14 unmodified linesValidate the answer:- Check format (list, USD, name, number).- Verify relevance.- Return 'valid' or 'invalid: [reason]'.- Numbers: Ensure non-negative for counts.- Allow reasonable answers even if not perfect to avoid excessive retries.Question: {question}Answer: {answer}""")self.graph = self._build_graph()async def fetch_file(self, task_id: str) -> pd.DataFrame | None:@retry(stop=stop_after_attempt(6), wait=wait_exponential(multiplier=1, min=2, max=5))def _fetch():file_url = f"{self.api_url}/files/{task_id}"3 unmodified linescontent = io.BytesIO(response.content)if file_url.endswith('.xlsx') or file_url.endswith('.xls'):df = pd.read_excel(content)logging.info(f"File fetched. Shape: {df.shape}, Columns: {list(df.columns)}")return dflogging.warning(f"Unsupported file type for task {task_id}")return None5 unmodified linesdef _build_graph(self):workflow = StateGraph(AgentState)# Set higher recursion limit for LangGraphworkflow.config = {"recursion_limit": 50}def classify(state: AgentState) -> AgentState:10 unmodified linestask_id=state["task_id"],attempts=state["attempts"]))response_content = str(response.content)action = response_content.split("Action: ")[1].split("\n")[0].strip() if "Action: " in response_content else "reason"action_input = response_content.split("Input: ")[1].strip() if "Input: " in response_content else "none"except Exception as e:7 unmodified linesasync def fetch_file_node(state: AgentState) -> AgentState:logging.info(f"Fetching file for task {state['task_id']}")if state["file_data"] is None and state["attempts"] < 3:try:state["file_data"] = await asyncio.wait_for(self.fetch_file(state["task_id"]), timeout=30)state["messages"].append(f"Fetched file: {state['file_data'] is not None}")6 unmodified linesasync def search_node(state: AgentState) -> AgentState:logging.info(f"Searching for task {state['task_id']}")if state["attempts"] < 3:action_input = state["action_input"]if action_input != "none":try:17 unmodified linesdef generate_answer(state: AgentState) -> AgentState:logging.info(f"Generating answer for task {state['task_id']}")file_data_str = state["file_data"].to_dict() if state["file_data"] is not None else "none"try:response = self.llm.invoke(self.answer_prompt.format(question=state["question"],20 unmodified lineslogging.error(f"Critique error: {str(e)}")critique = "valid" # Avoid looping on critique failurestate["messages"].append(f"Critique: {critique}")# Stricter exit condition to prevent infinite loopsstate["attempts"] += 1if "invalid" in critique.lower() and state["attempts"] < 2:state["action"] = "reason"state["action_input"] = "none"else:7 unmodified linesworkflow.add_node("critique", critique_answer)def route_action(state: AgentState) -> str:if state["attempts"] >= 3 or state["action"] is None:return ENDreturn state["action"] if state["action"] in ["fetch_file", "search", "reason"] else "generate_answer"13 unmodified lines1415161718192021222324 unmodified lines484950515253545556575859606162636465666768697043 unmodified lines11411511611711811912015 unmodified lines13613713813914014114222 unmodified lines1651661671681691701711721731741755 unmodified lines18118218318418518618718814 unmodified lines2032042052062072082092102112122132142152162172182193 unmodified lines2232242252262272282292302312322332342352365 unmodified lines24224324424524624724810 unmodified lines2592602612622632642657 unmodified lines2732742752762772782796 unmodified lines28628728828929029129217 unmodified lines31031131231331431531631731831932032132232320 unmodified lines3443453463473483493503517 unmodified lines35936036136236336436513 unmodified linesfrom tenacity import retry, stop_after_attempt, wait_exponentialimport ioimport sysimport speech_recognition as srimport tempfile# Set recursion limit for Pythonsys.setrecursionlimit(1500)# --- Setup Logging ---24 unmodified lineslogging.warning(f"All retries failed for query '{query}'. Falling back to reasoning.")return "Web search failed; using reasoning."# --- Audio Transcription ---def transcribe_audio(file_content: bytes) -> str:try:recognizer = sr.Recognizer()with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as temp_file:temp_file.write(file_content)temp_file_path = temp_file.namewith sr.AudioFile(temp_file_path) as source:audio = recognizer.record(source)text = recognizer.recognize_google(audio)os.unlink(temp_file_path)logging.info(f"Transcribed audio: {text[:200]}...")return textexcept Exception as e:logging.error(f"Audio transcription failed: {str(e)}")return "ERROR: Audio transcription failed"# --- Answer Formatting ---def format_answer(answer: str, question: str) -> str:"""Post-process answers to match GAIA's exact-match requirements."""43 unmodified linesmessages: Annotated[List, add_messages]question: strtask_id: strfile_data: pd.DataFrame | bytes | Nonesearch_result: stranswer: strattempts: int15 unmodified linesAnalyze the question to determine the required action:- List tasks (keywords: "list," "comma-separated," "categorize"): Action: reason, Input: none- File tasks (keywords: "attached," "Excel," "spreadsheet", ".mp3", "image"): Action: fetch_file, Input: none- Search tasks (keywords: "who," "when," "historical," "competition", "wikipedia"): Action: search, Input: specific query- Number tasks (keywords: "how many," "count"): Action: search, Input: specific query- Fallback: Action: reason, Input: none22 unmodified linesSteps:1. Analyze question format (list, USD, name, number).2. Use data:- File: Analyze DataFrame, audio transcript, or image description.- Search: Extract names, numbers, codes.3. Reason:- Lists: Filter, alphabetize.- Files: Sum columns, extract text, or describe visuals.- Search: Parse for key info.4. Format:- Lists: 'item1, item2' (alphabetized).5 unmodified linesSpecific instructions:- Mercedes Sosa studio albums (2000-2009): Misa Criolla (2000), Acústico (2002), Corazón Libre (2005), Cantora 1 (2009), Cantora 2 (2009). Answer: 5- Vegetable lists: Only non-botanical fruits (broccoli, celery, fresh basil, green beans, lettuce, sweet potatoes).- .mp3 files: Transcribe audio and extract relevant info.- Image-based (e.g., chess): Describe image or return error if no image provided.Examples:- Q: List of vegetables...14 unmodified linesValidate the answer:- Check format (list, USD, name, number).- Verify relevance to question.- Return 'valid' or 'invalid: [reason]'.- Numbers: Ensure non-negative for counts.- Allow reasonable answers to avoid excessive retries.Question: {question}Answer: {answer}""")self.graph = self._build_graph()async def fetch_file(self, task_id: str) -> pd.DataFrame | bytes | None:@retry(stop=stop_after_attempt(6), wait=wait_exponential(multiplier=1, min=2, max=5))def _fetch():file_url = f"{self.api_url}/files/{task_id}"3 unmodified linescontent = io.BytesIO(response.content)if file_url.endswith('.xlsx') or file_url.endswith('.xls'):df = pd.read_excel(content)logging.info(f"Excel file fetched. Shape: {df.shape}, Columns: {list(df.columns)}")return dfelif file_url.endswith('.mp3'):logging.info("Audio file fetched.")return response.contentelif file_url.endswith('.png') or file_url.endswith('.jpg'):logging.info("Image file fetched.")return response.contentlogging.warning(f"Unsupported file type for task {task_id}")return None5 unmodified linesdef _build_graph(self):workflow = StateGraph(AgentState)# Explicitly set recursion limitworkflow.config = {"recursion_limit": 50}def classify(state: AgentState) -> AgentState:10 unmodified linestask_id=state["task_id"],attempts=state["attempts"]))response_content = str(response.content).strip()action = response_content.split("Action: ")[1].split("\n")[0].strip() if "Action: " in response_content else "reason"action_input = response_content.split("Input: ")[1].strip() if "Input: " in response_content else "none"except Exception as e:7 unmodified linesasync def fetch_file_node(state: AgentState) -> AgentState:logging.info(f"Fetching file for task {state['task_id']}")if state["file_data"] is None and state["attempts"] < 2:try:state["file_data"] = await asyncio.wait_for(self.fetch_file(state["task_id"]), timeout=30)state["messages"].append(f"Fetched file: {state['file_data'] is not None}")6 unmodified linesasync def search_node(state: AgentState) -> AgentState:logging.info(f"Searching for task {state['task_id']}")if state["attempts"] < 2:action_input = state["action_input"]if action_input != "none":try:17 unmodified linesdef generate_answer(state: AgentState) -> AgentState:logging.info(f"Generating answer for task {state['task_id']}")file_data_str = "none"if isinstance(state["file_data"], pd.DataFrame):file_data_str = state["file_data"].to_dict()elif isinstance(state["file_data"], bytes):if "mp3" in state["question"].lower():file_data_str = transcribe_audio(state["file_data"])else:file_data_str = "Image data; cannot process directly."try:response = self.llm.invoke(self.answer_prompt.format(question=state["question"],20 unmodified lineslogging.error(f"Critique error: {str(e)}")critique = "valid" # Avoid looping on critique failurestate["messages"].append(f"Critique: {critique}")state["attempts"] += 1if "invalid" in critique.lower() and state["attempts"] < 1: # Reduced retries to 1state["action"] = "reason"state["action_input"] = "none"else:7 unmodified linesworkflow.add_node("critique", critique_answer)def route_action(state: AgentState) -> str:if state["attempts"] >= 2 or state["action"] is None:return ENDreturn state["action"] if state["action"] in ["fetch_file", "search", "reason"] else "generate_answer"
app.py+50-18