All files / src/providers/gemini Image.ts

84.21% Statements 16/19
58.33% Branches 7/12
100% Functions 2/2
84.21% Lines 16/19

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63            12x 12x       1x 1x   1x           1x                     1x   1x               1x       1x 1x 1x   1x       1x 1x   1x            
import { ImageRequest, ImageResponse } from "../Provider.js";
import { handleGeminiError } from "./Errors.js";
import { logger } from "../../utils/logger.js";
 
export class GeminiImage {
  constructor(
    private readonly baseUrl: string,
    private readonly apiKey: string
  ) {}
 
  async execute(request: ImageRequest): Promise<ImageResponse> {
    const modelId = request.model || "imagen-4.0-generate-001";
    const url = `${this.baseUrl}/models/${modelId}:predict?key=${this.apiKey}`;
 
    Iif (request.size) {
      logger.warn(
        `[Gemini] Ignoring size ${request.size}. Gemini does not support image size customization.`
      );
    }
 
    const body: Record<string, unknown> = {
      instances: [
        {
          prompt: request.prompt
        }
      ],
      parameters: {
        sampleCount: 1
      }
    };
 
    logger.logRequest("Gemini", "POST", url, body);
 
    const response = await fetch(url, {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify(body)
    });
 
    Iif (!response.ok) {
      await handleGeminiError(response, modelId);
    }
 
    const json = await response.json();
    logger.logResponse("Gemini", response.status, response.statusText, json);
    const imageData = json.predictions?.[0];
 
    Iif (!imageData || !imageData.bytesBase64Encoded) {
      throw new Error("Unexpected response format from Gemini image generation API");
    }
 
    const mimeType = imageData.mimeType || "image/png";
    const base64Data = imageData.bytesBase64Encoded;
 
    return {
      data: base64Data,
      mime_type: mimeType
    };
  }
}