function IMAGEN()

in vision/use-cases/hey_llm/src/main.ts [556:611]


function IMAGEN(
  prompt: string,
  seed = 1,
  model = DEFAULT_IMAGEN_MODEL,
  aspectRatio = DEFAULT_ASPECT_RATIO,
) {
  if (!prompt) return '';

  // If user specifies a blank string for model, it falls back to the default model.
  model = model ? model : DEFAULT_IMAGEN_MODEL;

  const cacheKey = generateHashValue(
    `imagen:${prompt}:${seed}:${model}:${aspectRatio}`,
  );
  const cache = CacheService.getDocumentCache();
  const cached = cache?.get(cacheKey);
  if (cached) {
    return cached;
  }
  const clientID = PropService.clientID;
  const clientSecret = PropService.clientSecret;
  if (!clientID || !clientSecret) {
    throw new Error('OAuth client ID / Secret not set.');
  }
  const oauthService = getGoogleService_(clientID, clientSecret);
  if (!PropService.driveFolderID) {
    PropService.driveFolderID = createDriveFolder_(oauthService);
  }
  const filename = sanitizeFileName(`${cacheKey}_${prompt.slice(0, 64)}.png`);
  const driveUrl = checkDriveImage_(
    oauthService,
    filename,
    PropService.driveFolderID,
  );
  if (driveUrl) {
    return driveUrl;
  }
  const pred = requestImagen_(oauthService, prompt, seed, model, aspectRatio);
  const thumbnailLink = uploadImageToDrive_(
    oauthService,
    pred.bytesBase64Encoded,
    filename,
    pred.mimeType,
    PropService.driveFolderID,
  );

  // Trim resize parameters that comes after the equal mark.
  const url =
    thumbnailLink.indexOf('=') > -1
      ? thumbnailLink.split('=').slice(0, -1).join('')
      : thumbnailLink;

  // Short cache duration is set intentionally because the thumbnail link might expire.
  cache?.put(cacheKey, url);
  return url;
}