Journalism AI - v3.0.9
    Preparing search index...

    Function askGemini

    • Interacts with Google's Gemini models to perform a wide range of tasks, from answering questions to analyzing multimedia content.

      Authentication: set AI_KEY (API key) or AI_PROJECT + AI_LOCATION (Vertex AI) environment variables, or pass credentials directly via options.

      Caching: model calls can be slow and costly, so original responses are cached in .journalism-cache by default. processResponse reruns on every call, including cache hits, and its output is never cached. Keep it lightweight and optimize heavier processing, especially for large workloads. Set cache: false to disable caching.

      File handling: pass files via files: [{ path, type }]. Attach local files, gs:// Cloud Storage URIs, or publicly accessible HTTP(S) URLs. Use type: "video" for YouTube URLs. For YouTube URLs and other video files, you can set videoMetadata with startOffset, endOffset, and fps.

      Web Search Grounding: set webSearch: true to let the model search the web in real time (extra API cost).

      Cost estimates: estimatedCost uses regular global USD list rates for supported models, including for reasoning tokens. Those rates apply to the estimate during promotions. Cached responses retain their original estimate.

      Thinking defaults to "low" when neither thinking option is supplied. If the call fails with a thinking configuration error, pass a supported thinkingLevel or thinkingBudget for your model.

      Safety filters are on by default (true) but off when using Vertex AI (false); override with safetyEnabled.

      Type Parameters

      • ResponseValue = unknown

        The type of result.response. Inferred from processResponse when provided and defaults to unknown.

      Parameters

      • prompt: string

        The primary text prompt.

      • Optionaloptions: {
            apiKey?: string;
            cache?: boolean;
            files?: {
                path: string;
                type: "image" | "video" | "audio" | "pdf" | "text";
                videoMetadata?: { endOffset?: string; fps?: number; startOffset?: string };
            }[];
            geminiParameters?: Partial<GenerateContentParameters>;
            location?: string;
            model?: string;
            processResponse?: (
                response: unknown,
            ) => ResponseValue | Promise<ResponseValue>;
            project?: string;
            safetyEnabled?: boolean;
            schemaJson?: unknown;
            systemPrompt?: string;
            temperature?: number;
            thinkingBudget?: number;
            thinkingLevel?: "minimal" | "low" | "medium" | "high";
            vertex?: boolean;
            webSearch?: boolean;
        }
        • OptionalapiKey?: string

          API key; defaults to AI_KEY env var.

        • Optionalcache?: boolean

          Cache the model response before user processing, not the callback output. Defaults to true.

        • Optionalfiles?: {
              path: string;
              type: "image" | "video" | "audio" | "pdf" | "text";
              videoMetadata?: { endOffset?: string; fps?: number; startOffset?: string };
          }[]

          Files to send alongside the prompt, in order. Each entry has a path (local path, gs:// URI, or HTTP(S) URL) and a type ("image", "video", "audio", "pdf", or "text"). For YouTube URLs and other video files, you can set videoMetadata with startOffset, endOffset, and fps. All files are appended as separate content parts after the prompt.

        • OptionalgeminiParameters?: Partial<GenerateContentParameters>

          Extra params merged into generateContent and included in the cache key. Requests with a custom fetch implementation or callable tools bypass the cache.

        • Optionallocation?: string

          GCP location; defaults to AI_LOCATION env var.

        • Optionalmodel?: string

          Model name; defaults to AI_MODEL env var.

        • OptionalprocessResponse?: (response: unknown) => ResponseValue | Promise<ResponseValue>

          Transform or validate the model response on every call, including cache hits. The callback output is never cached; rejected cached responses are removed.

        • Optionalproject?: string

          GCP project ID; defaults to AI_PROJECT env var.

        • OptionalsafetyEnabled?: boolean

          Override safety filter defaults; this library requires true with API-key authentication.

        • OptionalschemaJson?: unknown

          Zod JSON schema for structured output.

        • OptionalsystemPrompt?: string

          Optional system prompt.

        • Optionaltemperature?: number

          Sampling temperature sent to Gemini.

        • OptionalthinkingBudget?: number

          Reasoning token budget for models that accept budgets. Use 0 to disable thinking where supported, -1 for a dynamic budget, or a positive number for a fixed budget. An explicit thinkingLevel takes precedence.

        • OptionalthinkingLevel?: "minimal" | "low" | "medium" | "high"

          Use "minimal", "low", "medium", or "high" as supported by the model. Defaults to "low" when no budget is supplied. Set a level explicitly to request thought summaries.

        • Optionalvertex?: boolean

          Use Vertex AI authentication.

        • OptionalwebSearch?: boolean

          Enable web search grounding (extra cost).

      Returns Promise<
          {
              durationMs: number;
              estimatedCost: number
              | null;
              files: {
                  path: string;
                  type: "image" | "video" | "audio" | "pdf" | "text";
                  videoMetadata?: {
                      endOffset?: string;
                      fps?: number;
                      startOffset?: string;
                  };
              }[];
              fromCache: boolean;
              model: string;
              outputTokenCount: number;
              prompt: string;
              promptTokenCount: number;
              response: ResponseValue;
              safetyEnabled: boolean;
              systemPrompt: string
              | null;
              thinkingLevel: "minimal" | "low" | "medium" | "high" | null;
              thoughts: string | null;
              thoughtsTokenCount: number;
              tokensPerSecond: number | null;
              totalTokens: number;
              webSearch: boolean;
          },
      >

      const result = await askGemini("What is the capital of France?");
      console.log(result.response); // "Paris"
      // Pass credentials directly.
      const response = await askGemini("What is the capital of France?", {
      apiKey: "your_api_key",
      model: "gemini-3.5-flash",
      });

      // Vertex AI.
      const vertexResponse = await askGemini("What is the capital of France?", {
      vertex: true,
      project: "your_project_id",
      location: "us-central1",
      });
      // Web search grounding.
      const factCheck = await askGemini(
      `Verify: "Renewable energy now accounts for over 30% of global electricity generation."`,
      { webSearch: true },
      );
      // Structured JSON output with a Zod schema.
      import * as z from "zod";
      const schema = z.toJSONSchema(z.array(z.object({ name: z.string(), age: z.number() })));
      await askGemini("Give me 10 random people.", { schemaJson: schema });
      // Analyse a local image.
      const info = await askGemini("Describe this image.", {
      files: [{ path: "./photo.jpg", type: "image" }],
      });
      // Analyse a file stored in Google Cloud Storage.
      const result = await askGemini("Summarize this document.", {
      files: [{ path: "gs://my-bucket/report.pdf", type: "pdf" }],
      vertex: true,
      project: "my-gcp-project",
      location: "us-central1",
      });
      // Analyze the first five seconds of a public YouTube video.
      // At 0.5 fps, Gemini samples one frame every two seconds.
      const result = await askGemini("Describe what happens in this clip.", {
      files: [{
      path: "https://www.youtube.com/watch?v=0cBh_LwbkfE",
      type: "video",
      videoMetadata: { startOffset: "0s", endOffset: "5s", fps: 0.5 },
      }],
      });
      console.log(result.response);
      // Access token usage and estimated cost directly from the response.
      const result = await askGemini("What is the capital of France?");
      console.log(result.response); // "Paris"
      console.log(`${result.totalTokens} tokens, $${result.estimatedCost}`);