Spaces:
Build error
Build error
File size: 6,885 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 | 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}")
|