or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

batch-operations.mdcaching.mdchat-sessions.mdclient-configuration.mdcontent-generation.mdembeddings-tokens.mderror-handling.mdfile-search-stores.mdfiles-management.mdimage-operations.mdindex.mdlive-sessions.mdmodel-tuning.mdoperations.mdtools-functions.mdtypes-reference.mdvideo-generation.md

content-generation.mddocs/

0

# Content Generation

1

2

Generate text content using Gemini models with support for synchronous, asynchronous, and streaming responses. The SDK supports multimodal inputs (text, images, video, audio), structured outputs, system instructions, safety settings, and tool use.

3

4

## Core Imports

5

6

```java

7

import com.google.genai.Models;

8

import com.google.genai.AsyncModels;

9

import com.google.genai.ResponseStream;

10

import com.google.genai.types.GenerateContentResponse;

11

import com.google.genai.types.GenerateContentConfig;

12

import com.google.genai.types.Content;

13

import com.google.genai.types.Part;

14

import com.google.genai.types.Candidate;

15

import com.google.genai.types.UsageMetadata;

16

import java.util.concurrent.CompletableFuture;

17

```

18

19

## Models Service

20

21

```java { .api }

22

package com.google.genai;

23

24

public final class Models {

25

// Synchronous generation

26

public GenerateContentResponse generateContent(

27

String model,

28

String text,

29

GenerateContentConfig config);

30

31

public GenerateContentResponse generateContent(

32

String model,

33

Content content,

34

GenerateContentConfig config);

35

36

public GenerateContentResponse generateContent(

37

String model,

38

List<Content> contents,

39

GenerateContentConfig config);

40

41

// Streaming generation

42

public ResponseStream<GenerateContentResponse> generateContentStream(

43

String model,

44

String text,

45

GenerateContentConfig config);

46

47

public ResponseStream<GenerateContentResponse> generateContentStream(

48

String model,

49

Content content,

50

GenerateContentConfig config);

51

52

public ResponseStream<GenerateContentResponse> generateContentStream(

53

String model,

54

List<Content> contents,

55

GenerateContentConfig config);

56

}

57

```

58

59

## Async Models Service

60

61

```java { .api }

62

package com.google.genai;

63

64

public final class AsyncModels {

65

// Asynchronous generation

66

public CompletableFuture<GenerateContentResponse> generateContent(

67

String model,

68

String text,

69

GenerateContentConfig config);

70

71

public CompletableFuture<GenerateContentResponse> generateContent(

72

String model,

73

Content content,

74

GenerateContentConfig config);

75

76

public CompletableFuture<GenerateContentResponse> generateContent(

77

String model,

78

List<Content> contents,

79

GenerateContentConfig config);

80

81

// Asynchronous streaming

82

public CompletableFuture<ResponseStream<GenerateContentResponse>> generateContentStream(

83

String model,

84

String text,

85

GenerateContentConfig config);

86

87

public CompletableFuture<ResponseStream<GenerateContentResponse>> generateContentStream(

88

String model,

89

Content content,

90

GenerateContentConfig config);

91

92

public CompletableFuture<ResponseStream<GenerateContentResponse>> generateContentStream(

93

String model,

94

List<Content> contents,

95

GenerateContentConfig config);

96

}

97

```

98

99

## Generate Content Config

100

101

