from typing import Annotated, TypedDict, List, Union, Dict, Any, Literal from pathlib import Path from langchain_openai import ChatOpenAI from langchain_core.messages import ( HumanMessage, AIMessage, FunctionMessage, SystemMessage, ToolMessage, ) from langgraph.graph import StateGraph, END from langgraph.graph.message import add_messages from langgraph.prebuilt import ToolNode from langfuse.callback import CallbackHandler from langchain_community.tools import TavilySearchResults from langchain_core.tools import tool from pydantic import BaseModel, Field from langchain_core.documents import Document from langchain_core.documents.base import Blob from langchain_community.document_loaders import ( UnstructuredExcelLoader, # .xlsx / .xls UnstructuredImageLoader, # .png / .jpg ) from langchain_community.document_loaders.parsers.audio import ( OpenAIWhisperParserLocal, # .mp3 / .wav ) import os from tools_old.youtube_tool import YoutubeTool from tools_old.chess_tool import MateFinder from tools_old.video_tool import VideoAnalysisTool import json from e2b import Sandbox as E2BSandbox from pydantic import model_validator from langchain_google_genai import ChatGoogleGenerativeAI import openai # Initialize LLM gpt4o = ChatOpenAI(model="gpt-4o", api_key=os.getenv("OPENAI_API_KEY"), temperature=0.0) gemini_llm = ChatGoogleGenerativeAI(model="gemini-pro", google_api_key=os.getenv("GEMINI_API_KEY"), temperature=0.0) # Initialize existing tools search_tool_tavily = TavilySearchResults( max_results=3, include_answer=True, include_raw_content=False, include_images=True, search_depth="advanced", ) youtube = YoutubeTool() # Original instance chess_tool = MateFinder() # Assuming this is already a LangChain compatible tool video_tool = VideoAnalysisTool() # Assuming this is already a LangChain compatible tool # Define Input Schema for YoutubeTool class YoutubeToolInput(BaseModel): youtube_url: str = Field(description="The full URL of the YouTube video to be processed or analyzed.") question: str = Field(description="The question being asked about the YouTube video. This helps provide context for the analysis.") analysis_type: Literal['transcript', 'visual', 'both'] = Field( default='both', description="Specifies the type of analysis to perform: 'transcript' for text content, 'visual' for object/scene detection, or 'both'." ) @tool("youtube_video_analyzer", args_schema=YoutubeToolInput) def youtube_tool_with_schema(youtube_url: str, question: str, analysis_type: Literal['transcript', 'visual', 'both'] = 'both') -> str: """ Analyzes a YouTube video from the provided URL for its transcript and/or visual content. You must provide the 'youtube_url' and the 'question' being asked about the video. You can optionally specify 'analysis_type' as 'transcript', 'visual', or 'both' (defaults to 'both'). Use 'visual' if the question is about objects, scenes, or counts of things in the video. Use 'transcript' if the question is about spoken content. """ print(f"[TOOL WRAPPER] Called youtube_tool_with_schema with URL: {youtube_url}, Question: {question}, Analysis Type: {analysis_type}") try: query_dict = { "url": youtube_url, "question": question, "analysis_type": analysis_type } # Directly call the _run method of the YoutubeTool instance # to bypass BaseTool.run() argument parsing issues for this specific tool. result = youtube._run(query_dict) # Changed from youtube.run(query_dict) return str(result) # Ensure the output is a string for the agent except Exception as e: import traceback print(f"[TOOL WRAPPER] Error in youtube_tool_with_schema: {str(e)}\n{traceback.format_exc()}") return f"Error during YouTube tool execution: {str(e)}" # Define Tool Schemas using Pydantic for better validation and description class TavilySearchInput(BaseModel): query: str = Field(description="The search query to find information on the web. For Wikipedia searches, include 'wikipedia' in the query.") @tool("tavily_search_results_json", args_schema=TavilySearchInput) def tavily_search_tool(query: str) -> str: """ Performs a web search using Tavily to find up-to-date information, news, or details on a specific topic. This tool is ideal for queries requiring current events, specific facts, or general knowledge from the internet. If you need information from Wikipedia, ensure the word 'wikipedia' is part of your query. Example: User asks: "What's the weather in Paris?" Tool call: tavily_search_results_json(query="weather in Paris") User asks: "Tell me about LangGraph on Wikipedia." Tool call: tavily_search_results_json(query="LangGraph wikipedia") """ print(f"[TOOL REGISTRY] Called tavily_search_tool with query: {query}") # Enhance query for Wikipedia if specified if "wikipedia" in query.lower() and "site:wikipedia.org" not in query.lower(): query_enhanced = f"{query} site:wikipedia.org" print(f"[TOOL REGISTRY] Enhanced Wikipedia query: {query_enhanced}") return search_tool_tavily.invoke({"query": query_enhanced}) return search_tool_tavily.invoke({"query": query}) # E2B Code Execution Tool class E2BCodeExecutionInput(BaseModel): code: str | None = Field(default=None, description="The Python code string to execute. Use this if the code is directly available.") file_path: str | None = Field(default=None, description="Path to a Python file to execute. The content of this file will be run. Use this if the code is in a file.") @model_validator(mode='before') @classmethod def check_code_or_file_path_provided(cls, values: Dict[str, Any]) -> Dict[str, Any]: code_provided = values.get('code') is not None and values.get('code') != "" file_path_provided = values.get('file_path') is not None and values.get('file_path') != "" if not code_provided and not file_path_provided: raise ValueError('Either "code" or "file_path" must be provided.') if code_provided and file_path_provided: raise ValueError('Provide either "code" or "file_path", not both.') return values @tool("execute_python_code_e2b", args_schema=E2BCodeExecutionInput) def execute_python_e2b_tool(code: str | None = None, file_path: str | None = None) -> str: """ Executes Python code in a secure E2B sandbox. Provide either a 'code' string directly, or a 'file_path' to a Python script. The tool will return the standard output and standard error from the execution. This is useful for running arbitrary Python scripts, calculations, or simulations. Example: To run a simple print statement: execute_python_code_e2b(code="print('Hello from E2B!')") To run code from a file: execute_python_code_e2b(file_path="path/to/your/script.py") """ print(f"[TOOL REGISTRY] Called execute_python_e2b_tool with code: {'yes' if code else 'no'}, file_path: {file_path}") if os.getenv("E2B_API_KEY") is None: return "Error: E2B_API_KEY is not set. Please set this environment variable to use the E2B code interpreter." code_to_execute = code if file_path: try: expanded_file_path = Path(file_path).expanduser().resolve() if not expanded_file_path.is_file(): return f"Error: File not found at path: {file_path} (resolved to {expanded_file_path})" with open(expanded_file_path, "r") as f: code_to_execute = f.read() print(f"[TOOL REGISTRY] Read code from file: {expanded_file_path}") except Exception as e: return f"Error reading Python file {file_path}: {str(e)}" if not code_to_execute: # This case should ideally be caught by Pydantic validator earlier return "Error: No code provided for execution after attempting to load from file (if applicable)." try: print(f"[E2B TOOL] Attempting to create sandbox and run code (first 200 chars):\n{code_to_execute[:200]}...") with E2BSandbox() as sandbox: stdout, stderr, exec_error = sandbox.execute_python(code=code_to_execute) print(f"[E2B TOOL] Execution result - stdout: {stdout}, stderr: {stderr}, error: {exec_error}") if exec_error: error_message = f"Error during E2B execution: {exec_error.name}: {exec_error.value}\n" if exec_error.traceback_raw and isinstance(exec_error.traceback_raw, list): error_message += "Traceback:\n" + "\n".join(exec_error.traceback_raw) return error_message.strip() result_parts = [] if stdout: result_parts.append(f"Stdout:\n{stdout}") if stderr: result_parts.append(f"Stderr:\n{stderr}") if not result_parts: return "Code executed successfully with no output to stdout or stderr." return "\n".join(result_parts) except Exception as e: import traceback tb_str = traceback.format_exc() print(f"[E2B TOOL] Exception during E2B sandbox operation: {str(e)}\n{tb_str}") return f"Error with E2B sandbox execution: {str(e)}" # Tool schemas for LLM - This is no longer strictly needed in this format for bind_tools # but can be useful for other purposes or if we decide to generate prompts differently. # For now, we will rely on the @tool decorator and bind_tools. # TOOL_SCHEMAS = """...""" # Commented out as bind_tools handles this SYSTEM_PROMPT = '''You 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 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, apply the above rules depending of whether the element to be put in the list is a number or a string.''' @tool def parse_spreadsheet(path: str) -> List[Document]: """Load all cells of an Excel workbook into Documents.""" loader = UnstructuredExcelLoader(Path(path).expanduser()) return loader.load() @tool def transcribe_audio(path: str) -> str: """Whisper-transcribe an audio file locally.""" parser = OpenAIWhisperParserLocal(device="cpu") blob = Blob.from_path(path) docs = list(parser.parse(blob)) return "\n".join(d.page_content for d in docs) @tool def describe_image(path: str) -> List[Document]: """Generate one caption per image.""" try: loader = UnstructuredImageLoader(Path(path).expanduser(), mode="single") docs = loader.load() if not docs or not docs[0].page_content: return [Document(page_content="Unable to extract text from image")] return docs except Exception as e: return [Document(page_content=f"Error processing image: {str(e)}")] # We will collect all tools that the LLM can use here # For now, we only have tavily_search_tool correctly defined for LangGraph # TODO: Wrap other tools (youtube, chess_tool, video_tool, parse_spreadsheet, etc.) # with the @tool decorator and Pydantic schemas if they are to be used by the LLM. available_tools = [ tavily_search_tool, youtube_tool_with_schema, # Correctly wrapped version chess_tool, video_tool, parse_spreadsheet, transcribe_audio, describe_image, execute_python_e2b_tool, ] # Bind tools to the LLM gpt4o_with_tools = gpt4o.bind_tools(available_tools) gemini_with_tools = gemini_llm.bind_tools(available_tools) # State definition class AgentState(TypedDict): messages: Annotated[ List[Union[HumanMessage, AIMessage, FunctionMessage, SystemMessage, ToolMessage]], add_messages, ] next: str file_path: str | None message_count: int # Tracks LLM calls tool_call_count: int # Tracks tool invocations def agent_node(state: AgentState): """Process agent messages and determine next steps.""" state["message_count"] = state.get("message_count", 0) + 1 print(f"\n[AGENT NODE] Message count (LLM calls): {state['message_count']}") print(f"[AGENT NODE] Tool call count: {state.get('tool_call_count', 0)}") print(f"[AGENT NODE] Current messages: {[(type(m).__name__, m.content[:100] if isinstance(m.content, str) else m.content) for m in state['messages']]}") current_llm_with_tools = gpt4o_with_tools current_llm_plain = gpt4o llm_name = "GPT-4o" def get_llm_response(messages_payload, use_tools=True): nonlocal current_llm_with_tools, current_llm_plain, llm_name primary_llm_name = "GPT-4o" # First attempt with primary LLM (GPT-4o) current_llm_with_tools = gpt4o_with_tools current_llm_plain = gpt4o llm_name = primary_llm_name print(f"[AGENT NODE] Attempting LLM call with {llm_name}") try: if use_tools: return current_llm_with_tools.invoke(messages_payload) else: return current_llm_plain.invoke(messages_payload) except openai.RateLimitError as e: print(f"[AGENT NODE] OpenAI ({llm_name}) rate limit hit: {e}. Attempting fallback to Gemini.") # Directly attempt Gemini fallback, assuming gemini_llm and gemini_with_tools are initialized. current_llm_with_tools = gemini_with_tools current_llm_plain = gemini_llm llm_name = "Gemini" print(f"[AGENT NODE] Now using {llm_name} for this call.") try: if use_tools: return current_llm_with_tools.invoke(messages_payload) else: return current_llm_plain.invoke(messages_payload) except Exception as gemini_e: # Catch errors from Gemini call print(f"[AGENT NODE] Gemini ({llm_name}) call also failed: {gemini_e}. Rethrowing original OpenAI error after fallback attempt.") raise e # Rethrow the original openai.RateLimitError # No explicit rethrow here for the primary error if Gemini is not attempted or fails, # as the original error `e` would propagate if not caught by a Gemini success. # However, the above structure ensures `e` is re-thrown if Gemini fails. if state["message_count"] > 2 or state.get("tool_call_count", 0) >= 2: if state.get("tool_call_count", 0) >= 2 and state["message_count"] <=2 : # if tool limit reached early print("[AGENT NODE] Reached tool limit, attempting to generate final answer.") elif state["message_count"] > 2: print("[AGENT NODE] Reached LLM call limit, attempting to generate final answer.") forced_final_answer_prompt = state["messages"] + [SystemMessage(content="You have reached your operational limits. Please provide a FINAL ANSWER based on the information you have gathered so far. If you cannot answer, state that clearly.")] try: response = get_llm_response(forced_final_answer_prompt, use_tools=True) except Exception as e: print(f"[AGENT NODE] Both primary and fallback LLMs failed for forced final answer: {e}") return {"messages": [AIMessage(content="FINAL ANSWER: Could not generate a response due to LLM errors after hitting operational limits.")], "message_count": state["message_count"], "next": END} print(f"[AGENT NODE] LLM Response ({llm_name}, forcing final): {response.content[:100]}...") final_content = response.content if not final_content.startswith("FINAL ANSWER:"): final_content = f"FINAL ANSWER: {final_content}" return {"messages": [AIMessage(content=final_content)], "message_count": state["message_count"], "next": END} print(f"[AGENT NODE] Running LLM with tools (will attempt {gpt4o.model_name} first)") try: response = get_llm_response(state["messages"], use_tools=True) except Exception as e: print(f"[AGENT NODE] Both primary and fallback LLMs failed for main tool call: {e}") try: synthesize_prompt = state["messages"] + [SystemMessage("Primary and fallback LLMs failed to use tools. Please synthesize a final answer based on the conversation so far without using any tools.")] final_response_obj = get_llm_response(synthesize_prompt, use_tools=False) final_content = final_response_obj.content if not final_content.startswith("FINAL ANSWER:"): final_content = f"FINAL ANSWER: {final_content}" return {"messages": [AIMessage(content=final_content)], "message_count": state["message_count"], "next": END} except Exception as final_e: print(f"[AGENT NODE] Final synthesis attempt also failed: {final_e}") return {"messages": [AIMessage(content="FINAL ANSWER: Could not generate a response due to LLM errors.")], "message_count": state["message_count"], "next": END} print(f"[AGENT NODE] LLM Response ({llm_name}): {response.content[:100]}...") print(f"[AGENT NODE] LLM Response object type: {type(response)}") if hasattr(response, 'tool_calls') and response.tool_calls: print(f"[AGENT NODE] LLM ({llm_name}) tool_calls: {response.tool_calls}") has_tool_calls = hasattr(response, "tool_calls") and response.tool_calls and len(response.tool_calls) > 0 print(f"[AGENT NODE] Has tool calls ({llm_name}): {has_tool_calls}") if has_tool_calls and state.get("tool_call_count", 0) < 2: print(f"[AGENT NODE] Moving to tools node (called by {llm_name})") return {"messages": [response], "message_count": state["message_count"]} else: if has_tool_calls and state.get("tool_call_count", 0) >= 2: print(f"[AGENT NODE] Tool call limit reached, not executing further tools (LLM: {llm_name}). Generating final answer.") else: print(f"[AGENT NODE] No tool calls from LLM ({llm_name}) or tool limit reached. Generating final answer.") final_content = response.content if not final_content.startswith("FINAL ANSWER:"): final_content = f"FINAL ANSWER: {final_content}" if hasattr(response, "tool_calls") and response.tool_calls and len(response.tool_calls) > 0 : print(f"[AGENT NODE] Warning: LLM ({llm_name}) tried to call tool {response.tool_calls} but was overridden due to limits.") # Attempt a final synthesis without tools synthesize_prompt = state["messages"] + [response, SystemMessage("You have reached your operational limits or attempted to use a tool when not allowed. Please synthesize a final answer without using any tools based on the conversation so far.")] try: final_response_obj = get_llm_response(synthesize_prompt, use_tools=False) except Exception as e: print(f"[AGENT NODE] Both primary and fallback LLMs failed for override synthesis: {e}") return {"messages": [AIMessage(content="FINAL ANSWER: Could not generate a response due to LLM errors during override synthesis.")], "message_count": state["message_count"], "next": END} final_content = final_response_obj.content if not final_content.startswith("FINAL ANSWER:"): final_content = f"FINAL ANSWER: {final_content}" return {"messages": [AIMessage(content=final_content)], "message_count": state["message_count"], "next": END} # We will use the prebuilt ToolNode from LangGraph # It expects a list of LangChain tools tool_executor_node = ToolNode(available_tools) def after_tool_node(state: AgentState): """Increment tool call count and decide next step.""" state["tool_call_count"] = state.get("tool_call_count", 0) + 1 print(f"\n[AFTER TOOL NODE] Tool call count updated to: {state['tool_call_count']}") last_message = state["messages"][-1] print(f"[AFTER TOOL NODE] Last message type: {type(last_message)}") # If last message is a ToolMessage, it means a tool was just executed. # We should go back to the agent to process the tool's output. if isinstance(last_message, ToolMessage): print("[AFTER TOOL NODE] Tool executed. Returning to agent_node.") return {"next": "agent", "tool_call_count": state["tool_call_count"]} else: # This case should ideally not be hit if ToolNode works as expected # and agent_node correctly routes to tools. print("[AFTER TOOL NODE] No ToolMessage found after tool execution, unexpected state. Ending.") return {"next": END, "tool_call_count": state["tool_call_count"]} class OptimaAgent: def __init__(self): workflow = StateGraph(AgentState) workflow.add_node("agent", agent_node) # workflow.add_node("tools", tool_node) # Replacing with prebuilt ToolNode workflow.add_node("tool_executor", tool_executor_node) workflow.add_node("after_tools", after_tool_node) workflow.set_entry_point("agent") # If agent decides to use a tool, it goes to tool_executor # The output of agent_node (AIMessage with tool_calls) is the input to tool_executor_node workflow.add_conditional_edges( "agent", lambda x: "tool_executor" if hasattr(x["messages"][-1], "tool_calls") and x["messages"][-1].tool_calls else END, { "tool_executor": "tool_executor", END: END } ) # After tools are executed, go to 'after_tools' to update count and then back to agent workflow.add_edge("tool_executor", "after_tools") workflow.add_edge("after_tools", "agent") self.graph = workflow.compile() def __call__(self, user_text: str, file_path: str | None = None) -> str: print(f"\n[AGENT] Starting new conversation with query: {user_text}") langfuse_handler = CallbackHandler() initial_state = AgentState( messages=[ SystemMessage(content=SYSTEM_PROMPT), HumanMessage(content=user_text), ], next="", file_path=file_path, message_count=0, tool_call_count=0, ) print("[AGENT] Initial state:", initial_state) try: print("[AGENT] Running graph") # The config for recursion_limit should be on the .invoke call result = self.graph.invoke(initial_state, config={"callbacks": [langfuse_handler], "recursion_limit": 15}) print("[AGENT] Graph execution completed") # print("[AGENT] Final result state:", result) final_message = result["messages"][-1] if isinstance(final_message, (AIMessage, SystemMessage)) and "FINAL ANSWER:" in final_message.content: answer = final_message.content.split("FINAL ANSWER:", 1)[-1].strip() elif isinstance(final_message, FunctionMessage): # Should be ToolMessage with new structure answer = f"Observed tool output: {final_message.content}" # Fallback if graph ends unexpectedly elif isinstance(final_message, ToolMessage): answer = f"Observed tool output: {final_message.content}" # Fallback else: answer = str(final_message.content) # General fallback # Ensure "FINAL ANSWER:" prefix if somehow missing and it's the end. if not answer.startswith("FINAL ANSWER:") and result.get("next") == END and isinstance(final_message, AIMessage): if "FINAL ANSWER:" not in final_message.content: answer = f"FINAL ANSWER: {answer}" else: # It was already there but split failed or was complex answer = final_message.content.split("FINAL ANSWER:", 1)[-1].strip() print(f"[AGENT] Full answer: {answer}") print(f"[AGENT] FINAL ANSWER: {answer.split('FINAL ANSWER:', 1)[-1].strip()}") return answer except Exception as e: print(f"[AGENT] Error during execution: {str(e)}") import traceback traceback.print_exc() return f"I encountered an error: {str(e)}"