From d34d11f4c3b738303b15358802721625dde98910 Mon Sep 17 00:00:00 2001 From: Omkar Bansod Date: Fri, 7 Nov 2025 16:07:38 +0530 Subject: [PATCH 1/3] implement youtube-tool --- src/lib/agent/BrowserAgent.prompt.ts | 43 ++++- src/lib/agent/BrowserAgent.ts | 19 +++ src/lib/tools/YouTubeTool.ts | 241 +++++++++++++++++++++++++++ src/lib/tools/index.ts | 1 + 4 files changed, 303 insertions(+), 1 deletion(-) create mode 100644 src/lib/tools/YouTubeTool.ts diff --git a/src/lib/agent/BrowserAgent.prompt.ts b/src/lib/agent/BrowserAgent.prompt.ts index d23c60f4..32271338 100644 --- a/src/lib/agent/BrowserAgent.prompt.ts +++ b/src/lib/agent/BrowserAgent.prompt.ts @@ -8,6 +8,16 @@ You are now operating in EXECUTION MODE. You will be provided with: Your primary responsibility is to interpret each action and translate it into the correct tool calls, executing them within the browser environment. +# ⚠️ CRITICAL: YOUTUBE VIDEO TASKS +**If the current page is YouTube (youtube.com/watch or youtube.com/shorts) AND the task involves video content:** +- Summarize video → MUST use youtube_tool(action='summarize') +- Question about video → MUST use youtube_tool(action='ask', question='...') +- Get transcript → MUST use youtube_tool(action='transcript') + +**DO NOT use click/scroll/extract for YouTube VIDEO CONTENT - these tools CANNOT access video transcripts or content.** +Browser automation can only see the page UI (buttons, titles), not the actual video content or transcript. +Only youtube_tool can analyze what's IN the video. + # STEP BY STEP EXECUTION PROCESS 1. **Analyze the context:** Review the user task, current state, execution history, challenges, and reasoning done so far to understand the user's goal. This will give you enough context to understand what has been carried out so far and what should be done next. @@ -37,6 +47,8 @@ Your primary responsibility is to interpret each action and translate it into th - "Scroll to [element]" → LOOK at screenshot, find element's nodeId label, use scroll(nodeId) - "Press [key]" → use key(key) - "Extract [data]" → use extract(format, task) +- "Summarize YouTube video" → use youtube_tool(action='summarize') +- "Ask about YouTube video" → use youtube_tool(action='ask', question='...') - "Submit form" → LOOK at screenshot, find submit button's nodeId label, click(nodeId) ↳ If click fails → use visual_click("submit button description") @@ -112,6 +124,7 @@ Tab Control: Data Operations: - extract(format, task): Extract structured data matching JSON schema +- youtube_tool(action, question?, videoUrl?): Analyze YouTube videos (requires Gemini API) MCP Integration: - mcp(action, instanceId?, toolName?, toolArgs?): Access external services (Gmail, GitHub, etc.) @@ -173,6 +186,18 @@ You do NOT perform actions yourself. Your role is to propose clear, actionable n - After each round of execution, review the history and updated state, and refine your plan and suggest next steps as needed. - When the task is fully complete, provide a final answer and set \`taskComplete=true\`. Answer must be grounded based on latest browser state and screenshot. +# ⚠️ CRITICAL: YOUTUBE VIDEO TASK DETECTION +**Before planning ANY actions, check if this is a YouTube video task:** +- Is the URL youtube.com/watch or youtube.com/shorts? +- Does the task ask to: summarize, analyze, get transcript, or ask questions about the VIDEO CONTENT? + +**If YES to both → Your plan MUST include: "Use youtube_tool to [action]"** +- Example: "Use youtube_tool to summarize the video" +- Example: "Use youtube_tool to answer the question about [topic]" + +**DO NOT propose:** "Click Show transcript", "Extract page content", "Scroll down", "Click More actions" +**WHY:** Browser automation CANNOT access video content - only the page UI (buttons, titles). The youtube_tool uses Gemini's native video understanding to analyze the actual video content and transcript. + # STEP BY STEP REASONING 1. **Analysis of User Query, Execution History and Current/Updated Browser State:** @@ -202,9 +227,13 @@ ${toolDescriptions} - Google Docs: document reading, writing, and formatting - Notion: note and database management -**Always prefer MCP for these services over browser automation when possible.** +**Always prefer MCP for these services over browser automation when possible.** Example: Use "Use MCP to search Gmail for unread emails" instead of "Navigate to gmail.com". +**For YouTube video analysis, always use youtube_tool instead of extract or browser automation.** +The extract tool cannot access video content - only youtube_tool can analyze videos. +Example: Use "Use youtube_tool to summarize" instead of "Extract page content". + # EXAMPLES OF EFFECTIVE (GOOD) ACTIONS - Use BrowserOS info tool to retrieve agent details @@ -261,6 +290,18 @@ You do NOT perform actions yourself. Your role is to manage the TODO list, analy - After each round of execution, review the history and updated state, update the TODO list progress, and refine your plan and suggest next steps as needed. - When all TODO items are complete, provide a final answer and set \`allTodosComplete=true\`. Answer must be grounded based on latest browser state and screenshot. +# ⚠️ CRITICAL: YOUTUBE VIDEO TASK DETECTION +**Before planning ANY actions, check if this is a YouTube video task:** +- Is the URL youtube.com/watch or youtube.com/shorts? +- Does the task ask to: summarize, analyze, get transcript, or ask questions about the VIDEO CONTENT? + +**If YES to both → Your plan MUST include: "Use youtube_tool to [action]"** +- Example: "Use youtube_tool to summarize the video" +- Example: "Use youtube_tool to answer the question about [topic]" + +**DO NOT propose:** "Click Show transcript", "Extract page content", "Scroll down", "Click More actions" +**WHY:** Browser automation CANNOT access video content - only the page UI (buttons, titles). The youtube_tool uses Gemini's native video understanding to analyze the actual video content and transcript. + # STEP BY STEP REASONING 1. **Analysis of User Query, Execution History, TODO Progress and Current/Updated Browser State:** diff --git a/src/lib/agent/BrowserAgent.ts b/src/lib/agent/BrowserAgent.ts index f326fdb7..53804507 100644 --- a/src/lib/agent/BrowserAgent.ts +++ b/src/lib/agent/BrowserAgent.ts @@ -53,6 +53,7 @@ import { GetSelectedTabsTool, DateTool, MCPTool, + YouTubeTool, } from "@/lib/tools"; import { GlowAnimationService } from '@/lib/services/GlowAnimationService'; import { TokenCounter } from "../utils/TokenCounter"; @@ -287,6 +288,7 @@ export class BrowserAgent { this.toolManager.register(CelebrationTool(this.executionContext)); // Celebration/confetti tool this.toolManager.register(DateTool(this.executionContext)); // Date/time utilities this.toolManager.register(BrowserOSInfoTool(this.executionContext)); // BrowserOS info tool + this.toolManager.register(YouTubeTool(this.executionContext)); // YouTube video analysis // External integration tools this.toolManager.register(MCPTool(this.executionContext)); // MCP server integration @@ -302,6 +304,11 @@ export class BrowserAgent { // Populate tool descriptions after all tools are registered this.toolDescriptions = getToolDescriptions(this.executionContext.isLimitedContextMode()); + // DEBUG: Log tool descriptions to verify YouTube tool is included + console.log('🔍 DEBUG: Tool descriptions length:', this.toolDescriptions?.length || 0); + console.log('🔍 DEBUG: YouTube tool in descriptions:', this.toolDescriptions?.includes('youtube_tool') ? 'YES' : 'NO'); + console.log('🔍 DEBUG: First 500 chars of toolDescriptions:', this.toolDescriptions?.substring(0, 500)); + Logging.log( "BrowserAgent", `Registered ${this.toolManager.getAll().length} tools`, @@ -735,6 +742,13 @@ export class BrowserAgent { // System prompt for planner const systemPrompt = generatePlannerPrompt(this.toolDescriptions || ""); + // DEBUG: Log system prompt details + console.log('🎯 DEBUG: Planner system prompt length:', systemPrompt.length); + console.log('🎯 DEBUG: YouTube tool in planner prompt:', systemPrompt.includes('youtube_tool') ? 'YES' : 'NO'); + console.log('🎯 DEBUG: MANDATORY rule in prompt:', systemPrompt.includes('MANDATORY for YouTube') ? 'YES' : 'NO'); + console.log('🎯 DEBUG: Tool descriptions passed:', this.toolDescriptions ? 'EXISTS' : 'MISSING'); + console.log('🎯 DEBUG: First 1000 chars of planner prompt:', systemPrompt.substring(0, 1000)); + const systemPromptTokens = TokenCounter.countMessage(new SystemMessage(systemPrompt)); const fullHistoryTokens = TokenCounter.countMessage(new HumanMessage(fullHistory)); Logging.log("BrowserAgent", `Full execution history tokens: ${fullHistoryTokens}`, "info"); @@ -840,6 +854,11 @@ ${fullHistory} actions: string[], plannerOutput: PlannerOutput | PredefinedPlannerOutput ): Promise { + // DEBUG: Log what actions the planner proposed + console.log('🎭 DEBUG: Planner proposed actions:', actions); + console.log('🎭 DEBUG: Any action mentions youtube_tool:', actions.some(a => a.toLowerCase().includes('youtube')) ? 'YES' : 'NO'); + console.log('🎭 DEBUG: Any action mentions extract:', actions.some(a => a.toLowerCase().includes('extract')) ? 'YES' : 'NO'); + // Use the current iteration message manager from execution context const executorMM = new MessageManager(); const systemPrompt = generateExecutorPrompt(this._buildExecutionContext()); diff --git a/src/lib/tools/YouTubeTool.ts b/src/lib/tools/YouTubeTool.ts new file mode 100644 index 00000000..eb60fba7 --- /dev/null +++ b/src/lib/tools/YouTubeTool.ts @@ -0,0 +1,241 @@ +import { DynamicStructuredTool } from '@langchain/core/tools' +import { z } from 'zod' +import { ExecutionContext } from '@/lib/runtime/ExecutionContext' +import { PubSubChannel } from '@/lib/pubsub/PubSubChannel' +import { Logging } from '@/lib/utils/Logging' +import { LLMSettingsReader } from '@/lib/llm/settings/LLMSettingsReader' +import { BrowserOSProvider } from '@/lib/llm/settings/browserOSTypes' + +// Input schema +const YouTubeToolInputSchema = z.object({ + action: z.enum(['summarize', 'ask', 'transcript']) + .describe('Action to perform: summarize (get video summary), ask (answer question about video), transcript (get full transcript)'), + question: z.string().optional() + .describe('Question to ask about the video (required for "ask" action)'), + videoUrl: z.string().url().optional() + .describe('YouTube video URL (auto-detects from current tab if not provided)') +}) + +type YouTubeToolInput = z.infer + +export function YouTubeTool(context: ExecutionContext): DynamicStructuredTool { + return new DynamicStructuredTool({ + name: 'youtube_tool', + description: `Analyze YouTube videos using Gemini's native video understanding. Capabilities: + +• summarize: Get key takeaways and main points from any video +• ask: Ask specific questions about video content (requires "question" parameter) +• transcript: Get full video transcript with timestamps + +AUTO-DETECTION: If no videoUrl provided, analyzes the YouTube video in the current tab. + +NOTE: Requires Gemini API key configured in settings. + +EXAMPLES: +- "Summarize this YouTube video" +- "What does the video say about artificial intelligence?" +- "Get the full transcript of this video"`, + + schema: YouTubeToolInputSchema, + + func: async (args: YouTubeToolInput) => { + try { + context.incrementMetric('toolCalls') + + // Check if Gemini is available + const geminiAvailable = await _isGeminiAvailable() + if (!geminiAvailable) { + return JSON.stringify({ + ok: false, + error: 'YouTube video analysis requires Gemini API. Please configure a Gemini API key in settings to use this feature.' + }) + } + + // Get video URL + context.getPubSub().publishMessage( + PubSubChannel.createMessage('Analyzing YouTube video...', 'thinking') + ) + + let videoUrl = args.videoUrl + if (!videoUrl) { + const page = await context.browserContext.getCurrentPage() + videoUrl = page.url() + } + + // Validate YouTube URL + const videoId = _extractVideoId(videoUrl) + if (!videoId) { + return JSON.stringify({ + ok: false, + error: 'Not a valid YouTube video URL. Please navigate to a YouTube video or provide a video URL.' + }) + } + + // Process with Gemini + return await _processWithGemini(videoUrl, args, context) + + } catch (error) { + context.incrementMetric('errors') + Logging.log('YouTubeTool', `Error: ${error instanceof Error ? error.message : String(error)}`, 'error') + return JSON.stringify({ + ok: false, + error: `YouTube tool failed: ${error instanceof Error ? error.message : String(error)}` + }) + } + } + }) +} + +// ============= Helper Functions ============= + +/** + * Check if Gemini is available and configured + */ +async function _isGeminiAvailable(): Promise { + try { + const config = await LLMSettingsReader.readAllProviders() + const geminiProvider = config.providers.find((p: BrowserOSProvider) => p.type === 'google_gemini' && p.apiKey) + return !!geminiProvider + } catch (error) { + return false + } +} + +/** + * Process YouTube video using Gemini's native support via REST API + */ +async function _processWithGemini( + videoUrl: string, + args: YouTubeToolInput, + context: ExecutionContext +): Promise { + try { + // Get Gemini configuration + const config = await LLMSettingsReader.readAllProviders() + const geminiProvider = config.providers.find((p: BrowserOSProvider) => p.type === 'google_gemini' && p.apiKey) + + if (!geminiProvider || !geminiProvider.apiKey) { + throw new Error('Gemini API key not found') + } + + // Prepare the prompt based on action + let promptText: string + switch (args.action) { + case 'summarize': + promptText = `Please summarize this YouTube video in 3 sections: +1. **Main Topic**: What is this video about? (1-2 sentences) +2. **Key Takeaways**: The most important points (3-5 bullet points) +3. **Notable Insights**: Any particularly interesting or valuable information` + break + + case 'ask': + if (!args.question) { + return JSON.stringify({ + ok: false, + error: 'Question is required for "ask" action. Please provide a question parameter.' + }) + } + promptText = `Answer this question about the YouTube video: "${args.question}" + +Provide a clear, direct answer based on the video content. If the answer includes specific quotes or references, include them.` + break + + case 'transcript': + promptText = `Extract and provide the full transcript of this YouTube video with timestamps if available.` + break + + default: + throw new Error('Invalid action') + } + + context.getPubSub().publishMessage( + PubSubChannel.createMessage('Processing with Gemini...', 'thinking') + ) + + // Use Gemini REST API directly with proper fileData format + const modelId = geminiProvider.modelId || 'gemini-2.5-flash' + const apiUrl = `https://generativelanguage.googleapis.com/v1beta/models/${modelId}:generateContent` + + const requestBody = { + contents: [{ + parts: [ + { text: promptText }, + { file_data: { file_uri: videoUrl } } + ] + }], + generationConfig: { + temperature: 0.3, + maxOutputTokens: 2000 + } + } + + const response = await fetch(apiUrl, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'x-goog-api-key': geminiProvider.apiKey + }, + body: JSON.stringify(requestBody) + }) + + if (!response.ok) { + const errorText = await response.text() + Logging.log('YouTubeTool', `Gemini API error: ${response.status}`, 'error') + throw new Error(`Gemini API error: ${response.status} - ${errorText}`) + } + + const data = await response.json() + + // Extract the text from Gemini's response + const responseText = data.candidates?.[0]?.content?.parts?.[0]?.text + + if (!responseText) { + throw new Error('No text content in Gemini response') + } + + return JSON.stringify({ + ok: true, + output: args.action === 'transcript' + ? { transcript: responseText } + : args.action === 'ask' + ? { answer: responseText } + : { summary: responseText } + }) + + } catch (error) { + Logging.log('YouTubeTool', `Gemini processing error: ${error}`, 'error') + throw error + } +} + +/** + * Extract video ID from various YouTube URL formats + */ +function _extractVideoId(url: string): string | null { + try { + // youtube.com/watch?v=VIDEO_ID + const watchMatch = url.match(/[?&]v=([^&]+)/) + if (watchMatch) return watchMatch[1] + + // youtu.be/VIDEO_ID + const shortMatch = url.match(/youtu\.be\/([^?&]+)/) + if (shortMatch) return shortMatch[1] + + // youtube.com/embed/VIDEO_ID + const embedMatch = url.match(/youtube\.com\/embed\/([^?&]+)/) + if (embedMatch) return embedMatch[1] + + // youtube.com/v/VIDEO_ID + const vMatch = url.match(/youtube\.com\/v\/([^?&]+)/) + if (vMatch) return vMatch[1] + + // youtube.com/shorts/VIDEO_ID + const shortsMatch = url.match(/youtube\.com\/shorts\/([^?&]+)/) + if (shortsMatch) return shortsMatch[1] + + return null + } catch (error) { + Logging.log('YouTubeTool', `Error extracting video ID: ${error}`, 'error') + return null + } +} diff --git a/src/lib/tools/index.ts b/src/lib/tools/index.ts index 45cfc1d4..f3ed4be5 100644 --- a/src/lib/tools/index.ts +++ b/src/lib/tools/index.ts @@ -34,3 +34,4 @@ export * from './GetSelectedTabsTool' export * from './GroupTabsTool' export * from './BrowserOSInfoTool' export * from './DateTool' +export * from './YouTubeTool' From 069de4f13553e670b6a3c9438b1227b31f0c9afc Mon Sep 17 00:00:00 2001 From: Omkar Bansod Date: Fri, 7 Nov 2025 16:22:27 +0530 Subject: [PATCH 2/3] remove extra logs --- src/lib/agent/BrowserAgent.ts | 17 ----------------- 1 file changed, 17 deletions(-) diff --git a/src/lib/agent/BrowserAgent.ts b/src/lib/agent/BrowserAgent.ts index 53804507..d1aa1d7b 100644 --- a/src/lib/agent/BrowserAgent.ts +++ b/src/lib/agent/BrowserAgent.ts @@ -304,11 +304,6 @@ export class BrowserAgent { // Populate tool descriptions after all tools are registered this.toolDescriptions = getToolDescriptions(this.executionContext.isLimitedContextMode()); - // DEBUG: Log tool descriptions to verify YouTube tool is included - console.log('🔍 DEBUG: Tool descriptions length:', this.toolDescriptions?.length || 0); - console.log('🔍 DEBUG: YouTube tool in descriptions:', this.toolDescriptions?.includes('youtube_tool') ? 'YES' : 'NO'); - console.log('🔍 DEBUG: First 500 chars of toolDescriptions:', this.toolDescriptions?.substring(0, 500)); - Logging.log( "BrowserAgent", `Registered ${this.toolManager.getAll().length} tools`, @@ -742,13 +737,6 @@ export class BrowserAgent { // System prompt for planner const systemPrompt = generatePlannerPrompt(this.toolDescriptions || ""); - // DEBUG: Log system prompt details - console.log('🎯 DEBUG: Planner system prompt length:', systemPrompt.length); - console.log('🎯 DEBUG: YouTube tool in planner prompt:', systemPrompt.includes('youtube_tool') ? 'YES' : 'NO'); - console.log('🎯 DEBUG: MANDATORY rule in prompt:', systemPrompt.includes('MANDATORY for YouTube') ? 'YES' : 'NO'); - console.log('🎯 DEBUG: Tool descriptions passed:', this.toolDescriptions ? 'EXISTS' : 'MISSING'); - console.log('🎯 DEBUG: First 1000 chars of planner prompt:', systemPrompt.substring(0, 1000)); - const systemPromptTokens = TokenCounter.countMessage(new SystemMessage(systemPrompt)); const fullHistoryTokens = TokenCounter.countMessage(new HumanMessage(fullHistory)); Logging.log("BrowserAgent", `Full execution history tokens: ${fullHistoryTokens}`, "info"); @@ -854,11 +842,6 @@ ${fullHistory} actions: string[], plannerOutput: PlannerOutput | PredefinedPlannerOutput ): Promise { - // DEBUG: Log what actions the planner proposed - console.log('🎭 DEBUG: Planner proposed actions:', actions); - console.log('🎭 DEBUG: Any action mentions youtube_tool:', actions.some(a => a.toLowerCase().includes('youtube')) ? 'YES' : 'NO'); - console.log('🎭 DEBUG: Any action mentions extract:', actions.some(a => a.toLowerCase().includes('extract')) ? 'YES' : 'NO'); - // Use the current iteration message manager from execution context const executorMM = new MessageManager(); const systemPrompt = generateExecutorPrompt(this._buildExecutionContext()); From cffdcf87e2e91150cb23d0de72de58f4e9359d16 Mon Sep 17 00:00:00 2001 From: Omkar Bansod Date: Wed, 19 Nov 2025 19:07:35 +0530 Subject: [PATCH 3/3] fix gemini limitation issue by replacing literal with enum --- src/lib/tools/PdfExtract.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib/tools/PdfExtract.ts b/src/lib/tools/PdfExtract.ts index da399745..154b2760 100644 --- a/src/lib/tools/PdfExtract.ts +++ b/src/lib/tools/PdfExtract.ts @@ -75,7 +75,7 @@ AI-powered extraction (uses LLM): pages: z .union([ - z.literal("all"), + z.enum(["all"]), // Using enum instead of literal for Gemini API compatibility (Gemini doesn't support JSON Schema "const" keyword) z.object({ start: z.number(), end: z.number()