Google Gemini API Integration
Relevant source files
The following files were used as context for generating this wiki page:The Google Gemini API integration is a core feature of the YouTube Channel Analyzer, providing AI-powered insights into video content. It leverages the gemini-2.5-flash model to perform two primary functions: analyzing a YouTube video to determine its viral potential and providing an interactive chat assistant for follow-up questions. The integration is designed to be efficient, using Google Search grounding to access video content directly from its URL and provide up-to-date, context-aware analysis.
The system is split between the frontend React application, which initiates requests and displays results, and the backend tRPC API, which securely communicates with the Google Gemini API. Shared TypeScript types ensure data consistency across the full stack.
Sources: README.md:3, 29, apps/api/src/features/ai/ai.service.ts:7, 12-15
Architecture Overview
The integration follows a standard client-server model, where the frontend VideoAnalyzer component communicates with the backend API, which in turn acts as a proxy to the Google Gemini API.
This diagram illustrates the high-level data flow for an AI analysis request.
Backend Services
The core logic for interacting with the Gemini API resides in the ai.service.ts file. It uses the @google/genai library to communicate with the Google AI platform.
Sources: apps/api/src/features/ai/ai.service.ts:1, apps/api/package.json:18
Video Analysis (analyzeVideo)
This function is responsible for generating a "Viral Analysis Report" for a given YouTube video. It constructs a detailed prompt and uses Google Search as a tool for the AI to gather information about the video's content.
The process is as follows:
- Initialize the
GoogleGenAIclient with the API key. - Format the top 20 video comments into a string to provide audience sentiment context.
- Construct a detailed prompt including the video URL, title, description, and the formatted comments.
- Instruct the AI to act as an expert video strategist and return a specific JSON object.
- Send the request to the
gemini-2.5-flashmodel, enabling thegoogleSearchtool. - Parse the JSON response from the AI. The service includes robust parsing logic to handle variations in the AI's output format.
- Extract grounding metadata (sources used by the Google Search tool) and append it to the result.
- Return the structured
ViralAnalysisResultobject.
Sources: apps/api/src/features/ai/ai.service.ts:12-98
This flowchart shows the logic within the analyzeVideo function.
Conversational Chat (chatAboutVideo)
This function facilitates a follow-up conversation with the AI about a video that has already been analyzed. It maintains chat history to provide context for subsequent questions.
The process is as follows:
- Initialize the
GoogleGenAIclient. - Create a system instruction that provides context, including the video URL, title, and the previously generated analysis summary.
- Create a new chat session using the
gemini-2.5-flashmodel, passing the system instruction and the existing chat history. - Send the user's new message to the chat session.
- Return the AI's text response.
Sources: apps/api/src/features/ai/ai.service.ts:107-136
This sequence diagram illustrates a user asking a follow-up question.
API Endpoints (ai.router.ts)
The AI features are exposed via a tRPC router. Both endpoints are protectedProcedure, meaning they require user authentication.
| Procedure | Description | Input Schema |
|---|---|---|
ai.analyze | Analyzes a YouTube video and its comments to generate a viral analysis report. | z.object({ video: youtubeVideoSchema, comments: z.array(youtubeCommentSchema) }) |
ai.chat | Handles conversational follow-ups about a previously analyzed video. | z.object({ history: chatHistorySchema, message: z.string(), video: youtubeVideoSchema, analysis: viralAnalysisResultSchema }) |
Sources: apps/api/src/features/ai/ai.router.ts:13-47
Frontend Integration (VideoAnalyzer.tsx)
The VideoAnalyzer component in the apps/web package is the user-facing interface for the Gemini integration.
Key implementation details:
- State Management: Uses
useStateto manage the analysis result, loading states, errors, and chat messages. - Data Fetching: The
handleAnalyzefunction calls thetrpcClient.ai.analyze.mutateprocedure to fetch the analysis. - Local Storage Caching: After a successful analysis, the result is saved to
localStorageusing a key likevideo_analysis_{video.id}to avoid redundant API calls. It is loaded viauseEffectwhen the component mounts. - Chat Interaction: The
handleSendMessagefunction constructs the payload for thetrpcClient.ai.chat.mutateprocedure, including the chat history, and updates the chat UI optimistically.
Sources: apps/web/src/features/ai/components/video-analyzer.component.tsx:34-45, 66-83, 94-126
Shared Data Structures
The @repo/types package defines the data structures used by both the frontend and backend to ensure type safety.
Sources: packages/types/package.json:4, 40-47
ViralAnalysisResult
This type defines the structure of the JSON object returned by the analyzeVideo function.
| Field | Type | Description |
|---|---|---|
summary | string | A summary of the video's content. |
hooks | string[] | A list of "hooks" that explain why people clicked on the video. |
viralReasons | string[] | An explanation of the psychological reasons the video was shared. |
contentIdeas | string[] | A list of 3-5 new content ideas inspired by the video. |
sources | { title: string, uri: string }[] | (Optional) A list of web sources used by Gemini's search tool. |
Sources: apps/api/src/features/ai/ai.service.ts:4, 43-49, 81-96
ChatMessage
This type defines the structure for a single message in the chat interface.
| Field | Type | Description |
|---|---|---|
role | "user" | "model" | The author of the message. |
text | string | The content of the message. |
Sources: apps/web/src/features/ai/components/video-analyzer.component.tsx:5, 31, 100
Summary
The Google Gemini API integration is a cornerstone of the application, providing sophisticated, AI-driven content analysis. By using the gemini-2.5-flash model with Google Search grounding, the system can deliver deep insights into YouTube video performance. The architecture is robust, with clear separation of concerns between the frontend UI, the tRPC backend, and the AI service layer, all tied together with a shared type system.
Sources: README.md:29, apps/api/src/features/ai/ai.service.ts:7