```java { .api }

102

package com.google.genai.types;

103

104

public final class GenerateContentConfig {

105

public static Builder builder();

106

107

// System and instructions

108

public Optional<Content> systemInstruction();

109

110

// Generation parameters

111

public Optional<Double> temperature();

112

public Optional<Double> topP();

113

public Optional<Integer> topK();

114

public Optional<Integer> candidateCount();

115

public Optional<Integer> maxOutputTokens();

116

public Optional<List<String>> stopSequences();

117

public Optional<Integer> seed();

118

119

// Penalties

120

public Optional<Double> presencePenalty();

121

public Optional<Double> frequencyPenalty();

122

123

// Safety and filtering

124

public Optional<List<SafetySetting>> safetySettings();

125

126

// Tools

127

public Optional<List<Tool>> tools();

128

public Optional<ToolConfig> toolConfig();

129

public Optional<AutomaticFunctionCallingConfig> automaticFunctionCalling();

130

131

// Structured output

132

public Optional<String> responseMimeType();

133

public Optional<Schema> responseSchema();

134

public Optional<JsonNode> responseJsonSchema();

135

136

// Advanced features

137

public Optional<Boolean> responseLogprobs();

138

public Optional<Integer> logprobs();

139

public Optional<String> cachedContent();

140

public Optional<List<String>> responseModalities();

141

public Optional<String> mediaResolution();

142

public Optional<SpeechConfig> speechConfig();

143

public Optional<ThinkingConfig> thinkingConfig();

144

public Optional<ImageConfig> imageConfig();

145

146

// HTTP options

147

public Optional<HttpOptions> httpOptions();

148

}

149

```

150

151

## Generate Content Response

152

153

```java { .api }

154

package com.google.genai.types;

155

156

public final class GenerateContentResponse {

157

// Response data

158

public Optional<List<Candidate>> candidates();

159

public Optional<String> modelVersion();

160

public Optional<PromptFeedback> promptFeedback();

161

public Optional<UsageMetadata> usageMetadata();

162

public Optional<String> responseId();

163

public Optional<HttpResponse> sdkHttpResponse();

164

public Optional<List<Content>> automaticFunctionCallingHistory();

165

166

// Convenience methods

167

public String text();

168

public Part part(int index);

169

public Part part();

170

}

171

```

172

173

### Candidate

174

175

```java { .api }

176

package com.google.genai.types;

177

178

public final class Candidate {

179

public Optional<Content> content();

180

public Optional<String> finishReason();

181

public Optional<List<SafetyRating>> safetyRatings();

182

public Optional<CitationMetadata> citationMetadata();

183

public Optional<Integer> tokenCount();

184

public Optional<Integer> index();

185

public Optional<GroundingMetadata> groundingMetadata();

186

public Optional<Double> avgLogprobs();

187

public Optional<LogprobsResult> logprobsResult();

188

}

189

```

190

191

### Usage Metadata

192

193

```java { .api }

194

package com.google.genai.types;

195

196

public final class UsageMetadata {

197

public Optional<Integer> promptTokenCount();

198

public Optional<Integer> candidatesTokenCount();

199

public Optional<Integer> totalTokenCount();

200

public Optional<Integer> cachedContentTokenCount();

201

}

202

```

203

204

### Prompt Feedback

205

206

```java { .api }

207

package com.google.genai.types;

208

209

public final class PromptFeedback {

210

public Optional<String> blockReason();

211

public Optional<List<SafetyRating>> safetyRatings();

212

}

213

```

214

215

## Basic Usage

216

217

### Simple Text Generation

218

219

```java

220

import com.google.genai.Client;

221

import com.google.genai.types.GenerateContentResponse;

222

223

Client client = new Client();

224

225

GenerateContentResponse response = client.models.generateContent(

226

"gemini-2.0-flash",

227

"What is your name?",

228

null

229

);

230

231

System.out.println(response.text());

232

```

233

234

### With Configuration

235

236

```java

237

import com.google.genai.types.GenerateContentConfig;

238

239

GenerateContentConfig config = GenerateContentConfig.builder()

240

.temperature(0.7)

241

.maxOutputTokens(1024)

242

.topP(0.95)

243

.topK(40)

244

.build();

245

246

GenerateContentResponse response = client.models.generateContent(

247

"gemini-2.0-flash",

248

"Write a creative story about a robot",

249

config

250

);

251

252

System.out.println(response.text());

253

```

254

255

### Accessing Response Details

256

257

