AI API Router
Relevant source files
The following files were used as context for generating this wiki page:The AI API Router is a core component of the backend api application, responsible for handling all AI-related functionalities. Built using tRPC, it exposes procedures for analyzing YouTube video content and facilitating a conversational chat about the analysis. This router acts as a bridge between the frontend client and the backend AI service, which leverages the Google Gemini AI model to generate insights.
The architecture follows a clear separation of concerns, with the router (ai.router.ts) managing API endpoints, input validation, and authentication, while the service (ai.service.ts) contains the business logic for interacting with the Google Gemini API. All procedures within this router are protected, meaning they require user authentication to be accessed.
Sources: apps/api/src/features/ai/ai.router.ts, README.md:19-29, apps/api/src/trpc/router.ts:3-8
Architecture Overview
The AI feature is structured with a distinct router and service layer. The aiRouter is integrated into the main appRouter, making its procedures available under the ai namespace (e.g., ai.analyze, ai.chat).
This diagram illustrates the high-level data flow from a client request to the AI service.
This diagram shows the flow of an AI analysis request from the frontend component through the backend router and service to the external Gemini API and back.
Sources: apps/api/src/features/ai/ai.router.ts:16, apps/api/src/features/ai/ai.service.ts:13, apps/web/src/features/ai/components/video-analyzer.component.tsx:81, apps/api/src/trpc/router.ts:4-8
API Endpoints
The aiRouter defines two primary tRPC mutation procedures. Both are protectedProcedure, ensuring only authenticated users can access them.
Sources: apps/api/src/features/ai/ai.router.ts:16-45
ai.analyze
This mutation triggers an AI-powered analysis of a specific YouTube video. It takes video metadata and optional comments as input, uses the analyzeVideo service function to interact with the Gemini AI, and returns a structured analysis object. The frontend stores this analysis result in localStorage to prevent redundant API calls.
Sources: apps/api/src/features/ai/ai.router.ts:17-27, apps/web/src/features/ai/components/video-analyzer.component.tsx:64-68
Input Schema
| Parameter | Type | Description | Required |
|---|---|---|---|
video | youtubeVideoSchema | An object containing the YouTube video's metadata. | Yes |
comments | z.array(youtubeCommentSchema) | An array of comments from the video. Defaults to an empty array. | No |
Sources: apps/api/src/features/ai/ai.router.ts:19-22
Sequence Diagram
This diagram shows the sequence of events when the analyze mutation is called from the frontend.
ai.chat
This mutation enables a conversational follow-up based on a previously completed video analysis. It sends the chat history, a new user message, and the original video/analysis context to the chatAboutVideo service function.
Sources: apps/api/src/features/ai/ai.router.ts:32-45
Input Schema
| Parameter | Type | Description | Required |
|---|---|---|---|
history | chatHistorySchema | An array of previous chat messages. Defaults to an empty array. | No |
message | z.string().min(1) | The new message from the user. | Yes |
video | youtubeVideoSchema | The context of the video being discussed. | Yes |
analysis | viralAnalysisResultSchema | The context of the AI analysis being discussed. | Yes |
Sources: apps/api/src/features/ai/ai.router.ts:34-39
Sequence Diagram
Core Services (ai.service.ts)
The ai.service.ts file implements the core logic for communicating with the Google Gemini AI. It uses the @google/genai package and is configured with the GEMINI_API_KEY from environment variables. The model used is gemini-2.5-flash.
Sources: apps/api/src/features/ai/ai.service.ts:1-7
analyzeVideo(video, comments)
This function orchestrates the video analysis.
- Prompt Construction: It builds a detailed prompt instructing the AI to act as a video strategist. The prompt includes the video URL, title, description, and a summary of the top 20 comments.
- Google Search Grounding: It makes the API call with
tools: [{ googleSearch: {} }]enabled. This allows Gemini to access the video's content via its URL to provide a more accurate analysis. - JSON Parsing: It expects a strictly valid JSON object in response and includes logic to clean up and parse the response text, even if it's wrapped in markdown code fences.
- Source Extraction: After a successful response, it inspects the
groundingMetadatato extract the web sources used by the AI and appends them to the result object.
Sources: apps/api/src/features/ai/ai.service.ts:13-97
chatAboutVideo(history, message, video, analysis)
This function manages the conversational chat.
- Contextual System Instruction: It creates a chat session with a
systemInstructionthat provides the AI with the necessary context: the video URL, title, and a summary of the initial analysis. This ensures the AI's responses are relevant to the specific video being discussed. - History Management: It uses the
historyprovided from the client to maintain the conversation's state. - Message Sending: It sends the user's new
messageand returns the AI's text response.
Sources: apps/api/src/features/ai/ai.service.ts:111-135
Data Models & Types
The AI feature relies on shared TypeScript types defined in the @repo/types package. This ensures type safety between the frontend and backend.
Sources: packages/types/package.json:2-4, apps/api/src/features/ai/ai.router.ts:3-5
Key types are exported for use in other parts of the monorepo:
| Type Export | File Path in @repo/types | Description |
|---|---|---|
viral-analysis-result.type | src/ai/viral-analysis-result.type.ts | Defines the shape of the JSON object returned by the analyze endpoint. |
chat-message.type | src/ai/chat-message.type.ts | Defines the structure for a single chat message (role and text). |
Sources: packages/types/package.json:44-50
The viralAnalysisResultSchema defines the expected structure of the analysis:
summary:stringhooks:string[]viralReasons:string[]contentIdeas:string[]sources(optional):{ title: string, uri: string }[]
Sources: apps/api/src/features/ai/ai.router.ts:5, apps/api/src/features/ai/ai.service.ts:80-95