Skip to content

Unexpected GoogleAISafetyError: Finish reason: OTHER when using Gemini Flash 2.5 TTS models #754

@CodeWithOz

Description

@CodeWithOz

Description of the bug:

I'm using the Gemini 2.5 Flash models to generate audio for some dialogues that translate French to English. I'm getting this strange error GoogleAISafetyError: Finish reason: OTHER on text that doesn't contain any harmful content, even after I specifically disable blocking on the harm categories that we're allowed to control. Here's my code:

Speech generation test
// ./tmp.ts
import path from 'path';
import dotenv from 'dotenv';
import { generateSpeech, PRESENTERS } from './lib/tts';

dotenv.config({ path: path.join(process.cwd(), '.env.local') });

(async () => {
  const scripts: string[] = [
    '[laughs] Merci Marie! Alors, écoutez la première phrase, dans trois... deux... un...',
    `[happily] Je vais répéter la phrase, dans trois... deux... un... [inhales deeply] La phrase, c'est "[very slowly for emphasis] Mais arrêtez donc de dire toujours et encore félicitations.". [inhales deeply] Cette phrase veut dire "[English explanation] But stop saying "congratulations" again and again.". [inhales deeply] Les verbes utilisés ici sont "arrêtez" qui est conjugué de "arrêter" qui signifie "[English explanation] to stop" et "dire" qui est conjugué de "dire" qui signifie "[English explanation] to say".  [inhales deeply] Ensuite, voici des autres mots que vous devez connaître: "donc" signifie "[English explanation] so; used for emphasis or urgent request". "toujours" signifie "[English explanation] continuously; repeatedly". "encore" signifie "[English explanation] again; adds emphasis to repetition". "félicitations" signifie "[English explanation] congratulations (plural; expression of praise)". [inhales deeply] Enfin, il y a aussi des expressions idiomatiques que vous devez connaître: "arrêtez donc de" est une expression idiomatique qui veut littéralement dire "[English explanation] stop then of". Dans ce contexte, cela exprime l'idée de "[English explanation] do stop; please stop (emphatic imperative)" en anglais. "toujours et encore" est une expression idiomatique qui veut littéralement dire "[English explanation] always and again". Dans ce contexte, cela exprime l'idée de "[English explanation] over and over again; repeatedly" en anglais. [inhales deeply] Et maintenant, passons à la phrase suivante.`,
    `[happily] Parfait! Voilà la phrase suivante, dans trois... deux... un...`,
    `[happily] Je vais répéter la phrase, dans trois... deux... un... [inhales deeply] La phrase, c'est "[very slowly for emphasis] Bien sûr que félicitations, on l'utilise avec un s à la fin s'il vous plaît.". [inhales deeply] Cette phrase veut dire "[English explanation] Of course: "félicitations" — we use it with an s at the end, please.". [inhales deeply] Les verbes utilisés ici sont "l'utilise" qui est conjugué de "utiliser" qui signifie "[English explanation] to use" et "plaît" qui est conjugué de "plaire" qui signifie "[English explanation] to please (used as "please")".  [inhales deeply] Ensuite, voici des autres mots que vous devez connaître: "bien sûr" signifie "[English explanation] of course". "félicitations" signifie "[English explanation] congratulations". "s" signifie "[English explanation] the letter s (plural ending)". "fin" signifie "[English explanation] end". [inhales deeply] Enfin, il y a aussi des expressions idiomatiques que vous devez connaître: "Bien sûr que" est une expression idiomatique qui veut littéralement dire "[English explanation] well sure that". Dans ce contexte, cela exprime l'idée de "[English explanation] of course" en anglais. "s'il vous plaît" est une expression idiomatique qui veut littéralement dire "[English explanation] if it pleases you". Dans ce contexte, cela exprime l'idée de "[English explanation] please" en anglais. [inhales deeply] Et maintenant, passons à la phrase suivante.`,
    `[happily] Magnifique! Voilà la phrase suivante, dans trois... deux... un...`,
    `[happily] Je vais répéter la phrase, dans trois... deux... un... [inhales deeply] La phrase, c'est "[very slowly for emphasis] Mais il y a plein d'autres choses que vous pouvez dire, d'autres mots, d'autres expressions pour féliciter une personne, n'est-ce pas, en français". [inhales deeply] Cette phrase veut dire "[English explanation] But there are plenty of other things you can say, other words, other expressions to congratulate someone, right, in French". [inhales deeply] Les verbes utilisés ici sont "il y a" qui est conjugué de "avoir" qui signifie "[English explanation] there is or there are", "pouvez" qui est conjugué de "pouvoir" qui signifie "[English explanation] to be able to; can", "dire" qui est conjugué de "dire" qui signifie "[English explanation] to say", "féliciter" qui est conjugué de "féliciter" qui signifie "[English explanation] to congratulate" et "est" qui est conjugué de "être" qui signifie "[English explanation] to be (used in tag question)".  [inhales deeply] Ensuite, voici des autres mots que vous devez connaître: "plein" signifie "[English explanation] plenty of; a lot of". "autres" signifie "[English explanation] other". "choses" signifie "[English explanation] things". "mots" signifie "[English explanation] words". "expressions" signifie "[English explanation] expressions; set phrases". "personne" signifie "[English explanation] person; someone". "français" signifie "[English explanation] French (language)". [inhales deeply] Enfin, il y a aussi des expressions idiomatiques que vous devez connaître: "n'est-ce pas" est une expression idiomatique qui veut littéralement dire "[English explanation] isn't it?". Dans ce contexte, cela exprime l'idée de "[English explanation] right? (tag question asking for confirmation)" en anglais. "plein de" est une expression idiomatique qui veut littéralement dire "[English explanation] full of". Dans ce contexte, cela exprime l'idée de "[English explanation] a lot of; plenty of" en anglais. [inhales deeply] Et maintenant, passons à la phrase suivante.`,
    `[happily] Magnifique! Voilà la phrase suivante, dans trois... deux... un...`,
    `[happily] Je vais répéter la phrase, dans trois... deux... un... [inhales deeply] La phrase, c'est "[very slowly for emphasis] Cela vous permettra d'enrichir votre vocabulaire et de comprendre les expressions quand vous regardez vos séries françaises préférées.". [inhales deeply] Cette phrase veut dire "[English explanation] This will allow you to enrich your vocabulary and understand expressions when you watch your favorite French series.". [inhales deeply] Les verbes utilisés ici sont "permettra" qui est conjugué de "permettre" qui signifie "[English explanation] to allow or to enable", "d'enrichir" qui est conjugué de "enrichir" qui signifie "[English explanation] to enrich or to expand", "de comprendre" qui est conjugué de "comprendre" qui signifie "[English explanation] to understand" et "regardez" qui est conjugué de "regarder" qui signifie "[English explanation] to watch".  [inhales deeply] Ensuite, voici des autres mots que vous devez connaître: "vocabulaire" signifie "[English explanation] vocabulary". "expressions" signifie "[English explanation] expressions or phrases". "séries" signifie "[English explanation] TV series or shows". "votre" signifie "[English explanation] your (possessive)". "françaises" signifie "[English explanation] French (feminine plural)". "préférées" signifie "[English explanation] favorite (feminine plural)". [inhales deeply] Et maintenant, passons à la phrase suivante.`,
    `[happily] Parfait! Voilà la phrase suivante, dans trois... deux... un...`,
    `[happily] Je vais répéter la phrase, dans trois... deux... un... [inhales deeply] La phrase, c'est "[very slowly for emphasis] Donc, aujourd'hui, nous allons voir plein d'autres alternatives à félicitations.". [inhales deeply] Cette phrase veut dire "[English explanation] So, today we are going to look at lots of other alternatives to "congratulations."". [inhales deeply] Les verbes utilisés ici sont "allons" qui est conjugué de "aller" qui signifie "[English explanation] to go; used as "going to" for near future" et "voir" qui est conjugué de "voir" qui signifie "[English explanation] to see; to look at; to examine".  [inhales deeply] Ensuite, voici des autres mots que vous devez connaître: "Donc" signifie "[English explanation] So". "Aujourd'hui" signifie "[English explanation] today". "plein" signifie "[English explanation] lots of". "d'autres" signifie "[English explanation] other". "alternatives" signifie "[English explanation] other options". "félicitations" signifie "[English explanation] congratulations". [inhales deeply] Enfin, il y a aussi des expressions idiomatiques que vous devez connaître: "plein de" est une expression idiomatique qui veut littéralement dire "[English explanation] full of". Dans ce contexte, cela exprime l'idée de "[English explanation] lots of" en anglais. [inhales deeply] Et maintenant, passons à la phrase suivante.`,
    `[happily] Génial! Voilà la phrase suivante, dans trois... deux... un...`,
    `[happily] Je vais répéter la phrase, dans trois... deux... un... [inhales deeply] La phrase, c'est "[very slowly for emphasis] Alors, comme d'habitude, nous allons commencer par un langage neutre.". [inhales deeply] Cette phrase veut dire "[English explanation] So, as usual, we are going to start with neutral language.". [inhales deeply] Les verbes utilisés ici sont "allons" qui est conjugué de "aller" qui signifie "[English explanation] to go; used here as the near-future auxiliary 'to be going to'" et "commencer" qui est conjugué de "commencer" qui signifie "[English explanation] to begin; to start".  [inhales deeply] Ensuite, voici des autres mots que vous devez connaître: "alors" signifie "[English explanation] so; used to introduce or continue a statement". "langage" signifie "[English explanation] language; style or choice of words". "neutre" signifie "[English explanation] neutral; without bias or strong emotion". [inhales deeply] Enfin, il y a aussi des expressions idiomatiques que vous devez connaître: "comme d'habitude" est une expression idiomatique qui veut littéralement dire "[English explanation] like (one's) habit". Dans ce contexte, cela exprime l'idée de "[English explanation] as usual" en anglais. "commencer par" est une expression idiomatique qui veut littéralement dire "[English explanation] to start by". Dans ce contexte, cela exprime l'idée de "[English explanation] to begin with" en anglais. [inhales deeply] Et maintenant, passons à la phrase suivante.`,
    `[happily] Parfait! Voilà la phrase suivante, dans trois... deux... un...`,
    `[happily] Je vais répéter la phrase, dans trois... deux... un... [inhales deeply] La phrase, c'est "[very slowly for emphasis] Ensuite, passera à un registre familier et on terminera par le registre soutenu.". [inhales deeply] Cette phrase veut dire "[English explanation] Next, we'll move to an informal register and we'll finish with the formal register.". [inhales deeply] Les verbes utilisés ici sont "passera" qui est conjugué de "passer" qui signifie "[English explanation] to move to or to switch to (will moveorswitch)" et "terminera" qui est conjugué de "terminer" qui signifie "[English explanation] to finish or to end (will finishorend)".  [inhales deeply] Ensuite, voici des autres mots que vous devez connaître: "Ensuite" signifie "[English explanation] next; then". "registre" signifie "[English explanation] linguistic register; style of language". "familier" signifie "[English explanation] informal (colloquial tone)". "soutenu" signifie "[English explanation] formal or elevated (polished tone)". [inhales deeply] Enfin, il y a aussi des expressions idiomatiques que vous devez connaître: "passer à (un registre)" est une expression idiomatique qui veut littéralement dire "[English explanation] to pass to a register". Dans ce contexte, cela exprime l'idée de "[English explanation] to switch to a different style or tone" en anglais. "terminer par" est une expression idiomatique qui veut littéralement dire "[English explanation] to finish by". Dans ce contexte, cela exprime l'idée de "[English explanation] to end with; conclude with" en anglais. [inhales deeply] Et maintenant, passons à la phrase suivante.`,
    `[happily] Formidable! Voilà la phrase suivante, dans trois... deux... un...`,
    `[happily] Je vais répéter la phrase, dans trois... deux... un... [inhales deeply] La phrase, c'est "[very slowly for emphasis] Vous verrez que vous pourrez utiliser ces expressions notamment à l'écrit, pour féliciter, pour un mariage par exemple, ou la naissance d'un enfant.". [inhales deeply] Cette phrase veut dire "[English explanation] You will see that you will be able to use these expressions, especially in writing, to congratulate — for a wedding, for example, or the birth of a child.". [inhales deeply] Les verbes utilisés ici sont "verrez" qui est conjugué de "voir" qui signifie "[English explanation] to see", "pourrez" qui est conjugué de "pouvoir" qui signifie "[English explanation] to be able to; can", "utiliser" qui est conjugué de "utiliser" qui signifie "[English explanation] to use" et "féliciter" qui est conjugué de "féliciter" qui signifie "[English explanation] to congratulate".  [inhales deeply] Ensuite, voici des autres mots que vous devez connaître: "ces" signifie "[English explanation] these (demonstrative)". "expressions" signifie "[English explanation] expressions; set phrases". "notamment" signifie "[English explanation] notably or especially". "à l'écrit" signifie "[English explanation] in writing". "mariage" signifie "[English explanation] wedding". "naissance" signifie "[English explanation] birth". "enfant" signifie "[English explanation] child". [inhales deeply] Enfin, il y a aussi des expressions idiomatiques que vous devez connaître: "à l'écrit" est une expression idiomatique qui veut littéralement dire "[English explanation] to the written". Dans ce contexte, cela exprime l'idée de "[English explanation] in writing" en anglais. "par exemple" est une expression idiomatique qui veut littéralement dire "[English explanation] for example". Dans ce contexte, cela exprime l'idée de "[English explanation] for instance" en anglais. [inhales deeply] Et maintenant, passons à la phrase suivante.`,
    `[happily] Formidable! Voilà la phrase suivante, dans trois... deux... un...`,
    `[happily] Je vais répéter la phrase, dans trois... deux... un... [inhales deeply] La phrase, c'est "[very slowly for emphasis] Et on terminera par quelques phrases un petit peu pédantes et drôles que vous pourrez utiliser pour rigoler entre amis si vous le voulez.". [inhales deeply] Cette phrase veut dire "[English explanation] And we'll finish with a few slightly pedantic and funny phrases that you can use to joke around with friends if you want.". [inhales deeply] Les verbes utilisés ici sont "terminera" qui est conjugué de "terminer" qui signifie "[English explanation] to finish; to end", "pourrez" qui est conjugué de "pouvoir" qui signifie "[English explanation] to be able to; can", "utiliser" qui est conjugué de "utiliser" qui signifie "[English explanation] to use", "rigoler" qui est conjugué de "rigoler" qui signifie "[English explanation] to laugh; to joke around" et "voulez" qui est conjugué de "vouloir" qui signifie "[English explanation] to want".  [inhales deeply] Ensuite, voici des autres mots que vous devez connaître: "phrases" signifie "[English explanation] phrases; short sentences or expressions". "un petit peu" signifie "[English explanation] a little bit; slightly". "pédantes" signifie "[English explanation] pedantic; showing off knowledge". "drôles" signifie "[English explanation] funny; amusing". "amis" signifie "[English explanation] friends; people you hang out with". [inhales deeply] Enfin, il y a aussi des expressions idiomatiques que vous devez connaître: "terminer par" est une expression idiomatique qui veut littéralement dire "[English explanation] to finish by". Dans ce contexte, cela exprime l'idée de "[English explanation] to end with" en anglais. [inhales deeply] Et maintenant, passons à la phrase suivante.`,
    `[happily] Super! Voilà la phrase suivante, dans trois... deux... un...`,
    `[happily] Je vais répéter la phrase, dans trois... deux... un... [inhales deeply] La phrase, c'est "[very slowly for emphasis] Donc, registre neutre, qu'est-ce qu'on peut dire à la place de félicitations Un classique en français, qu'est-ce qu'on dit Bravo.". [inhales deeply] Cette phrase veut dire "[English explanation] So, neutral register: what can you say instead of "félicitations"? A classic in French — what do we say? "Bravo."". [inhales deeply] Les verbes utilisés ici sont "est" qui est conjugué de "être" qui signifie "[English explanation] to be", "peut" qui est conjugué de "pouvoir" qui signifie "[English explanation] to be able to or can", "dire" qui est conjugué de "dire" qui signifie "[English explanation] to say" et "dit" qui est conjugué de "dire" qui signifie "[English explanation] to say".  [inhales deeply] Ensuite, voici des autres mots que vous devez connaître: "Donc" signifie "[English explanation] So; therefore". "registre" signifie "[English explanation] register; level of formality". "neutre" signifie "[English explanation] neutral (not formal or informal)". "place" signifie "[English explanation] place; position (in 'à la place de')". "félicitations" signifie "[English explanation] congratulations". "classique" signifie "[English explanation] a classic; common or typical choice". "français" signifie "[English explanation] French (language)". [inhales deeply] Enfin, il y a aussi des expressions idiomatiques que vous devez connaître: "à la place de" est une expression idiomatique qui veut littéralement dire "[English explanation] at the place of". Dans ce contexte, cela exprime l'idée de "[English explanation] instead of" en anglais. "Un classique" est une expression idiomatique qui veut littéralement dire "[English explanation] a classic". Dans ce contexte, cela exprime l'idée de "[English explanation] a typical or common choice" en anglais. "registre neutre" est une expression idiomatique qui veut littéralement dire "[English explanation] neutral register". Dans ce contexte, cela exprime l'idée de "[English explanation] neutral level of formality" en anglais. [inhales deeply] Et maintenant, passons à la phrase suivante.`
  ];
  const presenterOrder = [PRESENTERS.CLEMENT, PRESENTERS.MARIE];
  for (let i = 0; i < scripts.length; i++) {
    const script = scripts[i];
    const baseName = `script_${i + 1}`;
    const currentPresenter = presenterOrder[Math.floor(i / 2) % presenterOrder.length];
    await generateSpeech(script, currentPresenter.voiceId, { workDir: process.cwd(), baseName });
    const scriptAudioPath = path.join(process.cwd(), `${baseName}.mp3`);
    console.log(`Script ${i + 1} audio path: ${scriptAudioPath}`);
  }
})();

