Delete agents.py
Browse files
agents.py
DELETED
|
@@ -1,227 +0,0 @@
|
|
| 1 |
-
import re
|
| 2 |
-
from datetime import datetime
|
| 3 |
-
from typing import Annotated
|
| 4 |
-
|
| 5 |
-
from dotenv import load_dotenv
|
| 6 |
-
from pydantic import BaseModel, Field
|
| 7 |
-
|
| 8 |
-
from langchain_core.messages import SystemMessage
|
| 9 |
-
from langchain_core.tools import tool
|
| 10 |
-
from langchain_google_genai import ChatGoogleGenerativeAI
|
| 11 |
-
from langchain_openai import ChatOpenAI
|
| 12 |
-
|
| 13 |
-
from langgraph.graph import END, START, MessagesState, StateGraph
|
| 14 |
-
from langgraph.graph.message import add_messages
|
| 15 |
-
from langgraph.prebuilt import ToolNode, tools_condition
|
| 16 |
-
from langgraph_supervisor.supervisor import create_supervisor
|
| 17 |
-
|
| 18 |
-
from youtube_transcript_api import (
|
| 19 |
-
NoTranscriptFound,
|
| 20 |
-
TranscriptsDisabled,
|
| 21 |
-
VideoUnavailable,
|
| 22 |
-
YouTubeTranscriptApi,
|
| 23 |
-
)
|
| 24 |
-
|
| 25 |
-
from prompts import WEB_SEARCH_PROMPT, YOUTUBE_PROMPT, MULTIMODAL_PROMPT
|
| 26 |
-
|
| 27 |
-
# Load environment variables from .env file
|
| 28 |
-
load_dotenv()
|
| 29 |
-
|
| 30 |
-
class AgentState(MessagesState):
|
| 31 |
-
"""
|
| 32 |
-
State class for agent workflows, tracks the message history.
|
| 33 |
-
"""
|
| 34 |
-
messages: Annotated[list, add_messages]
|
| 35 |
-
|
| 36 |
-
class YouTubeTranscriptInput(BaseModel):
|
| 37 |
-
"""
|
| 38 |
-
Input schema for the YouTube transcript tool.
|
| 39 |
-
"""
|
| 40 |
-
video_url: str = Field(description="YouTube URL or video ID.")
|
| 41 |
-
raw: bool = Field(default=False, description="Include timestamps?")
|
| 42 |
-
|
| 43 |
-
@tool("youtube_transcript", args_schema=YouTubeTranscriptInput)
|
| 44 |
-
def youtube_transcript(video_url: str, raw: bool = False) -> str:
|
| 45 |
-
"""
|
| 46 |
-
Fetches the transcript of a YouTube video given its URL or ID.
|
| 47 |
-
Returns plain text (no timestamps) or raw with timestamps.
|
| 48 |
-
"""
|
| 49 |
-
# Extract video ID from URL or use as-is if already an ID
|
| 50 |
-
if "youtube.com" in video_url or "youtu.be" in video_url:
|
| 51 |
-
match = re.search(r"(?:v=|youtu.be/)([\w-]{11})", video_url)
|
| 52 |
-
if not match:
|
| 53 |
-
return "Invalid YouTube URL or ID."
|
| 54 |
-
video_id = match.group(1)
|
| 55 |
-
else:
|
| 56 |
-
video_id = video_url.strip()
|
| 57 |
-
try:
|
| 58 |
-
# Fetch transcript using the API
|
| 59 |
-
transcript = YouTubeTranscriptApi.get_transcript(video_id)
|
| 60 |
-
if raw:
|
| 61 |
-
# Return transcript with timestamps
|
| 62 |
-
return "\n".join(f"{int(e['start'])}s: {e['text']}" for e in transcript)
|
| 63 |
-
# Return plain transcript text
|
| 64 |
-
return " ".join(e['text'] for e in transcript)
|
| 65 |
-
except TranscriptsDisabled:
|
| 66 |
-
return "Transcripts are disabled for this video."
|
| 67 |
-
except NoTranscriptFound:
|
| 68 |
-
return "No transcript found for this video."
|
| 69 |
-
except VideoUnavailable:
|
| 70 |
-
return "This video is unavailable."
|
| 71 |
-
except Exception as e:
|
| 72 |
-
return f"An error occurred while fetching the transcript: {e}"
|
| 73 |
-
|
| 74 |
-
def build_supervisor_agent(openai_key, google_key):
|
| 75 |
-
"""
|
| 76 |
-
Build the supervisor agent with the provided API keys.
|
| 77 |
-
|
| 78 |
-
Args:
|
| 79 |
-
openai_key (str): OpenAI API key.
|
| 80 |
-
google_key (str): Google API key.
|
| 81 |
-
|
| 82 |
-
Returns:
|
| 83 |
-
supervisor_agent: The compiled supervisor agent.
|
| 84 |
-
"""
|
| 85 |
-
# Initialize OpenAI LLM (gpt-4o) for general and web search tasks
|
| 86 |
-
openai_llm = ChatOpenAI(
|
| 87 |
-
model="gpt-4o",
|
| 88 |
-
use_responses_api=True,
|
| 89 |
-
api_key=openai_key
|
| 90 |
-
)
|
| 91 |
-
|
| 92 |
-
# Initialize Google Gemini LLM for YouTube and multimodal tasks
|
| 93 |
-
google_llm = ChatGoogleGenerativeAI(
|
| 94 |
-
model="gemini-2.5-flash-preview-04-17",
|
| 95 |
-
google_api_key=google_key,
|
| 96 |
-
)
|
| 97 |
-
|
| 98 |
-
tools = [youtube_transcript]
|
| 99 |
-
|
| 100 |
-
def create_web_search_graph() -> StateGraph:
|
| 101 |
-
"""
|
| 102 |
-
Create the web search agent graph.
|
| 103 |
-
|
| 104 |
-
Returns:
|
| 105 |
-
StateGraph: The compiled web search agent workflow.
|
| 106 |
-
"""
|
| 107 |
-
web_search_preview = [{"type": "web_search_preview"}]
|
| 108 |
-
# Bind the web search tool to the OpenAI LLM
|
| 109 |
-
llm_with_tools = openai_llm.bind_tools(web_search_preview)
|
| 110 |
-
|
| 111 |
-
def agent_node(state: AgentState) -> dict:
|
| 112 |
-
"""
|
| 113 |
-
Node function for handling web search queries.
|
| 114 |
-
|
| 115 |
-
Args:
|
| 116 |
-
state (AgentState): The current agent state.
|
| 117 |
-
|
| 118 |
-
Returns:
|
| 119 |
-
dict: Updated state with the LLM response.
|
| 120 |
-
"""
|
| 121 |
-
current_date = datetime.now().strftime("%B %d, %Y")
|
| 122 |
-
# Format the system prompt with the current date
|
| 123 |
-
system_message = SystemMessage(content=WEB_SEARCH_PROMPT.format(current_date=current_date))
|
| 124 |
-
# Re-bind tools for each invocation (defensive)
|
| 125 |
-
web_search_preview = [{"type": "web_search_preview"}]
|
| 126 |
-
response = llm_with_tools.bind_tools(web_search_preview).invoke(
|
| 127 |
-
[system_message] + state.get("messages")
|
| 128 |
-
)
|
| 129 |
-
return {"messages": state.get("messages") + [response]}
|
| 130 |
-
|
| 131 |
-
# Build the workflow graph
|
| 132 |
-
workflow = StateGraph(AgentState)
|
| 133 |
-
workflow.add_node("agent", agent_node)
|
| 134 |
-
workflow.add_edge(START, "agent")
|
| 135 |
-
workflow.add_edge("agent", END)
|
| 136 |
-
return workflow.compile(name="web_search_agent")
|
| 137 |
-
|
| 138 |
-
def create_youtube_viwer_graph() -> StateGraph:
|
| 139 |
-
"""
|
| 140 |
-
Create the YouTube viewer agent graph.
|
| 141 |
-
|
| 142 |
-
Returns:
|
| 143 |
-
StateGraph: The compiled YouTube viewer agent workflow.
|
| 144 |
-
"""
|
| 145 |
-
def agent_node(state: AgentState) -> dict:
|
| 146 |
-
"""
|
| 147 |
-
Node function for handling YouTube-related queries.
|
| 148 |
-
|
| 149 |
-
Args:
|
| 150 |
-
state (AgentState): The current agent state.
|
| 151 |
-
|
| 152 |
-
Returns:
|
| 153 |
-
dict: Updated state with the LLM response.
|
| 154 |
-
"""
|
| 155 |
-
current_date = datetime.now().strftime("%B %d, %Y")
|
| 156 |
-
# Format the system prompt with the current date
|
| 157 |
-
system_message = SystemMessage(content=YOUTUBE_PROMPT.format(current_date=current_date))
|
| 158 |
-
# Bind the YouTube transcript tool to the Gemini LLM
|
| 159 |
-
llm_with_tools = google_llm.bind_tools(tools)
|
| 160 |
-
response = llm_with_tools.invoke([system_message] + state.get("messages"))
|
| 161 |
-
return {"messages": state.get("messages") + [response]}
|
| 162 |
-
|
| 163 |
-
# Build the workflow graph with tool node and conditional routing
|
| 164 |
-
workflow = StateGraph(AgentState)
|
| 165 |
-
workflow.add_node("llm", agent_node)
|
| 166 |
-
workflow.add_node("tools", ToolNode(tools))
|
| 167 |
-
workflow.set_entry_point("llm")
|
| 168 |
-
workflow.add_conditional_edges(
|
| 169 |
-
"llm",
|
| 170 |
-
tools_condition,
|
| 171 |
-
{
|
| 172 |
-
"tools": "tools", # If tool is needed, go to tools node
|
| 173 |
-
"__end__": END, # Otherwise, end the workflow
|
| 174 |
-
},
|
| 175 |
-
)
|
| 176 |
-
workflow.add_edge("tools", "llm") # After tool, return to LLM node
|
| 177 |
-
return workflow.compile(name="youtube_viwer_agent")
|
| 178 |
-
|
| 179 |
-
def create_multimodal_agent_graph() -> StateGraph:
|
| 180 |
-
"""
|
| 181 |
-
Create the multimodal agent graph using Gemini for best multimodal support.
|
| 182 |
-
|
| 183 |
-
Returns:
|
| 184 |
-
StateGraph: The compiled multimodal agent workflow.
|
| 185 |
-
"""
|
| 186 |
-
def agent_node(state: AgentState) -> dict:
|
| 187 |
-
"""
|
| 188 |
-
Node function for handling multimodal queries.
|
| 189 |
-
|
| 190 |
-
Args:
|
| 191 |
-
state (AgentState): The current agent state.
|
| 192 |
-
|
| 193 |
-
Returns:
|
| 194 |
-
dict: Updated state with the LLM response.
|
| 195 |
-
"""
|
| 196 |
-
current_date = datetime.now().strftime("%B %d, %Y")
|
| 197 |
-
# Compose the system message with the multimodal prompt and current date
|
| 198 |
-
system_message = SystemMessage(content=MULTIMODAL_PROMPT + f" Today's date: {current_date}.")
|
| 199 |
-
messages = [system_message] + state.get("messages")
|
| 200 |
-
# Invoke Gemini LLM for multimodal reasoning
|
| 201 |
-
response = google_llm.invoke(messages)
|
| 202 |
-
return {"messages": state.get("messages") + [response]}
|
| 203 |
-
|
| 204 |
-
# Build the workflow graph
|
| 205 |
-
workflow = StateGraph(AgentState)
|
| 206 |
-
workflow.add_node("agent", agent_node)
|
| 207 |
-
workflow.add_edge(START, "agent")
|
| 208 |
-
workflow.add_edge("agent", END)
|
| 209 |
-
return workflow.compile(name="multimodal_agent")
|
| 210 |
-
|
| 211 |
-
# Instantiate the agent graphs
|
| 212 |
-
multimodal_agent = create_multimodal_agent_graph()
|
| 213 |
-
web_search_agent = create_web_search_graph()
|
| 214 |
-
youtube_agent = create_youtube_viwer_graph()
|
| 215 |
-
|
| 216 |
-
# Create the supervisor workflow to route queries to the appropriate sub-agent
|
| 217 |
-
supervisor_workflow = create_supervisor(
|
| 218 |
-
[web_search_agent, youtube_agent, multimodal_agent],
|
| 219 |
-
model=openai_llm,
|
| 220 |
-
prompt=(
|
| 221 |
-
"You are a supervisor. For each question, call one of your sub-agents and return their answer directly to the user. Do not modify, summarize, or rephrase the answer."
|
| 222 |
-
)
|
| 223 |
-
)
|
| 224 |
-
|
| 225 |
-
# Compile the supervisor agent for use in the application
|
| 226 |
-
supervisor_agent = supervisor_workflow.compile(name="supervisor_agent")
|
| 227 |
-
return supervisor_agent
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|