```java

258

GenerateContentResponse response = client.models.generateContent(

259

"gemini-2.0-flash",

260

"Tell me about AI",

261

null

262

);

263

264

// Get text (convenience method)

265

String text = response.text();

266

267

// Get first part

268

Part part = response.part();

269

270

// Get specific part by index

271

Part part2 = response.part(0);

272

273

// Access candidates

274

response.candidates().ifPresent(candidates -> {

275

for (Candidate candidate : candidates) {

276

System.out.println("Finish reason: " + candidate.finishReason().orElse("N/A"));

277

System.out.println("Token count: " + candidate.tokenCount().orElse(0));

278

}

279

});

280

281

// Access usage metadata

282

response.usageMetadata().ifPresent(usage -> {

283

System.out.println("Prompt tokens: " + usage.promptTokenCount().orElse(0));

284

System.out.println("Response tokens: " + usage.candidatesTokenCount().orElse(0));

285

System.out.println("Total tokens: " + usage.totalTokenCount().orElse(0));

286

});

287

288

// Access HTTP response metadata

289

response.sdkHttpResponse().ifPresent(httpResponse -> {

290

System.out.println("Headers: " + httpResponse.headers());

291

});

292

```

293

294

## Multimodal Input

295

296

### Text and Image

297

298

```java

299

import com.google.genai.types.Content;

300

import com.google.genai.types.Part;

301

302

Content content = Content.fromParts(

303

Part.fromText("Describe this image"),

304

Part.fromUri("gs://path/to/image.jpg", "image/jpeg")

305

);

306

307

GenerateContentResponse response = client.models.generateContent(

308

"gemini-2.0-flash",

309

content,

310

null

311

);

312

313

System.out.println(response.text());

314

```

315

316

### With Local Image File

317

318

```java

319

import com.google.genai.types.Image;

320

import java.nio.file.Files;

321

import java.nio.file.Paths;

322

323

// Read image bytes

324

byte[] imageBytes = Files.readAllBytes(Paths.get("path/to/image.jpg"));

325

326

// Create image from bytes

327

Image image = Image.builder()

328

.imageBytes(imageBytes)

329

.mimeType("image/jpeg")

330

.build();

331

332

Content content = Content.fromParts(

333

Part.fromText("What's in this image?"),

334

Part.fromImage(image)

335

);

336

337

GenerateContentResponse response = client.models.generateContent(

338

"gemini-2.0-flash",

339

content,

340

null

341

);

342

```

343

344

### Video Input

345

346

```java

347

import com.google.genai.types.Video;

348

349

Video video = Video.builder()

350

.videoUri("gs://path/to/video.mp4")

351

.mimeType("video/mp4")

352

.build();

353

354

Content content = Content.fromParts(

355

Part.fromText("Summarize this video"),

356

Part.fromVideo(video)

357

);

358

359

GenerateContentResponse response = client.models.generateContent(

360

"gemini-2.0-flash",

361

content,

362

null

363

);

364

```

365

366

### Multiple Content Parts

367

368

```java

369

import com.google.common.collect.ImmutableList;

370

371

Content content = Content.builder()

372

.parts(ImmutableList.of(

373

Part.fromText("Compare these two images:"),

374

Part.fromUri("gs://bucket/image1.jpg", "image/jpeg"),

375

Part.fromUri("gs://bucket/image2.jpg", "image/jpeg")

376

))

377

.role("user")

378

.build();

379

380

GenerateContentResponse response = client.models.generateContent(

381

"gemini-2.0-flash",

382

content,

383

null

384

);

385

```

386

387

## System Instructions

388

389

```java

390

import com.google.genai.types.Content;

391

import com.google.genai.types.Part;

392

import com.google.genai.types.GenerateContentConfig;

393

394

Content systemInstruction = Content.fromParts(

395

Part.fromText("You are a helpful assistant that speaks like Shakespeare.")

396

);

397

398

GenerateContentConfig config = GenerateContentConfig.builder()

399

.systemInstruction(systemInstruction)

400

.build();

401

402

GenerateContentResponse response = client.models.generateContent(

403

"gemini-2.0-flash",

404

"Tell me about the weather",

405

config

406

);

407

```

408

409

## Safety Settings

410

411

