Journalism AI - v3.0.7
    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 }]. Local paths and gs:// GCS URLs are both supported for images, audio, video, PDF, and text.

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

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

      Type Parameters

      • TResponse = unknown

      Parameters

      • prompt: string

        The primary text prompt.

      • Optionaloptions: {
            apiKey?: string;
            cache?: boolean;
            files?: {
                path: string;
                type: "image" | "video" | "audio" | "pdf" | "text";
            }[];
            geminiParameters?: Partial<GenerateContentParameters>;
            location?: string;
            model?: string;
            processResponse?: (response: unknown) => TResponse | Promise<TResponse>;
            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" }[]

          Files to send alongside the prompt, in order. Each entry has a path (local path or gs:// URL) and a type ("image", "video", "audio", "pdf", or "text"). All files are appended as separate content parts after the prompt.

        • OptionalgeminiParameters?: Partial<GenerateContentParameters>

          Extra params merged into generateContent.

        • Optionallocation?: string

          GCP location; defaults to AI_LOCATION env var.

        • Optionalmodel?: string

          Model name; defaults to AI_MODEL env var.

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

          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. Use 0 to disable thinking, -1 for a dynamic budget, or a positive number for a fixed budget. Ignored when thinkingLevel is provided.

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

          Thinking level: "minimal" | "low" | "medium" | "high".

        • 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";
              }[];
              fromCache: boolean;
              model: string;
              outputTokenCount: number;
              prompt: string;
              promptTokenCount: number;
              response: TResponse;
              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",
      });
      // 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}`);