Spaces:
Sleeping
Sleeping
Update app.py
Browse files7 unmodified lines89101112131 unmodified line151617181920212223244 unmodified lines2930313233343536373839404142434445464734 unmodified lines82838485868788894 unmodified lines94959697989919 unmodified lines1191201211221231241251267 unmodified lines13413513613713813914037 unmodified lines17817918018118218318418 unmodified lines20320420520620720820921064 unmodified lines27527627727827928028111 unmodified lines29329429529629729829930010 unmodified lines31131231331431531631731826 unmodified lines3453463473483493503513523533543554 unmodified lines36036136236336436517 unmodified lines3833843853863873886 unmodified lines39539639739839940040122 unmodified lines4244254264274284294307 unmodified linesimport pandas as pdimport toolsfrom smolagents import CodeAgenttry:from smolagents import InferenceClientModel as _HFModel # smolagents >= 1.0except ImportError:1 unmodified linefrom smolagents.models import HfApiModel as _HFModelexcept ImportError:from smolagents import HfApiModel as _HFModelfrom typing import TypedDict, List, Dict, Any, Optionalfrom langgraph.graph import StateGraph, START, ENDfrom langchain_core.messages import HumanMessage# (Keep Constants as is)4 unmodified linesdef _build_hf_model(model_name: str):"""Build a text model across smolagents versions."""for kwargs in ({"model_id": model_name, "max_new_tokens": 2048, "temperature": 0.3},{"repo_id": model_name, "max_new_tokens": 2048, "temperature": 0.3},):try:return _HFModel(**kwargs)except (TypeError, Exception):continueraise RuntimeError(f"Cannot instantiate model {model_name} with available smolagents version")# Text/math models via smolagentsmodel = _build_hf_model("Qwen3.5-35B-A3B")math_model = _build_hf_model("Qwen/Qwen2.5-Math-1.5B")# FireRed OCR (Transformers) loaded lazily to avoid startup crashes_fire_red_model = None34 unmodified linesreturn str(content)return str(response)#define the stateclass AgentState(TypedDict):question: str4 unmodified linesis_math: Optional[bool]have_image: Optional[bool]final_answer: Optional[str] # The final answer produced by the agentmessages: List[Dict[str, Any]] # Track conversation with LLM for analysis#define nodes19 unmodified lines"have_image": false}}"""messages = [HumanMessage(content=prompt)]response = model.invoke(messages)# Parse JSON from the model's responseimport json, rematch = re.search(r'\{.*?\}', raw, re.DOTALL)7 unmodified lineshave_file = bool(data.get("have_file", False))is_math = bool(data.get("is_math", False))have_image = bool(data.get("have_image", False))print(f"Classification result: is_searching={is_searching}, have_file={have_file}, is_math={is_math}, have_image={have_image}")mew_messages = state.get("messages", []) + [{"role": "system", "content": "Classify the question to determine which tools to use."},37 unmodified lines# Use ImageReaderTool to download the image as base64image_reader = tools.ImageReaderTool()image_data_uri = image_reader(task_id) if task_id and file_name else ""if not image_data_uri or image_data_uri.startswith("Failed"):print(f"Could not download image for task {task_id}")18 unmodified lines"transcribed_text": "All text visible in the image transcribed here."}}"""try:# Decode base64 data URI into bytes/PIL image_, b64_data = image_data_uri.split(",", 1)64 unmodified lines# Use the file_reader tool to fetch the file contentfile_reader = tools.FileReaderTool()file_content = file_reader(task_id) if task_id and file_name else ""# Build prompt with the retrieved file contentfile_context = ""11 unmodified lines{{"extracted_info": "The relevant extracted information from the file."}}"""messages = [HumanMessage(content=prompt)]response = model.invoke(messages)extracted_info = _extract_text_from_response(response)print(f"Extracted file info: {extracted_info[:100]}...")new_messages = state.get("messages", []) + [10 unmodified lines"""Agent handles a math problem if classified as a math problem."""question = state["question"]print(f"Agent is handling a math problem: {question[:50]}...")messages = [HumanMessage(content=f"Solve the following math problem step by step:\n\n{question}")]response = math_model.invoke(messages)solution = _extract_text_from_response(response)print(f"Math solution: {solution[:100]}...")new_messages = state.get("messages", []) + [26 unmodified linesContext gathered:{context}"""messages = [HumanMessage(content=prompt)]# Use the general model for final answer synthesisresponse = model.invoke(messages)raw_response = _extract_text_from_response(response)# Extract the final answer after "FINAL ANSWER:" if presentif "FINAL ANSWER:" in raw_response:final_answer = raw_response.split("FINAL ANSWER:")[-1].strip()4 unmodified linesreturn {"final_answer": final_answer}def route_after_classify(state: AgentState) -> str:"""Routing function: decide which handler to invoke based on classification."""if state.get("have_image"):17 unmodified linesagent_graph.add_node("handle_file", handle_file)agent_graph.add_node("handle_math", handle_math)agent_graph.add_node("answer", answer)agent_graph.add_edge(START, "read")agent_graph.add_edge("read", "classify")6 unmodified linesagent_graph.add_edge("handle_image", "answer")agent_graph.add_edge("handle_file", "answer")agent_graph.add_edge("handle_math", "answer")agent_graph.add_edge("answer", END)compiled_agent = agent_graph.compile()22 unmodified lines"have_file": False,"is_math": False,"have_image": False,"final_answer": ""})# Extract the final answer from the state7 unmodified lines8910111213141 unmodified line161718192021222324252627284 unmodified lines33343536373839404142434445464748495051525334 unmodified lines8889909192934 unmodified lines989910010110210310419 unmodified lines1241251261271281291301311327 unmodified lines14014114214314414537 unmodified lines18318418518618718818918 unmodified lines20820921021121221321464 unmodified lines27928028128228328428511 unmodified lines29729829930030130230330410 unmodified lines31531631731831932032132226 unmodified lines3493503513523533543553563573583594 unmodified lines36436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441517 unmodified lines4334344354364374384396 unmodified lines44644744844945045145245345445545622 unmodified lines4794804814824834844854867 unmodified linesimport pandas as pdimport toolsfrom smolagents import CodeAgent# Resolve the correct LLM model class across smolagents versionstry:from smolagents import InferenceClientModel as _HFModel # smolagents >= 1.0except ImportError:1 unmodified linefrom smolagents.models import HfApiModel as _HFModelexcept ImportError:from smolagents import HfApiModel as _HFModelfrom typing import TypedDict, List, Dict, Any, Optionalfrom langgraph.graph import StateGraph, START, ENDfrom langchain_core.messages import HumanMessage # kept for LangGraph compatibility# Helper to build a smolagents-compatible message listdef _msg(content: str) -> list:return [{"role": "user", "content": content}]# (Keep Constants as is)4 unmodified linesdef _build_hf_model(model_name: str):"""Build a text model across smolagents versions."""for kwargs in ({"model_id": model_name, "max_tokens": 2048, "temperature": 0.3},{"model_id": model_name, "max_new_tokens": 2048, "temperature": 0.3},{"repo_id": model_name, "max_tokens": 2048, "temperature": 0.3},{"repo_id": model_name, "max_new_tokens": 2048, "temperature": 0.3},):try:return _HFModel(**kwargs)except TypeError:continueraise RuntimeError(f"Cannot instantiate model {model_name} with available smolagents version")# Text/math models via smolagentsmodel = _build_hf_model("meta-llama/Llama-3.2-3B-Instruct") # General model for classification and final answer synthesismath_model = _build_hf_model("deepseek-ai/deepseek-math-7b-instruct")# FireRed OCR (Transformers) loaded lazily to avoid startup crashes_fire_red_model = None34 unmodified linesreturn str(content)return str(response)#define the stateclass AgentState(TypedDict):question: str4 unmodified linesis_math: Optional[bool]have_image: Optional[bool]final_answer: Optional[str] # The final answer produced by the agentretry_count: Optional[int] # Number of retries so farmessages: List[Dict[str, Any]] # Track conversation with LLM for analysis#define nodes19 unmodified lines"have_image": false}}"""messages = _msg(prompt)response = model(messages)raw = _extract_text_from_response(response)# Parse JSON from the model's responseimport json, rematch = re.search(r'\{.*?\}', raw, re.DOTALL)7 unmodified lineshave_file = bool(data.get("have_file", False))is_math = bool(data.get("is_math", False))have_image = bool(data.get("have_image", False))print(f"Classification result: is_searching={is_searching}, have_file={have_file}, is_math={is_math}, have_image={have_image}")mew_messages = state.get("messages", []) + [{"role": "system", "content": "Classify the question to determine which tools to use."},37 unmodified lines# Use ImageReaderTool to download the image as base64image_reader = tools.ImageReaderTool()image_data_uri = image_reader(task_id, file_name) if task_id and file_name else ""if not image_data_uri or image_data_uri.startswith("Failed"):print(f"Could not download image for task {task_id}")18 unmodified lines"transcribed_text": "All text visible in the image transcribed here."}}"""# Run OCR through FireRed-OCR using Transformerstry:# Decode base64 data URI into bytes/PIL image_, b64_data = image_data_uri.split(",", 1)64 unmodified lines# Use the file_reader tool to fetch the file contentfile_reader = tools.FileReaderTool()file_content = file_reader(task_id, file_name) if task_id and file_name else ""# Build prompt with the retrieved file contentfile_context = ""11 unmodified lines{{"extracted_info": "The relevant extracted information from the file."}}"""messages = _msg(prompt)response = model(messages)extracted_info = _extract_text_from_response(response)print(f"Extracted file info: {extracted_info[:100]}...")new_messages = state.get("messages", []) + [10 unmodified lines"""Agent handles a math problem if classified as a math problem."""question = state["question"]print(f"Agent is handling a math problem: {question[:50]}...")messages = _msg(f"Solve the following math problem step by step:\n\n{question}")response = math_model(messages)solution = _extract_text_from_response(response)print(f"Math solution: {solution[:100]}...")new_messages = state.get("messages", []) + [26 unmodified linesContext gathered:{context}"""messages = _msg(prompt)# Use the general model for final answer synthesisresponse = model(messages)raw_response = _extract_text_from_response(response)# Extract the final answer after "FINAL ANSWER:" if presentif "FINAL ANSWER:" in raw_response:final_answer = raw_response.split("FINAL ANSWER:")[-1].strip()4 unmodified linesreturn {"final_answer": final_answer}def evaluate(state: AgentState) -> dict:"""LLM evaluates whether the current final_answer is adequate.If not, increments retry_count so the graph can loop back."""import json, requestion = state["question"]current_answer = state.get("final_answer", "")retry_count = state.get("retry_count", 0) or 0prompt = f"""You are a strict evaluator. Given the question and a candidate answer, decide if the answer is complete, relevant, and not an error message.Question: {question}Candidate answer: {current_answer}Return ONLY a JSON object:{{"is_adequate": true}} if the answer looks correct and complete,{{"is_adequate": false}} if the answer is wrong, incomplete, an error, or just says it could not find information."""response = model(_msg(prompt))raw = _extract_text_from_response(response)match = re.search(r'\{.*?\}', raw, re.DOTALL)data = {}if match:try:data = json.loads(match.group())except json.JSONDecodeError:passis_adequate = bool(data.get("is_adequate", True)) # default: acceptprint(f"Evaluation: is_adequate={is_adequate}, retry_count={retry_count}")return {"retry_count": retry_count + (0 if is_adequate else 1),"is_searching": False if not is_adequate else state.get("is_searching"),"have_file": False if not is_adequate else state.get("have_file"),"is_math": False if not is_adequate else state.get("is_math"),"have_image": False if not is_adequate else state.get("have_image"),}def route_after_evaluate(state: AgentState) -> str:"""If answer was inadequate and retries remain, search web for more context."""retry_count = state.get("retry_count", 0) or 0if retry_count > 0 and retry_count <= 2:print(f"Answer inadequate — retry {retry_count}/2, routing to web search")return "handle_search"return ENDdef route_after_classify(state: AgentState) -> str:"""Routing function: decide which handler to invoke based on classification."""if state.get("have_image"):17 unmodified linesagent_graph.add_node("handle_file", handle_file)agent_graph.add_node("handle_math", handle_math)agent_graph.add_node("answer", answer)agent_graph.add_node("evaluate", evaluate)agent_graph.add_edge(START, "read")agent_graph.add_edge("read", "classify")6 unmodified linesagent_graph.add_edge("handle_image", "answer")agent_graph.add_edge("handle_file", "answer")agent_graph.add_edge("handle_math", "answer")agent_graph.add_edge("answer", "evaluate")agent_graph.add_conditional_edges("evaluate",route_after_evaluate,)compiled_agent = agent_graph.compile()22 unmodified lines"have_file": False,"is_math": False,"have_image": False,"final_answer": "","retry_count": 0})# Extract the final answer from the state
app.py+79-23