// ./lib/tts.ts
import { ChatGoogle } from '@langchain/google-webauth';
import { HumanMessage, SystemMessage } from '@langchain/core/messages';

/**
 * Audio tags used throughout the codebase with explanations
 */
export const AUDIO_TAGS = [
  {
    tag: '[cheerfully]',
    explanation: 'speaker speaks in a cheerful, upbeat manner',
  },
  {
    tag: '[warmly]',
    explanation: 'speaker speaks with warmth and friendliness',
  },
  {
    tag: '[casually]',
    explanation: 'speaker speaks in a casual, relaxed manner',
  },
  {
    tag: '[energetically]',
    explanation: 'speaker speaks with high energy and enthusiasm',
  },
  {
    tag: '[enthusiastically]',
    explanation: 'speaker speaks with great enthusiasm and excitement',
  },
  {
    tag: '[giggles]',
    explanation: 'speaker giggles or laughs lightly',
  },
  { tag: '[laughs]', explanation: 'speaker laughs' },
  {
    tag: '[encouraging]',
    explanation: 'speaker speaks in an encouraging, supportive manner',
  },
  {
    tag: '[excitedly]',
    explanation: 'speaker expresses excitement or high enthusiasm',
  },
  {
    tag: '[happily]',
    explanation: 'speaker speaks in a happy, content manner',
  },
  {
    tag: '[gratefully]',
    explanation: 'speaker expresses gratitude or thankfulness',
  },
  {
    tag: '[inhales deeply]',
    explanation: 'speaker takes a deep breath before speaking',
  },
  {
    tag: '[very slowly for emphasis]',
    explanation: 'speaker speaks very slowly to emphasize the following words',
  },
  {
    tag: '[strong English accent]',
    explanation:
      'speaker uses a strong English accent for the following English text',
  },
];