```java

412

import com.google.genai.types.SafetySetting;

413

import com.google.genai.types.HarmCategory;

414

import com.google.genai.types.HarmBlockThreshold;

415

import com.google.common.collect.ImmutableList;

416

417

ImmutableList<SafetySetting> safetySettings = ImmutableList.of(

418

SafetySetting.builder()

419

.category(HarmCategory.Known.HARM_CATEGORY_HATE_SPEECH)

420

.threshold(HarmBlockThreshold.Known.BLOCK_ONLY_HIGH)

421

.build(),

422

SafetySetting.builder()

423

.category(HarmCategory.Known.HARM_CATEGORY_DANGEROUS_CONTENT)

424

.threshold(HarmBlockThreshold.Known.BLOCK_MEDIUM_AND_ABOVE)

425

.build(),

426

SafetySetting.builder()

427

.category(HarmCategory.Known.HARM_CATEGORY_SEXUALLY_EXPLICIT)

428

.threshold(HarmBlockThreshold.Known.BLOCK_LOW_AND_ABOVE)

429

.build()

430

);

431

432

GenerateContentConfig config = GenerateContentConfig.builder()

433

.safetySettings(safetySettings)

434

.build();

435

436

GenerateContentResponse response = client.models.generateContent(

437

"gemini-2.0-flash",

438

"Your prompt here",

439

config

440

);

441

442

// Check if prompt was blocked

443

response.promptFeedback().ifPresent(feedback -> {

444

if (feedback.blockReason().isPresent()) {

445

System.out.println("Blocked: " + feedback.blockReason().get());

446

}

447

});

448

```

449

450

## Structured Output

451

452

### JSON Schema Response

453

454

```java

455

import com.google.genai.types.Schema;

456

import com.google.genai.types.Type;

457

import com.google.common.collect.ImmutableMap;

458

import com.google.common.collect.ImmutableList;

459

460

// Define schema using ImmutableMap

461

ImmutableMap<String, Object> schema = ImmutableMap.of(

462

"type", "object",

463

"properties", ImmutableMap.of(

464

"recipe_name", ImmutableMap.of("type", "string"),

465

"ingredients", ImmutableMap.of(

466

"type", "array",

467

"items", ImmutableMap.of("type", "string")

468

),

469

"steps", ImmutableMap.of(

470

"type", "array",

471

"items", ImmutableMap.of("type", "string")

472

)

473

),

474

"required", ImmutableList.of("recipe_name", "ingredients", "steps")

475

);

476

477

GenerateContentConfig config = GenerateContentConfig.builder()

478

.responseMimeType("application/json")

479

.responseSchema(schema)

480

.build();

481

482

GenerateContentResponse response = client.models.generateContent(

483

"gemini-2.0-flash",

484

"Give me a recipe for chocolate chip cookies",

485

config

486

);

487

488

// Response will be valid JSON matching the schema

489

System.out.println(response.text());

490

```

491

492

### Using Schema Builder

493

494

```java

495

import com.google.genai.types.Schema;

496

import com.google.genai.types.Type;

497

import com.google.common.collect.ImmutableMap;

498

import com.google.common.collect.ImmutableList;

499

500

Schema schema = Schema.builder()

501

.type(Type.Known.OBJECT)

502

.properties(ImmutableMap.of(

503

"name", Schema.builder()

504

.type(Type.Known.STRING)

505

.description("Person's name")

506

.build(),

507

"age", Schema.builder()

508

.type(Type.Known.INTEGER)

509

.description("Person's age")

510

.build()

511

))

512

.required(ImmutableList.of("name", "age"))

513

.build();

514

515

GenerateContentConfig config = GenerateContentConfig.builder()

516

.responseMimeType("application/json")

517

.responseSchema(schema)

518

.build();

519

```

520

521

## Streaming

522

523

### Basic Streaming

524

525

```java

526

import com.google.genai.ResponseStream;

527

528

try (ResponseStream<GenerateContentResponse> stream =

529

client.models.generateContentStream(

530

"gemini-2.0-flash",

531

"Tell me a long story",

532

null)) {

533

534

for (GenerateContentResponse chunk : stream) {

535

System.out.print(chunk.text());

536

}

537

System.out.println();

538

}

539

```

