Skip to content

GeminiChatSession

GeminiChatSession provides stateful multi-turn conversations with Gemini models. Each session maintains a conversation history so the model can reference prior messages without the caller re-sending them.

Lifecycle

A chat session is scoped to a single process invocation. For cross-invocation persistence (e.g. across serverless function calls), store the history externally and pass it in via GeminiChatCreateOptions.history.

Import

import { GeminiClient } from "@modernpath/agent-framework";

const client = new GeminiClient({ apiKey: process.env.GEMINI_API_KEY! });
const chat = client.createChat({
  systemPrompt: "You are a helpful assistant.",
});

GeminiChatSession is not imported directly -- it is created via GeminiClient.createChat().

Constructor Options

GeminiChatCreateOptions

Property Type Default Description
systemPrompt string -- System instruction prepended to the conversation. Injected as the first message in history.
history Array<{ role, parts }> [] Pre-existing conversation history to restore a previous session.
config.temperature number Client default Sampling temperature for this session.
config.maxOutputTokens number Client default Max output tokens per response in this session.

History entry format:

{
  role: "user" | "model" | "system";
  parts: Array<{ text: string }>;
}

Methods

sendMessage()

Send a message and receive the full model response.

async sendMessage(
  message: string,
  config?: Record<string, any>,
): Promise<{ text: string; usage?: GeminiUsage }>
Parameter Type Description
message string The user message to send.
config Record<string, any> Optional per-message generation config overrides.

Returns: An object containing the model's response text and optional usage metadata.

Basic multi-turn conversation

const chat = client.createChat({
  systemPrompt: "You are a building HVAC expert.",
});

const r1 = await chat.sendMessage("What causes cold complaints in apartments?");
console.log(r1.text);

const r2 = await chat.sendMessage("How should I check the radiator valves?");
console.log(r2.text);
// The model has context from both messages.

sendMessageStream()

Send a message and receive the response as a stream of text chunks.

async *sendMessageStream(
  message: string,
  config?: Record<string, any>,
): AsyncGenerator<string>
Parameter Type Description
message string The user message to send.
config Record<string, any> Optional per-message generation config overrides.

Yields: string chunks as they arrive from the model.

Streaming a chat response

const chat = client.createChat();

for await (const chunk of chat.sendMessageStream("Explain step by step.")) {
  process.stdout.write(chunk);
}

getHistory()

Retrieve the full conversation history, including system prompt, user messages, and model responses.

getHistory(): Array<{ role: string; content: string }>

Persisting history for cross-invocation chat

// At the end of a serverless invocation:
const history = chat.getHistory();
await conversationStore.save(sessionId, history);

// In the next invocation:
const savedHistory = await conversationStore.load(sessionId);
const chat = client.createChat({ history: savedHistory });

Full Example

import { GeminiClient } from "@modernpath/agent-framework";

const client = new GeminiClient({
  apiKey: process.env.GEMINI_API_KEY!,
  model: "gemini-3-flash-preview",
});

async function troubleshootingChat() {
  const chat = client.createChat({
    systemPrompt: `You are an HVAC troubleshooting assistant.
Ask clarifying questions when needed. Be concise.`,
    config: {
      temperature: 0.4,
      maxOutputTokens: 1024,
    },
  });

  // Turn 1
  const r1 = await chat.sendMessage(
    "Apartment 4B is reporting cold temperatures despite high outdoor temps.",
  );
  console.log("Assistant:", r1.text);

  // Turn 2
  const r2 = await chat.sendMessage(
    "The supply water temperature is 65C and the return is 62C.",
  );
  console.log("Assistant:", r2.text);

  // Turn 3 -- streaming
  process.stdout.write("Assistant: ");
  for await (const chunk of chat.sendMessageStream(
    "What should I check next?",
  )) {
    process.stdout.write(chunk);
  }
  console.log();

  // Persist for next invocation
  const history = chat.getHistory();
  return history;
}