/05. Maintaining Conversation History

    05. Maintaining Conversation History

    Explanation

    While `generateContent` is great for one-off tasks (like summarization), conversational bots require context. The `ai.chats.create` method returns a stateful object that automatically appends user queries and model responses to a growing 'history' array. Every time you call `.sendMessage()`, it sends that entire history block back to the API, creating the illusion of memory.

    Example

    const chat = ai.chats.create({ model: 'gemini-2.5-flash' });
    const res1 = await chat.sendMessage({ message: 'Hi, I am Bob.' });
    const res2 = await chat.sendMessage({ message: 'What is my name?' });
    console.log(res2.text); // "Your name is Bob."

    Exercise Task

    AI models are stateless; they don't remember previous messages unless you send the entire history every time. Let's use the SDK's built-in chat session manager. **Step 1.** Initialize `GoogleGenAI`. **Step 2.** Create a chat session using `ai.chats.create({ model: 'gemini-2.5-flash' })`. **Step 3.** Send a message: `"I have 5 apples."` and log the response text. **Step 4.** Send another message: `"I ate 2 of them. How many do I have left?"` and log the response.

    script.js
    Console

    Click "Run" to execute your code...

    🍪 We Value Your Privacy

    We use cookies to enhance your browsing experience, serve personalized ads or content, and analyze our traffic. By clicking "Accept All", you consent to our use of cookies according to our Privacy Policy.

    Learn More