540

541

### Streaming with Configuration

542

543

```java

544

GenerateContentConfig config = GenerateContentConfig.builder()

545

.temperature(0.9)

546

.maxOutputTokens(2048)

547

.build();

548

549

try (ResponseStream<GenerateContentResponse> stream =

550

client.models.generateContentStream(

551

"gemini-2.0-flash",

552

"Write a detailed essay about AI",

553

config)) {

554

555

for (GenerateContentResponse chunk : stream) {

556

// Process each chunk as it arrives

557

System.out.print(chunk.text());

558

System.out.flush();

559

}

560

}

561

```

562

563

### Streaming with Multimodal Input

564

565

```java

566

import com.google.genai.types.Content;

567

import com.google.genai.types.Part;

568

569

Content content = Content.fromParts(

570

Part.fromText("Describe this image in detail"),

571

Part.fromUri("gs://bucket/image.jpg", "image/jpeg")

572

);

573

574

try (ResponseStream<GenerateContentResponse> stream =

575

client.models.generateContentStream("gemini-2.0-flash", content, null)) {

576

577

for (GenerateContentResponse chunk : stream) {

578

System.out.print(chunk.text());

579

}

580

}

581

```

582

583

## Asynchronous Generation

584

585

### Basic Async

586

587

```java

588

import java.util.concurrent.CompletableFuture;

589

590

CompletableFuture<GenerateContentResponse> future =

591

client.async.models.generateContent(

592

"gemini-2.0-flash",

593

"What is AI?",

594

null

595

);

596

597

// Use thenAccept for callback

598

future.thenAccept(response -> {

599

System.out.println("Async response: " + response.text());

600

});

601

602

// Or block and wait

603

GenerateContentResponse response = future.join();

604

System.out.println(response.text());

605

```

606

607

### Multiple Async Requests

608

609

```java

610

import java.util.concurrent.CompletableFuture;

611

import java.util.List;

612

import java.util.stream.Collectors;

613

614

List<CompletableFuture<GenerateContentResponse>> futures = List.of(

615

client.async.models.generateContent("gemini-2.0-flash", "What is AI?", null),

616

client.async.models.generateContent("gemini-2.0-flash", "What is ML?", null),

617

client.async.models.generateContent("gemini-2.0-flash", "What is DL?", null)

618

);

619

620

// Wait for all to complete

621

CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))

622

.thenRun(() -> {

623

List<String> responses = futures.stream()

624

.map(CompletableFuture::join)

625

.map(GenerateContentResponse::text)

626

.collect(Collectors.toList());

627

628

responses.forEach(System.out::println);

629

});

630

```

631

632

### Async with Error Handling

633

634

```java

635

CompletableFuture<GenerateContentResponse> future =

636

client.async.models.generateContent(

637

"gemini-2.0-flash",

638

"Your prompt",

639

null

640

);

641

642

future

643

.thenAccept(response -> {

644

System.out.println("Success: " + response.text());

645

})

646

.exceptionally(throwable -> {

647

System.err.println("Error: " + throwable.getMessage());

648

return null;

649

});

650

```

651

652

### Async Streaming

653

654

```java

655

CompletableFuture<ResponseStream<GenerateContentResponse>> futureStream =

656

client.async.models.generateContentStream(

657

"gemini-2.0-flash",

658

"Tell a story",

659

null

660

);

661

662

futureStream.thenAccept(stream -> {

663

try (ResponseStream<GenerateContentResponse> s = stream) {

664

for (GenerateContentResponse chunk : s) {

665

System.out.print(chunk.text());

666

}

667

}

668

});

669

```

670

671

## Multiple Candidates

672

673

