File size: 24,819 Bytes
6715b3e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
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)}"