export const PRESENTERS = {
  MARIE: {
    name: 'Marie',
    voiceId: 'Zephyr',
  },
  CLEMENT: {
    name: 'Clément',
    voiceId: 'Puck',
  },
  CELIAN: {
    name: 'Célian',
    voiceId: 'Algieba',
  },
};

/**
 * Generate system prompt for Gemini TTS speech generation
 */
function getSpeechSystemPrompt(): string {
  const tagExplanations = AUDIO_TAGS.map(
    tag => `- ${tag.tag}: ${tag.explanation}`
  ).join('\n');

  return `You are a text-to-speech system that converts speech scripts into natural, expressive audio. That means your objective is to GENERATE ONLY AUDIO, NOT TEXT.

You will receive a speech script from a single speaker. They are a French speaker who is translating French sentences, phrases, words, etc. into English.
Your task is to read the provided speech script and convert it into speech, paying close attention to all audio direction tags and instructions.

AUDIO TAGS:
The script may contain square-bracketed tags that provide direction on how to speak certain parts. These tags indicate tone, emotion, pacing, or actions. Here are all the possible tags you may encounter:

${tagExplanations}

INSTRUCTIONS:
1. First and most importantly, GENERATE ONLY AUDIO, NOT TEXT.
2. When you encounter an audio tag, interpret it and apply it to the following text until the next tag or end of that speaker's line, except when the tag is within quotes, in which case apply it to the text within the quotes
3. Multiple tags can appear together (e.g., [inhales deeply] [excitedly]); apply all of them appropriately
4. Pay special attention to tags that modify pronunciation (e.g., [English explanation])
5. Natural pauses should be indicated by punctuation or the context
6. Speak naturally and expressively, matching the emotion and tone indicated by the tags
7. Maintain the character and personality of the speaker consistently
8. Lastly, GENERATE ONLY AUDIO, NOT TEXT.

Now generate the audio for the following speech script.

IMPORTANT: Remember to GENERATE ONLY AUDIO, NOT TEXT.`;
}

