diff --git a/src/lib/agent/BrowserAgent.prompt.ts b/src/lib/agent/BrowserAgent.prompt.ts index 49f4322d..ce278ed6 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) - pdf_extract(format, task?, page?, pages?): Extract data from PDF documents with selective PDF.js capabilities ↳ Raw metadata: format={metadata: true} (no LLM cost) ↳ Raw text: format={text: true} (no LLM cost) @@ -181,6 +194,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:** @@ -210,9 +235,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". + # PDF HANDLING GUIDANCE **Detecting PDFs:** If the current page is a PDF (URL ends with .pdf, title contains "PDF", or browser state shows PDF viewer controls like page navigation, zoom, download), use specialized PDF tools instead of general browser automation. @@ -236,7 +265,7 @@ Example: Use "Use MCP to search Gmail for unread emails" instead of "Navigate to **Page Selection:** - \`page: [3, 5]\` for specific pages -- \`pages: {start: 1, end: 5}\` for ranges +- \`pages: {start: 1, end: 5}\` for ranges - \`pages: "all"\` for entire document (default) - **50-Page Limit:** All PDF.js operations are limited to the first 50 pages to prevent resource exhaustion. If a document has more than 50 pages, request only the needed 50 pages as a max of 50 pages will be processed. @@ -308,6 +337,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 6130cc9b..b09743ec 100644 --- a/src/lib/agent/BrowserAgent.ts +++ b/src/lib/agent/BrowserAgent.ts @@ -53,6 +53,7 @@ import { GetSelectedTabsTool, DateTool, MCPTool, + YouTubeTool, PdfExtractTool, } from "@/lib/tools"; import { GlowAnimationService } from '@/lib/services/GlowAnimationService'; @@ -288,6 +289,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 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() 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 d7733f15..238b6645 100644 --- a/src/lib/tools/index.ts +++ b/src/lib/tools/index.ts @@ -35,3 +35,4 @@ export * from './GetSelectedTabsTool' export * from './GroupTabsTool' export * from './BrowserOSInfoTool' export * from './DateTool' +export * from './YouTubeTool'