Spaces:
Sleeping
Sleeping
Download agent.py from DiegoSanC/Final_Assignment_Template: direct link, hf CLI and curl.
- Browser
- Download file 19.4 kB
-
https://huggingface.co/spaces/DiegoSanC/Final_Assignment_Template/resolve/main/agent.py
- Command line
-
hf download hf://spaces/DiegoSanC/Final_Assignment_Template/agent.py
-
curl -L -o agent.py https://huggingface.co/spaces/DiegoSanC/Final_Assignment_Template/resolve/main/agent.py
19.4 kB
| from dotenv import load_dotenv | |
| from langchain_core.messages import SystemMessage, HumanMessage | |
| from langchain_openai import ChatOpenAI | |
| from langchain_google_genai import ChatGoogleGenerativeAI | |
| from langgraph.graph import StateGraph, START, MessagesState | |
| from langgraph.prebuilt import ToolNode, tools_condition | |
| import requests | |
| import base64 | |
| import tiktoken | |
| import logging | |
| import io | |
| from openpyxl import load_workbook | |
| from langg_agent_tools import (add, subtract, multiply, divide, modulo, wikipedia_search, | |
| arxiv_search, youtube_transcript, web_search_tavily) | |
| from langchain_experimental.tools import PythonREPLTool | |
| from system_prompts import system_prompt | |
| load_dotenv() | |
| logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') | |
| logger = logging.getLogger(__name__) | |
| # Create a Python REPL tool instance | |
| python_repl = PythonREPLTool() | |
| tools = [add, subtract, multiply, | |
| divide, modulo, wikipedia_search, | |
| youtube_transcript, python_repl, web_search_tavily] | |
| system_message = SystemMessage(content=system_prompt) | |
| class LangGraphAgent: | |
| def __init__(self, tasks_api: str): | |
| self.llm = ChatOpenAI(model="o4-mini", max_retries=2) | |
| #self.llm = ChatOpenAI(model="gpt-4o", max_retries=2) | |
| #self.llm = ChatGoogleGenerativeAI(model="gemini-2.0-flash", temperature=0, google_api_key=os.getenv("GEMINI_API_KEY")) | |
| self.model_type = "openai" | |
| self.llm_with_tools = self.llm.bind_tools(tools) | |
| self.tasks_api = tasks_api | |
| self.encoding = tiktoken.encoding_for_model("gpt-4o") | |
| self.max_tokens = 25000 # Leave some buffer below the 30k limit | |
| self.apply_max_tokens = True | |
| self.logged_message_count = 0 # Track how many messages we've already logged | |
| def instructor(state: MessagesState): | |
| logger.info("π INSTRUCTOR NODE - Processing messages") | |
| logger.info(f"π Current state has {len(state['messages'])} message(s)") | |
| # Log only new messages that haven't been logged yet | |
| for i, msg in enumerate(state["messages"]): | |
| if i >= self.logged_message_count: | |
| logger.info(f"π New Message {i+1}: {self._truncate_message_for_log(msg)}") | |
| # Update the count of logged messages | |
| self.logged_message_count = len(state["messages"]) | |
| new_messages = [system_message] + state["messages"] | |
| logger.info(f"β INSTRUCTOR NODE - Added system message, total messages: {len(new_messages)}") | |
| # Update count to include system message | |
| self.logged_message_count = len(new_messages) | |
| return {"messages": new_messages} | |
| def assistant(state: MessagesState): | |
| logger.info("π€ ASSISTANT NODE - Processing messages") | |
| logger.info(f"π Received {len(state['messages'])} message(s)") | |
| # Log only new messages that haven't been logged yet | |
| for i, msg in enumerate(state["messages"]): | |
| if i >= self.logged_message_count: | |
| logger.info(f"π New Input Message {i+1}: {self._truncate_message_for_log(msg)}") | |
| # Update the count of logged messages | |
| self.logged_message_count = len(state["messages"]) | |
| if not self.apply_max_tokens: | |
| response = self.llm_with_tools.invoke(state["messages"]) | |
| logger.info(f"π¬ ASSISTANT RESPONSE: {self._truncate_message_for_log(response)}") | |
| return {"messages": [response]} | |
| messages = state["messages"] | |
| original_count = len(messages) | |
| # Truncate messages if they exceed token limit | |
| while self.count_tokens(messages) > self.max_tokens and len(messages) > 2: | |
| # Remove the oldest message (but keep system message) | |
| messages = [messages[0]] + messages[2:] | |
| if len(messages) < original_count: | |
| logger.info(f"β οΈ Truncated messages from {original_count} to {len(messages)} due to token limit") | |
| response = self.llm_with_tools.invoke(messages) | |
| logger.info(f"π¬ ASSISTANT RESPONSE: {self._truncate_message_for_log(response)}") | |
| return {"messages": [response]} | |
| def tools_node(state: MessagesState): | |
| logger.info("π§ TOOLS NODE - Processing tool calls") | |
| logger.info(f"π Received {len(state['messages'])} message(s)") | |
| # Log only new messages that haven't been logged yet | |
| for i, msg in enumerate(state["messages"]): | |
| if i >= self.logged_message_count: | |
| logger.info(f"π New Tool Input Message {i+1}: {self._truncate_message_for_log(msg)}") | |
| # Update the count of logged messages | |
| self.logged_message_count = len(state["messages"]) | |
| # Find the last message which should contain tool calls | |
| last_message = state["messages"][-1] if state["messages"] else None | |
| if last_message: | |
| tool_calls = getattr(last_message, 'tool_calls', None) | |
| if tool_calls: | |
| for i, tool_call in enumerate(tool_calls): | |
| tool_name = tool_call.get('name', 'Unknown') if isinstance(tool_call, dict) else getattr(tool_call, 'name', 'Unknown') | |
| tool_args = tool_call.get('args', {}) if isinstance(tool_call, dict) else getattr(tool_call, 'args', {}) | |
| logger.info(f"π οΈ Tool Call {i+1}: {tool_name} - {str(tool_args)[:200]}...") | |
| else: | |
| logger.info("βΉοΈ No tool calls found in last message") | |
| # Execute the tools using the original ToolNode | |
| tool_node = ToolNode(tools) | |
| result = tool_node.invoke(state) | |
| # Log the tool results | |
| if result and "messages" in result: | |
| logger.info(f"π§ TOOLS NODE - Generated {len(result['messages'])} response message(s)") | |
| for i, msg in enumerate(result["messages"]): | |
| logger.info(f"π¨ Tool Result {i+1}: {self._truncate_message_for_log(msg)}") | |
| return result | |
| builder = StateGraph(MessagesState) | |
| builder.add_node("instructor", instructor) | |
| builder.add_node("assistant", assistant) | |
| builder.add_node("tools", tools_node) | |
| builder.add_edge(START, "instructor") | |
| builder.add_edge("instructor", "assistant") | |
| builder.add_conditional_edges("assistant", tools_condition) | |
| builder.add_edge("tools", "assistant") | |
| self.graph = builder.compile() | |
| def _truncate_message_for_log(self, message, max_length: int = 500) -> str: | |
| """Helper method to truncate messages for logging""" | |
| try: | |
| if hasattr(message, 'content'): | |
| content = message.content | |
| msg_type = type(message).__name__ | |
| # Check if this is an AIMessage with tool calls but empty content | |
| if msg_type == "AIMessage": | |
| tool_calls = getattr(message, 'tool_calls', None) | |
| if tool_calls and len(tool_calls) > 0: | |
| # If there are tool calls, show a summary instead of empty content | |
| if not content or (isinstance(content, str) and content.strip() == ""): | |
| tool_names = [] | |
| for tool_call in tool_calls: | |
| tool_name = tool_call.get('name', 'Unknown') if isinstance(tool_call, dict) else getattr(tool_call, 'name', 'Unknown') | |
| tool_names.append(str(tool_name)) | |
| return f"[{msg_type}] Making tool call(s): {', '.join(tool_names)}" | |
| # Handle different content types | |
| if isinstance(content, list): | |
| # For multimodal content (list of dicts) | |
| content_str = str(content) | |
| elif isinstance(content, str): | |
| content_str = content | |
| else: | |
| content_str = str(content) | |
| # Skip logging if content is empty or just whitespace | |
| if not content_str or content_str.strip() == "": | |
| return f"[{msg_type}] <empty content>" | |
| if len(content_str) > max_length: | |
| truncated = content_str[:max_length] + "..." | |
| return f"[{msg_type}] {truncated}" | |
| else: | |
| return f"[{msg_type}] {content_str}" | |
| else: | |
| content = str(message) | |
| if len(content) > max_length: | |
| return content[:max_length] + "..." | |
| else: | |
| return content | |
| except Exception as e: | |
| return f"[Error logging message: {str(e)}]" | |
| def __call__(self, question_dict: dict) -> str: | |
| question = question_dict.get("question", None) | |
| task_id = question_dict.get("task_id", None) | |
| file_name = question_dict.get("file_name", None) | |
| # Reset message count for each new agent call | |
| self.logged_message_count = 0 | |
| # Add real-time logging | |
| logger.info("=" * 80) | |
| logger.info("π€ AGENT RECEIVED NEW REQUEST") | |
| logger.info("=" * 80) | |
| logger.info(f"π Question: {question[:100]}{'...' if len(str(question)) > 100 else ''}") | |
| logger.info(f"π’ Task ID: {task_id}") | |
| logger.info(f"π File Name: {file_name if file_name else 'None'}") | |
| if file_name: | |
| file_url = self.compose_file_url(task_id) | |
| logger.info(f"π File URL: {file_url}") | |
| logger.info("π Starting agent execution...") | |
| print(f"Agent invoked with question: {question}") | |
| content = [{"type": "text", "text": question}] | |
| if file_name: | |
| file_url = self.compose_file_url(task_id) | |
| logger.info(f"π₯ Processing file: {file_name}") | |
| updated_content = self.update_content(content, file_name, file_url, model_type=self.model_type) | |
| if updated_content is not None: | |
| content = updated_content | |
| logger.info(f"β File processed successfully") | |
| else: | |
| logger.warning(f"β οΈ File processing failed or returned None") | |
| messages = [HumanMessage(content=content)] | |
| logger.info(f"π Invoking LLM with {len(messages)} message(s)") | |
| logger.info("%"*70) | |
| logger.info(f"Agent messages: {messages}") | |
| logger.info("%"*70) | |
| answer = self.graph.invoke({"messages": messages}) | |
| logger.info("%"*70) | |
| logger.info(f"Agent complete answer: {answer}") | |
| logger.info("%"*70) | |
| answer_text = answer["messages"][-1].content | |
| if "FINAL ANSWER" in answer_text: | |
| answer_text = answer_text.split("FINAL ANSWER:")[1].strip() | |
| logger.info(f"β Extracted final answer: {answer_text[:50]}{'...' if len(answer_text) > 50 else ''}") | |
| else: | |
| logger.warning("β οΈ No 'FINAL ANSWER' format found in response") | |
| logger.info("%"*70) | |
| logger.info(f"Agent answer text: {answer_text}") | |
| logger.info("%"*70) | |
| logger.info("π― AGENT REQUEST COMPLETED") | |
| logger.info("=" * 80) | |
| return answer_text | |
| def compose_file_url(self, task_id: str): | |
| return f"{self.tasks_api}/files/{task_id}" | |
| def download_file(self, file_url: str): | |
| response = requests.get(file_url) | |
| encoded_file = base64.b64encode(response.content).decode("utf-8") | |
| return encoded_file | |
| def update_content(self, content: list, file_name: str, file_url: str, model_type: str): | |
| try: | |
| if file_name.endswith(".png"): | |
| if model_type == "openai": | |
| content.append({"type": "image_url", "image_url": {"url": file_url}}) | |
| elif model_type == "google": | |
| content.append({"type": "image_url", "image_url": file_url}) | |
| elif file_name.endswith(".py"): | |
| # For Python files, download and include as text | |
| content = self.adapt_content(content, file_name, file_url, file_type="python") | |
| elif file_name.endswith((".txt", ".md", ".csv")): | |
| # For other text-based files, download and include as text | |
| content = self.adapt_content(content, file_name, file_url, file_type="text") | |
| elif file_name.endswith(".xlsx"): | |
| content = self.adapt_content(content, file_name, file_url, file_type="excel") | |
| else: | |
| # For other file types, try the file attachment approach | |
| # But note: this might not work with all file types | |
| encoded_file = self.download_file(file_url) | |
| content.append({ | |
| "type": "file", | |
| "file": { | |
| "data": encoded_file, | |
| "filename": file_name | |
| } | |
| }) | |
| return content | |
| except Exception as e: | |
| print(f"Error updating content: {e}") | |
| content.append({ | |
| "type": "text", | |
| "text": f"\n\nError processing file '{file_name}': {str(e)}" | |
| }) | |
| def adapt_content(self, content: list, file_name: str, file_url: str, file_type: str): | |
| response = requests.get(file_url) | |
| if response.status_code != 200: | |
| content.append({ | |
| "type": "text", | |
| "text": f"\n\nError: Could not download file '{file_name}'" | |
| }) | |
| return content | |
| if response.status_code == 200: | |
| file_content = response.text | |
| if file_type == "python": | |
| logger.info("@" * 70) | |
| logger.info(f"Python file content: {file_content}") | |
| logger.info("@" * 70) | |
| content.append({ | |
| "type": "text", | |
| "text": f"\n\nAttached Python file '{file_name}':\n```python\n{file_content}\n```" | |
| }) | |
| elif file_type == "text": | |
| logger.info("@" * 70) | |
| logger.info(f"Text file content: {file_content}") | |
| logger.info("@" * 70) | |
| content.append({ | |
| "type": "text", | |
| "text": f"\n\nAttached text file '{file_name}':\n```\n{file_content}\n```" | |
| }) | |
| elif file_type == "excel": | |
| # Process Excel file and convert to readable text | |
| excel_content = self.process_excel_file(response.content, file_name) | |
| logger.info("@" * 70) | |
| logger.info(f"Excel file content: {excel_content}") | |
| logger.info("@" * 70) | |
| content.append({ | |
| "type": "text", | |
| "text": f"\n\n{excel_content}" | |
| }) | |
| return content | |
| def process_excel_file(self, file_content_bytes: bytes, file_name: str) -> str: | |
| """ | |
| Process Excel file content and convert it to readable text format | |
| Args: | |
| file_content_bytes: Raw bytes content of the Excel file | |
| file_name: Name of the Excel file | |
| Returns: | |
| String representation of the Excel content | |
| """ | |
| try: | |
| # Create a BytesIO object from the bytes content | |
| file_stream = io.BytesIO(file_content_bytes) | |
| # Load the workbook | |
| workbook = load_workbook(file_stream, read_only=True) | |
| result_text = f"Excel file '{file_name}' contents:\n\n" | |
| # Process each worksheet | |
| for sheet_name in workbook.sheetnames: | |
| worksheet = workbook[sheet_name] | |
| result_text += f"=== Sheet: {sheet_name} ===\n" | |
| # Get all data from the worksheet | |
| rows_data = [] | |
| for row in worksheet.iter_rows(values_only=True): | |
| # Filter out completely empty rows | |
| if any(cell is not None for cell in row): | |
| # Convert None values to empty strings and handle different data types | |
| cleaned_row = [] | |
| for cell in row: | |
| if cell is None: | |
| cleaned_row.append("") | |
| else: | |
| cleaned_row.append(str(cell)) | |
| rows_data.append(cleaned_row) | |
| # Convert to table format | |
| if rows_data: | |
| # Find the maximum number of columns | |
| max_cols = max(len(row) for row in rows_data) if rows_data else 0 | |
| # Pad rows to have the same number of columns | |
| for row in rows_data: | |
| while len(row) < max_cols: | |
| row.append("") | |
| # Create table format | |
| if len(rows_data) > 0: | |
| # Header row (if exists) | |
| if len(rows_data) > 1: | |
| header = " | ".join(f"{cell:15}" for cell in rows_data[0]) | |
| result_text += f"{header}\n" | |
| result_text += "-" * len(header) + "\n" | |
| data_rows = rows_data[1:] | |
| else: | |
| data_rows = rows_data | |
| # Data rows (limit to first 50 rows to avoid too much content) | |
| for i, row in enumerate(data_rows[:50]): | |
| row_text = " | ".join(f"{cell:15}" for cell in row) | |
| result_text += f"{row_text}\n" | |
| if len(data_rows) > 50: | |
| result_text += f"... (showing first 50 rows out of {len(data_rows)} total rows)\n" | |
| else: | |
| result_text += "No data found in this sheet.\n" | |
| result_text += "\n" | |
| workbook.close() | |
| return result_text | |
| except Exception as e: | |
| return f"Error processing Excel file '{file_name}': {str(e)}" | |
| def count_tokens(self, messages): | |
| """Count tokens in a list of messages""" | |
| total_tokens = 0 | |
| for message in messages: | |
| if hasattr(message, 'content'): | |
| total_tokens += len(self.encoding.encode(str(message.content))) | |
| return total_tokens |