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
1
2
3
4
5
6
7
8
9
10
11
12
import { GoogleGenAI } from 'https://esm.
sh/@google/genai';
const ai = new GoogleGenAI({ apiKey:
'PASTE_YOUR_API_KEY_HERE' });
async function chat() {
// 1. Create a chat session
// 2. Send first message
// 3. Send second message
}
Console
Click "Run" to execute your code...