Skip to main content

Chat Conversations with Gemini

Maintain context over multiple messages in a conversation using Gemini's chat functionality.

import { GoogleGenerativeAI } from "@google/generative-ai";

const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY);
const model = genAI.getGenerativeModel({ model: "gemini-2.0-flash" });

// Start a chat session
const chat = model.startChat({
history: [
{
role: "user",
parts: "Hello, Gemini."
},
{
role: "model",
parts: "Hi there! How can I assist you today?"
}
]
});

// Continue the conversation
const result1 = await chat.sendMessage("I have 3 cats. How many paws are in total?");
console.log(result1.response.text());

const result2 = await chat.sendMessage("Can you translate that answer into French?");
console.log(result2.response.text());

Chat Configuration Options

  • history: Array of previous messages
  • context: Additional context for the conversation
  • examples: Example interactions to guide the model

Best Practices for Chat

  1. Keep conversation history concise
  2. Provide clear context when needed
  3. Use examples to guide model behavior