```java

674

GenerateContentConfig config = GenerateContentConfig.builder()

675

.candidateCount(3) // Request 3 different responses

676

.temperature(0.9)

677

.build();

678

679

GenerateContentResponse response = client.models.generateContent(

680

"gemini-2.0-flash",

681

"Write a creative opening line for a story",

682

config

683

);

684

685

// Access all candidates

686

response.candidates().ifPresent(candidates -> {

687

for (int i = 0; i < candidates.size(); i++) {

688

Candidate candidate = candidates.get(i);

689

System.out.println("Candidate " + (i + 1) + ":");

690

candidate.content().ifPresent(content -> {

691

content.parts().ifPresent(parts -> {

692

parts.forEach(part -> {

693

part.text().ifPresent(System.out::println);

694

});

695

});

696

});

697

System.out.println();

698

}

699

});

700

```

701

702

## Advanced Features

703

704

### Response Modalities

705

706

```java

707

import com.google.common.collect.ImmutableList;

708

709

GenerateContentConfig config = GenerateContentConfig.builder()

710

.responseModalities(ImmutableList.of("TEXT", "IMAGE"))

711

.build();

712

713

GenerateContentResponse response = client.models.generateContent(

714

"gemini-2.0-flash",

715

"Create an image of a sunset",

716

config

717

);

718

```

719

720

### Thinking Configuration

721

722

```java

723

import com.google.genai.types.ThinkingConfig;

724

725

GenerateContentConfig config = GenerateContentConfig.builder()

726

.thinkingConfig(ThinkingConfig.builder()

727

.thinkingBudget(0) // Disable thinking mode

728

.build())

729

.build();

730

731

GenerateContentResponse response = client.models.generateContent(

732

"gemini-2.0-flash",

733

"Solve this problem",

734

config

735

);

736

```

737

738

### Log Probabilities

739

740

```java

741

GenerateContentConfig config = GenerateContentConfig.builder()

742

.responseLogprobs(true)

743

.logprobs(5) // Return top 5 log probabilities per token

744

.build();

745

746

GenerateContentResponse response = client.models.generateContent(

747

"gemini-2.0-flash",

748

"Complete this: The quick brown",

749

config

750

);

751

752

// Access log probabilities

753

response.candidates().ifPresent(candidates -> {

754

candidates.get(0).logprobsResult().ifPresent(logprobs -> {

755

System.out.println("Log probabilities: " + logprobs);

756

});

757

});

758

```

759

760

### Stop Sequences

761

762

```java

763

import com.google.common.collect.ImmutableList;

764

765

GenerateContentConfig config = GenerateContentConfig.builder()

766

.stopSequences(ImmutableList.of("\n\n", "END", "###"))

767

.build();

768

769

GenerateContentResponse response = client.models.generateContent(

770

"gemini-2.0-flash",

771

"Write a paragraph",

772

config

773

);

774

// Generation stops when any stop sequence is encountered

775

```

776

777

### Seed for Reproducibility

778

779

```java

780

GenerateContentConfig config = GenerateContentConfig.builder()

781

.seed(42)

782

.temperature(0.0)

783

.build();

784

785

// Same prompt with same seed should produce similar results

786

GenerateContentResponse response1 = client.models.generateContent(

787

"gemini-2.0-flash", "Tell me a fact", config);

788

GenerateContentResponse response2 = client.models.generateContent(

789

"gemini-2.0-flash", "Tell me a fact", config);

790

```

791

792

## Using Cached Content

793

794

```java

795

// First create cached content (see caching.md)

796

String cachedContentName = "cachedContents/abc123";

797

798

GenerateContentConfig config = GenerateContentConfig.builder()

799

.cachedContent(cachedContentName)

800

.build();

801

802

GenerateContentResponse response = client.models.generateContent(

803

"gemini-2.0-flash",

804

"Based on the cached context, answer this question",

805

config

806

);

807

```

808

809

## Response Stream Class

810

811

```java { .api }

812

package com.google.genai;

813

814

public final class ResponseStream<T> implements Iterable<T>, AutoCloseable {

815

public Iterator<T> iterator();

816

public void close();

817

}

818

```

819

820

The ResponseStream implements both `Iterable<T>` and `AutoCloseable`, making it suitable for use in try-with-resources blocks and foreach loops.

821