0
# Chat Sessions
1
2
Create and manage multi-turn chat sessions with automatic history management. Chat sessions maintain conversation context across multiple message exchanges.
3
4
## Core Imports
5
6
```java
7
import com.google.genai.Chats;
8
import com.google.genai.Chat;
9
import com.google.genai.AsyncChats;
10
import com.google.genai.AsyncChat;
11
import com.google.genai.ResponseStream;
12
import com.google.genai.types.GenerateContentResponse;
13
import com.google.genai.types.GenerateContentConfig;
14
import com.google.genai.types.Content;
15
import java.util.List;
16
import java.util.concurrent.CompletableFuture;
17
```
18
19
## Chats Service
20
21
```java { .api }
22
package com.google.genai;
23
24
public class Chats {
25
public Chat create(String model, GenerateContentConfig config);
26
public Chat create(String model);
27
}
28
```
29
30
## Chat Class
31
32
```java { .api }
33
package com.google.genai;
34
35
public class Chat {
36
// Send messages (synchronous)
37
public GenerateContentResponse sendMessage(String text);
38
public GenerateContentResponse sendMessage(String text, GenerateContentConfig config);
39
public GenerateContentResponse sendMessage(Content content);
40
public GenerateContentResponse sendMessage(Content content, GenerateContentConfig config);
41
public GenerateContentResponse sendMessage(List<Content> contents);
42
public GenerateContentResponse sendMessage(List<Content> contents, GenerateContentConfig config);
43
44
// Stream messages
45
public ResponseStream<GenerateContentResponse> sendMessageStream(String text);
46
public ResponseStream<GenerateContentResponse> sendMessageStream(String text, GenerateContentConfig config);
47
public ResponseStream<GenerateContentResponse> sendMessageStream(Content content);
48
public ResponseStream<GenerateContentResponse> sendMessageStream(Content content, GenerateContentConfig config);
49
public ResponseStream<GenerateContentResponse> sendMessageStream(List<Content> contents);
50
public ResponseStream<GenerateContentResponse> sendMessageStream(List<Content> contents, GenerateContentConfig config);
51
}
52
```
53
54
## Async Chats Service
55
56
```java { .api }
57
package com.google.genai;
58
59
public class AsyncChats {
60
public AsyncChat create(String model, GenerateContentConfig config);
61
public AsyncChat create(String model);
62
}
63
```
64
65
## Async Chat Class
66
67
```java { .api }
68
package com.google.genai;
69
70
public class AsyncChat {
71
// Send messages (asynchronous)
72
public CompletableFuture<GenerateContentResponse> sendMessage(String text);
73
public CompletableFuture<GenerateContentResponse> sendMessage(String text, GenerateContentConfig config);
74
public CompletableFuture<GenerateContentResponse> sendMessage(Content content);
75
public CompletableFuture<GenerateContentResponse> sendMessage(Content content, GenerateContentConfig config);
76
public CompletableFuture<GenerateContentResponse> sendMessage(List<Content> contents);
77
public CompletableFuture<GenerateContentResponse> sendMessage(List<Content> contents, GenerateContentConfig config);
78
79
// Stream messages (asynchronous)
80
public CompletableFuture<ResponseStream<GenerateContentResponse>> sendMessageStream(String text);
81
public CompletableFuture<ResponseStream<GenerateContentResponse>> sendMessageStream(String text, GenerateContentConfig config);
82
public CompletableFuture<ResponseStream<GenerateContentResponse>> sendMessageStream(Content content);
83
public CompletableFuture<ResponseStream<GenerateContentResponse>> sendMessageStream(Content content, GenerateContentConfig config);
84
public CompletableFuture<ResponseStream<GenerateContentResponse>> sendMessageStream(List<Content> contents);
85
public CompletableFuture<ResponseStream<GenerateContentResponse>> sendMessageStream(List<Content> contents, GenerateContentConfig config);
86
}
87
```
88
89
## Basic Usage
90
91
### Create and Use Chat
92
93
```java
94
import com.google.genai.Client;
95
import com.google.genai.Chat;
96
97
Client client = new Client();
98
99
// Create chat session
100
Chat chat = client.chats.create("gemini-2.0-flash");
101
102
// Send first message
103
GenerateContentResponse response1 = chat.sendMessage("Hello! My name is Alice.");
104
System.out.println("Bot: " + response1.text());
105
106
// Send follow-up (context is maintained)
107
GenerateContentResponse response2 = chat.sendMessage("What's my name?");
108
System.out.println("Bot: " + response2.text());
109
// Expected: "Your name is Alice." (remembers previous message)
110
```
111
112
### Chat with Configuration
113
114
```java
115
import com.google.genai.types.GenerateContentConfig;
116
import com.google.genai.types.Content;
117
import com.google.genai.types.Part;
118
119
// Create system instruction
120
Content systemInstruction = Content.fromParts(
121
Part.fromText("You are a helpful math tutor. Be encouraging and explain step by step.")
122
);
123
124
GenerateContentConfig config = GenerateContentConfig.builder()
125
.systemInstruction(systemInstruction)
126
.temperature(0.2)
127
.build();
128
129
Chat chat = client.chats.create("gemini-2.0-flash", config);
130
131
GenerateContentResponse response = chat.sendMessage("How do I solve x + 5 = 10?");
132
System.out.println(response.text());
133
```
134
135
## Multi-Turn Conversations
136
137
### Extended Conversation
138
139
```java
140
Chat chat = client.chats.create("gemini-2.0-flash");
141
142
// Turn 1
143
chat.sendMessage("I'm planning a trip to Paris.");
144
// Bot responds with suggestions
145
146
// Turn 2
147
chat.sendMessage("What's the best time to visit?");
148
// Bot understands context (Paris)
149
150
// Turn 3
151
chat.sendMessage("How many days should I spend there?");
152
// Bot continues conversation naturally
153
154
// Turn 4
155
chat.sendMessage("What are must-see attractions?");
156
// Bot provides Paris-specific attractions
157
```
158
159
### Interactive Chat Loop
160
161
```java
162
import java.util.Scanner;
163
164
Chat chat = client.chats.create("gemini-2.0-flash");
165
Scanner scanner = new Scanner(System.in);
166
167
System.out.println("Chat started. Type 'exit' to quit.");
168
169
while (true) {
170
System.out.print("You: ");
171
String userInput = scanner.nextLine();
172
173
if ("exit".equalsIgnoreCase(userInput)) {
174
break;
175
}
176
177
GenerateContentResponse response = chat.sendMessage(userInput);
178
System.out.println("Bot: " + response.text());
179
System.out.println();
180
}
181
182
scanner.close();
183
```
184
185
## History Management
186
187
**Note**: The Chat class maintains conversation history internally but does not expose methods to directly access or clear the history. History is automatically maintained across `sendMessage()` and `sendMessageStream()` calls within the same Chat instance. To start a new conversation without previous history, create a new Chat instance.
188
189
```java
190
Chat chat1 = client.chats.create("gemini-2.0-flash");
191
192
chat1.sendMessage("Tell me about AI");
193
chat1.sendMessage("What are neural networks?");
194
chat1.sendMessage("Explain backpropagation");
195
196
// Model remembers context from previous messages
197
// History is maintained automatically
198
199
// To start fresh conversation, create a new Chat instance
200
Chat chat2 = client.chats.create("gemini-2.0-flash");
201
chat2.sendMessage("Let's talk about something completely different");
202
// No history from chat1
203
```
204
205
## Streaming Chat
206
207
### Basic Streaming
208
209
```java
210
Chat chat = client.chats.create("gemini-2.0-flash");
211
212
System.out.print("Bot: ");
213
try (ResponseStream<GenerateContentResponse> stream =
214
chat.sendMessageStream("Tell me a story")) {
215
216
for (GenerateContentResponse chunk : stream) {
217
System.out.print(chunk.text());
218
}
219
System.out.println();
220
}
221
222
// Continue conversation
223
GenerateContentResponse response = chat.sendMessage("Make it shorter");
224
System.out.println("Bot: " + response.text());
225
```
226
227
### Streaming Interactive Chat
228
229
```java
230
import java.util.Scanner;
231
232
Chat chat = client.chats.create("gemini-2.0-flash");
233
Scanner scanner = new Scanner(System.in);
234
235
while (true) {
236
System.out.print("You: ");
237
String input = scanner.nextLine();
238
239
if ("exit".equalsIgnoreCase(input)) break;
240
241
System.out.print("Bot: ");
242
try (ResponseStream<GenerateContentResponse> stream =
243
chat.sendMessageStream(input)) {
244
245
for (GenerateContentResponse chunk : stream) {
246
System.out.print(chunk.text());
247
System.out.flush();
248
}
249
System.out.println("\n");
250
}
251
}
252
```
253
254
## Multimodal Chat
255
256
### Chat with Images
257
258
```java
259
import com.google.genai.types.Content;
260
import com.google.genai.types.Part;
261
262
Chat chat = client.chats.create("gemini-2.0-flash");
263
264
// First message with image
265
Content imageContent = Content.fromParts(
266
Part.fromText("What's in this image?"),
267
Part.fromUri("gs://bucket/image.jpg", "image/jpeg")
268
);
269
270
GenerateContentResponse response1 = chat.sendMessage(imageContent);
271
System.out.println(response1.text());
272
273
// Follow-up without image (model remembers the image)
274
GenerateContentResponse response2 = chat.sendMessage("What colors are prominent?");
275
System.out.println(response2.text());
276
277
// Another follow-up
278
GenerateContentResponse response3 = chat.sendMessage("Describe the lighting");
279
System.out.println(response3.text());
280
```
281
282
### Mixed Media Chat
283
284
```java
285
Chat chat = client.chats.create("gemini-2.0-flash");
286
287
// Message 1: Text only
288
chat.sendMessage("I'm analyzing some data");
289
290
// Message 2: With image
291
Content imageMsg = Content.fromParts(
292
Part.fromText("Here's a chart"),
293
Part.fromUri("gs://bucket/chart.png", "image/png")
294
);
295
chat.sendMessage(imageMsg);
296
297
// Message 3: With document
298
Content docMsg = Content.fromParts(
299
Part.fromText("And here's the report"),
300
Part.fromUri("gs://bucket/report.pdf", "application/pdf")
301
);
302
chat.sendMessage(docMsg);
303
304
// Message 4: Follow-up question
305
GenerateContentResponse response = chat.sendMessage(
306
"What are the key findings from the chart and report?"
307
);
308
System.out.println(response.text());
309
```
310
311
## Async Chat
312
313
### Basic Async Chat
314
315
```java
316
import java.util.concurrent.CompletableFuture;
317
318
AsyncChat chat = client.async.chats.create("gemini-2.0-flash");
319
320
CompletableFuture<GenerateContentResponse> future1 =
321
chat.sendMessage("What is machine learning?");
322
323
future1.thenAccept(response -> {
324
System.out.println("Response 1: " + response.text());
325
326
// Send follow-up
327
chat.sendMessage("Give me an example")
328
.thenAccept(response2 -> {
329
System.out.println("Response 2: " + response2.text());
330
});
331
});
332
```
333
334
### Async Streaming
335
336
```java
337
AsyncChat chat = client.async.chats.create("gemini-2.0-flash");
338
339
CompletableFuture<ResponseStream<GenerateContentResponse>> futureStream =
340
chat.sendMessageStream("Tell me about space");
341
342
futureStream.thenAccept(stream -> {
343
try (ResponseStream<GenerateContentResponse> s = stream) {
344
System.out.print("Bot: ");
345
for (GenerateContentResponse chunk : s) {
346
System.out.print(chunk.text());
347
}
348
System.out.println();
349
}
350
});
351
```
352
353
## Per-Message Configuration
354
355
### Override Config Per Message
356
357
```java
358
// Create chat with default config
359
GenerateContentConfig defaultConfig = GenerateContentConfig.builder()
360
.temperature(0.7)
361
.build();
362
363
Chat chat = client.chats.create("gemini-2.0-flash", defaultConfig);
364
365
// Send with default config
366
chat.sendMessage("Tell me something creative");
367
368
// Override for specific message
369
GenerateContentConfig factualConfig = GenerateContentConfig.builder()
370
.temperature(0.1)
371
.build();
372
373
chat.sendMessage("Now give me just facts about the sun", factualConfig);
374
```
375
376
## Thread Safety
377
378
**Important**: Chat and AsyncChat instances are NOT thread-safe. Each chat session manages conversation history and should not be accessed from multiple threads simultaneously.
379
380
```java
381
// Wrong - Don't do this
382
Chat chat = client.chats.create("gemini-2.0-flash");
383
384
// Multiple threads accessing same chat - UNSAFE
385
new Thread(() -> chat.sendMessage("Hello from thread 1")).start();
386
new Thread(() -> chat.sendMessage("Hello from thread 2")).start();
387
388
// Right - Create separate chat per thread
389
new Thread(() -> {
390
Chat threadChat = client.chats.create("gemini-2.0-flash");
391
threadChat.sendMessage("Hello from thread 1");
392
}).start();
393
```
394
395
## Best Practices
396
397
### Handle Long Conversations
398
399
```java
400
Chat chat = client.chats.create("gemini-2.0-flash");
401
402
int maxTurns = 20;
403
int turnCount = 0;
404
405
while (turnCount < maxTurns) {
406
// ... chat interaction ...
407
turnCount++;
408
409
// Check token usage
410
List<Content> history = chat.history();
411
// If history too long, summarize and start fresh
412
if (history.size() > 40) {
413
// Get summary of conversation
414
GenerateContentResponse summary = chat.sendMessage(
415
"Summarize our conversation so far in 2-3 sentences"
416
);
417
418
// Start fresh with summary as context
419
chat.clearHistory();
420
421
// Continue with summary
422
GenerateContentConfig config = GenerateContentConfig.builder()
423
.systemInstruction(Content.fromParts(
424
Part.fromText("Previous conversation summary: " + summary.text())
425
))
426
.build();
427
428
chat = client.chats.create("gemini-2.0-flash", config);
429
}
430
}
431
```
432
433
### Save and Restore Conversation
434
435
```java
436
import com.google.common.collect.ImmutableList;
437
438
// During conversation
439
Chat chat = client.chats.create("gemini-2.0-flash");
440
chat.sendMessage("Hello");
441
chat.sendMessage("Tell me about AI");
442
443
// Save history
444
List<Content> savedHistory = ImmutableList.copyOf(chat.history());
445
446
// Later, create new chat with saved history
447
Chat newChat = client.chats.create("gemini-2.0-flash");
448
449
// Restore history by sending it as context
450
if (!savedHistory.isEmpty()) {
451
// Send saved messages to rebuild context
452
newChat.sendMessage(savedHistory);
453
}
454
455
// Continue conversation
456
newChat.sendMessage("Continue where we left off");
457
```
458
459
### Error Handling in Chat
460
461
```java
462
import com.google.genai.errors.ApiException;
463
464
Chat chat = client.chats.create("gemini-2.0-flash");
465
466
try {
467
GenerateContentResponse response = chat.sendMessage("Your message");
468
System.out.println(response.text());
469
} catch (ApiException e) {
470
if (e.code() == 429) {
471
System.err.println("Rate limited, waiting...");
472
Thread.sleep(5000);
473
// Retry
474
GenerateContentResponse response = chat.sendMessage("Your message");
475
} else {
476
System.err.println("Error: " + e.message());
477
}
478
}
479
```
480