Persistent hallucination by gemini 3.5 flash using gemini-api

Gemini-api generates random set of results with meaningful sentences which are out of context for the input prompt (AI hallucination).
Here is the scenario under which this problem occurs :
I am fetching results from gemini-api (gemini 3.5 flash) using from my typescript react application. The first input to the api gives this hallucinated results, the subsequent results are valid results for the input prompt. So this problem persist as whenever I make changes or reload the application the first result from the api again gives hallucinated results.
Also it needs to be mentioned is that, passing a simple string to the api works fine, the bug only occurs only when concatenated string is passed in the api (For my application the string is mathfield value string generated using mathlive and a starter string (like : "Give me a brief breakdown of the following equation : " + math equation) to make the prompt as a complete question).

Hello @Tathagata_Karmakar ,

To help us investigate this, could you please provide:

  • A minimal code snippet showing your API call and configuration parameters.
  • The exact prompt sent on the first request.
  • The hallucinated output text returned by the model.

Here is the code snippet :

import { useRef, useState } from "react";
import "mathlive";
import "./math-field.css"
import { GEMINI_URL } from "../constants";

function MathEquation() {
    
  const mathfieldRef = useRef(null);
  const [question,setQuestion]=useState('');
  const [result,setResult]=useState(undefined);

  const handleFocus = () => {
    if (mathfieldRef.current){
      mathfieldRef.current.executeCommand("selectAll");
    }
  };

  const LatexOutput = async () => {
    console.log(mathfieldRef.current.value)
    setQuestion("In very short what equation is this : " + mathfieldRef.current.value)
    console.log("In very short what equation is this : " + mathfieldRef.current.value)
    console.log(typeof mathfieldRef.current.value)
    console.log(typeof "In very short what equation is this : " + mathfieldRef.current.value)
  }

  const payload = {
    "contents": [{
      "parts":[{"text":question}]
    }]
  }

  const askQuestion = async()=>{
    let response = await fetch(GEMINI_URL,{
      method:"POST",
      body:JSON.stringify(payload)
    })

    const data = await response.json();
    console.log(data.candidates[0].content.parts[0].text)
    setResult(data.candidates[0].content.parts[0].text)
  }

  return (
    <div>
      <math-field
        ref={mathfieldRef}
        onFocus={handleFocus}
      >
        {'_{Enter \\ equation \\ ...}'}
      </math-field>

      <button onClick={()=>{
        LatexOutput(); 
        askQuestion();
      }}>Evaluate</button>

      <div className='text-white'>
        {result}
      </div>      
    </div>
  );
}
export default MathEquation;

the async function ‘askQuestion’ makes the api call, and prompt (variable ‘question’) is constructed using the async function ‘LatexOutput’.

The prompt sent on the first request : “In very short what equation is this : ax^2+bx+c=0”
(Also no matter what prompt is given to the first call the generated output is random.)

The hallucinated output given are random every time here is one such output:

Yes, you can use an external database with AWS Cognito, but not as a direct, plug-and-play replacement for Cognito’s built-in user directory.

Cognito requires its own User Pool to manage sessions, tokens (JWTs), and OAuth flows. However, AWS provides several integration patterns—primarily using AWS Lambda triggers—to connect Cognito with external databases like PostgreSQL, MySQL, MongoDB, or DynamoDB.

Here are the 4 most common ways to use an external database with AWS Cognito:


1. “Just-in-Time” (JIT) User Migration (Most Common)

If you have an existing database of users and want to move them to AWS Cognito without forcing them to reset their passwords, you can migrate them dynamically as they log in.

  • How it works:
    1. A user attempts to sign in.
    2. Cognito checks if the user exists in its User Pool. If not, it fires a User Migration Lambda trigger.
    3. The Lambda function queries your external database, verifies the user’s password (using your legacy hashing algorithm), and retrieves user details.
    4. If valid, the Lambda returns the user data to Cognito.
    5. Cognito automatically creates the user in its own User Pool and logs them in.
  • Best for: Migrating legacy applications to AWS Cognito.

2. Custom Authentication Flow (Keeping the External DB as Source of Truth)

If you want to keep your external database as the primary identity provider and only use Cognito to issue JWT tokens, you can implement a custom authentication flow.

  • How it works:
    1. You configure Cognito to use a Custom Authentication Flow (using DEFINE_AUTH_CHALLENGE, CREATE_AUTH_CHALLENGE, and VERIFY_AUTH_CHALLENGE_RESPONSE Lambda triggers).
    2. When a user logs in, your Lambda functions handle the verification process by querying your external database.
    3. Once the Lambda verifies the credentials against your external DB, Cognito issues the standard ID, Access, and Refresh tokens.
  • Best for: Architectures where the external database must remain the single source of truth for passwords and credentials.

3. Data Synchronization (Auth in Cognito, Metadata in External DB)

Cognito is great for authentication, but it is not a good database for rich user profiles, search, or relational data (Cognito limits you to 50 custom attributes, and you cannot easily run complex queries).

The standard architectural pattern is to store credentials in Cognito and profile data in an external database (like Amazon RDS or DynamoDB).

  • How it works:
    1. A user signs up in Cognito.
    2. After successful verification, Cognito fires the Post Confirmation Lambda trigger.
    3. The Lambda function takes the Cognito sub (the unique User ID) and creates a corresponding user profile row in your external database.
    4. Your application uses the Cognito sub as a foreign key in your external database to query user-specific data (e.g., shopping carts, profiles, settings).
  • Best for: Almost all modern SaaS applications.

4. Federation (SAML/OIDC)

If your external database is already managed by an identity solution (like Keycloak, Auth0, Okta, or Active Directory), you don’t need to connect directly to the database.

  • How it works: You configure Cognito to federate with the external Identity Provider (IdP) via SAML 2.0 or OpenID Connect (OIDC).
  • Best for: Enterprise SSO (Single Sign-On) integrations.

Summary: Which should you choose?

Your Goal Recommended Approach
Move users from a legacy database to Cognito User Migration Lambda Trigger (Approach 1)
Keep passwords in your own DB, but get Cognito tokens Custom Auth Flow Lambdas (Approach 2)
Store rich user profiles, address books, app data Post-Confirmation Sync to RDS/DynamoDB (Approach 3)

**
Also I would like to mention that I suspect for the first call the api might be receiving an empty prompt, but wouldn’t that raise an error?**