/**
 * Generate speech using Google Gemini TTS for a single speaker
 */
export async function generateSpeech(
  text: string,
  voiceId: string,
  opts?: { workDir?: string; baseName?: string }
): Promise<void> {
  const apiKey = process.env.GOOGLE_API_KEY;

  if (!apiKey) {
    throw new Error('Google API key not configured');
  }

  try {
    const modelName = 'gemini-2.5-flash-preview-tts';
    const responseModalities = ['audio'];
    const speechConfig = voiceId;

    const model = new ChatGoogle({
      modelName,
      responseModalities,
      speechConfig,
      apiKey,
      safetySettings: [
        {
          category: HarmCategory.HARM_CATEGORY_HARASSMENT,
          threshold: HarmBlockThreshold.BLOCK_NONE,
        },
        {
          category: HarmCategory.HARM_CATEGORY_HATE_SPEECH,
          threshold: HarmBlockThreshold.BLOCK_NONE,
        },
        {
          category: HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT,
          threshold: HarmBlockThreshold.BLOCK_NONE,
        },
        {
          category: HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT,
          threshold: HarmBlockThreshold.BLOCK_NONE,
        },
      ],
    });

    const systemPrompt = getSpeechSystemPrompt();
    const humanMessageContent = `Here's the speech script inside triple backticks:\n\n\`\`\`\n${text}\n\`\`\`\n\nNow generate the AUDIO, NOT TEXT, for this speech script.`;
    const messages = [
      new HumanMessage(`${systemPrompt}\n\n${humanMessageContent}`),
    ];

    const result = await model.invoke(messages);

    const audioContent = result?.content?.[0] as unknown as {
      data?: string;
      mimeType?: string;
      media?: string;
    };
    if (!audioContent || !audioContent.data) {
      throw new Error('No audio data returned from Gemini TTS');
    }
    const mimeType = audioContent.mimeType;
    console.log(`[generateSpeech] mimeType: ${mimeType}`);
    const audioPcmData = audioContent.data;
    console.log(`[generateSpeech] audioPcmData: ${audioPcmData.length} bytes`);
    const pcmBuffer = Buffer.from(audioPcmData, 'base64');
    // Parse MIME type like: audio/L16;codec=pcm;rate=24000
    let parsedSampleRate = 24000;
    let parsedBitDepth = 16;
    if (typeof mimeType === 'string') {
      const rateMatch = mimeType.match(/(?:^|[;\s])rate=(\d+)/i);
      const depthMatch = mimeType.match(/^audio\/L(\d+)/i);
      if (rateMatch)
        parsedSampleRate = parseInt(rateMatch[1], 10) || parsedSampleRate;
      if (depthMatch)
        parsedBitDepth = parseInt(depthMatch[1], 10) || parsedBitDepth;
    }
    const outputDir = opts?.workDir || os.tmpdir();
    const baseName = opts?.baseName || `speech_${Date.now()}`;
    await pcmBufferToMp3(pcmBuffer, outputDir, baseName, {
      sampleRate: parsedSampleRate,
      channels: 1,
      bitrate: '192k',
      codec: 'libmp3lame',
      bitDepth: parsedBitDepth,
    });
  } catch (error) {
    console.error('Google Gemini TTS speech error:', error);
    throw new Error(`Failed to generate speech: ${error}`);
  }
}

I get that error on the 6th array member (index 5). On my first attempt, the error didn't happen until the very last array member. On my second attempt, the error happened on the 10th array member (index 9). So it looked like the block started happening progressively earlier in the loop, from 20 to 10 to 6 iterations into the loop. I'm confused as to how any of these sentences can be blocked for safety reasons. It looks more like a rate limit/throttle than safety reasons. Can someone please shed some light on this?

Actual vs expected behavior:

Expected behavior: all the scripts should generate audio without this error.
Actual behavior: after some rounds of the loop, the model raises the error GoogleAISafetyError: Finish reason: OTHER.

Any other information you'd like to share?

Environment details

  • Programming language: typescript
  • OS: MacOS Sequoia 15.6.1 (24G90)
  • Language runtime version: Node.js v24.4.1
  • Package versions:
    • @langchain/google-webauth: 1.0.0
    • @google/genai: 1.27.0
    • langchain: 1.0.1
    • dotenv: 17.2.3

Steps to reproduce

  1. create a new typescript project with the files described above
  2. install the packages mentioned above
  3. run npx tsx tmp.ts

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions