import os from typing import Annotated, TypedDict, List, Optional from langchain_openai import ChatOpenAI from langchain_community.tools.tavily_search import TavilySearchResults from langchain_core.messages import BaseMessage, HumanMessage from langgraph.graph import StateGraph, END from langgraph.graph.message import add_messages from langgraph.prebuilt import ToolNode, tools_condition from nodes.planner import planner_node from nodes.answer_composer import answer_composer_node from nodes.tool_wrappers import process_video_chain, run_audio_transcription from tools.e2b_executor import execute_python_e2b_tool from nodes.image_tool_wrapper import image_analyzer_tool ORIGINAL_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.""" class AgentState(TypedDict): messages: Annotated[List[BaseMessage], add_messages] task_id: Optional[str] # --- Tool Setup --- # Tools that the planner LLM will be explicitly aware of and can choose from. # This list is curated to reduce token count in the planner's prompt. planner_facing_tools = [ TavilySearchResults(max_results=5), execute_python_e2b_tool, process_video_chain, image_analyzer_tool, run_audio_transcription, ] # ---- DEBUG: Print tool names ---- print("--- Planner Facing Tools (before binding) ---") for t in planner_facing_tools: tool_name = getattr(t, 'name', 'Unknown name') print(f"- Tool: {tool_name}, Type: {type(t)}") if hasattr(t, 'description') : print(f" Desc: {t.description[:70]}...") print("------------------------------------------") # ---- END DEBUG ---- # The ToolNode that will execute tools called by the planner. # It MUST be initialized with the same set of tools the planner is aware of. tool_executor_node = ToolNode(planner_facing_tools) # --- LLM Setup --- planner_llm = ChatOpenAI(model="gpt-4o", api_key=os.getenv("OPENAI_API_KEY"), temperature=0.0) # Bind planner LLM only to the curated list of tools planner_llm_with_tools = planner_llm.bind_tools(planner_facing_tools) # --- Graph Definition --- def planner_entry_node(state: AgentState): """Wrapper for the planner_node to be used in the graph. This node calls the imported planner_node from nodes/planner.py, passing the required planner_llm_with_tools and descriptions for planner_facing_tools. """ print("---CALLING PLANNER WRAPPER NODE (agent.py)---") # Generate descriptions only for the tools the planner is aware of tool_descriptions = "\n".join([ f"- {tool.name}: {tool.description}" for tool in planner_facing_tools ]) return planner_node(state, llm_instance=planner_llm_with_tools, available_tools_descriptions=tool_descriptions) graph_builder = StateGraph(AgentState) graph_builder.add_node("planner", planner_entry_node) graph_builder.add_node("tool_executor", tool_executor_node) graph_builder.add_node("answer_composer", answer_composer_node) graph_builder.set_entry_point("planner") graph_builder.add_conditional_edges( "planner", tools_condition, { "tools": "tool_executor", END: "answer_composer", }, ) graph_builder.add_edge("tool_executor", "planner") graph_builder.add_edge("answer_composer", END) assistant_graph = graph_builder.compile() try: assistant_graph.get_graph().draw_png(output_file_path="workflow_graph.png") print("New workflow graph saved to workflow_graph.png") except Exception as e: print(f"Could not draw graph: {e}. Pygraphviz might be missing or not set up correctly.") class OptimaAgent: def __init__(self): self.graph = assistant_graph self.initial_system_prompt_content = ORIGINAL_SYSTEM_PROMPT def __call__(self, query: str, task_id: str, file_path: str = None): print(f"User: {query}\nTask ID: {task_id}") current_query = query if file_path: current_query = f"File path: {file_path}\n\n{query}" initial_messages: List[BaseMessage] = [ HumanMessage(content=current_query), ] initial_state = AgentState(messages=initial_messages, task_id=task_id) final_state = self.graph.invoke(initial_state) if final_state and "messages" in final_state: all_messages = final_state["messages"] if all_messages: print("\n=== Final Assistant Response (from new graph) ===") final_message = all_messages[-1] final_message.pretty_print() print("---END---") content = final_message.content if "FINAL ANSWER:" in content: answer = content.split("FINAL ANSWER:")[-1].strip() return answer print("Warning: 'FINAL ANSWER:' not found in the final message from the graph.") return content else: print("\n--- Assistant (new graph) finished with no messages. ---") return "No response generated" else: print("\n--- Assistant (new graph) finished with unexpected state: ---") print(final_state) return "Error: Unexpected state from new graph" if __name__ == "__main__": agent = OptimaAgent() example_task_id = "cli_test_task_001" print(f"\nRunning new agent with a query about LangGraph (Task ID: {example_task_id})...\n") result = agent("What is LangGraph? Explain briefly.", task_id=example_task_id) print(f"Final Answer: {result}") video_url_for_test = "https://www.youtube.com/watch?v=dQw4w9WgXcQ" print(f"\nRunning new agent with a video query for URL: {video_url_for_test} (Task ID: {example_task_id})...\n") result_video = agent(f"What is this video about? Summarize its content. Video URL: {video_url_for_test}", task_id=example_task_id) print(f"Final Answer from video query: {result_video}") python_code_query = "Calculate 25 * 4 and tell me the result using Python." print(f"\nRunning new agent with Python code execution query (Task ID: {example_task_id})...\n") result_python = agent(python_code_query, task_id=example_task_id) print(f"Final Answer from Python query: {result_python}")