diff --git a/examples/src/main/java/com/google/genai/examples/FileSearchCallContentExample.java b/examples/src/main/java/com/google/genai/examples/FileSearchCallContentExample.java new file mode 100644 index 00000000000..a535d7fbae7 --- /dev/null +++ b/examples/src/main/java/com/google/genai/examples/FileSearchCallContentExample.java @@ -0,0 +1,65 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.genai.examples; + +import com.google.genai.types.interactions.content.FileSearchCallContent; + +/** + * Example demonstrating the usage of FileSearchCallContent. + * + *
FileSearchCallContent represents a file search operation call in the Interactions API. + * Unlike other tool calls, FileSearchCallContent contains only the type and call ID. + * All search configuration (stores, top_k, filters) is defined in the FileSearch. + */ +public class FileSearchCallContentExample { + + public static void main(String[] args) { + // Example 1: Create FileSearchCallContent using builder + FileSearchCallContent content1 = + FileSearchCallContent.builder() + .id("file-search-call-123") + .build(); + + System.out.println("FileSearchCallContent (using builder) JSON:"); + System.out.println(content1.toJson()); + System.out.println(); + + // Example 2: Create FileSearchCallContent using convenience method + FileSearchCallContent content2 = + FileSearchCallContent.of("call-456"); + + System.out.println("FileSearchCallContent (using of() method) JSON:"); + System.out.println(content2.toJson()); + System.out.println(); + + // Example 3: Deserialize from JSON + String json = content2.toJson(); + FileSearchCallContent deserialized = FileSearchCallContent.fromJson(json); + + System.out.println("Deserialized FileSearchCallContent:"); + System.out.println(" ID: " + deserialized.id()); + System.out.println(); + + // Example 4: Create FileSearchCallContent without ID (optional) + FileSearchCallContent content3 = + FileSearchCallContent.builder() + .build(); + + System.out.println("FileSearchCallContent (no ID) JSON:"); + System.out.println(content3.toJson()); + } +} diff --git a/examples/src/main/java/com/google/genai/examples/InteractionsApiVersionExample.java b/examples/src/main/java/com/google/genai/examples/InteractionsApiVersionExample.java new file mode 100644 index 00000000000..1c9f6affd1b --- /dev/null +++ b/examples/src/main/java/com/google/genai/examples/InteractionsApiVersionExample.java @@ -0,0 +1,397 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.genai.examples; + +import com.google.genai.Client; +import com.google.genai.types.HttpOptions; +import com.google.genai.types.interactions.CreateInteractionConfig; +import com.google.genai.types.interactions.GetInteractionConfig; +import com.google.genai.types.interactions.Interaction; +import com.google.genai.types.interactions.content.AudioContent; +import com.google.genai.types.interactions.content.Content; +import com.google.genai.types.interactions.content.TextContent; + +/** + * Demonstrates API version usage in Interactions API with real API calls. + * + *
This example shows: + *
Each example makes real API calls and prints: + *
Usage: + *
Note: The Interactions API is in beta and subject to change. + */ +public class InteractionsApiVersionExample { + + public static void main(String[] args) { + System.out.println("=== Interactions API Version Examples ==="); + System.out.println("Testing api_version functionality with real API calls\n"); + + example1_clientLevelApiVersion(); + System.out.println("\n" + "=".repeat(80) + "\n"); + + example2_requestLevelApiVersion(); + System.out.println("\n" + "=".repeat(80) + "\n"); + + example3_precedence(); + System.out.println("\n" + "=".repeat(80) + "\n"); + + example4_invalidApiVersion(); + System.out.println("\n" + "=".repeat(80) + "\n"); + + example5_allConfigTypes(); + System.out.println("\n" + "=".repeat(80) + "\n"); + + example6_requestApiVersionPreservesClientSettings(); + + System.out.println("\n=== All Examples Completed ==="); + } + + /** + * Example 1: Set api_version at client-level (v1beta - valid). + */ + private static void example1_clientLevelApiVersion() { + System.out.println("--- Example 1: Client-Level API Version (v1beta) ---"); + + try { + // Set api_version for ALL requests from this client + HttpOptions httpOptions = HttpOptions.builder() + .apiVersion("v1beta") + .timeout(30000) + .build(); + + Client client = Client.builder() + .httpOptions(httpOptions) + .build(); + + // Text content example + TextContent textContent = TextContent.of("What is the capital of France?"); + + CreateInteractionConfig config = CreateInteractionConfig.builder() + .model("gemini-3-flash-preview") + .inputFromContents(textContent) + .build(); + + System.out.println("\n=== REQUEST ==="); + System.out.println(config.toJson()); + System.out.println(); + + Interaction response = client.interactions.create(config); + + System.out.println("=== RESPONSE ==="); + System.out.println(response.toJson()); + System.out.println(); + + printResults(response); + + System.out.println("✓ Success: Client-level api_version v1beta works\n"); + } catch (Exception e) { + System.err.println("✗ Error: " + e.getMessage()); + e.printStackTrace(); + } + } + + /** + * Example 2: Override api_version for a specific request (v1alpha - valid). + */ + private static void example2_requestLevelApiVersion() { + System.out.println("--- Example 2: Request-Level API Version Override (v1alpha) ---"); + + try { + Client client = new Client(); + + // Audio content example + String audioUri = "https://storage.googleapis.com/cloud-samples-data/speech/brooklyn_bridge.mp3"; + AudioContent audioContent = AudioContent.fromUri(audioUri, "audio/mp3"); + TextContent audioPrompt = TextContent.of("Transcribe this audio."); + + CreateInteractionConfig config = CreateInteractionConfig.builder() + .model("gemini-3-flash-preview") + .inputFromContents(audioPrompt, audioContent) + .apiVersion("v1alpha") // ← Request-level override + .build(); + + System.out.println("\n=== REQUEST ==="); + System.out.println(config.toJson()); + System.out.println(); + + Interaction response = client.interactions.create(config); + + System.out.println("=== RESPONSE ==="); + System.out.println(response.toJson()); + System.out.println(); + + printResults(response); + + System.out.println("✓ Success: Request-level api_version v1alpha works\n"); + } catch (Exception e) { + System.err.println("✗ Error: " + e.getMessage()); + e.printStackTrace(); + } + } + + /** + * Example 3: Demonstrate precedence (request-level overrides client-level). + */ + private static void example3_precedence() { + System.out.println("--- Example 3: Precedence (Request > Client) ---"); + + try { + // Client has v1 api_version AND 30s timeout + HttpOptions clientOptions = HttpOptions.builder() + .apiVersion("v1") + .timeout(30000) // ← Client timeout will be preserved + .build(); + + Client client = Client.builder() + .httpOptions(clientOptions) + .build(); + + TextContent textContent = TextContent.of("What is quantum computing?"); + + // Request overrides ONLY api_version (timeout is NOT overridden) + CreateInteractionConfig config = CreateInteractionConfig.builder() + .model("gemini-3-flash-preview") + .inputFromContents(textContent) + .apiVersion("v1beta") // ← Overrides client-level v1 + .build(); + + System.out.println("Client-level api_version: v1"); + System.out.println("Client-level timeout: 30000ms"); + System.out.println("Request-level api_version: v1beta"); + System.out.println("Request-level timeout: (not set)"); + System.out.println("Expected: v1beta api_version + 30000ms timeout\n"); + + System.out.println("=== REQUEST ==="); + System.out.println(config.toJson()); + System.out.println(); + + Interaction response = client.interactions.create(config); + + System.out.println("=== RESPONSE ==="); + System.out.println(response.toJson()); + System.out.println(); + + printResults(response); + + System.out.println("✓ Success: Request-level api_version takes precedence\n"); + } catch (Exception e) { + System.err.println("✗ Error: " + e.getMessage()); + e.printStackTrace(); + } + } + + /** + * Example 4: Invalid API version (error case). + */ + private static void example4_invalidApiVersion() { + System.out.println("--- Example 4: Invalid API Version (Error Test) ---"); + + try { + Client client = new Client(); + + TextContent textContent = TextContent.of("Hello world"); + + CreateInteractionConfig config = CreateInteractionConfig.builder() + .model("gemini-3-flash-preview") + .inputFromContents(textContent) + .apiVersion("v999invalid") // ← Invalid version + .build(); + + System.out.println("\n=== REQUEST ==="); + System.out.println(config.toJson()); + System.out.println(); + + System.out.println("Attempting to create interaction with invalid api_version: v999invalid"); + + Interaction response = client.interactions.create(config); + + System.out.println("=== RESPONSE ==="); + System.out.println(response.toJson()); + System.out.println(); + + System.out.println("✗ Unexpected: Invalid API version should have failed\n"); + } catch (Exception e) { + System.out.println("✓ Expected Error Caught:"); + System.out.println(" Message: " + e.getMessage()); + System.out.println(" Type: " + e.getClass().getSimpleName()); + System.out.println(" This is expected behavior - invalid API versions are rejected\n"); + } + } + + /** + * Example 5: api_version works with all config types. + */ + private static void example5_allConfigTypes() { + System.out.println("--- Example 5: All Config Types Support api_version ---"); + + try { + Client client = new Client(); + + // Create interaction + TextContent textContent = TextContent.of("Tell me a short joke"); + + CreateInteractionConfig createConfig = CreateInteractionConfig.builder() + .model("gemini-3-flash-preview") + .inputFromContents(textContent) + .apiVersion("v1beta") + .build(); + + System.out.println("CreateInteractionConfig with api_version: v1beta"); + System.out.println("\n=== REQUEST ==="); + System.out.println(createConfig.toJson()); + System.out.println(); + + Interaction created = client.interactions.create(createConfig); + + System.out.println("=== RESPONSE ==="); + System.out.println(created.toJson()); + System.out.println(); + + printResults(created); + + // Get interaction with api_version + GetInteractionConfig getConfig = GetInteractionConfig.builder() + .apiVersion("v1beta") + .build(); + + System.out.println("\nGetInteractionConfig with api_version: v1beta"); + Interaction retrieved = client.interactions.get(created.id(), getConfig); + System.out.println("Retrieved Interaction ID: " + retrieved.id()); + + System.out.println("\n✓ Success: All config types work with api_version\n"); + } catch (Exception e) { + System.err.println("✗ Error: " + e.getMessage()); + e.printStackTrace(); + } + } + + /** + * Example 6: Proves that request-level api_version ONLY overrides api_version, + * preserving all other client-level settings (timeout, headers, etc.). + */ + private static void example6_requestApiVersionPreservesClientSettings() { + System.out.println("--- Example 6: Request api_version Preserves Client Settings ---"); + System.out.println("This example proves that setting api_version in the request config"); + System.out.println("does NOT override other client-level HttpOptions like timeout.\n"); + + try { + // Create client with MULTIPLE HttpOptions settings + HttpOptions clientOptions = HttpOptions.builder() + .apiVersion("v1") // ← Client-level api_version + .timeout(60000) // ← Client-level timeout (60 seconds) + .build(); + + Client client = Client.builder() + .httpOptions(clientOptions) + .build(); + + System.out.println("Client HttpOptions:"); + System.out.println(" api_version: v1"); + System.out.println(" timeout: 60000ms (60 seconds)"); + System.out.println(); + + // Create config that ONLY sets api_version (not timeout) + TextContent textContent = TextContent.of("Explain quantum entanglement in simple terms"); + + CreateInteractionConfig config = CreateInteractionConfig.builder() + .model("gemini-3-flash-preview") + .inputFromContents(textContent) + .apiVersion("v1beta") // ← Override ONLY api_version + .build(); + + System.out.println("Request Config:"); + System.out.println(" api_version: v1beta (overrides client v1)"); + System.out.println(" timeout: NOT SET (should preserve client's 60000ms)"); + System.out.println(); + + System.out.println("Expected behavior:"); + System.out.println(" ✓ API request will use api_version v1beta (from request)"); + System.out.println(" ✓ API request will use timeout 60000ms (from client - preserved!)"); + System.out.println(); + + System.out.println("=== REQUEST ==="); + System.out.println(config.toJson()); + System.out.println(); + + long startTime = System.currentTimeMillis(); + Interaction response = client.interactions.create(config); + long duration = System.currentTimeMillis() - startTime; + + System.out.println("=== RESPONSE ==="); + System.out.println(response.toJson()); + System.out.println(); + + printResults(response); + + System.out.println("\nRequest completed in " + duration + "ms"); + System.out.println("✓ Success: Request completed within client timeout (60000ms)"); + System.out.println("✓ This proves client timeout was preserved even though config set api_version"); + System.out.println(); + + System.out.println("Key Insight:"); + System.out.println(" The request-level api_version (v1beta) was used for the API endpoint,"); + System.out.println(" BUT the client-level timeout (60000ms) was still applied to the request."); + System.out.println(" This demonstrates SELECTIVE OVERRIDE: only api_version changed,"); + System.out.println(" all other HttpOptions (timeout, headers, etc.) were preserved."); + + System.out.println("\n✓ Success: Request-level api_version preserves client-level settings\n"); + } catch (Exception e) { + System.err.println("✗ Error: " + e.getMessage()); + e.printStackTrace(); + } + } + + /** Prints extracted results from the interaction response. */ + private static void printResults(Interaction interaction) { + System.out.println("Results:"); + System.out.println(" Interaction ID: " + interaction.id()); + System.out.println(" Status: " + interaction.status()); + + if (!interaction.outputs().isPresent() || interaction.outputs().get().isEmpty()) { + System.out.println(" Outputs: (none)"); + return; + } + + for (Content output : interaction.outputs().get()) { + if (output instanceof TextContent) { + TextContent t = (TextContent) output; + String text = t.text().orElse("(empty)"); + System.out.println(" Text: " + text.substring(0, Math.min(200, text.length())) + "..."); + } + } + } +} diff --git a/examples/src/main/java/com/google/genai/examples/InteractionsAsyncCreate.java b/examples/src/main/java/com/google/genai/examples/InteractionsAsyncCreate.java new file mode 100644 index 00000000000..4e10f9193fb --- /dev/null +++ b/examples/src/main/java/com/google/genai/examples/InteractionsAsyncCreate.java @@ -0,0 +1,116 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.genai.examples; + +import com.google.genai.Client; +import com.google.genai.types.interactions.CreateInteractionConfig; +import com.google.genai.types.interactions.Interaction; +import com.google.genai.types.interactions.content.Content; +import com.google.genai.types.interactions.content.TextContent; +import java.util.concurrent.CompletableFuture; + +/** + * Example: Async Create with the Interactions API + * + *
Demonstrates async operations using CompletableFuture for non-blocking requests. + * + *
To run this example: + *
Note: The Interactions API is currently in beta.
+ */
+public final class InteractionsAsyncCreate {
+
+ public static void main(String[] args) {
+ Client client = new Client();
+
+ System.out.println("=== Interactions API: Async Create Example ===\n");
+
+ try {
+ // ===== Basic Async Create =====
+ System.out.println("--- Async Create with Callback ---\n");
+
+ // Using the convenience overload: create(model, text)
+ String model = "gemini-3-flash-preview";
+ String prompt = "What is the capital of France?";
+
+ System.out.println("=== REQUEST ===");
+ System.out.println("Model: " + model);
+ System.out.println("Input: " + prompt);
+ System.out.println();
+
+ System.out.println("Sending async request...\n");
+
+ CompletableFuture This example shows:
+ * To run this example:
+ * Note: The Interactions API is currently in beta.
+ */
+public final class InteractionsAudioContent {
+
+ public static void main(String[] args) {
+ Client client = new Client();
+
+ System.out.println("=== Interactions API: Audio Content Example ===\n");
+
+ try {
+ // ===== PART 1: Audio from URI =====
+ System.out.println("--- PART 1: Audio from URI ---\n");
+
+ String audioUri = "https://storage.googleapis.com/cloud-samples-data/speech/brooklyn_bridge.mp3";
+ AudioContent audioContent = AudioContent.fromUri(audioUri, "audio/mp3");
+ TextContent textPrompt = TextContent.of("Transcribe this audio.");
+
+ Input input = Input.fromContents(textPrompt, audioContent);
+
+ Interaction response = client.interactions.create("gemini-3-flash-preview", input);
+
+ System.out.println("=== RESPONSE ===");
+ System.out.println(response.toJson());
+ System.out.println();
+
+ printResults(response);
+
+ // ===== PART 2: Audio from Inline Data (base64) =====
+ System.out.println("\n--- PART 2: Audio from Inline Data (Base64) ---\n");
+
+ // Small WAV file header encoded as base64
+ String base64Data = "UklGRiQAAABXQVZFZm10IBAAAAABAAEAQB8AAAB9AAACABAAZGF0YQAAAAA=";
+ AudioContent audioFromData = AudioContent.fromData(base64Data, "audio/wav");
+ TextContent textPrompt2 = TextContent.of("What do you hear in this audio?");
+
+ Input input2 = Input.fromContents(textPrompt2, audioFromData);
+
+ Interaction response2 = client.interactions.create("gemini-3-flash-preview", input2);
+
+ System.out.println("=== RESPONSE ===");
+ System.out.println(response2.toJson());
+ System.out.println();
+
+ printResults(response2);
+
+ System.out.println("\n=== Example completed ===");
+
+ } catch (Exception e) {
+ System.err.println("Error: " + e.getMessage());
+ e.printStackTrace();
+ }
+ }
+
+ private static void printResults(Interaction interaction) {
+ System.out.println("Results:");
+ System.out.println(" Interaction ID: " + interaction.id());
+ System.out.println(" Status: " + interaction.status());
+
+ if (interaction.outputs().isPresent() && !interaction.outputs().get().isEmpty()) {
+ for (Content output : interaction.outputs().get()) {
+ if (output instanceof TextContent) {
+ System.out.println(" Text: " + ((TextContent) output).text().orElse("(empty)"));
+ } else {
+ System.out.println(" " + output.getClass().getSimpleName());
+ }
+ }
+ }
+ }
+
+ private InteractionsAudioContent() {}
+}
diff --git a/examples/src/main/java/com/google/genai/examples/InteractionsCancelExample.java b/examples/src/main/java/com/google/genai/examples/InteractionsCancelExample.java
new file mode 100644
index 00000000000..422223619c0
--- /dev/null
+++ b/examples/src/main/java/com/google/genai/examples/InteractionsCancelExample.java
@@ -0,0 +1,133 @@
+/*
+ * Copyright 2025 Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.genai.examples;
+
+import com.google.genai.Client;
+import com.google.genai.types.interactions.CancelInteractionConfig;
+import com.google.genai.types.interactions.CreateInteractionConfig;
+import com.google.genai.types.interactions.GetInteractionConfig;
+import com.google.genai.types.interactions.Interaction;
+import com.google.genai.types.interactions.content.Content;
+import com.google.genai.types.interactions.content.TextContent;
+
+/**
+ * Example: Cancel Interaction API
+ *
+ * Demonstrates the interactions.cancel() API for background interactions.
+ *
+ * Note: Only interactions created with background=true can be cancelled.
+ *
+ * To run this example:
+ * Note: The Interactions API is currently in beta.
+ */
+public final class InteractionsCancelExample {
+
+ public static void main(String[] args) {
+ Client client = new Client();
+
+ System.out.println("=== Interactions API: Cancel Example ===\n");
+
+ try {
+ // ===== STEP 1: Create Background Interaction =====
+ System.out.println("--- STEP 1: Create Background Interaction ---\n");
+
+ CreateInteractionConfig createConfig =
+ CreateInteractionConfig.builder()
+ .agent("deep-research-pro-preview-12-2025")
+ .input("Write an essay about space exploration.")
+ .background(true)
+ .build();
+
+ System.out.println("=== REQUEST ===");
+ System.out.println(createConfig.toJson());
+ System.out.println();
+
+ Interaction interaction = client.interactions.create(createConfig);
+
+ System.out.println("=== RESPONSE ===");
+ System.out.println(interaction.toJson());
+ System.out.println();
+
+ printResults(interaction);
+
+ String interactionId = interaction.id();
+
+ // ===== STEP 2: Cancel the Interaction =====
+ System.out.println("\n--- STEP 2: Cancel the Interaction ---\n");
+
+ try {
+ Interaction cancelled = client.interactions.cancel(interactionId);
+
+ System.out.println("=== RESPONSE ===");
+ System.out.println(cancelled.toJson());
+ System.out.println();
+
+ printResults(cancelled);
+ } catch (Exception e) {
+ System.out.println("Results:");
+ System.out.println(" Cancel failed: " + e.getMessage());
+ System.out.println(" (May happen if interaction completed too quickly)");
+ }
+
+ // ===== STEP 3: Verify Final State =====
+ System.out.println("\n--- STEP 3: Verify Final State ---\n");
+
+ try {
+ Interaction retrieved = client.interactions.get(interactionId);
+
+ System.out.println("=== RESPONSE ===");
+ System.out.println(retrieved.toJson());
+ System.out.println();
+
+ printResults(retrieved);
+ } catch (Exception e) {
+ System.out.println("Results:");
+ System.out.println(" Get failed: " + e.getMessage());
+ }
+
+ System.out.println("\n=== Example completed ===");
+
+ } catch (Exception e) {
+ System.err.println("Error: " + e.getMessage());
+ e.printStackTrace();
+ }
+ }
+
+ private static void printResults(Interaction interaction) {
+ System.out.println("Results:");
+ System.out.println(" Interaction ID: " + interaction.id());
+ System.out.println(" Status: " + interaction.status());
+
+ if (interaction.outputs().isPresent() && !interaction.outputs().get().isEmpty()) {
+ for (Content output : interaction.outputs().get()) {
+ if (output instanceof TextContent) {
+ System.out.println(" Text: " + ((TextContent) output).text().orElse("(empty)"));
+ } else {
+ System.out.println(" " + output.getClass().getSimpleName());
+ }
+ }
+ }
+ }
+
+ private InteractionsCancelExample() {}
+}
diff --git a/examples/src/main/java/com/google/genai/examples/InteractionsChainedConversation.java b/examples/src/main/java/com/google/genai/examples/InteractionsChainedConversation.java
new file mode 100644
index 00000000000..16acbfdb165
--- /dev/null
+++ b/examples/src/main/java/com/google/genai/examples/InteractionsChainedConversation.java
@@ -0,0 +1,265 @@
+/*
+ * Copyright 2025 Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.genai.examples;
+
+import com.google.genai.Client;
+import com.google.genai.types.interactions.CreateInteractionConfig;
+import com.google.genai.types.interactions.Interaction;
+import com.google.genai.types.interactions.Usage;
+import com.google.genai.types.interactions.content.Content;
+import com.google.genai.types.interactions.content.TextContent;
+
+/**
+ * Example: Conversation Continuity with previousInteractionId
+ *
+ * Demonstrates how to chain multiple API calls into a continuous conversation using
+ * {@code previousInteractionId}. This is useful when:
+ *
+ * How it works: Each interaction returns an ID. Pass this ID as
+ * {@code previousInteractionId} in the next request to link them together.
+ *
+ * To run this example:
+ *
+ * Note: The Interactions API is currently in beta.
+ */
+public final class InteractionsChainedConversation {
+
+ private static final String SEPARATOR = "─".repeat(60);
+ private static final String MODEL = "gemini-3-flash-preview";
+ private static final String SYSTEM_INSTRUCTION =
+ "You are a helpful cooking assistant. Keep responses brief (2-3 sentences max).";
+
+ public static void main(String[] args) {
+ Client client = new Client();
+
+ printHeader("Chained Conversation Example");
+ System.out.println("This example shows how to chain interactions for conversation continuity.");
+ System.out.println("Each response ID becomes the 'previousInteractionId' for the next request.");
+ System.out.println();
+
+ try {
+ // ═══════════════════════════════════════════════════════════════
+ // TURN 1: Start the conversation
+ // ═══════════════════════════════════════════════════════════════
+ printTurnHeader(1, "Starting conversation", null);
+
+ String prompt1 = "What ingredients do I need for pasta aglio e olio?";
+ printRequest(prompt1, null);
+
+ CreateInteractionConfig config1 =
+ CreateInteractionConfig.builder()
+ .model(MODEL)
+ .systemInstruction(SYSTEM_INSTRUCTION)
+ .input(prompt1)
+ .build();
+
+ Interaction response1 = client.interactions.create(config1);
+ printResponse(response1);
+
+ // ═══════════════════════════════════════════════════════════════
+ // TURN 2: Follow-up question (linked to turn 1)
+ // ═══════════════════════════════════════════════════════════════
+ printTurnHeader(2, "Follow-up question", response1.id());
+
+ String prompt2 = "How long should I cook the garlic?";
+ printRequest(prompt2, response1.id());
+
+ CreateInteractionConfig config2 =
+ CreateInteractionConfig.builder()
+ .model(MODEL)
+ .systemInstruction(SYSTEM_INSTRUCTION)
+ .input(prompt2)
+ .previousInteractionId(response1.id()) // Link to previous
+ .build();
+
+ Interaction response2 = client.interactions.create(config2);
+ printResponse(response2);
+
+ // ═══════════════════════════════════════════════════════════════
+ // TURN 3: Another follow-up (linked to turn 2)
+ // ═══════════════════════════════════════════════════════════════
+ printTurnHeader(3, "Asking about variations", response2.id());
+
+ String prompt3 = "What protein can I add?";
+ printRequest(prompt3, response2.id());
+
+ CreateInteractionConfig config3 =
+ CreateInteractionConfig.builder()
+ .model(MODEL)
+ .systemInstruction(SYSTEM_INSTRUCTION)
+ .input(prompt3)
+ .previousInteractionId(response2.id()) // Link to previous
+ .build();
+
+ Interaction response3 = client.interactions.create(config3);
+ printResponse(response3);
+
+ // ═══════════════════════════════════════════════════════════════
+ // TURN 4: Test context retention (linked to turn 3)
+ // ═══════════════════════════════════════════════════════════════
+ printTurnHeader(4, "Testing context retention", response3.id());
+
+ String prompt4 = "Summarize our recipe discussion in one sentence.";
+ printRequest(prompt4, response3.id());
+
+ CreateInteractionConfig config4 =
+ CreateInteractionConfig.builder()
+ .model(MODEL)
+ .systemInstruction(SYSTEM_INSTRUCTION)
+ .input(prompt4)
+ .previousInteractionId(response3.id()) // Link to previous
+ .build();
+
+ Interaction response4 = client.interactions.create(config4);
+ printResponse(response4);
+
+ // ═══════════════════════════════════════════════════════════════
+ // Summary
+ // ═══════════════════════════════════════════════════════════════
+ printSection("Conversation Chain Summary");
+ System.out.println(" Turn 1: " + response1.id());
+ System.out.println(" ↓");
+ System.out.println(" Turn 2: " + response2.id());
+ System.out.println(" ↓");
+ System.out.println(" Turn 3: " + response3.id());
+ System.out.println(" ↓");
+ System.out.println(" Turn 4: " + response4.id());
+ System.out.println();
+ System.out.println(" ✓ All turns linked via previousInteractionId");
+ System.out.println(" ✓ Context preserved across 4 separate API calls");
+
+ printFooter("Example completed successfully");
+
+ } catch (Exception e) {
+ printFooter("Error: " + e.getMessage());
+ e.printStackTrace();
+ }
+ }
+
+ // ─────────────────────────────────────────────────────────────
+ // Output Formatting Helpers
+ // ─────────────────────────────────────────────────────────────
+
+ private static void printHeader(String title) {
+ System.out.println();
+ System.out.println("╔" + "═".repeat(58) + "╗");
+ System.out.println("║ " + centerText(title, 54) + " ║");
+ System.out.println("╚" + "═".repeat(58) + "╝");
+ System.out.println();
+ }
+
+ private static void printTurnHeader(int turnNumber, String description, String previousId) {
+ System.out.println();
+ System.out.println("┌" + "─".repeat(58) + "┐");
+ System.out.println("│ TURN " + turnNumber + ": " + description
+ + " ".repeat(Math.max(0, 47 - description.length())) + "│");
+ System.out.println("└" + "─".repeat(58) + "┘");
+ if (previousId != null) {
+ System.out.println(" → Linking to: " + previousId);
+ } else {
+ System.out.println(" → Starting fresh (no previous interaction)");
+ }
+ System.out.println();
+ }
+
+ private static void printSection(String title) {
+ System.out.println();
+ System.out.println(SEPARATOR);
+ System.out.println(" " + title);
+ System.out.println(SEPARATOR);
+ }
+
+ private static void printFooter(String message) {
+ System.out.println();
+ System.out.println(SEPARATOR);
+ System.out.println(" " + message);
+ System.out.println(SEPARATOR);
+ System.out.println();
+ }
+
+ private static String centerText(String text, int width) {
+ if (text.length() >= width) {
+ return text;
+ }
+ int padding = (width - text.length()) / 2;
+ return " ".repeat(padding) + text + " ".repeat(width - text.length() - padding);
+ }
+
+ private static void printRequest(String prompt, String previousId) {
+ System.out.println(" REQUEST:");
+ System.out.println(" Model: " + MODEL);
+ System.out.println(" Input: \"" + prompt + "\"");
+ if (previousId != null) {
+ System.out.println(" previousInteractionId: " + previousId);
+ }
+ System.out.println();
+ }
+
+ private static void printResponse(Interaction interaction) {
+ // Metadata
+ System.out.println(" Interaction ID: " + interaction.id());
+ System.out.println(" Status: " + interaction.status());
+ interaction.previousInteractionId()
+ .ifPresent(id -> System.out.println(" Previous ID: " + id));
+
+ // Response text
+ System.out.println();
+ System.out.println(" Response:");
+ String text = getTextOutput(interaction);
+ // Indent each line of the response
+ for (String line : text.split("\n")) {
+ System.out.println(" " + line);
+ }
+
+ // Token usage
+ if (interaction.usage().isPresent()) {
+ Usage usage = interaction.usage().get();
+ System.out.println();
+ System.out.println(" Tokens: " + usage.totalInputTokens().orElse(0) + " in / "
+ + usage.totalOutputTokens().orElse(0) + " out");
+ }
+ }
+
+ private static String getTextOutput(Interaction interaction) {
+ if (!interaction.outputs().isPresent() || interaction.outputs().get().isEmpty()) {
+ return "(no output)";
+ }
+
+ for (Content output : interaction.outputs().get()) {
+ if (output instanceof TextContent) {
+ TextContent textContent = (TextContent) output;
+ return textContent.text().orElse("(empty)");
+ }
+ }
+ return "(no text output)";
+ }
+
+ private InteractionsChainedConversation() {}
+}
diff --git a/examples/src/main/java/com/google/genai/examples/InteractionsCodeExecution.java b/examples/src/main/java/com/google/genai/examples/InteractionsCodeExecution.java
new file mode 100644
index 00000000000..a421511846c
--- /dev/null
+++ b/examples/src/main/java/com/google/genai/examples/InteractionsCodeExecution.java
@@ -0,0 +1,140 @@
+/*
+ * Copyright 2025 Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Usage:
+ *
+ * Note: The Interactions API is currently only available via the Gemini Developer API (not
+ * Vertex AI).
+ *
+ * 1. Set an API key environment variable. You can find a list of available API keys here:
+ * https://aistudio.google.com/app/apikey
+ *
+ * export GOOGLE_API_KEY=YOUR_API_KEY
+ *
+ * 2. Compile the java package and run the sample code.
+ *
+ * mvn clean compile
+ *
+ * mvn exec:java -Dexec.mainClass="com.google.genai.examples.InteractionsCodeExecution"
+ */
+package com.google.genai.examples;
+
+import com.google.genai.Client;
+import com.google.genai.types.interactions.CreateInteractionConfig;
+import com.google.genai.types.interactions.Interaction;
+import com.google.genai.types.interactions.content.CodeExecutionCallContent;
+import com.google.genai.types.interactions.content.CodeExecutionResultContent;
+import com.google.genai.types.interactions.content.Content;
+import com.google.genai.types.interactions.content.TextContent;
+import com.google.genai.types.interactions.tools.CodeExecution;
+
+/**
+ * Example: Code Execution Tool with the Interactions API
+ *
+ * Demonstrates how to use the CodeExecution to enable the model to execute code as part of
+ * generation. The model can write and run code to solve problems.
+ *
+ * Note: The Interactions API is in beta and subject to change.
+ */
+public final class InteractionsCodeExecution {
+
+ public static void main(String[] args) {
+ // Instantiate the client. The client gets the API key from the environment variable
+ // `GOOGLE_API_KEY`.
+ //
+ Client client = new Client();
+
+ System.out.println("=== Interactions API: Code Execution Tool Example ===\n");
+
+ // ===== STEP 1: Create CodeExecution =====
+ System.out.println("STEP 1: Create CodeExecution\n");
+
+ CodeExecution codeTool = CodeExecution.builder().build();
+
+ System.out.println("CodeExecution created successfully\n");
+
+ // ===== STEP 2: Create interaction with Code Execution enabled =====
+ System.out.println("---\n");
+ System.out.println("STEP 2: Create interaction with Code Execution enabled\n");
+
+ String userQuestion =
+ "Calculate the first 20 Fibonacci numbers and find their sum. "
+ + "Show me the code and the result.";
+ System.out.println("User: " + userQuestion + "\n");
+
+ CreateInteractionConfig config =
+ CreateInteractionConfig.builder()
+ .model("gemini-3-flash-preview")
+ .input(userQuestion)
+ .tools(codeTool)
+ .build();
+
+ // Print the request JSON
+ System.out.println("=== REQUEST ===");
+ System.out.println(config.toJson());
+ System.out.println();
+
+ Interaction response = client.interactions.create(config);
+
+ // Print the response JSON
+ System.out.println("=== RESPONSE ===");
+ System.out.println(response.toJson());
+ System.out.println();
+
+ // ===== STEP 3: Extract and display the results =====
+ System.out.println("---\n");
+ System.out.println("STEP 3: Extract and display the results\n");
+
+ System.out.println("Response received. Interaction ID: " + response.id());
+ System.out.println();
+
+ if (response.outputs().isPresent()) {
+ for (Content content : response.outputs().get()) {
+ if (content instanceof TextContent) {
+ System.out.println("Text: " + ((TextContent) content).text().orElse("(empty)"));
+ System.out.println();
+ } else if (content instanceof CodeExecutionCallContent) {
+ CodeExecutionCallContent codeCall = (CodeExecutionCallContent) content;
+ System.out.println("Code Execution Call:");
+ System.out.println(" ID: " + codeCall.id());
+ if (codeCall.arguments().isPresent()) {
+ System.out.println(" Language: " + codeCall.arguments().get().language().orElse("N/A"));
+ System.out.println(" Code:");
+ System.out.println(" ---");
+ System.out.println(codeCall.arguments().get().code().orElse("(empty)"));
+ System.out.println(" ---");
+ }
+ System.out.println();
+ } else if (content instanceof CodeExecutionResultContent) {
+ CodeExecutionResultContent codeResult = (CodeExecutionResultContent) content;
+ System.out.println("Code Execution Result:");
+ System.out.println(" Call ID: " + codeResult.callId().orElse("N/A"));
+ System.out.println(" Is Error: " + codeResult.isError().orElse(false));
+ System.out.println(" Result:");
+ System.out.println(" ---");
+ System.out.println(codeResult.result().orElse("(empty)"));
+ System.out.println(" ---");
+ System.out.println();
+ }
+ }
+ }
+
+ System.out.println("\n=== Example completed ===");
+ }
+
+ private InteractionsCodeExecution() {}
+}
diff --git a/examples/src/main/java/com/google/genai/examples/InteractionsComputerUse.java b/examples/src/main/java/com/google/genai/examples/InteractionsComputerUse.java
new file mode 100644
index 00000000000..ce700b1a0dd
--- /dev/null
+++ b/examples/src/main/java/com/google/genai/examples/InteractionsComputerUse.java
@@ -0,0 +1,172 @@
+/*
+ * Copyright 2025 Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Usage:
+ *
+ * Note: The Interactions API is currently only available via the Gemini Developer API (not
+ * Vertex AI).
+ *
+ * IMPORTANT: Computer Use tool may require special API access. This example demonstrates the
+ * configuration but may not work without proper authorization.
+ *
+ * 1. Set an API key environment variable. You can find a list of available API keys here:
+ * https://aistudio.google.com/app/apikey
+ *
+ * export GOOGLE_API_KEY=YOUR_API_KEY
+ *
+ * 2. Compile the java package and run the sample code.
+ *
+ * mvn clean compile
+ *
+ * mvn exec:java -Dexec.mainClass="com.google.genai.examples.InteractionsComputerUse"
+ */
+package com.google.genai.examples;
+
+import com.google.genai.Client;
+import com.google.genai.types.interactions.CreateInteractionConfig;
+import com.google.genai.types.interactions.Interaction;
+import com.google.genai.types.interactions.content.Content;
+import com.google.genai.types.interactions.content.TextContent;
+import com.google.genai.types.interactions.tools.ComputerUse;
+
+/**
+ * Example: Computer Use Tool with the Interactions API
+ *
+ * Demonstrates how to use the ComputerUse to enable the model to interact with a computer
+ * environment. This tool allows the model to control applications, browse web pages, and perform
+ * other computer-based tasks.
+ *
+ * IMPORTANT NOTES:
+ * Note: The Interactions API is in beta and subject to change.
+ */
+public final class InteractionsComputerUse {
+
+ public static void main(String[] args) {
+ // Instantiate the client. The client gets the API key from the environment variable
+ // `GOOGLE_API_KEY`.
+ //
+ Client client = new Client();
+
+ System.out.println("=== Interactions API: Computer Use Tool Example ===\n");
+
+ System.out.println(
+ "IMPORTANT: Computer Use tool may require special API access and authorization.\n");
+
+ // ===== STEP 1: Create ComputerUse =====
+ System.out.println("STEP 1: Create ComputerUse\n");
+
+ // Configure the computer use environment
+ // Common environments: "browser" for web browsing, "desktop" for full desktop access
+ //
+ // IMPORTANT: ComputerUse is a configuration that enables computer use capabilities.
+ // Unlike FunctionCall or CodeExecution, it does NOT have corresponding
+ // ComputerUseCallContent or ComputerUseResultContent types.
+ // Results are returned as standard content types (TextContent, ImageContent, etc.)
+ ComputerUse computerTool =
+ ComputerUse.builder()
+ .environment("browser")
+ // Optionally exclude predefined functions
+ // .excludedPredefinedFunctions("function1", "function2")
+ .build();
+
+ System.out.println("ComputerUse created successfully");
+ System.out.println("Environment: " + computerTool.environment().orElse("default"));
+ System.out.println();
+
+ // ===== STEP 2: Create interaction with Computer Use enabled =====
+ System.out.println("---\n");
+ System.out.println("STEP 2: Create interaction with Computer Use enabled\n");
+
+ String userQuestion = "Navigate to https://www.example.com and tell me what you see.";
+ System.out.println("User: " + userQuestion + "\n");
+
+ CreateInteractionConfig config =
+ CreateInteractionConfig.builder()
+ .model("gemini-3-flash-preview")
+ .input(userQuestion)
+ .tools(computerTool)
+ .build();
+
+ // Print the request JSON
+ System.out.println("=== REQUEST ===");
+ System.out.println(config.toJson());
+ System.out.println();
+
+ try {
+ Interaction response = client.interactions.create(config);
+
+ // Print the response JSON
+ System.out.println("=== RESPONSE ===");
+ System.out.println(response.toJson());
+ System.out.println();
+
+ // ===== STEP 3: Extract and display the results =====
+ System.out.println("---\n");
+ System.out.println("STEP 3: Extract and display the results\n");
+
+ System.out.println("Response received. Interaction ID: " + response.id());
+ System.out.println();
+
+ if (response.outputs().isPresent()) {
+ for (Content content : response.outputs().get()) {
+ System.out.println("Content Type: " + content.getClass().getSimpleName());
+
+ if (content instanceof TextContent) {
+ System.out.println("Text: " + ((TextContent) content).text().orElse("(empty)"));
+ System.out.println();
+ }
+
+ // IMPORTANT: ComputerUse does NOT have dedicated content types
+ // (no ComputerUseCallContent or ComputerUseResultContent).
+ //
+ // Instead, computer use operations return results as:
+ // - TextContent: For textual responses and descriptions
+ // - ImageContent: For screenshots of computer actions
+ // - Other standard content types as needed
+ //
+ // This is different from tools like FunctionCall, CodeExecution, etc.,
+ // which have explicit call/result content type pairs.
+ }
+ }
+
+ System.out.println("\n=== Example completed successfully ===");
+
+ } catch (Exception e) {
+ System.err.println("\n=== Error occurred ===");
+ System.err.println("Error: " + e.getMessage());
+ System.err.println(
+ "\nNote: Computer Use tool may require special API access or authorization.");
+ System.err.println("Please check:");
+ System.err.println(" 1. Your API key has Computer Use permissions");
+ System.err.println(" 2. The feature is enabled for your account");
+ System.err.println(" 3. You're using a model that supports Computer Use");
+ e.printStackTrace();
+ }
+ }
+
+ private InteractionsComputerUse() {}
+}
diff --git a/examples/src/main/java/com/google/genai/examples/InteractionsCreateExample.java b/examples/src/main/java/com/google/genai/examples/InteractionsCreateExample.java
new file mode 100644
index 00000000000..94735b91e20
--- /dev/null
+++ b/examples/src/main/java/com/google/genai/examples/InteractionsCreateExample.java
@@ -0,0 +1,275 @@
+/*
+ * Copyright 2025 Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Usage:
+ *
+ * Note: The Interactions API is currently only available via the Gemini Developer API (not
+ * Vertex AI).
+ *
+ * 1. Set an API key environment variable. You can find a list of available API keys here:
+ * https://aistudio.google.com/app/apikey
+ *
+ * export GOOGLE_API_KEY=YOUR_API_KEY
+ *
+ * 2. Compile the java package and run the sample code.
+ *
+ * mvn clean compile
+ *
+ * mvn exec:java -Dexec.mainClass="com.google.genai.examples.InteractionsCreateExample"
+ */
+package com.google.genai.examples;
+
+import com.google.genai.Client;
+import com.google.genai.types.interactions.CreateInteractionConfig;
+import com.google.genai.types.interactions.Interaction;
+import com.google.genai.types.interactions.content.AudioContent;
+import com.google.genai.types.interactions.content.Content;
+import com.google.genai.types.interactions.content.DocumentContent;
+import com.google.genai.types.interactions.content.ImageContent;
+import com.google.genai.types.interactions.content.TextContent;
+import com.google.genai.types.interactions.content.ThoughtContent;
+import com.google.genai.types.interactions.content.VideoContent;
+
+/**
+ * Example: Create Interaction with All Content Types
+ *
+ * Demonstrates interactions.create() with all available INPUT content types:
+ *
+ * Also shows all possible OUTPUT content types that may be returned.
+ *
+ * Note: The Interactions API is in beta and subject to change.
+ */
+public final class InteractionsCreateExample {
+
+ public static void main(String[] args) {
+ // Instantiate the client. The client gets the API key from the environment variable
+ // `GOOGLE_API_KEY`.
+ //
+ Client client = new Client();
+
+ System.out.println("=== Interactions API: All Content Types Example ===\n");
+
+ try {
+ // ===== PART 1: TextContent =====
+ System.out.println("--- PART 1: TextContent ---\n");
+
+ TextContent textContent = TextContent.of("What is the meaning of life?");
+
+ CreateInteractionConfig textConfig =
+ CreateInteractionConfig.builder()
+ .model("gemini-3-flash-preview")
+ .inputFromContents(textContent)
+ .build();
+
+ System.out.println("=== REQUEST ===");
+ System.out.println(textConfig.toJson());
+ System.out.println();
+
+ Interaction textResponse = client.interactions.create(textConfig);
+
+ System.out.println("=== RESPONSE ===");
+ System.out.println(textResponse.toJson());
+ System.out.println();
+
+ printResults(textResponse);
+
+ // ===== PART 2: ImageContent =====
+ System.out.println("\n--- PART 2: ImageContent ---\n");
+
+ String imageUri = "https://storage.googleapis.com/generativeai-downloads/images/cake.jpg";
+ ImageContent imageContent = ImageContent.fromUri(imageUri, "image/jpeg");
+ TextContent imagePrompt = TextContent.of("Describe this image in detail.");
+
+ CreateInteractionConfig imageConfig =
+ CreateInteractionConfig.builder()
+ .model("gemini-3-flash-preview")
+ .inputFromContents(imagePrompt, imageContent)
+ .build();
+
+ System.out.println("=== REQUEST ===");
+ System.out.println(imageConfig.toJson());
+ System.out.println();
+
+ Interaction imageResponse = client.interactions.create(imageConfig);
+
+ System.out.println("=== RESPONSE ===");
+ System.out.println(imageResponse.toJson());
+ System.out.println();
+
+ printResults(imageResponse);
+
+ // ===== PART 3: AudioContent =====
+ System.out.println("\n--- PART 3: AudioContent ---\n");
+
+ String audioUri = "https://storage.googleapis.com/cloud-samples-data/speech/brooklyn_bridge.mp3";
+ AudioContent audioContent = AudioContent.fromUri(audioUri, "audio/mp3");
+ TextContent audioPrompt = TextContent.of("Transcribe this audio.");
+
+ CreateInteractionConfig audioConfig =
+ CreateInteractionConfig.builder()
+ .model("gemini-3-flash-preview")
+ .inputFromContents(audioPrompt, audioContent)
+ .build();
+
+ System.out.println("=== REQUEST ===");
+ System.out.println(audioConfig.toJson());
+ System.out.println();
+
+ Interaction audioResponse = client.interactions.create(audioConfig);
+
+ System.out.println("=== RESPONSE ===");
+ System.out.println(audioResponse.toJson());
+ System.out.println();
+
+ printResults(audioResponse);
+
+ // ===== PART 4: VideoContent =====
+ System.out.println("\n--- PART 4: VideoContent ---\n");
+
+ String videoUri = "https://storage.googleapis.com/cloud-samples-data/generative-ai/video/pixel8.mp4";
+ VideoContent videoContent = VideoContent.fromUri(videoUri, "video/mp4");
+ TextContent videoPrompt = TextContent.of("Describe what happens in this video.");
+
+ CreateInteractionConfig videoConfig =
+ CreateInteractionConfig.builder()
+ .model("gemini-3-flash-preview")
+ .inputFromContents(videoPrompt, videoContent)
+ .build();
+
+ System.out.println("=== REQUEST ===");
+ System.out.println(videoConfig.toJson());
+ System.out.println();
+
+ Interaction videoResponse = client.interactions.create(videoConfig);
+
+ System.out.println("=== RESPONSE ===");
+ System.out.println(videoResponse.toJson());
+ System.out.println();
+
+ printResults(videoResponse);
+
+ // ===== PART 5: DocumentContent (PDF) =====
+ System.out.println("\n--- PART 5: DocumentContent ---\n");
+
+ String pdfUri = "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf";
+ DocumentContent documentContent = DocumentContent.fromUri(pdfUri, "application/pdf");
+ TextContent docPrompt = TextContent.of("Summarize the main points of this document.");
+
+ CreateInteractionConfig docConfig =
+ CreateInteractionConfig.builder()
+ .model("gemini-3-flash-preview")
+ .inputFromContents(docPrompt, documentContent)
+ .build();
+
+ System.out.println("=== REQUEST ===");
+ System.out.println(docConfig.toJson());
+ System.out.println();
+
+ Interaction docResponse = client.interactions.create(docConfig);
+
+ System.out.println("=== RESPONSE ===");
+ System.out.println(docResponse.toJson());
+ System.out.println();
+
+ printResults(docResponse);
+
+ // ===== PART 6: Multiple Content Types Combined =====
+ System.out.println("\n--- PART 6: Multiple Content Types Combined ---\n");
+
+ // Note: Using gemini-3-flash-preview for multi-modal (image + video) combined requests
+ ImageContent cakeImage = ImageContent.fromUri(
+ "https://storage.googleapis.com/generativeai-downloads/images/cake.jpg", "image/jpeg");
+ VideoContent pixelVideo = VideoContent.fromUri(
+ "https://storage.googleapis.com/cloud-samples-data/generative-ai/video/pixel8.mp4", "video/mp4");
+ TextContent multiPrompt = TextContent.of("Compare the cake image with what you see in the video. Are they related?");
+
+ CreateInteractionConfig multiConfig =
+ CreateInteractionConfig.builder()
+ .model("gemini-3-flash-preview")
+ .inputFromContents(multiPrompt, cakeImage, pixelVideo)
+ .build();
+
+ System.out.println("=== REQUEST ===");
+ System.out.println(multiConfig.toJson());
+ System.out.println();
+
+ Interaction multiResponse = client.interactions.create(multiConfig);
+
+ System.out.println("=== RESPONSE ===");
+ System.out.println(multiResponse.toJson());
+ System.out.println();
+
+ printResults(multiResponse);
+
+ // ===== PART 7: Verify with Get API =====
+ System.out.println("\n--- PART 7: Verify Last Interaction (Get API) ---\n");
+
+ Interaction retrieved = client.interactions.get(multiResponse.id());
+
+ System.out.println("=== RESPONSE ===");
+ System.out.println(retrieved.toJson());
+ System.out.println();
+
+ printResults(retrieved);
+
+ System.out.println("\n=== Example completed ===");
+
+ } catch (Exception e) {
+ System.err.println("Error: " + e.getMessage());
+ e.printStackTrace();
+ }
+ }
+
+ /** Prints extracted results from the interaction response. */
+ private static void printResults(Interaction interaction) {
+ System.out.println("Results:");
+ System.out.println(" Interaction ID: " + interaction.id());
+ System.out.println(" Status: " + interaction.status());
+
+ if (!interaction.outputs().isPresent() || interaction.outputs().get().isEmpty()) {
+ System.out.println(" Outputs: (none)");
+ return;
+ }
+
+ for (Content output : interaction.outputs().get()) {
+ if (output instanceof TextContent) {
+ TextContent t = (TextContent) output;
+ String text = t.text().orElse("(empty)");
+ System.out.println(" Text: " + text);
+ } else if (output instanceof ThoughtContent) {
+ ThoughtContent tc = (ThoughtContent) output;
+ System.out.println(" ThoughtContent:");
+ System.out.println(" signature: " + tc.signature().orElse("(none)"));
+ if (tc.summary().isPresent()) {
+ System.out.println(" summaries: " + tc.summary().get().size());
+ }
+ } else {
+ System.out.println(" " + output.getClass().getSimpleName());
+ }
+ }
+ }
+
+ private InteractionsCreateExample() {}
+}
diff --git a/examples/src/main/java/com/google/genai/examples/InteractionsDeleteExample.java b/examples/src/main/java/com/google/genai/examples/InteractionsDeleteExample.java
new file mode 100644
index 00000000000..815227090e3
--- /dev/null
+++ b/examples/src/main/java/com/google/genai/examples/InteractionsDeleteExample.java
@@ -0,0 +1,113 @@
+/*
+ * Copyright 2025 Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.genai.examples;
+
+import com.google.genai.Client;
+import com.google.genai.types.interactions.Interaction;
+import com.google.genai.types.interactions.content.Content;
+import com.google.genai.types.interactions.content.TextContent;
+
+/**
+ * Example: Delete Interaction API
+ *
+ * Demonstrates the interactions.delete() API to delete an interaction.
+ *
+ * To run this example:
+ * Note: The Interactions API is currently in beta.
+ */
+public final class InteractionsDeleteExample {
+
+ public static void main(String[] args) {
+ Client client = new Client();
+
+ System.out.println("=== Interactions API: Delete Example ===\n");
+
+ try {
+ // ===== STEP 1: Create an Interaction =====
+ System.out.println("--- STEP 1: Create an Interaction ---\n");
+
+ // Using the convenience overload: create(model, text)
+ String model = "gemini-3-flash-preview";
+ String prompt = "What is the capital of France?";
+
+ System.out.println("=== REQUEST ===");
+ System.out.println("Model: " + model);
+ System.out.println("Input: " + prompt);
+ System.out.println();
+
+ Interaction interaction = client.interactions.create(model, prompt);
+
+ System.out.println("=== RESPONSE ===");
+ System.out.println(interaction.toJson());
+ System.out.println();
+
+ printResults(interaction);
+
+ String interactionId = interaction.id();
+
+ // ===== STEP 2: Delete the Interaction =====
+ System.out.println("\n--- STEP 2: Delete the Interaction ---\n");
+
+ client.interactions.delete(interactionId);
+
+ System.out.println("Results:");
+ System.out.println(" Interaction deleted successfully: " + interactionId);
+
+ // ===== STEP 3: Verify Deletion =====
+ System.out.println("\n--- STEP 3: Verify Deletion (Get should fail) ---\n");
+
+ try {
+ client.interactions.get(interactionId);
+ System.out.println("ERROR: Should have thrown an exception!");
+ } catch (Exception e) {
+ System.out.println("Results:");
+ System.out.println(" Error: " + e.getMessage());
+ System.out.println(" (Expected - interaction was deleted)");
+ }
+
+ System.out.println("\n=== Example completed ===");
+
+ } catch (Exception e) {
+ System.err.println("Error: " + e.getMessage());
+ e.printStackTrace();
+ }
+ }
+
+ private static void printResults(Interaction interaction) {
+ System.out.println("Results:");
+ System.out.println(" Interaction ID: " + interaction.id());
+ System.out.println(" Status: " + interaction.status());
+
+ if (interaction.outputs().isPresent() && !interaction.outputs().get().isEmpty()) {
+ for (Content output : interaction.outputs().get()) {
+ if (output instanceof TextContent) {
+ System.out.println(" Text: " + ((TextContent) output).text().orElse("(empty)"));
+ } else {
+ System.out.println(" " + output.getClass().getSimpleName());
+ }
+ }
+ }
+ }
+
+ private InteractionsDeleteExample() {}
+}
diff --git a/examples/src/main/java/com/google/genai/examples/InteractionsDocumentContent.java b/examples/src/main/java/com/google/genai/examples/InteractionsDocumentContent.java
new file mode 100644
index 00000000000..a89ee51c6b8
--- /dev/null
+++ b/examples/src/main/java/com/google/genai/examples/InteractionsDocumentContent.java
@@ -0,0 +1,113 @@
+/*
+ * Copyright 2025 Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.genai.examples;
+
+import com.google.genai.Client;
+import com.google.genai.types.interactions.Input;
+import com.google.genai.types.interactions.Interaction;
+import com.google.genai.types.interactions.content.Content;
+import com.google.genai.types.interactions.content.DocumentContent;
+import com.google.genai.types.interactions.content.TextContent;
+
+/**
+ * Example demonstrating document analysis using DocumentContent with the Interactions API.
+ *
+ * This example shows:
+ * To run this example:
+ * Note: The Interactions API is currently in beta.
+ */
+public final class InteractionsDocumentContent {
+
+ public static void main(String[] args) {
+ Client client = new Client();
+
+ System.out.println("=== Interactions API: Document Content Example ===\n");
+
+ try {
+ // ===== PART 1: Document from URI =====
+ System.out.println("--- PART 1: Document from URI ---\n");
+
+ String documentUri = "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf";
+ DocumentContent documentContent = DocumentContent.fromUri(documentUri, "application/pdf");
+ TextContent textPrompt = TextContent.of("Summarize this document.");
+
+ Input input = Input.fromContents(textPrompt, documentContent);
+
+ Interaction response = client.interactions.create("gemini-3-flash-preview", input);
+
+ System.out.println("=== RESPONSE ===");
+ System.out.println(response.toJson());
+ System.out.println();
+
+ printResults(response);
+
+ // ===== PART 2: Document from Inline Data (base64) =====
+ System.out.println("\n--- PART 2: Document from Inline Data (Base64) ---\n");
+
+ // Minimal valid PDF document (1 page with "Hello World")
+ String base64Data =
+ "JVBERi0xLjQKJeLjz9MKMSAwIG9iago8PAovVHlwZSAvQ2F0YWxvZwovUGFnZXMgMiAwIFIKPj4KZW5kb2JqCjIgMCBvYmoKPDwKL1R5cGUgL1BhZ2VzCi9LaWRzIFszIDAgUl0KL0NvdW50IDEKL01lZGlhQm94IFswIDAgNjEyIDc5Ml0KPj4KZW5kb2JqCjMgMCBvYmoKPDwKL1R5cGUgL1BhZ2UKL1BhcmVudCAyIDAgUgovUmVzb3VyY2VzIDw8Ci9Gb250IDw8Ci9GMSA0IDAgUgo+Pgo+PgovQ29udGVudHMgNSAwIFIKPj4KZW5kb2JqCjQgMCBvYmoKPDwKL1R5cGUgL0ZvbnQKL1N1YnR5cGUgL1R5cGUxCi9CYXNlRm9udCAvSGVsdmV0aWNhCj4+CmVuZG9iago1IDAgb2JqCjw8Ci9MZW5ndGggNDQKPj4Kc3RyZWFtCkJUCi9GMSA0OCBUZgoxMCA3MDAgVGQKKEhlbGxvIFdvcmxkKSBUagpFVAplbmRzdHJlYW0KZW5kb2JqCnhyZWYKMCA2CjAwMDAwMDAwMDAgNjU1MzUgZgogCjAwMDAwMDAwMTUgMDAwMDAgbiAKMDAwMDAwMDA2NCAwMDAwMCBuIAowMDAwMDAwMTUxIDAwMDAwIG4gCjAwMDAwMDAyNjIgMDAwMDAgbiAKMDAwMDAwMDM0OSAwMDAwMCBuIAp0cmFpbGVyCjw8Ci9TaXplIDYKL1Jvb3QgMSAwIFIKPj4Kc3RhcnR4cmVmCjQ0MgolJUVPRgo=";
+ DocumentContent documentFromData = DocumentContent.fromData(base64Data, "application/pdf");
+ TextContent textPrompt2 = TextContent.of("What is the content of this document?");
+
+ Input input2 = Input.fromContents(textPrompt2, documentFromData);
+
+ Interaction response2 = client.interactions.create("gemini-3-flash-preview", input2);
+
+ System.out.println("=== RESPONSE ===");
+ System.out.println(response2.toJson());
+ System.out.println();
+
+ printResults(response2);
+
+ System.out.println("\n=== Example completed ===");
+
+ } catch (Exception e) {
+ System.err.println("Error: " + e.getMessage());
+ e.printStackTrace();
+ }
+ }
+
+ private static void printResults(Interaction interaction) {
+ System.out.println("Results:");
+ System.out.println(" Interaction ID: " + interaction.id());
+ System.out.println(" Status: " + interaction.status());
+
+ if (interaction.outputs().isPresent() && !interaction.outputs().get().isEmpty()) {
+ for (Content output : interaction.outputs().get()) {
+ if (output instanceof TextContent) {
+ System.out.println(" Text: " + ((TextContent) output).text().orElse("(empty)"));
+ } else {
+ System.out.println(" " + output.getClass().getSimpleName());
+ }
+ }
+ }
+ }
+
+ private InteractionsDocumentContent() {}
+}
diff --git a/examples/src/main/java/com/google/genai/examples/InteractionsFileSearch.java b/examples/src/main/java/com/google/genai/examples/InteractionsFileSearch.java
new file mode 100644
index 00000000000..6af198ce1e2
--- /dev/null
+++ b/examples/src/main/java/com/google/genai/examples/InteractionsFileSearch.java
@@ -0,0 +1,199 @@
+/*
+ * Copyright 2025 Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Usage:
+ *
+ * Note: The Interactions API is currently only available via the Gemini Developer API (not
+ * Vertex AI).
+ *
+ * IMPORTANT: This example requires file search stores to be created beforehand.
+ *
+ * Setup Instructions:
+ *
+ * 1. Create a file search store using the Google AI API:
+ *
+ * Using gcloud CLI or API:
+ *
+ * curl -X POST https://generativelanguage.googleapis.com/v1beta/fileSearchStores \
+ *
+ * -H "Authorization: Bearer $(gcloud auth print-access-token)" \
+ *
+ * -H "Content-Type: application/json" \
+ *
+ * -d '{"displayName": "my-document-store"}'
+ *
+ * 2. Upload files to the store:
+ *
+ * curl -X POST
+ * https://generativelanguage.googleapis.com/v1beta/fileSearchStores/STORE_NAME/documents \
+ *
+ * -H "Authorization: Bearer $(gcloud auth print-access-token)" \
+ *
+ * -F "file=@/path/to/document.pdf"
+ *
+ * 3. Set an API key environment variable:
+ *
+ * export GOOGLE_API_KEY=YOUR_API_KEY
+ *
+ * 4. Update the store name in this example to match your created store.
+ *
+ * 5. Compile and run:
+ *
+ * mvn clean compile
+ *
+ * mvn exec:java -Dexec.mainClass="com.google.genai.examples.InteractionsFileSearch"
+ */
+package com.google.genai.examples;
+
+import com.google.genai.Client;
+import com.google.genai.types.interactions.CreateInteractionConfig;
+import com.google.genai.types.interactions.Interaction;
+import com.google.genai.types.interactions.FileSearchResult;
+import com.google.genai.types.interactions.content.FileSearchResultContent;
+import com.google.genai.types.interactions.content.Content;
+import com.google.genai.types.interactions.content.TextContent;
+import com.google.genai.types.interactions.tools.FileSearch;
+
+/**
+ * Example: File Search Tool with the Interactions API
+ *
+ * Demonstrates how to use the FileSearch to enable the model to search through file stores.
+ * This is useful for RAG (Retrieval-Augmented Generation) use cases where you want the model to
+ * answer questions based on your documents.
+ *
+ * IMPORTANT: Requires file search stores to be created beforehand. See usage instructions
+ * above.
+ *
+ * Note: The Interactions API is in beta and subject to change.
+ */
+public final class InteractionsFileSearch {
+
+ public static void main(String[] args) {
+ // Instantiate the client. The client gets the API key from the environment variable
+ // `GOOGLE_API_KEY`.
+ //
+ Client client = new Client();
+
+ System.out.println("=== Interactions API: File Search Tool Example ===\n");
+
+ System.out.println("IMPORTANT: This example requires file search stores to be created.\n");
+ System.out.println("See the file header comments for setup instructions.\n");
+
+ // ===== STEP 1: Create FileSearch =====
+ System.out.println("STEP 1: Create FileSearch\n");
+
+ // Configure the file search tool
+ // Update the store names to match your created file search stores
+ FileSearch fileSearchTool =
+ FileSearch.builder()
+ .fileSearchStoreNames(
+ "my-document-store-1",
+ "my-document-store-2" // You can search across multiple stores
+ )
+ .topK(10) // Maximum number of results to return
+ // Optional: Add metadata filter
+ // .metadataFilter(ImmutableMap.of("category", "technical", "year", 2025))
+ .build();
+
+ System.out.println("FileSearch created successfully");
+ System.out.println(
+ "Store Names: " + fileSearchTool.fileSearchStoreNames().orElse(java.util.List.of()));
+ System.out.println("Top K: " + fileSearchTool.topK().orElse(10));
+ System.out.println();
+
+ // ===== STEP 2: Create interaction with File Search enabled =====
+ System.out.println("---\n");
+ System.out.println("STEP 2: Create interaction with File Search enabled\n");
+
+ String userQuestion =
+ "What are the main features described in the documentation? "
+ + "Please search through the uploaded files.";
+ System.out.println("User: " + userQuestion + "\n");
+
+ CreateInteractionConfig config =
+ CreateInteractionConfig.builder()
+ .model("gemini-3-flash-preview")
+ .input(userQuestion)
+ .tools(fileSearchTool)
+ .build();
+
+ // Print the request JSON
+ System.out.println("=== REQUEST ===");
+ System.out.println(config.toJson());
+ System.out.println();
+
+ try {
+ Interaction response = client.interactions.create(config);
+
+ // Print the response JSON
+ System.out.println("=== RESPONSE ===");
+ System.out.println(response.toJson());
+ System.out.println();
+
+ // ===== STEP 3: Extract and display the results =====
+ System.out.println("---\n");
+ System.out.println("STEP 3: Extract and display the results\n");
+
+ System.out.println("Response received. Interaction ID: " + response.id());
+ System.out.println();
+
+ if (response.outputs().isPresent()) {
+ for (Content content : response.outputs().get()) {
+ if (content instanceof TextContent) {
+ System.out.println("Text: " + ((TextContent) content).text().orElse("(empty)"));
+ System.out.println();
+ } else if (content instanceof FileSearchResultContent) {
+ FileSearchResultContent searchResult = (FileSearchResultContent) content;
+ System.out.println("File Search Result:");
+
+ if (searchResult.result().isPresent()) {
+ for (FileSearchResult result : searchResult.result().get()) {
+ System.out.println(" Title: " + result.title().orElse("N/A"));
+ System.out.println(" File Search Store: " + result.fileSearchStore().orElse("N/A"));
+
+ if (result.text().isPresent()) {
+ String text = result.text().get();
+ System.out.println(" Text (first 500 chars):");
+ System.out.println(" ---");
+ System.out.println(text.length() > 500 ? text.substring(0, 500) + "..." : text);
+ System.out.println(" ---");
+ System.out.println(" Total text length: " + text.length() + " chars");
+ }
+ }
+ }
+ System.out.println();
+ }
+ }
+ }
+
+ System.out.println("\n=== Example completed successfully ===");
+
+ } catch (Exception e) {
+ System.err.println("\n=== Error occurred ===");
+ System.err.println("Error: " + e.getMessage());
+ System.err.println("\nNote: This example requires file search stores to be created.");
+ System.err.println("Please check:");
+ System.err.println(" 1. File search stores exist with the names specified");
+ System.err.println(" 2. Files have been uploaded to the stores");
+ System.err.println(" 3. Your API key has access to the stores");
+ System.err.println(" 4. The store names in this example match your actual store names");
+ e.printStackTrace();
+ }
+ }
+
+ private InteractionsFileSearch() {}
+}
diff --git a/examples/src/main/java/com/google/genai/examples/InteractionsFunctionCalling.java b/examples/src/main/java/com/google/genai/examples/InteractionsFunctionCalling.java
new file mode 100644
index 00000000000..a2878780f47
--- /dev/null
+++ b/examples/src/main/java/com/google/genai/examples/InteractionsFunctionCalling.java
@@ -0,0 +1,201 @@
+/*
+ * Copyright 2025 Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.genai.examples;
+
+import com.google.common.collect.ImmutableMap;
+import com.google.genai.Client;
+import com.google.genai.types.Schema;
+import com.google.genai.types.interactions.CreateInteractionConfig;
+import com.google.genai.types.interactions.Interaction;
+import com.google.genai.types.interactions.content.Content;
+import com.google.genai.types.interactions.content.FunctionCallContent;
+import com.google.genai.types.interactions.content.FunctionResultContent;
+import com.google.genai.types.interactions.content.TextContent;
+import com.google.genai.types.interactions.tools.Function;
+import java.util.Map;
+
+/**
+ * Example: Function Calling with the Interactions API
+ *
+ * Demonstrates manual function calling where you define functions, extract calls from responses,
+ * execute them, and send results back.
+ *
+ * To run this example:
+ * Note: The Interactions API is currently in beta.
+ */
+public final class InteractionsFunctionCalling {
+
+ public static void main(String[] args) {
+ // [START interactions_client_init]
+ Client client = new Client();
+ // [END interactions_client_init]
+
+ System.out.println("=== Interactions API: Function Calling Example ===\n");
+
+ try {
+ // ===== STEP 1: Define the Function =====
+ System.out.println("--- STEP 1: Define the Function ---\n");
+
+ // [START interactions_function_calling]
+ // [START interactions_function_declaration]
+ Function weatherTool =
+ Function.builder()
+ .name("get_weather")
+ .description("Get the current weather for a location")
+ .parameters(
+ Schema.builder()
+ .type("object")
+ .properties(
+ Map.of(
+ "location",
+ Schema.builder()
+ .type("string")
+ .description("The city name")
+ .build()))
+ .required("location")
+ .build())
+ .build();
+ // [END interactions_function_declaration]
+
+ System.out.println("Function defined: get_weather\n");
+
+ // ===== STEP 2: First Request - Ask about weather =====
+ System.out.println("--- STEP 2: First Request (triggers function call) ---\n");
+
+ CreateInteractionConfig config1 =
+ CreateInteractionConfig.builder()
+ .model("gemini-3-flash-preview")
+ .input("What's the weather like in Paris?")
+ .tools(weatherTool)
+ .build();
+
+ System.out.println("=== REQUEST ===");
+ System.out.println(config1.toJson());
+ System.out.println();
+
+ Interaction response1 = client.interactions.create(config1);
+
+ System.out.println("=== RESPONSE ===");
+ System.out.println(response1.toJson());
+ System.out.println();
+
+ printResults(response1);
+
+ // Extract function call
+ FunctionCallContent functionCall = extractFunctionCall(response1);
+ if (functionCall == null) {
+ System.out.println("ERROR: Expected a function call but didn't receive one.");
+ return;
+ }
+
+ System.out.println(" Function Call ID: " + functionCall.id());
+ System.out.println(" Function Name: " + functionCall.name());
+ System.out.println(" Arguments: " + functionCall.arguments());
+
+ // ===== STEP 3: Execute Function and Send Result =====
+ System.out.println("\n--- STEP 3: Execute Function and Send Result ---\n");
+
+ Map Demonstrates the interactions.get() API to retrieve an interaction by ID.
+ *
+ * To run this example:
+ * Note: The Interactions API is currently in beta.
+ */
+public final class InteractionsGetExample {
+
+ public static void main(String[] args) {
+ Client client = new Client();
+
+ System.out.println("=== Interactions API: Get Example ===\n");
+
+ try {
+ // ===== STEP 1: Create an Interaction =====
+ System.out.println("--- STEP 1: Create an Interaction ---\n");
+
+ // Using the convenience overload: create(model, text)
+ String model = "gemini-3-flash-preview";
+ String prompt = "Explain quantum computing in 2-3 sentences.";
+
+ System.out.println("=== REQUEST ===");
+ System.out.println("Model: " + model);
+ System.out.println("Input: " + prompt);
+ System.out.println();
+
+ Interaction interaction = client.interactions.create(model, prompt);
+
+ System.out.println("=== RESPONSE ===");
+ System.out.println(interaction.toJson());
+ System.out.println();
+
+ printResults(interaction);
+
+ // ===== STEP 2: Get Interaction by ID =====
+ System.out.println("\n--- STEP 2: Get Interaction by ID ---\n");
+
+ String interactionId = interaction.id();
+ Interaction retrieved = client.interactions.get(interactionId);
+
+ System.out.println("=== RESPONSE ===");
+ System.out.println(retrieved.toJson());
+ System.out.println();
+
+ printResults(retrieved);
+
+ System.out.println("\n=== Example completed ===");
+
+ } catch (Exception e) {
+ System.err.println("Error: " + e.getMessage());
+ e.printStackTrace();
+ }
+ }
+
+ private static void printResults(Interaction interaction) {
+ System.out.println("Results:");
+ System.out.println(" Interaction ID: " + interaction.id());
+ System.out.println(" Status: " + interaction.status());
+
+ if (interaction.outputs().isPresent() && !interaction.outputs().get().isEmpty()) {
+ for (Content output : interaction.outputs().get()) {
+ if (output instanceof TextContent) {
+ System.out.println(" Text: " + ((TextContent) output).text().orElse("(empty)"));
+ } else {
+ System.out.println(" " + output.getClass().getSimpleName());
+ }
+ }
+ }
+ }
+
+ private InteractionsGetExample() {}
+}
diff --git a/examples/src/main/java/com/google/genai/examples/InteractionsGoogleSearch.java b/examples/src/main/java/com/google/genai/examples/InteractionsGoogleSearch.java
new file mode 100644
index 00000000000..9f2b431de40
--- /dev/null
+++ b/examples/src/main/java/com/google/genai/examples/InteractionsGoogleSearch.java
@@ -0,0 +1,118 @@
+/*
+ * Copyright 2025 Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.genai.examples;
+
+import com.google.genai.Client;
+import com.google.genai.types.interactions.CreateInteractionConfig;
+import com.google.genai.types.interactions.GoogleSearchResult;
+import com.google.genai.types.interactions.Interaction;
+import com.google.genai.types.interactions.content.Content;
+import com.google.genai.types.interactions.content.GoogleSearchCallContent;
+import com.google.genai.types.interactions.content.GoogleSearchResultContent;
+import com.google.genai.types.interactions.content.TextContent;
+import com.google.genai.types.interactions.tools.GoogleSearch;
+import java.util.List;
+
+/**
+ * Example: Google Search Tool with the Interactions API
+ *
+ * Demonstrates how to use the GoogleSearch tool to enable the model to search the web.
+ *
+ * To run this example:
+ * Note: The Interactions API is currently in beta.
+ */
+public final class InteractionsGoogleSearch {
+
+ public static void main(String[] args) {
+ Client client = new Client();
+
+ System.out.println("=== Interactions API: Google Search Tool Example ===\n");
+
+ try {
+ GoogleSearch searchTool = GoogleSearch.builder().build();
+
+ CreateInteractionConfig config =
+ CreateInteractionConfig.builder()
+ .model("gemini-3-flash-preview")
+ .input("What are the latest developments in quantum computing in 2025?")
+ .tools(searchTool)
+ .build();
+
+ System.out.println("=== REQUEST ===");
+ System.out.println(config.toJson());
+ System.out.println();
+
+ Interaction response = client.interactions.create(config);
+
+ System.out.println("=== RESPONSE ===");
+ System.out.println(response.toJson());
+ System.out.println();
+
+ printResults(response);
+
+ System.out.println("\n=== Example completed ===");
+
+ } catch (Exception e) {
+ System.err.println("Error: " + e.getMessage());
+ e.printStackTrace();
+ }
+ }
+
+ private static void printResults(Interaction interaction) {
+ System.out.println("Results:");
+ System.out.println(" Interaction ID: " + interaction.id());
+ System.out.println(" Status: " + interaction.status());
+
+ if (!interaction.outputs().isPresent() || interaction.outputs().get().isEmpty()) {
+ System.out.println(" Outputs: (none)");
+ return;
+ }
+
+ for (Content output : interaction.outputs().get()) {
+ if (output instanceof TextContent) {
+ System.out.println(" Text: " + ((TextContent) output).text().orElse("(empty)"));
+ } else if (output instanceof GoogleSearchCallContent) {
+ GoogleSearchCallContent searchCall = (GoogleSearchCallContent) output;
+ System.out.println(" GoogleSearchCall: id=" + searchCall.id());
+ if (searchCall.arguments().isPresent()) {
+ System.out.println(" queries: " + searchCall.arguments().get().queries().orElse(List.of()));
+ }
+ } else if (output instanceof GoogleSearchResultContent) {
+ GoogleSearchResultContent searchResult = (GoogleSearchResultContent) output;
+ System.out.println(" GoogleSearchResult: callId=" + searchResult.callId().orElse("N/A"));
+ if (searchResult.result().isPresent()) {
+ List This example shows:
+ * To run this example:
+ * Note: The Interactions API is currently in beta.
+ */
+public final class InteractionsImageContent {
+
+ public static void main(String[] args) {
+ Client client = new Client();
+
+ System.out.println("=== Interactions API: Image Content Example ===\n");
+
+ try {
+ // ===== PART 1: Image from URI =====
+ System.out.println("--- PART 1: Image from URI ---\n");
+
+ String imageUri = "https://storage.googleapis.com/generativeai-downloads/images/cake.jpg";
+ ImageContent imageContent = ImageContent.fromUri(imageUri, "image/jpeg");
+ TextContent textPrompt = TextContent.of("Describe what you see in this image.");
+
+ Input input = Input.fromContents(textPrompt, imageContent);
+
+ Interaction response = client.interactions.create("gemini-3-flash-preview", input);
+
+ System.out.println("=== RESPONSE ===");
+ System.out.println(response.toJson());
+ System.out.println();
+
+ printResults(response);
+
+ // ===== PART 2: Image from Inline Data (base64) =====
+ System.out.println("\n--- PART 2: Image from Inline Data (Base64) ---\n");
+
+ // Small 1x1 red pixel PNG encoded as base64
+ String base64Data =
+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFBQIAX8jx0gAAAABJRU5ErkJggg==";
+ ImageContent imageFromData = ImageContent.fromData(base64Data, "image/png");
+ TextContent textPrompt2 = TextContent.of("What color is this image?");
+
+ Input input2 = Input.fromContents(textPrompt2, imageFromData);
+
+ Interaction response2 = client.interactions.create("gemini-3-flash-preview", input2);
+
+ System.out.println("=== RESPONSE ===");
+ System.out.println(response2.toJson());
+ System.out.println();
+
+ printResults(response2);
+
+ System.out.println("\n=== Example completed ===");
+
+ } catch (Exception e) {
+ System.err.println("Error: " + e.getMessage());
+ e.printStackTrace();
+ }
+ }
+
+ private static void printResults(Interaction interaction) {
+ System.out.println("Results:");
+ System.out.println(" Interaction ID: " + interaction.id());
+ System.out.println(" Status: " + interaction.status());
+
+ if (interaction.outputs().isPresent() && !interaction.outputs().get().isEmpty()) {
+ for (Content output : interaction.outputs().get()) {
+ if (output instanceof TextContent) {
+ System.out.println(" Text: " + ((TextContent) output).text().orElse("(empty)"));
+ } else {
+ System.out.println(" " + output.getClass().getSimpleName());
+ }
+ }
+ }
+ }
+
+ private InteractionsImageContent() {}
+}
diff --git a/examples/src/main/java/com/google/genai/examples/InteractionsMcpServer.java b/examples/src/main/java/com/google/genai/examples/InteractionsMcpServer.java
new file mode 100644
index 00000000000..5535b137350
--- /dev/null
+++ b/examples/src/main/java/com/google/genai/examples/InteractionsMcpServer.java
@@ -0,0 +1,186 @@
+/*
+ * Copyright 2025 Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Usage:
+ *
+ * Note: The Interactions API is currently only available via the Gemini Developer API (not
+ * Vertex AI).
+ *
+ * IMPORTANT: This example requires a running MCP (Model Context Protocol) server.
+ *
+ * Setup Instructions:
+ *
+ * 1. Set up an MCP server. You can use one of the reference implementations:
+ *
+ * - MCP Server SDK: https://github.com/modelcontextprotocol/servers
+ *
+ * - Example: Weather MCP Server (Python)
+ *
+ * pip install mcp
+ *
+ * python -m mcp.server.weather --port 8080
+ *
+ * 2. Set an API key environment variable:
+ *
+ * export GOOGLE_API_KEY=YOUR_API_KEY
+ *
+ * 3. Update the MCP server URL in this example to point to your running MCP server.
+ *
+ * 4. Compile and run:
+ *
+ * mvn clean compile
+ *
+ * mvn exec:java -Dexec.mainClass="com.google.genai.examples.InteractionsMcpServer"
+ */
+package com.google.genai.examples;
+
+import com.google.common.collect.ImmutableMap;
+import com.google.genai.Client;
+import com.google.genai.types.interactions.CreateInteractionConfig;
+import com.google.genai.types.interactions.Interaction;
+import com.google.genai.types.interactions.content.Content;
+import com.google.genai.types.interactions.content.McpServerToolCallContent;
+import com.google.genai.types.interactions.content.McpServerToolResultContent;
+import com.google.genai.types.interactions.content.TextContent;
+import com.google.genai.types.interactions.tools.McpServer;
+
+/**
+ * Example: MCP Server Tool with the Interactions API
+ *
+ * Demonstrates how to use the McpServer to enable the model to interact with an MCP (Model
+ * Context Protocol) server. This allows integration with external tools and services that implement
+ * the MCP protocol.
+ *
+ * IMPORTANT: Requires a running MCP server. See usage instructions above.
+ *
+ * Note: The Interactions API is in beta and subject to change.
+ */
+public final class InteractionsMcpServer {
+
+ public static void main(String[] args) {
+ // Instantiate the client. The client gets the API key from the environment variable
+ // `GOOGLE_API_KEY`.
+ //
+ Client client = new Client();
+
+ System.out.println("=== Interactions API: MCP Server Tool Example ===\n");
+
+ System.out.println("IMPORTANT: This example requires a running MCP server.\n");
+ System.out.println("See the file header comments for setup instructions.\n");
+
+ // ===== STEP 1: Create McpServer =====
+ System.out.println("STEP 1: Create McpServer\n");
+
+ // Configure the MCP server connection
+ // Update these values to match your MCP server setup
+ McpServer mcpTool =
+ McpServer.builder()
+ .name("my-mcp-server")
+ .url("http://localhost:8080/mcp") // Update this URL to your MCP server
+ // Optional: Add custom headers if your MCP server requires authentication
+ .headers(
+ ImmutableMap.of(
+ "Content-Type", "application/json"
+ // "Authorization", "Bearer YOUR_TOKEN"
+ ))
+ // Optional: Restrict to specific tools from the MCP server
+ // .allowedTools("weather", "calculator")
+ .build();
+
+ System.out.println("McpServer created successfully");
+ System.out.println("Name: " + mcpTool.name().orElse("N/A"));
+ System.out.println("URL: " + mcpTool.url().orElse("N/A"));
+ System.out.println();
+
+ // ===== STEP 2: Create interaction with MCP Server enabled =====
+ System.out.println("---\n");
+ System.out.println("STEP 2: Create interaction with MCP Server enabled\n");
+
+ String userQuestion =
+ "What's the weather like in San Francisco? "
+ + "(This uses the MCP server's weather tool)";
+ System.out.println("User: " + userQuestion + "\n");
+
+ CreateInteractionConfig config =
+ CreateInteractionConfig.builder()
+ .model("gemini-3-flash-preview")
+ .input(userQuestion)
+ .tools(mcpTool)
+ .build();
+
+ // Print the request JSON
+ System.out.println("=== REQUEST ===");
+ System.out.println(config.toJson());
+ System.out.println();
+
+ try {
+ Interaction response = client.interactions.create(config);
+
+ // Print the response JSON
+ System.out.println("=== RESPONSE ===");
+ System.out.println(response.toJson());
+ System.out.println();
+
+ // ===== STEP 3: Extract and display the results =====
+ System.out.println("---\n");
+ System.out.println("STEP 3: Extract and display the results\n");
+
+ System.out.println("Response received. Interaction ID: " + response.id());
+ System.out.println();
+
+ if (response.outputs().isPresent()) {
+ for (Content content : response.outputs().get()) {
+ if (content instanceof TextContent) {
+ System.out.println("Text: " + ((TextContent) content).text().orElse("(empty)"));
+ System.out.println();
+ } else if (content instanceof McpServerToolCallContent) {
+ McpServerToolCallContent mcpCall = (McpServerToolCallContent) content;
+ System.out.println("MCP Server Tool Call:");
+ System.out.println(" ID: " + mcpCall.id());
+ System.out.println(" Tool Name: " + mcpCall.name());
+ System.out.println(" Server Name: " + mcpCall.serverName());
+ System.out.println(" Arguments: " + mcpCall.arguments());
+ System.out.println();
+ } else if (content instanceof McpServerToolResultContent) {
+ McpServerToolResultContent mcpResult = (McpServerToolResultContent) content;
+ System.out.println("MCP Server Tool Result:");
+ System.out.println(" Call ID: " + mcpResult.callId());
+ System.out.println(" Tool Name: " + mcpResult.name().orElse("N/A"));
+ System.out.println(" Server Name: " + mcpResult.serverName().orElse("N/A"));
+ System.out.println(" Result: " + mcpResult.result());
+ System.out.println();
+ }
+ }
+ }
+
+ System.out.println("\n=== Example completed successfully ===");
+
+ } catch (Exception e) {
+ System.err.println("\n=== Error occurred ===");
+ System.err.println("Error: " + e.getMessage());
+ System.err.println("\nNote: This example requires a running MCP server.");
+ System.err.println("Please check:");
+ System.err.println(" 1. Your MCP server is running and accessible");
+ System.err.println(" 2. The URL in this example matches your MCP server endpoint");
+ System.err.println(" 3. Any required authentication headers are configured");
+ System.err.println(" 4. Your firewall allows connections to the MCP server");
+ e.printStackTrace();
+ }
+ }
+
+ private InteractionsMcpServer() {}
+}
diff --git a/examples/src/main/java/com/google/genai/examples/InteractionsMediaResolution.java b/examples/src/main/java/com/google/genai/examples/InteractionsMediaResolution.java
new file mode 100644
index 00000000000..6e55c79fb13
--- /dev/null
+++ b/examples/src/main/java/com/google/genai/examples/InteractionsMediaResolution.java
@@ -0,0 +1,96 @@
+/*
+ * Copyright 2025 Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.genai.examples;
+
+import com.google.genai.Client;
+import com.google.genai.types.interactions.Input;
+import com.google.genai.types.interactions.Interaction;
+import com.google.genai.types.interactions.MediaResolution;
+import com.google.genai.types.interactions.content.Content;
+import com.google.genai.types.interactions.content.ImageContent;
+import com.google.genai.types.interactions.content.TextContent;
+
+/**
+ * Example demonstrating MediaResolution with ImageContent in the Interactions API.
+ *
+ * This example shows how to specify image resolution when analyzing images.
+ *
+ * To run this example:
+ * Note: The Interactions API is currently in beta.
+ */
+public final class InteractionsMediaResolution {
+
+ public static void main(String[] args) {
+ Client client = new Client();
+
+ System.out.println("=== Interactions API: Media Resolution Example ===\n");
+
+ try {
+ String imageUri = "https://storage.googleapis.com/generativeai-downloads/images/cake.jpg";
+
+ // Create ImageContent with HIGH resolution
+ MediaResolution resolution = new MediaResolution(MediaResolution.Known.HIGH);
+ ImageContent imageContent = ImageContent.builder()
+ .uri(imageUri)
+ .mimeType(new com.google.genai.types.interactions.ImageMimeType("image/jpeg"))
+ .resolution(resolution)
+ .build();
+
+ TextContent textPrompt = TextContent.of("Describe this image in detail.");
+
+ Input input = Input.fromContents(textPrompt, imageContent);
+
+ Interaction response = client.interactions.create("gemini-3-flash-preview", input);
+
+ System.out.println("=== RESPONSE ===");
+ System.out.println(response.toJson());
+ System.out.println();
+
+ printResults(response);
+
+ System.out.println("\n=== Example completed ===");
+
+ } catch (Exception e) {
+ System.err.println("Error: " + e.getMessage());
+ e.printStackTrace();
+ }
+ }
+
+ private static void printResults(Interaction interaction) {
+ System.out.println("Results:");
+ System.out.println(" Interaction ID: " + interaction.id());
+ System.out.println(" Status: " + interaction.status());
+
+ if (interaction.outputs().isPresent() && !interaction.outputs().get().isEmpty()) {
+ for (Content output : interaction.outputs().get()) {
+ if (output instanceof TextContent) {
+ System.out.println(" Text: " + ((TextContent) output).text().orElse("(empty)"));
+ } else {
+ System.out.println(" " + output.getClass().getSimpleName());
+ }
+ }
+ }
+ }
+
+ private InteractionsMediaResolution() {}
+}
diff --git a/examples/src/main/java/com/google/genai/examples/InteractionsMultiTurnConversation.java b/examples/src/main/java/com/google/genai/examples/InteractionsMultiTurnConversation.java
new file mode 100644
index 00000000000..397cd0b23d1
--- /dev/null
+++ b/examples/src/main/java/com/google/genai/examples/InteractionsMultiTurnConversation.java
@@ -0,0 +1,94 @@
+/*
+ * Copyright 2025 Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.genai.examples;
+
+import com.google.genai.Client;
+import com.google.genai.types.interactions.Input;
+import com.google.genai.types.interactions.Interaction;
+import com.google.genai.types.interactions.Turn;
+import com.google.genai.types.interactions.content.Content;
+import com.google.genai.types.interactions.content.TextContent;
+
+/**
+ * Example: Multi-Turn Conversation with Turn objects
+ *
+ * Demonstrates a multi-turn conversation using Turn objects with role assignment.
+ *
+ * To run this example:
+ * Note: The Interactions API is currently in beta.
+ */
+public final class InteractionsMultiTurnConversation {
+
+ public static void main(String[] args) {
+ Client client = new Client();
+
+ System.out.println("=== Interactions API: Multi-Turn Conversation Example ===\n");
+
+ try {
+ // Using the convenience overload: create(model, Input)
+ // Input.fromTurns() creates multi-turn conversation input
+ String model = "gemini-3-flash-preview";
+ Input conversation = Input.fromTurns(
+ Turn.user("I'm planning a trip to Paris."),
+ Turn.model("That's wonderful! Paris is a beautiful city. What would you like to know?"),
+ Turn.user("What are the top 3 must-see attractions?"));
+
+ System.out.println("=== REQUEST ===");
+ System.out.println("Model: " + model);
+ System.out.println("Input: " + conversation.toJson());
+ System.out.println();
+
+ Interaction response = client.interactions.create(model, conversation);
+
+ System.out.println("=== RESPONSE ===");
+ System.out.println(response.toJson());
+ System.out.println();
+
+ printResults(response);
+
+ System.out.println("\n=== Example completed ===");
+
+ } catch (Exception e) {
+ System.err.println("Error: " + e.getMessage());
+ e.printStackTrace();
+ }
+ }
+
+ private static void printResults(Interaction interaction) {
+ System.out.println("Results:");
+ System.out.println(" Interaction ID: " + interaction.id());
+ System.out.println(" Status: " + interaction.status());
+
+ if (interaction.outputs().isPresent() && !interaction.outputs().get().isEmpty()) {
+ for (Content output : interaction.outputs().get()) {
+ if (output instanceof TextContent) {
+ System.out.println(" Text: " + ((TextContent) output).text().orElse("(empty)"));
+ } else {
+ System.out.println(" " + output.getClass().getSimpleName());
+ }
+ }
+ }
+ }
+
+ private InteractionsMultiTurnConversation() {}
+}
diff --git a/examples/src/main/java/com/google/genai/examples/InteractionsMultipleContents.java b/examples/src/main/java/com/google/genai/examples/InteractionsMultipleContents.java
new file mode 100644
index 00000000000..89b0969d247
--- /dev/null
+++ b/examples/src/main/java/com/google/genai/examples/InteractionsMultipleContents.java
@@ -0,0 +1,85 @@
+/*
+ * Copyright 2025 Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.genai.examples;
+
+import com.google.genai.Client;
+import com.google.genai.types.interactions.Input;
+import com.google.genai.types.interactions.Interaction;
+import com.google.genai.types.interactions.content.Content;
+import com.google.genai.types.interactions.content.TextContent;
+
+/**
+ * Example: Single Turn with Multiple Content Items
+ *
+ * Demonstrates using Content objects to send multiple content items in a single turn.
+ *
+ * To run this example:
+ * Note: The Interactions API is currently in beta.
+ */
+public final class InteractionsMultipleContents {
+
+ public static void main(String[] args) {
+ Client client = new Client();
+
+ System.out.println("=== Interactions API: Multiple Contents Example ===\n");
+
+ try {
+ TextContent content1 = TextContent.of("Tell me about the Eiffel Tower.");
+ TextContent content2 = TextContent.of("Keep it brief, under 50 words.");
+
+ Input input = Input.fromContents(content1, content2);
+
+ Interaction response = client.interactions.create("gemini-3-flash-preview", input);
+
+ System.out.println("=== RESPONSE ===");
+ System.out.println(response.toJson());
+ System.out.println();
+
+ printResults(response);
+
+ System.out.println("\n=== Example completed ===");
+
+ } catch (Exception e) {
+ System.err.println("Error: " + e.getMessage());
+ e.printStackTrace();
+ }
+ }
+
+ private static void printResults(Interaction interaction) {
+ System.out.println("Results:");
+ System.out.println(" Interaction ID: " + interaction.id());
+ System.out.println(" Status: " + interaction.status());
+
+ if (interaction.outputs().isPresent() && !interaction.outputs().get().isEmpty()) {
+ for (Content output : interaction.outputs().get()) {
+ if (output instanceof TextContent) {
+ System.out.println(" Text: " + ((TextContent) output).text().orElse("(empty)"));
+ } else {
+ System.out.println(" " + output.getClass().getSimpleName());
+ }
+ }
+ }
+ }
+
+ private InteractionsMultipleContents() {}
+}
diff --git a/examples/src/main/java/com/google/genai/examples/InteractionsMultipleToolsLifecycle.java.backup b/examples/src/main/java/com/google/genai/examples/InteractionsMultipleToolsLifecycle.java.backup
new file mode 100644
index 00000000000..282c5190e55
--- /dev/null
+++ b/examples/src/main/java/com/google/genai/examples/InteractionsMultipleToolsLifecycle.java.backup
@@ -0,0 +1,592 @@
+/*
+ * Copyright 2025 Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Usage:
+ *
+ * Note: The Interactions API is currently only available via the Gemini Developer API (not
+ * Vertex AI).
+ *
+ * 1. Set an API key environment variable. You can find a list of available API keys here:
+ * https://aistudio.google.com/app/apikey
+ *
+ * export GOOGLE_API_KEY=YOUR_API_KEY
+ *
+ * 2. Compile the java package and run the sample code.
+ *
+ * mvn clean compile
+ *
+ * mvn exec:java -Dexec.mainClass="com.google.genai.examples.InteractionsMultipleToolsLifecycle"
+ */
+package com.google.genai.examples;
+
+import com.google.common.collect.ImmutableMap;
+import com.google.genai.Client;
+import com.google.genai.types.Schema;
+import com.google.genai.types.interactions.CancelInteractionConfig;
+import com.google.genai.types.interactions.CreateInteractionConfig;
+import com.google.genai.types.interactions.DeleteInteractionConfig;
+import com.google.genai.types.interactions.DeleteInteractionResponse;
+import com.google.genai.types.interactions.GetInteractionConfig;
+import com.google.genai.types.interactions.Interaction;
+import com.google.genai.types.interactions.content.Content;
+import com.google.genai.types.interactions.content.FunctionCallContent;
+import com.google.genai.types.interactions.content.TextContent;
+import com.google.genai.types.interactions.tools.CodeExecutionTool;
+import com.google.genai.types.interactions.tools.FunctionTool;
+import com.google.genai.types.interactions.tools.GoogleSearchTool;
+import com.google.genai.types.interactions.tools.Tool;
+import com.google.genai.types.interactions.tools.UrlContextTool;
+import java.lang.reflect.Method;
+import java.time.LocalDateTime;
+import java.time.format.DateTimeFormatter;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Example: Multiple Tools with Full Interaction Lifecycle
+ *
+ * Demonstrates:
+ *
+ * All requests and responses are logged and validated.
+ *
+ * Note: The Interactions API is in beta and subject to change.
+ */
+public final class InteractionsMultipleToolsLifecycle {
+
+ private static final String SEPARATOR = "=".repeat(80);
+ private static final String SUB_SEPARATOR = "-".repeat(80);
+ private static final DateTimeFormatter TIMESTAMP_FORMAT =
+ DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
+
+ public static void main(String[] args) throws Exception {
+ // Instantiate the client
+ Client client = new Client();
+
+ System.out.println(SEPARATOR);
+ System.out.println("Interactions API: Multiple Tools Full Lifecycle Example");
+ System.out.println(SEPARATOR);
+ System.out.println();
+
+ try {
+ // ========================================
+ // STEP 1: CREATE - Create interaction with multiple tools
+ // ========================================
+ Interaction createResponse = stepCreate(client);
+
+ // ========================================
+ // STEP 2: GET - Retrieve and validate
+ // ========================================
+ Interaction getResponse = stepGet(client, createResponse);
+
+ // ========================================
+ // STEP 3: CANCEL - Cancel the interaction
+ // ========================================
+ Interaction cancelResponse = stepCancel(client, createResponse.id());
+
+ // ========================================
+ // STEP 4: GET after CANCEL - Verify cancelled
+ // ========================================
+ Interaction getAfterCancelResponse = stepGetAfterCancel(client, createResponse.id());
+
+ // ========================================
+ // STEP 5: DELETE - Delete the interaction
+ // ========================================
+ DeleteInteractionResponse deleteResponse = stepDelete(client, createResponse.id());
+
+ // ========================================
+ // STEP 6: GET after DELETE - Verify deleted
+ // ========================================
+ stepGetAfterDelete(client, createResponse.id());
+
+ System.out.println();
+ System.out.println(SEPARATOR);
+ System.out.println("✅ ALL LIFECYCLE STEPS COMPLETED SUCCESSFULLY");
+ System.out.println(SEPARATOR);
+
+ } catch (Exception e) {
+ System.err.println();
+ System.err.println(SEPARATOR);
+ System.err.println("❌ ERROR: " + e.getMessage());
+ System.err.println(SEPARATOR);
+ e.printStackTrace();
+ System.exit(1);
+ }
+ }
+
+ // ==================================================================================
+ // STEP 1: CREATE
+ // ==================================================================================
+
+ private static Interaction stepCreate(Client client) throws Exception {
+ printStepHeader("STEP 1: CREATE", "Create interaction with multiple tools");
+
+ // Define all tools
+ List This method is public and static so it can be invoked via reflection for AFC.
+ */
+ public static Map Note: The Interactions API is currently only available via the Gemini Developer API (not
+ * Vertex AI).
+ *
+ * 1. Set an API key environment variable. You can find a list of available API keys here:
+ * https://aistudio.google.com/app/apikey
+ *
+ * export GOOGLE_API_KEY=YOUR_API_KEY
+ *
+ * 2. Compile the java package and run the sample code.
+ *
+ * mvn clean compile
+ *
+ * mvn exec:java -Dexec.mainClass="com.google.genai.examples.InteractionsResponseFormat"
+ */
+package com.google.genai.examples;
+
+import com.google.common.collect.ImmutableMap;
+import com.google.genai.Client;
+import com.google.genai.types.Schema;
+import com.google.genai.types.Type;
+import com.google.genai.types.interactions.CreateInteractionConfig;
+import com.google.genai.types.interactions.Interaction;
+import com.google.genai.types.interactions.content.Content;
+import com.google.genai.types.interactions.content.TextContent;
+
+/**
+ * Example: Interactions API with Response Format (Structured JSON Output)
+ *
+ * Demonstrates how to use the responseFormat field in CreateInteractionConfig to get structured
+ * JSON responses from the Interactions API. This is useful when you need the model to return data
+ * in a specific schema that can be parsed programmatically.
+ *
+ * The example shows:
+ *
+ * Note: The Interactions API is in beta and subject to change.
+ */
+public final class InteractionsResponseFormat {
+
+ public static void main(String[] args) {
+ // Instantiate the client. The client gets the API key from the environment variable
+ // `GOOGLE_API_KEY`.
+ //
+ Client client = new Client();
+
+ System.out.println("=== Interactions API: Response Format Example ===\n");
+
+ try {
+ // Define the schema for the expected response structure.
+ // This schema requests a recipe with name, ingredients list, and prep time.
+ Schema responseSchema =
+ Schema.builder()
+ .type(new Type(Type.Known.OBJECT))
+ .properties(
+ ImmutableMap.of(
+ "recipe_name",
+ Schema.builder().type(new Type(Type.Known.STRING)).build(),
+ "ingredients",
+ Schema.builder()
+ .type(new Type(Type.Known.ARRAY))
+ .items(Schema.builder().type(new Type(Type.Known.STRING)))
+ .build(),
+ "prep_time_minutes",
+ Schema.builder().type(new Type(Type.Known.INTEGER)).build()))
+ .required("recipe_name", "ingredients")
+ .build();
+
+ // Create the interaction config with the response format schema.
+ CreateInteractionConfig config =
+ CreateInteractionConfig.builder()
+ .model("gemini-3-flash-preview")
+ .input("Give me a recipe for chocolate chip cookies.")
+ .responseFormat(responseSchema)
+ .build();
+
+ System.out.println("=== REQUEST ===");
+ System.out.println(config.toJson());
+ System.out.println();
+
+ // Execute the interaction.
+ Interaction response = client.interactions.create(config);
+
+ System.out.println("=== RESPONSE ===");
+ System.out.println(response.toJson());
+ System.out.println();
+
+ // Print extracted results.
+ printResults(response);
+
+ System.out.println("\n=== Example completed ===");
+
+ } catch (Exception e) {
+ System.err.println("Error: " + e.getMessage());
+ e.printStackTrace();
+ }
+ }
+
+ /** Prints extracted results from the interaction response. */
+ private static void printResults(Interaction interaction) {
+ System.out.println("Results:");
+ System.out.println(" Interaction ID: " + interaction.id());
+ System.out.println(" Status: " + interaction.status());
+
+ if (!interaction.outputs().isPresent() || interaction.outputs().get().isEmpty()) {
+ System.out.println(" Outputs: (none)");
+ return;
+ }
+
+ System.out.println(" Outputs:");
+ for (Content output : interaction.outputs().get()) {
+ if (output instanceof TextContent) {
+ TextContent t = (TextContent) output;
+ String text = t.text().orElse("(empty)");
+ System.out.println(" Structured JSON Response:");
+ System.out.println(" " + text);
+ } else {
+ System.out.println(" " + output.getClass().getSimpleName());
+ }
+ }
+ }
+
+ private InteractionsResponseFormat() {}
+}
diff --git a/examples/src/main/java/com/google/genai/examples/InteractionsSimpleExample.java b/examples/src/main/java/com/google/genai/examples/InteractionsSimpleExample.java
new file mode 100644
index 00000000000..dee3aa42ca4
--- /dev/null
+++ b/examples/src/main/java/com/google/genai/examples/InteractionsSimpleExample.java
@@ -0,0 +1,92 @@
+/*
+ * Copyright 2025 Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Usage:
+ *
+ * 1. Set an API key environment variable. You can find a list of available API keys here:
+ * https://aistudio.google.com/app/apikey
+ *
+ * export GOOGLE_API_KEY=YOUR_API_KEY
+ *
+ * 2. Compile the java package and run the sample code.
+ *
+ * mvn clean compile
+ *
+ * mvn exec:java -Dexec.mainClass="com.google.genai.examples.InteractionsSimpleExample"
+ */
+package com.google.genai.examples;
+
+import com.google.genai.Client;
+import com.google.genai.types.interactions.Interaction;
+import com.google.genai.types.interactions.content.Content;
+import com.google.genai.types.interactions.content.TextContent;
+
+/**
+ * Example: Simple Text Interaction
+ *
+ * Demonstrates the simplest way to create an interaction using the convenience overload:
+ * {@code create(model, text)}
+ *
+ * This is the most concise way to interact with the Interactions API when you just need to send
+ * a simple text message and get a response.
+ *
+ * Note: The Interactions API is in beta and subject to change.
+ */
+public final class InteractionsSimpleExample {
+
+ public static void main(String[] args) {
+ // Instantiate the client. The client gets the API key from the environment variable
+ // `GOOGLE_API_KEY`.
+ Client client = new Client();
+
+ System.out.println("=== Simple Text Interaction ===\n");
+
+ try {
+ // Simplest possible interaction - just model and text!
+ Interaction response = client.interactions.create(
+ "gemini-3-flash-preview",
+ "What is the capital of France?"
+ );
+
+ System.out.println("Status: " + response.status());
+ System.out.println("Response: " + getTextOutput(response));
+
+ System.out.println("\n=== Example completed ===");
+
+ } catch (Exception e) {
+ System.err.println("Error: " + e.getMessage());
+ e.printStackTrace();
+ }
+ }
+
+ /** Extracts the first text output from an interaction response. */
+ private static String getTextOutput(Interaction interaction) {
+ if (!interaction.outputs().isPresent() || interaction.outputs().get().isEmpty()) {
+ return "(no output)";
+ }
+
+ for (Content output : interaction.outputs().get()) {
+ if (output instanceof TextContent) {
+ TextContent textContent = (TextContent) output;
+ return textContent.text().orElse("(empty)");
+ }
+ }
+ return "(no text output)";
+ }
+
+ private InteractionsSimpleExample() {}
+}
diff --git a/examples/src/main/java/com/google/genai/examples/InteractionsStreamResumptionExample.java b/examples/src/main/java/com/google/genai/examples/InteractionsStreamResumptionExample.java
new file mode 100644
index 00000000000..34abc9ad306
--- /dev/null
+++ b/examples/src/main/java/com/google/genai/examples/InteractionsStreamResumptionExample.java
@@ -0,0 +1,174 @@
+/*
+ * Copyright 2025 Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Usage:
+ *
+ * Note: The Interactions API is currently only available via the Gemini Developer API (not
+ * Vertex AI).
+ *
+ * 1. Set an API key environment variable. You can find a list of available API keys here:
+ * https://aistudio.google.com/app/apikey
+ *
+ * export GOOGLE_API_KEY=YOUR_API_KEY
+ *
+ * 2. Compile the java package and run the sample code.
+ *
+ * mvn clean compile
+ *
+ * mvn exec:java -Dexec.mainClass="com.google.genai.examples.InteractionsStreamResumptionExample"
+ */
+package com.google.genai.examples;
+
+import com.google.genai.Client;
+import com.google.genai.InteractionEventStream;
+import com.google.genai.types.interactions.GetInteractionConfig;
+import com.google.genai.types.interactions.streaming.ContentDelta;
+import com.google.genai.types.interactions.streaming.InteractionEvent;
+import com.google.genai.types.interactions.streaming.InteractionSseEvent;
+import com.google.genai.types.interactions.streaming.delta.Delta;
+import com.google.genai.types.interactions.streaming.delta.TextDelta;
+
+/**
+ * Example: Stream Resumption for Interactions
+ *
+ * Demonstrates how to resume a streaming interaction after a connection interruption. This is
+ * useful for:
+ *
+ * The key concept is tracking the {@code eventId} from each event and using it with
+ * {@code lastEventId} in GetInteractionConfig to resume from where you left off.
+ *
+ * Note: The Interactions API is in beta and subject to change.
+ */
+public final class InteractionsStreamResumptionExample {
+
+ public static void main(String[] args) {
+ Client client = new Client();
+
+ System.out.println("=== Interactions API: Stream Resumption Example ===\n");
+
+ try {
+ // Track the last event ID and interaction ID for resumption
+ String lastEventId = null;
+ String interactionId = null;
+ StringBuilder collectedText = new StringBuilder();
+ int eventCount = 0;
+ int eventsBeforeSimulatedFailure = 3; // Simulate failure after 3 events
+
+ // Using the convenience overload: createStream(model, text)
+ String model = "gemini-3-flash-preview";
+ String prompt = "Write a haiku about Java programming.";
+
+ System.out.println("--- Starting initial stream (will simulate failure) ---\n");
+
+ // First attempt - simulating a connection failure partway through
+ try (InteractionEventStream This example shows how to:
+ * Key Concepts:
+ * Usage:
+ * Note: The Interactions API is currently only available via the Gemini Developer API (not
+ * Vertex AI).
+ *
+ * 1. Set an API key environment variable. You can find a list of available API keys here:
+ * https://aistudio.google.com/app/apikey
+ *
+ * export GOOGLE_API_KEY=YOUR_API_KEY
+ *
+ * 2. Compile the java package and run the sample code.
+ *
+ * mvn clean compile
+ *
+ * mvn exec:java -Dexec.mainClass="com.google.genai.examples.InteractionsStreamingAudioContent"
+ */
+package com.google.genai.examples;
+
+import com.google.genai.Client;
+import com.google.genai.InteractionEventStream;
+import com.google.genai.JsonSerializable;
+import com.google.genai.types.interactions.Input;
+import com.google.genai.types.interactions.content.AudioContent;
+import com.google.genai.types.interactions.content.TextContent;
+import com.google.genai.types.interactions.streaming.ContentDelta;
+import com.google.genai.types.interactions.streaming.ContentStart;
+import com.google.genai.types.interactions.streaming.ContentStop;
+import com.google.genai.types.interactions.streaming.ErrorEvent;
+import com.google.genai.types.interactions.streaming.InteractionEvent;
+import com.google.genai.types.interactions.streaming.InteractionSseEvent;
+import com.google.genai.types.interactions.streaming.delta.Delta;
+import com.google.genai.types.interactions.streaming.delta.TextDelta;
+
+/**
+ * Example demonstrating streaming audio transcription using AudioContent with the Interactions API.
+ *
+ * This example shows:
+ * Note: The Interactions API is currently in beta.
+ */
+public final class InteractionsStreamingAudioContent {
+
+ public static void main(String[] args) {
+ Client client = new Client();
+
+ System.out.println("=== Interactions API: Streaming Audio Content Example ===\n");
+
+ try {
+ // ===== PART 1: Audio from URI (Streaming) =====
+ System.out.println("--- PART 1: Audio from URI (Streaming) ---\n");
+
+ String audioUri = "https://storage.googleapis.com/cloud-samples-data/speech/brooklyn_bridge.mp3";
+ AudioContent audioContent = AudioContent.fromUri(audioUri, "audio/mp3");
+ TextContent textPrompt = TextContent.of("Transcribe this audio.");
+
+ // Using simplified streaming API: createStream(model, input)
+ Input input = Input.fromContents(textPrompt, audioContent);
+
+ System.out.println("Streaming response:\n");
+
+ int eventCount = 0;
+ StringBuilder fullResponse = new StringBuilder();
+
+ try (InteractionEventStream Note: The Interactions API is currently only available via the Gemini Developer API (not
+ * Vertex AI).
+ *
+ * 1. Set an API key environment variable. You can find a list of available API keys here:
+ * https://aistudio.google.com/app/apikey
+ *
+ * export GOOGLE_API_KEY=YOUR_API_KEY
+ *
+ * 2. Compile the java package and run the sample code.
+ *
+ * mvn clean compile
+ *
+ * mvn exec:java -Dexec.mainClass="com.google.genai.examples.InteractionsStreamingCodeExecution"
+ */
+package com.google.genai.examples;
+
+import com.google.genai.Client;
+import com.google.genai.InteractionEventStream;
+import com.google.genai.JsonSerializable;
+import com.google.genai.types.interactions.CreateInteractionConfig;
+import com.google.genai.types.interactions.streaming.ContentDelta;
+import com.google.genai.types.interactions.streaming.ContentStart;
+import com.google.genai.types.interactions.streaming.ContentStop;
+import com.google.genai.types.interactions.streaming.ErrorEvent;
+import com.google.genai.types.interactions.streaming.InteractionEvent;
+import com.google.genai.types.interactions.streaming.InteractionSseEvent;
+import com.google.genai.types.interactions.streaming.delta.CodeExecutionCallDelta;
+import com.google.genai.types.interactions.streaming.delta.CodeExecutionResultDelta;
+import com.google.genai.types.interactions.streaming.delta.Delta;
+import com.google.genai.types.interactions.streaming.delta.TextDelta;
+import com.google.genai.types.interactions.tools.CodeExecution;
+
+/**
+ * Example: Streaming Code Execution Tool with the Interactions API
+ *
+ * Demonstrates how to use the CodeExecution tool with streaming to enable the model
+ * to write and execute code, receiving results incrementally.
+ *
+ * This example shows:
+ * Note: The Interactions API is currently in beta.
+ */
+public final class InteractionsStreamingCodeExecution {
+
+ public static void main(String[] args) {
+ Client client = new Client();
+
+ System.out.println("=== Interactions API: Streaming Code Execution Tool Example ===\n");
+
+ try {
+ CodeExecution codeTool = CodeExecution.builder().build();
+
+ String userQuestion =
+ "Calculate the first 20 Fibonacci numbers and find their sum. "
+ + "Show me the code and the result.";
+
+ CreateInteractionConfig config =
+ CreateInteractionConfig.builder()
+ .model("gemini-3-flash-preview")
+ .input(userQuestion)
+ .tools(codeTool)
+ .build();
+
+ System.out.println("User: " + userQuestion + "\n");
+ System.out.println("=== REQUEST ===");
+ System.out.println(config.toJson());
+ System.out.println();
+
+ System.out.println("Streaming response:\n");
+
+ int eventCount = 0;
+ StringBuilder fullResponse = new StringBuilder();
+ int codeCallDeltaCount = 0;
+ int codeResultDeltaCount = 0;
+
+ try (InteractionEventStream Note: The Interactions API is currently only available via the Gemini Developer API (not
+ * Vertex AI).
+ *
+ * 1. Set an API key environment variable. You can find a list of available API keys here:
+ * https://aistudio.google.com/app/apikey
+ *
+ * export GOOGLE_API_KEY=YOUR_API_KEY
+ *
+ * 2. Compile the java package and run the sample code.
+ *
+ * mvn clean compile
+ *
+ * mvn exec:java -Dexec.mainClass="com.google.genai.examples.InteractionsStreamingDocumentContent"
+ */
+package com.google.genai.examples;
+
+import com.google.genai.Client;
+import com.google.genai.InteractionEventStream;
+import com.google.genai.JsonSerializable;
+import com.google.genai.types.interactions.Input;
+import com.google.genai.types.interactions.content.DocumentContent;
+import com.google.genai.types.interactions.content.TextContent;
+import com.google.genai.types.interactions.streaming.ContentDelta;
+import com.google.genai.types.interactions.streaming.ContentStart;
+import com.google.genai.types.interactions.streaming.ContentStop;
+import com.google.genai.types.interactions.streaming.ErrorEvent;
+import com.google.genai.types.interactions.streaming.InteractionEvent;
+import com.google.genai.types.interactions.streaming.InteractionSseEvent;
+import com.google.genai.types.interactions.streaming.delta.Delta;
+import com.google.genai.types.interactions.streaming.delta.TextDelta;
+
+/**
+ * Example demonstrating streaming document analysis using DocumentContent with the Interactions API.
+ *
+ * This example shows:
+ * Note: The Interactions API is currently in beta.
+ */
+public final class InteractionsStreamingDocumentContent {
+
+ public static void main(String[] args) {
+ Client client = new Client();
+
+ System.out.println("=== Interactions API: Streaming Document Content Example ===\n");
+
+ try {
+ // ===== PART 1: Document from URI (Streaming) =====
+ System.out.println("--- PART 1: Document from URI (Streaming) ---\n");
+
+ String documentUri = "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf";
+ DocumentContent documentContent = DocumentContent.fromUri(documentUri, "application/pdf");
+ TextContent textPrompt = TextContent.of("Summarize this document.");
+
+ // Using simplified streaming API: createStream(model, input)
+ Input input = Input.fromContents(textPrompt, documentContent);
+
+ System.out.println("Streaming response:\n");
+
+ int eventCount = 0;
+ StringBuilder fullResponse = new StringBuilder();
+
+ try (InteractionEventStream Note: The Interactions API is currently only available via the Gemini Developer API (not
+ * Vertex AI).
+ *
+ * 1. Set an API key environment variable. You can find a list of available API keys here:
+ * https://aistudio.google.com/app/apikey
+ *
+ * export GOOGLE_API_KEY=YOUR_API_KEY
+ *
+ * 2. Compile the java package and run the sample code.
+ *
+ * mvn clean compile
+ *
+ * mvn exec:java -Dexec.mainClass="com.google.genai.examples.InteractionsStreamingExample"
+ */
+package com.google.genai.examples;
+
+import com.google.genai.Client;
+import com.google.genai.JsonSerializable;
+import com.google.genai.InteractionEventStream;
+import com.google.genai.types.interactions.streaming.ContentDelta;
+import com.google.genai.types.interactions.streaming.ContentStart;
+import com.google.genai.types.interactions.streaming.ContentStop;
+import com.google.genai.types.interactions.streaming.ErrorEvent;
+import com.google.genai.types.interactions.streaming.InteractionEvent;
+import com.google.genai.types.interactions.streaming.InteractionStatusUpdate;
+import com.google.genai.types.interactions.streaming.InteractionSseEvent;
+import com.google.genai.types.interactions.streaming.delta.Delta;
+import com.google.genai.types.interactions.streaming.delta.FunctionCallDelta;
+import com.google.genai.types.interactions.streaming.delta.TextDelta;
+
+/**
+ * Example: Streaming Interactions
+ *
+ * Demonstrates the streaming API for interactions, which allows receiving real-time incremental
+ * updates as the model generates its response.
+ *
+ * Streaming is useful for:
+ *
+ * Note: The Interactions API is in beta and subject to change.
+ */
+public final class InteractionsStreamingExample {
+
+ public static void main(String[] args) {
+ Client client = new Client();
+
+ System.out.println("=== Interactions API: Streaming Example ===\n");
+
+ try {
+ // ===== PART 1: Basic Streaming =====
+ System.out.println("--- PART 1: Basic Streaming ---\n");
+
+ // Using the convenience overload: createStream(model, text)
+ String model = "gemini-3-flash-preview";
+ String prompt1 = "Count from 1 to 10, saying each number on a new line.";
+
+ // Log request
+ System.out.println("[REQUEST]");
+ System.out.println(" Model: " + model);
+ System.out.println(" Input: " + prompt1);
+ System.out.println();
+
+ System.out.println("Streaming response:\n");
+
+ int eventCount = 0;
+ try (InteractionEventStream Note: The Interactions API is currently only available via the Gemini Developer API (not
+ * Vertex AI).
+ *
+ * 1. Set an API key environment variable. You can find a list of available API keys here:
+ * https://aistudio.google.com/app/apikey
+ *
+ * export GOOGLE_API_KEY=YOUR_API_KEY
+ *
+ * 2. Compile the java package and run the sample code.
+ *
+ * mvn clean compile
+ *
+ * mvn exec:java -Dexec.mainClass="com.google.genai.examples.InteractionsStreamingGoogleSearch"
+ */
+package com.google.genai.examples;
+
+import com.google.genai.Client;
+import com.google.genai.InteractionEventStream;
+import com.google.genai.JsonSerializable;
+import com.google.genai.types.interactions.CreateInteractionConfig;
+import com.google.genai.types.interactions.streaming.ContentDelta;
+import com.google.genai.types.interactions.streaming.ContentStart;
+import com.google.genai.types.interactions.streaming.ContentStop;
+import com.google.genai.types.interactions.streaming.ErrorEvent;
+import com.google.genai.types.interactions.streaming.InteractionEvent;
+import com.google.genai.types.interactions.streaming.InteractionSseEvent;
+import com.google.genai.types.interactions.streaming.delta.Delta;
+import com.google.genai.types.interactions.streaming.delta.GoogleSearchCallDelta;
+import com.google.genai.types.interactions.streaming.delta.GoogleSearchResultDelta;
+import com.google.genai.types.interactions.streaming.delta.TextDelta;
+import com.google.genai.types.interactions.tools.GoogleSearch;
+
+/**
+ * Example: Streaming Google Search Tool with the Interactions API
+ *
+ * Demonstrates how to use the GoogleSearch tool with streaming to enable the model
+ * to search the web and receive results incrementally.
+ *
+ * This example shows:
+ * Note: The Interactions API is currently in beta.
+ */
+public final class InteractionsStreamingGoogleSearch {
+
+ public static void main(String[] args) {
+ Client client = new Client();
+
+ System.out.println("=== Interactions API: Streaming Google Search Tool Example ===\n");
+
+ try {
+ GoogleSearch searchTool = GoogleSearch.builder().build();
+
+ CreateInteractionConfig config =
+ CreateInteractionConfig.builder()
+ .model("gemini-3-flash-preview")
+ .input("What are the latest developments in quantum computing in 2025?")
+ .tools(searchTool)
+ .build();
+
+ System.out.println("=== REQUEST ===");
+ System.out.println(config.toJson());
+ System.out.println();
+
+ System.out.println("Streaming response:\n");
+
+ int eventCount = 0;
+ StringBuilder fullResponse = new StringBuilder();
+ int searchCallDeltaCount = 0;
+ int searchResultDeltaCount = 0;
+
+ try (InteractionEventStream Note: The Interactions API is currently only available via the Gemini Developer API (not
+ * Vertex AI).
+ *
+ * 1. Set an API key environment variable. You can find a list of available API keys here:
+ * https://aistudio.google.com/app/apikey
+ *
+ * export GOOGLE_API_KEY=YOUR_API_KEY
+ *
+ * 2. Compile the java package and run the sample code.
+ *
+ * mvn clean compile
+ *
+ * mvn exec:java -Dexec.mainClass="com.google.genai.examples.InteractionsStreamingImageContent"
+ */
+package com.google.genai.examples;
+
+import com.google.genai.Client;
+import com.google.genai.InteractionEventStream;
+import com.google.genai.JsonSerializable;
+import com.google.genai.types.interactions.Input;
+import com.google.genai.types.interactions.content.ImageContent;
+import com.google.genai.types.interactions.content.TextContent;
+import com.google.genai.types.interactions.streaming.ContentDelta;
+import com.google.genai.types.interactions.streaming.ContentStart;
+import com.google.genai.types.interactions.streaming.ContentStop;
+import com.google.genai.types.interactions.streaming.ErrorEvent;
+import com.google.genai.types.interactions.streaming.InteractionEvent;
+import com.google.genai.types.interactions.streaming.InteractionSseEvent;
+import com.google.genai.types.interactions.streaming.delta.Delta;
+import com.google.genai.types.interactions.streaming.delta.TextDelta;
+
+/**
+ * Example demonstrating streaming image analysis using ImageContent with the Interactions API.
+ *
+ * This example shows:
+ * Note: The Interactions API is currently in beta.
+ */
+public final class InteractionsStreamingImageContent {
+
+ public static void main(String[] args) {
+ Client client = new Client();
+
+ System.out.println("=== Interactions API: Streaming Image Content Example ===\n");
+
+ try {
+ // ===== PART 1: Image from URI (Streaming) =====
+ System.out.println("--- PART 1: Image from URI (Streaming) ---\n");
+
+ String imageUri = "https://storage.googleapis.com/generativeai-downloads/images/cake.jpg";
+ ImageContent imageContent = ImageContent.fromUri(imageUri, "image/jpeg");
+ TextContent textPrompt = TextContent.of("Describe what you see in this image.");
+
+ // Using simplified streaming API: createStream(model, input)
+ Input input = Input.fromContents(textPrompt, imageContent);
+
+ System.out.println("Streaming response:\n");
+
+ int eventCount = 0;
+ StringBuilder fullResponse = new StringBuilder();
+
+ try (InteractionEventStream Note: The Interactions API is currently only available via the Gemini Developer API (not
+ * Vertex AI).
+ *
+ * 1. Set an API key environment variable. You can find a list of available API keys here:
+ * https://aistudio.google.com/app/apikey
+ *
+ * export GOOGLE_API_KEY=YOUR_API_KEY
+ *
+ * 2. Compile the java package and run the sample code.
+ *
+ * mvn clean compile
+ *
+ * mvn exec:java -Dexec.mainClass="com.google.genai.examples.InteractionsStreamingImageGeneration"
+ */
+package com.google.genai.examples;
+
+import com.google.genai.Client;
+import com.google.genai.InteractionEventStream;
+import com.google.genai.JsonSerializable;
+import com.google.genai.types.interactions.CreateInteractionConfig;
+import com.google.genai.types.interactions.streaming.ContentDelta;
+import com.google.genai.types.interactions.streaming.ContentStart;
+import com.google.genai.types.interactions.streaming.ContentStop;
+import com.google.genai.types.interactions.streaming.ErrorEvent;
+import com.google.genai.types.interactions.streaming.InteractionEvent;
+import com.google.genai.types.interactions.streaming.InteractionSseEvent;
+import com.google.genai.types.interactions.streaming.delta.Delta;
+import com.google.genai.types.interactions.streaming.delta.ImageDelta;
+import com.google.genai.types.interactions.streaming.delta.TextDelta;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Base64;
+
+/**
+ * Example demonstrating streaming image generation using the Interactions API.
+ *
+ * This is the reverse of image analysis - instead of sending an image and getting text,
+ * we send a text prompt and receive a generated image.
+ *
+ * This example shows:
+ * Note: The Interactions API is currently in beta.
+ */
+public final class InteractionsStreamingImageGeneration {
+
+ public static void main(String[] args) {
+ Client client = new Client();
+
+ System.out.println("=== Interactions API: Streaming Image Generation Example ===\n");
+
+ try {
+ // ===== Image Generation with Streaming =====
+ System.out.println("--- Generating Image from Text Prompt (Streaming) ---\n");
+
+ String prompt = "Generate a beautiful painting of a sunset over the ocean with "
+ + "vibrant orange and purple colors, with a small sailboat in the distance.";
+
+ CreateInteractionConfig config =
+ CreateInteractionConfig.builder()
+ .model("gemini-3-pro-image-preview") // Model that supports image generation
+ .input(prompt)
+ .responseModalities("TEXT", "IMAGE") // Request both text and image output
+ .build();
+
+ System.out.println("Prompt: " + prompt);
+ System.out.println();
+ System.out.println("=== REQUEST ===");
+ System.out.println(config.toJson());
+ System.out.println();
+
+ System.out.println("Streaming response:\n");
+
+ int eventCount = 0;
+ StringBuilder fullTextResponse = new StringBuilder();
+ int imageDeltaCount = 0;
+ StringBuilder imageDataBuilder = new StringBuilder();
+ String imageMimeType = null;
+
+ try (InteractionEventStream Note: The Interactions API is currently only available via the Gemini Developer API (not
+ * Vertex AI).
+ *
+ * 1. Set an API key environment variable. You can find a list of available API keys here:
+ * https://aistudio.google.com/app/apikey
+ *
+ * export GOOGLE_API_KEY=YOUR_API_KEY
+ *
+ * 2. Compile the java package and run the sample code.
+ *
+ * mvn clean compile
+ *
+ * mvn exec:java -Dexec.mainClass="com.google.genai.examples.InteractionsStreamingMedia"
+ */
+package com.google.genai.examples;
+
+import com.google.genai.Client;
+import com.google.genai.InteractionEventStream;
+import com.google.genai.JsonSerializable;
+import com.google.genai.types.interactions.Input;
+import com.google.genai.types.interactions.content.ImageContent;
+import com.google.genai.types.interactions.content.TextContent;
+import com.google.genai.types.interactions.content.VideoContent;
+import com.google.genai.types.interactions.streaming.ContentDelta;
+import com.google.genai.types.interactions.streaming.InteractionSseEvent;
+import com.google.genai.types.interactions.streaming.delta.Delta;
+import com.google.genai.types.interactions.streaming.delta.ImageDelta;
+import com.google.genai.types.interactions.streaming.delta.TextDelta;
+import com.google.genai.types.interactions.streaming.delta.VideoDelta;
+
+/**
+ * Example: Streaming Media Content Deltas
+ *
+ * Demonstrates streaming for media-related delta types:
+ *
+ * This example shows:
+ *
+ * Note: The Interactions API is in beta and subject to change.
+ */
+public final class InteractionsStreamingMedia {
+
+ public static void main(String[] args) {
+ Client client = new Client();
+
+ System.out.println("=== Interactions API: Streaming Media Deltas ===\n");
+
+ try {
+ // ===== PART 1: Image Analysis Streaming =====
+ System.out.println("--- PART 1: Image Analysis Streaming (ImageDelta) ---\n");
+
+ ImageContent imageContent =
+ ImageContent.fromUri(
+ "https://storage.googleapis.com/generativeai-downloads/images/cake.jpg",
+ "image/jpeg");
+ TextContent imagePrompt = TextContent.of("Describe this image in detail. What do you see?");
+
+ // Using simplified streaming API: createStream(model, input)
+ Input imageInput = Input.fromContents(imagePrompt, imageContent);
+
+ System.out.println("Streaming image analysis:\n");
+
+ int eventCount1 = 0;
+ StringBuilder textBuffer1 = new StringBuilder();
+ int imageDeltaCount = 0;
+
+ try (InteractionEventStream Note: The Interactions API is currently only available via the Gemini Developer API (not
+ * Vertex AI).
+ *
+ * 1. Set an API key environment variable. You can find a list of available API keys here:
+ * https://aistudio.google.com/app/apikey
+ *
+ * export GOOGLE_API_KEY=YOUR_API_KEY
+ *
+ * 2. Compile the java package and run the sample code.
+ *
+ * mvn clean compile
+ *
+ * mvn exec:java -Dexec.mainClass="com.google.genai.examples.InteractionsStreamingMultiTurnConversation"
+ */
+package com.google.genai.examples;
+
+import com.google.genai.Client;
+import com.google.genai.InteractionEventStream;
+import com.google.genai.JsonSerializable;
+import com.google.genai.types.interactions.Input;
+import com.google.genai.types.interactions.Turn;
+import com.google.genai.types.interactions.streaming.ContentDelta;
+
+// Note: Turn.user() and Turn.model() factory methods simplify multi-turn creation.
+import com.google.genai.types.interactions.streaming.ContentStart;
+import com.google.genai.types.interactions.streaming.ContentStop;
+import com.google.genai.types.interactions.streaming.ErrorEvent;
+import com.google.genai.types.interactions.streaming.InteractionEvent;
+import com.google.genai.types.interactions.streaming.InteractionSseEvent;
+import com.google.genai.types.interactions.streaming.delta.Delta;
+import com.google.genai.types.interactions.streaming.delta.TextDelta;
+
+/**
+ * Example: Streaming Multi-Turn Conversation with Turn objects
+ *
+ * Demonstrates a multi-turn conversation using Turn objects with role assignment
+ * and streaming responses.
+ *
+ * Note: The Interactions API is currently in beta.
+ */
+public final class InteractionsStreamingMultiTurnConversation {
+
+ public static void main(String[] args) {
+ Client client = new Client();
+
+ System.out.println("=== Interactions API: Streaming Multi-Turn Conversation Example ===\n");
+
+ try {
+ // Using the convenience overload: createStream(model, Input)
+ // Input.fromTurns() creates multi-turn conversation input
+ String model = "gemini-3-flash-preview";
+ Input conversation = Input.fromTurns(
+ Turn.user("I'm planning a trip to Paris."),
+ Turn.model("That's wonderful! Paris is a beautiful city. What would you like to know?"),
+ Turn.user("What are the top 3 must-see attractions?"));
+
+ System.out.println("=== REQUEST ===");
+ System.out.println("Model: " + model);
+ System.out.println("Input: " + conversation.toJson());
+ System.out.println();
+
+ System.out.println("Streaming response:\n");
+
+ int eventCount = 0;
+ StringBuilder fullResponse = new StringBuilder();
+
+ try (InteractionEventStream Note: The Interactions API is currently only available via the Gemini Developer API (not
+ * Vertex AI).
+ *
+ * 1. Set an API key environment variable. You can find a list of available API keys here:
+ * https://aistudio.google.com/app/apikey
+ *
+ * export GOOGLE_API_KEY=YOUR_API_KEY
+ *
+ * 2. Compile the java package and run the sample code.
+ *
+ * mvn clean compile
+ *
+ * mvn exec:java -Dexec.mainClass="com.google.genai.examples.InteractionsStreamingMultipleContents"
+ */
+package com.google.genai.examples;
+
+import com.google.genai.Client;
+import com.google.genai.InteractionEventStream;
+import com.google.genai.JsonSerializable;
+import com.google.genai.types.interactions.Input;
+import com.google.genai.types.interactions.content.TextContent;
+import com.google.genai.types.interactions.streaming.ContentDelta;
+import com.google.genai.types.interactions.streaming.ContentStart;
+import com.google.genai.types.interactions.streaming.ContentStop;
+import com.google.genai.types.interactions.streaming.ErrorEvent;
+import com.google.genai.types.interactions.streaming.InteractionEvent;
+import com.google.genai.types.interactions.streaming.InteractionSseEvent;
+import com.google.genai.types.interactions.streaming.delta.Delta;
+import com.google.genai.types.interactions.streaming.delta.TextDelta;
+
+/**
+ * Example: Streaming Single Turn with Multiple Content Items
+ *
+ * Demonstrates using Content objects to send multiple content items in a single turn
+ * with streaming responses.
+ *
+ * Note: The Interactions API is currently in beta.
+ */
+public final class InteractionsStreamingMultipleContents {
+
+ public static void main(String[] args) {
+ Client client = new Client();
+
+ System.out.println("=== Interactions API: Streaming Multiple Contents Example ===\n");
+
+ try {
+ TextContent content1 = TextContent.of("Tell me about the Eiffel Tower.");
+ TextContent content2 = TextContent.of("Keep it brief, under 50 words.");
+
+ // Using simplified streaming API: createStream(model, input)
+ Input input = Input.fromContents(content1, content2);
+
+ System.out.println("Streaming response:\n");
+
+ int eventCount = 0;
+ StringBuilder fullResponse = new StringBuilder();
+
+ try (InteractionEventStream Note: The Interactions API is currently only available via the Gemini Developer API (not
+ * Vertex AI).
+ *
+ * 1. Set an API key environment variable. You can find a list of available API keys here:
+ * https://aistudio.google.com/app/apikey
+ *
+ * export GOOGLE_API_KEY=YOUR_API_KEY
+ *
+ * 2. Compile the java package and run the sample code.
+ *
+ * mvn clean compile
+ *
+ * mvn exec:java -Dexec.mainClass="com.google.genai.examples.InteractionsStreamingTextAndThought"
+ */
+package com.google.genai.examples;
+
+import com.google.genai.Client;
+import com.google.genai.JsonSerializable;
+import com.google.genai.InteractionEventStream;
+import com.google.genai.types.interactions.content.ImageContent;
+import com.google.genai.types.interactions.content.TextContent;
+import com.google.genai.types.interactions.content.ThoughtSummaryContent;
+import com.google.genai.types.interactions.streaming.ContentDelta;
+import com.google.genai.types.interactions.streaming.InteractionSseEvent;
+import com.google.genai.types.interactions.streaming.delta.Delta;
+import com.google.genai.types.interactions.streaming.delta.TextDelta;
+import com.google.genai.types.interactions.streaming.delta.ThoughtSignatureDelta;
+import com.google.genai.types.interactions.streaming.delta.ThoughtSummaryDelta;
+
+/**
+ * Example: Streaming Text and Thought Deltas
+ *
+ * Demonstrates streaming for text and thought-related delta types:
+ *
+ * This example shows:
+ *
+ * Note: The Interactions API is in beta and subject to change.
+ */
+public final class InteractionsStreamingTextAndThought {
+
+ public static void main(String[] args) {
+ Client client = new Client();
+
+ System.out.println("=== Interactions API: Streaming Text and Thought Deltas ===\n");
+
+ try {
+ // ===== PART 1: Basic Text Streaming =====
+ System.out.println("--- PART 1: Basic Text Streaming (TextDelta) ---\n");
+
+ // Using the convenience overload: createStream(model, text)
+ String model = "gemini-3-flash-preview";
+ String prompt1 = "Count from 1 to 10, saying each number on a new line.";
+
+ System.out.println("[REQUEST]");
+ System.out.println(" Model: " + model);
+ System.out.println(" Input: " + prompt1);
+ System.out.println();
+
+ System.out.println("Streaming response:\n");
+
+ int eventCount1 = 0;
+ StringBuilder textBuffer1 = new StringBuilder();
+
+ try (InteractionEventStream Note: The Interactions API is currently only available via the Gemini Developer API (not
+ * Vertex AI).
+ *
+ * 1. Set an API key environment variable. You can find a list of available API keys here:
+ * https://aistudio.google.com/app/apikey
+ *
+ * export GOOGLE_API_KEY=YOUR_API_KEY
+ *
+ * 2. Compile the java package and run the sample code.
+ *
+ * mvn clean compile
+ *
+ * mvn exec:java -Dexec.mainClass="com.google.genai.examples.InteractionsStreamingThoughtSummary"
+ */
+package com.google.genai.examples;
+
+import com.google.genai.Client;
+import com.google.genai.InteractionEventStream;
+import com.google.genai.JsonSerializable;
+import com.google.genai.types.interactions.CreateInteractionConfig;
+import com.google.genai.types.interactions.GenerationConfig;
+import com.google.genai.types.interactions.ThinkingLevel;
+import com.google.genai.types.interactions.ThinkingSummaries;
+import com.google.genai.types.interactions.content.ImageContent;
+import com.google.genai.types.interactions.content.TextContent;
+import com.google.genai.types.interactions.content.ThoughtSummaryContent;
+import com.google.genai.types.interactions.streaming.ContentDelta;
+import com.google.genai.types.interactions.streaming.ContentStart;
+import com.google.genai.types.interactions.streaming.ContentStop;
+import com.google.genai.types.interactions.streaming.ErrorEvent;
+import com.google.genai.types.interactions.streaming.InteractionEvent;
+import com.google.genai.types.interactions.streaming.InteractionSseEvent;
+import com.google.genai.types.interactions.streaming.delta.Delta;
+import com.google.genai.types.interactions.streaming.delta.TextDelta;
+import com.google.genai.types.interactions.streaming.delta.ThoughtSignatureDelta;
+import com.google.genai.types.interactions.streaming.delta.ThoughtSummaryDelta;
+
+/**
+ * Example demonstrating streaming ThoughtSummaryDelta with the Interactions API.
+ *
+ * This example shows how to:
+ * ThoughtSummaryDelta.content is a polymorphic type that can be either:
+ * To trigger thought summaries, you must configure:
+ * Note: The Interactions API is in beta and subject to change.
+ */
+public final class InteractionsStreamingThoughtSummary {
+
+ public static void main(String[] args) {
+ Client client = new Client();
+
+ System.out.println("=== Interactions API: Streaming ThoughtSummaryDelta Example ===\n");
+ System.out.println("This example demonstrates the polymorphic ThoughtSummaryContent type,");
+ System.out.println("which can be either TextContent or ImageContent.\n");
+
+ try {
+ // ===== PART 1: Complex Reasoning with Thinking Summaries =====
+ System.out.println("--- PART 1: Complex Reasoning with ThoughtSummaryDelta ---\n");
+
+ // Configure generation with thinking enabled
+ GenerationConfig generationConfig = GenerationConfig.builder()
+ .thinkingLevel(new ThinkingLevel(ThinkingLevel.Known.HIGH))
+ .thinkingSummaries(new ThinkingSummaries(ThinkingSummaries.Known.AUTO))
+ .build();
+
+ CreateInteractionConfig config = CreateInteractionConfig.builder()
+ .model("gemini-3-flash-preview")
+ .generationConfig(generationConfig)
+ .input("Solve this step by step: A train leaves Station A at 9:00 AM traveling at "
+ + "60 mph. Another train leaves Station B (120 miles away) at 9:30 AM traveling "
+ + "toward Station A at 80 mph. At what time do they meet?")
+ .build();
+
+ System.out.println("=== REQUEST ===");
+ System.out.println(config.toJson());
+ System.out.println();
+
+ System.out.println("Streaming response:\n");
+
+ int eventCount = 0;
+ StringBuilder textBuffer = new StringBuilder();
+ StringBuilder thoughtSummaryBuffer = new StringBuilder();
+ int thoughtSummaryCount = 0;
+ int textContentCount = 0;
+ int imageContentCount = 0;
+
+ try (InteractionEventStream Note: The Interactions API is currently only available via the Gemini Developer API (not
+ * Vertex AI).
+ *
+ * 1. Set an API key environment variable. You can find a list of available API keys here:
+ * https://aistudio.google.com/app/apikey
+ *
+ * export GOOGLE_API_KEY=YOUR_API_KEY
+ *
+ * 2. Compile the java package and run the sample code.
+ *
+ * mvn clean compile
+ *
+ * mvn exec:java
+ * -Dexec.mainClass="com.google.genai.examples.InteractionsStreamingThoughtSummaryWithImage"
+ */
+package com.google.genai.examples;
+
+import com.google.genai.Client;
+import com.google.genai.InteractionEventStream;
+import com.google.genai.JsonSerializable;
+import com.google.genai.types.interactions.CreateInteractionConfig;
+import com.google.genai.types.interactions.GenerationConfig;
+import com.google.genai.types.interactions.ThinkingLevel;
+import com.google.genai.types.interactions.ThinkingSummaries;
+import com.google.genai.types.interactions.content.ImageContent;
+import com.google.genai.types.interactions.content.TextContent;
+import com.google.genai.types.interactions.content.ThoughtSummaryContent;
+import com.google.genai.types.interactions.streaming.ContentDelta;
+import com.google.genai.types.interactions.streaming.ContentStart;
+import com.google.genai.types.interactions.streaming.ContentStop;
+import com.google.genai.types.interactions.streaming.ErrorEvent;
+import com.google.genai.types.interactions.streaming.InteractionEvent;
+import com.google.genai.types.interactions.streaming.InteractionSseEvent;
+import com.google.genai.types.interactions.streaming.delta.Delta;
+import com.google.genai.types.interactions.streaming.delta.TextDelta;
+import com.google.genai.types.interactions.streaming.delta.ThoughtSignatureDelta;
+import com.google.genai.types.interactions.streaming.delta.ThoughtSummaryDelta;
+
+/**
+ * Example attempting to trigger ImageContent in ThoughtSummaryDelta.
+ *
+ * This example explores whether the API returns ImageContent in thought summaries when:
+ * According to the OpenAPI spec, ThoughtSummaryDelta.content can be either:
+ * Note: The Interactions API is in beta and ImageContent in thought summaries may not
+ * be fully available yet.
+ */
+public final class InteractionsStreamingThoughtSummaryWithImage {
+
+ public static void main(String[] args) {
+ Client client = new Client();
+
+ System.out.println("=== Interactions API: ThoughtSummary with Image Input ===\n");
+ System.out.println("Testing whether ImageContent appears in ThoughtSummaryDelta\n");
+
+ try {
+ // ===== Simple VIBGYOR Colors Request =====
+ System.out.println("--- Requesting VIBGYOR Rainbow Colors as Images ---\n");
+
+ GenerationConfig generationConfig = GenerationConfig.builder()
+ .thinkingLevel(new ThinkingLevel(ThinkingLevel.Known.HIGH))
+ .thinkingSummaries(new ThinkingSummaries(ThinkingSummaries.Known.AUTO))
+ .build();
+
+ // Note: Commented alternative prompt for generating VIBGYOR rainbow colors
+ // TextContent prompt = TextContent.of("Generate images showing the 7 VIBGYOR rainbow colors...");
+ TextContent prompt = TextContent.of("Generate simple image showing RED color");
+
+ CreateInteractionConfig config = CreateInteractionConfig.builder()
+ .model("gemini-3-pro-image-preview")
+ .generationConfig(generationConfig)
+ .inputFromContents(prompt)
+ .build();
+
+ System.out.println("=== REQUEST ===");
+ System.out.println(config.toJson());
+ System.out.println();
+
+ runStreamingAnalysis(client, config, "VIBGYOR Colors");
+
+ System.out.println("\n=== All tests completed ===");
+
+ } catch (Exception e) {
+ System.err.println("Error: " + e.getMessage());
+ e.printStackTrace();
+ }
+ }
+
+ private static void runStreamingAnalysis(Client client, CreateInteractionConfig config,
+ String testName) {
+ System.out.println("Streaming response for: " + testName + "\n");
+
+ int eventCount = 0;
+ StringBuilder textBuffer = new StringBuilder();
+ int thoughtSummaryCount = 0;
+ int textContentCount = 0;
+ int imageContentCount = 0;
+
+ try (InteractionEventStream Note: The Interactions API is currently only available via the Gemini Developer API (not
+ * Vertex AI).
+ *
+ * 1. Set an API key environment variable. You can find a list of available API keys here:
+ * https://aistudio.google.com/app/apikey
+ *
+ * export GOOGLE_API_KEY=YOUR_API_KEY
+ *
+ * 2. Compile the java package and run the sample code.
+ *
+ * mvn clean compile
+ *
+ * mvn exec:java -Dexec.mainClass="com.google.genai.examples.InteractionsStreamingToolCalls"
+ */
+package com.google.genai.examples;
+
+import com.google.genai.Client;
+import com.google.genai.JsonSerializable;
+import com.google.genai.InteractionEventStream;
+import com.google.genai.types.Schema;
+import com.google.genai.types.interactions.CreateInteractionConfig;
+import com.google.genai.types.interactions.streaming.ContentDelta;
+import com.google.genai.types.interactions.streaming.InteractionSseEvent;
+import com.google.genai.types.interactions.streaming.delta.Delta;
+import com.google.genai.types.interactions.streaming.delta.FunctionCallDelta;
+import com.google.genai.types.interactions.streaming.delta.GoogleSearchCallDelta;
+import com.google.genai.types.interactions.streaming.delta.TextDelta;
+import com.google.genai.types.interactions.streaming.delta.UrlContextCallDelta;
+import com.google.genai.types.interactions.tools.Function;
+import com.google.genai.types.interactions.tools.GoogleSearch;
+import com.google.genai.types.interactions.tools.UrlContext;
+import java.util.Map;
+
+/**
+ * Example: Streaming Tool Call Deltas
+ *
+ * Demonstrates streaming for tool invocation delta types:
+ *
+ * This example shows:
+ *
+ * Note: The Interactions API is in beta and subject to change.
+ */
+public final class InteractionsStreamingToolCalls {
+
+ public static void main(String[] args) {
+ Client client = new Client();
+
+ System.out.println("=== Interactions API: Streaming Tool Call Deltas ===\n");
+
+ try {
+ // ===== PART 1: Function Calling Streaming =====
+ System.out.println("--- PART 1: Function Calling Streaming (FunctionCallDelta) ---\n");
+
+ Function weatherTool =
+ Function.builder()
+ .name("get_weather")
+ .description("Get the current weather for a location")
+ .parameters(
+ Schema.builder()
+ .type("object")
+ .properties(
+ Map.of(
+ "location",
+ Schema.builder()
+ .type("string")
+ .description("The city name")
+ .build()))
+ .required("location")
+ .build())
+ .build();
+
+ CreateInteractionConfig functionConfig =
+ CreateInteractionConfig.builder()
+ .model("gemini-3-flash-preview")
+ .input("What's the weather in Paris and London?")
+ .tools(weatherTool)
+ .build();
+
+ System.out.println("[REQUEST] CreateInteractionConfig:");
+ System.out.println(functionConfig.toJson());
+ System.out.println();
+
+ System.out.println("Streaming function calls:\n");
+
+ int eventCount1 = 0;
+ StringBuilder textBuffer1 = new StringBuilder();
+ int functionCallDeltaCount = 0;
+
+ try (InteractionEventStream Note: The Interactions API is currently only available via the Gemini Developer API (not
+ * Vertex AI).
+ *
+ * 1. Set an API key environment variable. You can find a list of available API keys here:
+ * https://aistudio.google.com/app/apikey
+ *
+ * export GOOGLE_API_KEY=YOUR_API_KEY
+ *
+ * 2. Compile the java package and run the sample code.
+ *
+ * mvn clean compile
+ *
+ * mvn exec:java -Dexec.mainClass="com.google.genai.examples.InteractionsStreamingToolResults"
+ */
+package com.google.genai.examples;
+
+import com.google.genai.Client;
+import com.google.genai.JsonSerializable;
+import com.google.genai.InteractionEventStream;
+import com.google.genai.types.Schema;
+import com.google.genai.types.interactions.CreateInteractionConfig;
+import com.google.genai.types.interactions.streaming.ContentDelta;
+import com.google.genai.types.interactions.streaming.InteractionSseEvent;
+import com.google.genai.types.interactions.streaming.delta.Delta;
+import com.google.genai.types.interactions.streaming.delta.FunctionResultDelta;
+import com.google.genai.types.interactions.streaming.delta.GoogleSearchResultDelta;
+import com.google.genai.types.interactions.streaming.delta.TextDelta;
+import com.google.genai.types.interactions.streaming.delta.UrlContextResultDelta;
+import com.google.genai.types.interactions.tools.Function;
+import com.google.genai.types.interactions.tools.GoogleSearch;
+import com.google.genai.types.interactions.tools.UrlContext;
+import java.util.Map;
+
+/**
+ * Example: Streaming Tool Result Deltas
+ *
+ * Demonstrates streaming for tool result delta types:
+ *
+ * This example shows:
+ *
+ * Note: The Interactions API is in beta and subject to change.
+ */
+public final class InteractionsStreamingToolResults {
+
+ public static void main(String[] args) {
+ Client client = new Client();
+
+ System.out.println("=== Interactions API: Streaming Tool Result Deltas ===\n");
+
+ try {
+ // ===== PART 1: Google Search Results Streaming =====
+ System.out.println("--- PART 1: Google Search Results Streaming (GoogleSearchResultDelta) ---\n");
+
+ GoogleSearch searchTool = GoogleSearch.builder().build();
+
+ CreateInteractionConfig searchConfig =
+ CreateInteractionConfig.builder()
+ .model("gemini-3-flash-preview")
+ .input("Search for the top 5 AI breakthroughs in 2025")
+ .tools(searchTool)
+ .build();
+
+ System.out.println("[REQUEST] CreateInteractionConfig:");
+ System.out.println(searchConfig.toJson());
+ System.out.println();
+
+ System.out.println("Streaming Google Search results:\n");
+
+ int eventCount1 = 0;
+ StringBuilder textBuffer1 = new StringBuilder();
+ int searchResultDeltaCount = 0;
+
+ try (InteractionEventStream Note: The Interactions API is currently only available via the Gemini Developer API (not
+ * Vertex AI).
+ *
+ * 1. Set an API key environment variable. You can find a list of available API keys here:
+ * https://aistudio.google.com/app/apikey
+ *
+ * export GOOGLE_API_KEY=YOUR_API_KEY
+ *
+ * 2. Compile the java package and run the sample code.
+ *
+ * mvn clean compile
+ *
+ * mvn exec:java -Dexec.mainClass="com.google.genai.examples.InteractionsStreamingUrlContext"
+ */
+package com.google.genai.examples;
+
+import com.google.genai.Client;
+import com.google.genai.InteractionEventStream;
+import com.google.genai.JsonSerializable;
+import com.google.genai.types.interactions.CreateInteractionConfig;
+import com.google.genai.types.interactions.streaming.ContentDelta;
+import com.google.genai.types.interactions.streaming.ContentStart;
+import com.google.genai.types.interactions.streaming.ContentStop;
+import com.google.genai.types.interactions.streaming.ErrorEvent;
+import com.google.genai.types.interactions.streaming.InteractionEvent;
+import com.google.genai.types.interactions.streaming.InteractionSseEvent;
+import com.google.genai.types.interactions.streaming.delta.Delta;
+import com.google.genai.types.interactions.streaming.delta.TextDelta;
+import com.google.genai.types.interactions.streaming.delta.UrlContextCallDelta;
+import com.google.genai.types.interactions.streaming.delta.UrlContextResultDelta;
+import com.google.genai.types.interactions.tools.UrlContext;
+
+/**
+ * Example: Streaming URL Context Tool with the Interactions API
+ *
+ * Demonstrates how to use the UrlContext tool with streaming to enable the model
+ * to fetch and use content from URLs, receiving results incrementally.
+ *
+ * This example shows:
+ * Note: The Interactions API is currently in beta.
+ */
+public final class InteractionsStreamingUrlContext {
+
+ public static void main(String[] args) {
+ Client client = new Client();
+
+ System.out.println("=== Interactions API: Streaming URL Context Tool Example ===\n");
+
+ try {
+ UrlContext urlTool = UrlContext.builder().build();
+
+ String userQuestion =
+ "Please fetch and summarize the content from https://www.wikipedia.org/wiki/Artificial_intelligence";
+
+ CreateInteractionConfig config =
+ CreateInteractionConfig.builder()
+ .model("gemini-3-flash-preview")
+ .input(userQuestion)
+ .tools(urlTool)
+ .build();
+
+ System.out.println("User: " + userQuestion + "\n");
+ System.out.println("=== REQUEST ===");
+ System.out.println(config.toJson());
+ System.out.println();
+
+ System.out.println("Streaming response:\n");
+
+ int eventCount = 0;
+ StringBuilder fullResponse = new StringBuilder();
+ int urlCallDeltaCount = 0;
+ int urlResultDeltaCount = 0;
+
+ try (InteractionEventStream Note: The Interactions API is currently only available via the Gemini Developer API (not
+ * Vertex AI).
+ *
+ * 1. Set an API key environment variable. You can find a list of available API keys here:
+ * https://aistudio.google.com/app/apikey
+ *
+ * export GOOGLE_API_KEY=YOUR_API_KEY
+ *
+ * 2. Compile the java package and run the sample code.
+ *
+ * mvn clean compile
+ *
+ * mvn exec:java -Dexec.mainClass="com.google.genai.examples.InteractionsStreamingVideoContent"
+ */
+package com.google.genai.examples;
+
+import com.google.genai.Client;
+import com.google.genai.InteractionEventStream;
+import com.google.genai.JsonSerializable;
+import com.google.genai.types.interactions.Input;
+import com.google.genai.types.interactions.content.TextContent;
+import com.google.genai.types.interactions.content.VideoContent;
+import com.google.genai.types.interactions.streaming.ContentDelta;
+import com.google.genai.types.interactions.streaming.ContentStart;
+import com.google.genai.types.interactions.streaming.ContentStop;
+import com.google.genai.types.interactions.streaming.ErrorEvent;
+import com.google.genai.types.interactions.streaming.InteractionEvent;
+import com.google.genai.types.interactions.streaming.InteractionSseEvent;
+import com.google.genai.types.interactions.streaming.delta.Delta;
+import com.google.genai.types.interactions.streaming.delta.TextDelta;
+
+/**
+ * Example demonstrating streaming video analysis using VideoContent with the Interactions API.
+ *
+ * This example shows:
+ * Note: Inline base64-encoded video is not shown because video files are typically
+ * large and not suitable for inline embedding.
+ *
+ * Note: The Interactions API is currently in beta.
+ */
+public final class InteractionsStreamingVideoContent {
+
+ public static void main(String[] args) {
+ Client client = new Client();
+
+ System.out.println("=== Interactions API: Streaming Video Content Example ===\n");
+
+ try {
+ // ===== Video from URI (Streaming) =====
+ System.out.println("--- Video from URI (Streaming) ---\n");
+
+ String videoUri = "https://storage.googleapis.com/cloud-samples-data/generative-ai/video/pixel8.mp4";
+ VideoContent videoContent = VideoContent.fromUri(videoUri, "video/mp4");
+ TextContent textPrompt = TextContent.of("Describe what happens in this video.");
+
+ // Using simplified streaming API: createStream(model, input)
+ Input input = Input.fromContents(textPrompt, videoContent);
+
+ System.out.println("Streaming response:\n");
+
+ int eventCount = 0;
+ StringBuilder fullResponse = new StringBuilder();
+
+ try (InteractionEventStream Note: The Interactions API is currently only available via the Gemini Developer API (not
+ * Vertex AI).
+ *
+ * 1. Set an API key environment variable:
+ *
+ * export GOOGLE_API_KEY=YOUR_API_KEY
+ *
+ * 2. Compile and run:
+ *
+ * mvn clean compile
+ *
+ * mvn exec:java -Dexec.mainClass="com.google.genai.examples.InteractionsTextAnnotations"
+ */
+package com.google.genai.examples;
+
+import com.google.genai.Client;
+import com.google.genai.types.interactions.Interaction;
+import com.google.genai.types.interactions.Annotation;
+import com.google.genai.types.interactions.content.Content;
+import com.google.genai.types.interactions.content.TextContent;
+import java.util.List;
+
+/**
+ * TextContent Annotations Testing Example
+ *
+ * This example demonstrates testing for the annotations field in TextContent responses
+ * from the Interactions API. The annotations field provides citation information for
+ * model-generated content.
+ *
+ * Structure: TextContent contains:
+ * - type: "text"
+ * - text: The actual text content
+ * - annotations: Optional array of Annotation objects for citations
+ *
+ * Each Annotation contains:
+ * - start_index: Start byte position of cited segment
+ * - end_index: End byte position of cited segment (exclusive)
+ * - source: Source reference (URL, title, etc.)
+ *
+ * This example tests various prompts to see if the API returns annotations.
+ *
+ * Note: The Interactions API is in beta and subject to change.
+ */
+public final class InteractionsTextAnnotations {
+
+ public static void main(String[] args) {
+ Client client = new Client();
+
+ System.out.println("=== TextContent Annotations Testing Example ===\n");
+ System.out.println("Testing if the Interactions API returns annotations in TextContent\n");
+
+ // Test Case 1: Simple factual question
+ testAnnotations(
+ client,
+ "Test Case 1: Simple Factual Question",
+ "What is the capital of France?");
+
+ // Test Case 2: Question that might trigger citations
+ testAnnotations(
+ client,
+ "Test Case 2: Request with Explicit Citation Request",
+ "Tell me about climate change and cite your sources.");
+
+ // Test Case 3: Research-oriented question
+ testAnnotations(
+ client,
+ "Test Case 3: Research Question",
+ "What are the latest advancements in quantum computing? Please provide citations.");
+
+ // Test Case 4: Grounding/search request
+ testAnnotations(
+ client,
+ "Test Case 4: Grounding Request",
+ "Search for information about the Paris Agreement and summarize it with citations.");
+
+ System.out.println("\n=== All test cases completed ===");
+ }
+
+ private static final String MODEL = "gemini-3-flash-preview";
+
+ /**
+ * Test helper that makes an API call and checks for annotations in the response.
+ */
+ private static void testAnnotations(Client client, String testName, String prompt) {
+ System.out.println("\n--- " + testName + " ---\n");
+
+ try {
+ // Using the convenience overload: create(model, text)
+ System.out.println("=== REQUEST ===");
+ System.out.println("Model: " + MODEL);
+ System.out.println("Input: " + prompt);
+ System.out.println();
+
+ Interaction response = client.interactions.create(MODEL, prompt);
+
+ System.out.println("=== RESPONSE ===");
+ System.out.println(response.toJson());
+ System.out.println();
+
+ analyzeAnnotations(response);
+
+ } catch (Exception e) {
+ System.err.println("ERROR in " + testName + ":");
+ System.err.println(" Exception: " + e.getClass().getName());
+ System.err.println(" Message: " + e.getMessage());
+ e.printStackTrace();
+ }
+ }
+
+ /**
+ * Analyzes interaction outputs to find and display annotations.
+ */
+ private static void analyzeAnnotations(Interaction interaction) {
+ System.out.println("Results:");
+
+ if (!interaction.outputs().isPresent() || interaction.outputs().get().isEmpty()) {
+ System.out.println(" ❌ No outputs found in response");
+ return;
+ }
+
+ boolean foundAnnotations = false;
+ int textContentCount = 0;
+ int totalAnnotations = 0;
+
+ for (Content content : interaction.outputs().get()) {
+ if (content instanceof TextContent) {
+ textContentCount++;
+ TextContent textContent = (TextContent) content;
+
+ System.out.println("\n TextContent #" + textContentCount + ":");
+ System.out.println(" Text: " + textContent.text().orElse("(empty)"));
+
+ if (textContent.annotations().isPresent() && !textContent.annotations().get().isEmpty()) {
+ foundAnnotations = true;
+ List Note: The Interactions API is currently only available via the Gemini Developer API (not
+ * Vertex AI).
+ *
+ * 1. Set an API key environment variable. You can find a list of available API keys here:
+ * https://aistudio.google.com/app/apikey
+ *
+ * export GOOGLE_API_KEY=YOUR_API_KEY
+ *
+ * 2. Compile the java package and run the sample code.
+ *
+ * mvn clean compile
+ *
+ * mvn exec:java
+ * -Dexec.mainClass="com.google.genai.examples.InteractionsThoughtContent"
+ */
+package com.google.genai.examples;
+
+import com.google.genai.Client;
+import com.google.genai.types.interactions.Interaction;
+import com.google.genai.types.interactions.content.ImageContent;
+import com.google.genai.types.interactions.content.Content;
+import com.google.genai.types.interactions.content.TextContent;
+import com.google.genai.types.interactions.content.ThoughtContent;
+import com.google.genai.types.interactions.content.ThoughtSummaryContent;
+import java.util.List;
+
+/**
+ * ThoughtContent Testing Example
+ *
+ * This example tests the ThoughtContent functionality to understand how the model's internal
+ * reasoning is exposed through the Interactions API.
+ *
+ * Structure: ThoughtContent contains:
+ * - signature: A cryptographic signature for the thought
+ * - summary: Optional list of Content (TextContent, ImageContent, etc.)
+ *
+ * The summary field matches Python's structure: Optional[List[Union[TextContent, ImageContent]]]
+ * allowing the model to provide reasoning summaries with both text and visual elements.
+ *
+ * Test Cases: 1. Simple Math Reasoning - Basic arithmetic with step-by-step thinking 2. Complex
+ * Logic Puzzle - Multi-step reasoning task 3. Reasoning with extended thinking mode
+ *
+ * Note: The Interactions API is in beta and subject to change.
+ */
+public final class InteractionsThoughtContent {
+
+ private static final String MODEL = "gemini-3-flash-preview";
+
+ public static void main(String[] args) {
+ Client client = new Client();
+
+ System.out.println("=== ThoughtContent Testing Example ===\n");
+ System.out.println("Testing model's internal reasoning (ThoughtContent)\n");
+
+ // Test Case 1: Simple Math Reasoning
+ testSimpleMathReasoning(client);
+
+ // Test Case 2: Complex Logic Puzzle
+ testComplexLogicPuzzle(client);
+
+ // Test Case 3: Extended Thinking Mode
+ testExtendedThinking(client);
+
+ System.out.println("\n=== All tests completed ===");
+ }
+
+ /**
+ * Test Case 1: Simple Math Reasoning
+ *
+ * Tests if ThoughtContent appears for basic arithmetic reasoning.
+ */
+ private static void testSimpleMathReasoning(Client client) {
+ System.out.println("\n--- Test Case 1: Simple Math Reasoning ---\n");
+
+ // Using the convenience overload: create(model, text)
+ String prompt = "Think step by step: What is 15 * 24?";
+
+ System.out.println("=== REQUEST ===");
+ System.out.println("Model: " + MODEL);
+ System.out.println("Input: " + prompt);
+ System.out.println();
+
+ try {
+ Interaction response = client.interactions.create(MODEL, prompt);
+
+ System.out.println("=== RESPONSE ===");
+ System.out.println(response.toJson());
+ System.out.println();
+
+ printResults(response);
+ analyzeContent(response);
+
+ } catch (Exception e) {
+ System.err.println("ERROR in Test Case 1:");
+ System.err.println(" Exception: " + e.getClass().getName());
+ System.err.println(" Message: " + e.getMessage());
+ e.printStackTrace();
+ }
+ }
+
+ /**
+ * Test Case 2: Complex Logic Puzzle
+ *
+ * Tests ThoughtContent with a more complex reasoning task that requires multiple steps.
+ */
+ private static void testComplexLogicPuzzle(Client client) {
+ System.out.println("\n--- Test Case 2: Complex Logic Puzzle ---\n");
+
+ String prompt =
+ "Solve this logic puzzle step by step:\n"
+ + "Three friends - Alice, Bob, and Carol - each have a different favorite color (red,"
+ + " blue, or green).\n"
+ + "- Alice doesn't like blue\n"
+ + "- Bob's favorite color is not red\n"
+ + "- Carol likes green\n"
+ + "What is each person's favorite color? Show your reasoning.";
+
+ System.out.println("=== REQUEST ===");
+ System.out.println("Model: " + MODEL);
+ System.out.println("Input: " + prompt);
+ System.out.println();
+
+ try {
+ Interaction response = client.interactions.create(MODEL, prompt);
+
+ System.out.println("=== RESPONSE ===");
+ System.out.println(response.toJson());
+ System.out.println();
+
+ printResults(response);
+ analyzeContent(response);
+
+ } catch (Exception e) {
+ System.err.println("ERROR in Test Case 2:");
+ System.err.println(" Exception: " + e.getClass().getName());
+ System.err.println(" Message: " + e.getMessage());
+ e.printStackTrace();
+ }
+ }
+
+ /**
+ * Test Case 3: Extended Thinking Mode
+ *
+ * Tests ThoughtContent with a reasoning-heavy task.
+ */
+ private static void testExtendedThinking(Client client) {
+ System.out.println("\n--- Test Case 3: Extended Thinking Test ---\n");
+
+ String prompt =
+ "Calculate the following and explain your reasoning:\n"
+ + "If a train travels at 60 mph for 2.5 hours, then speeds up to 80 mph for another 1.5"
+ + " hours, how far does it travel in total?";
+
+ System.out.println("=== REQUEST ===");
+ System.out.println("Model: " + MODEL);
+ System.out.println("Input: " + prompt);
+ System.out.println();
+
+ try {
+ Interaction response = client.interactions.create(MODEL, prompt);
+
+ System.out.println("=== RESPONSE ===");
+ System.out.println(response.toJson());
+ System.out.println();
+
+ printResults(response);
+ analyzeContent(response);
+
+ } catch (Exception e) {
+ System.err.println("ERROR in Test Case 3:");
+ System.err.println(" Exception: " + e.getClass().getName());
+ System.err.println(" Message: " + e.getMessage());
+ e.printStackTrace();
+ }
+ }
+
+ private static void printResults(Interaction interaction) {
+ System.out.println("Results:");
+ System.out.println(" Interaction ID: " + interaction.id());
+ System.out.println(" Status: " + interaction.status());
+ }
+
+ /**
+ * Analyzes interaction content to identify and display ThoughtContent.
+ *
+ * This method: - Iterates through all outputs in the interaction - Identifies ThoughtContent
+ * instances - Displays thought signatures and summaries - Compares actual structure with expected
+ * structure
+ */
+ private static void analyzeContent(Interaction interaction) {
+ System.out.println("CONTENT ANALYSIS:");
+
+ if (!interaction.outputs().isPresent() || interaction.outputs().get().isEmpty()) {
+ System.out.println(" No outputs found in response");
+ return;
+ }
+
+ int thoughtCount = 0;
+ int textCount = 0;
+ int otherCount = 0;
+
+ System.out.println("\n Analyzing " + interaction.outputs().get().size() + " output(s):");
+
+ for (Content content : interaction.outputs().get()) {
+ System.out.println("\n Content Type: " + content.getClass().getSimpleName());
+
+ if (content instanceof ThoughtContent) {
+ thoughtCount++;
+ ThoughtContent thought = (ThoughtContent) content;
+
+ System.out.println(" >>> THOUGHT CONTENT FOUND <<<");
+ System.out.println(" Signature: " + thought.signature().orElse("(none)"));
+
+ if (thought.summary().isPresent()) {
+ List Note: The Interactions API is currently only available via the Gemini Developer API (not
+ * Vertex AI).
+ *
+ * 1. Set an API key environment variable. You can find a list of available API keys here:
+ * https://aistudio.google.com/app/apikey
+ *
+ * export GOOGLE_API_KEY=YOUR_API_KEY
+ *
+ * 2. Compile the java package and run the sample code.
+ *
+ * mvn clean compile
+ *
+ * mvn exec:java -Dexec.mainClass="com.google.genai.examples.InteractionsUrlContext"
+ */
+package com.google.genai.examples;
+
+import com.google.genai.Client;
+import com.google.genai.types.interactions.CreateInteractionConfig;
+import com.google.genai.types.interactions.Interaction;
+import com.google.genai.types.interactions.UrlContextResult;
+import com.google.genai.types.interactions.content.Content;
+import com.google.genai.types.interactions.content.TextContent;
+import com.google.genai.types.interactions.content.UrlContextCallContent;
+import com.google.genai.types.interactions.content.UrlContextResultContent;
+import com.google.genai.types.interactions.tools.UrlContext;
+import java.util.List;
+
+/**
+ * Example: URL Context Tool with the Interactions API
+ *
+ * Demonstrates how to use the UrlContext to enable the model to retrieve and use context
+ * from URLs. The model can fetch web pages and use their content to answer questions.
+ *
+ * Note: The Interactions API is in beta and subject to change.
+ */
+public final class InteractionsUrlContext {
+
+ public static void main(String[] args) {
+ // Instantiate the client. The client gets the API key from the environment variable
+ // `GOOGLE_API_KEY`.
+ //
+ Client client = new Client();
+
+ System.out.println("=== Interactions API: URL Context Tool Example ===\n");
+
+ // ===== STEP 1: Create UrlContext =====
+ System.out.println("STEP 1: Create UrlContext\n");
+
+ UrlContext urlTool = UrlContext.builder().build();
+
+ System.out.println("UrlContext created successfully\n");
+
+ // ===== STEP 2: Create interaction with URL Context enabled =====
+ System.out.println("---\n");
+ System.out.println("STEP 2: Create interaction with URL Context enabled\n");
+
+ String userQuestion =
+ "Please fetch and summarize the content from https://www.wikipedia.org/wiki/Artificial_intelligence";
+ System.out.println("User: " + userQuestion + "\n");
+
+ CreateInteractionConfig config =
+ CreateInteractionConfig.builder()
+ .model("gemini-3-flash-preview")
+ .input(userQuestion)
+ .tools(urlTool)
+ .build();
+
+ // Print the request JSON
+ System.out.println("=== REQUEST ===");
+ System.out.println(config.toJson());
+ System.out.println();
+
+ Interaction response = client.interactions.create(config);
+
+ // Print the response JSON
+ System.out.println("=== RESPONSE ===");
+ System.out.println(response.toJson());
+ System.out.println();
+
+ // ===== STEP 3: Extract and display the results =====
+ System.out.println("---\n");
+ System.out.println("STEP 3: Extract and display the results\n");
+
+ System.out.println("Response received. Interaction ID: " + response.id());
+ System.out.println();
+
+ if (response.outputs().isPresent()) {
+ for (Content content : response.outputs().get()) {
+ if (content instanceof TextContent) {
+ System.out.println("Text: " + ((TextContent) content).text().orElse("(empty)"));
+ System.out.println();
+ } else if (content instanceof UrlContextCallContent) {
+ UrlContextCallContent urlCall = (UrlContextCallContent) content;
+ System.out.println("URL Context Call:");
+ System.out.println(" ID: " + urlCall.id());
+ if (urlCall.arguments().isPresent()) {
+ System.out.println(" URLs: " + urlCall.arguments().get().urls().orElse(java.util.List.of()));
+ }
+ System.out.println();
+ } else if (content instanceof UrlContextResultContent) {
+ UrlContextResultContent urlResult = (UrlContextResultContent) content;
+ System.out.println("URL Context Result:");
+ System.out.println(" Call ID: " + urlResult.callId().orElse("N/A"));
+ System.out.println(" Is Error: " + urlResult.isError().orElse(false));
+
+ if (urlResult.result().isPresent()) {
+ List This example shows:
+ * Note: Inline base64-encoded video is not shown because video files are typically
+ * large and not suitable for inline embedding.
+ *
+ * To run this example:
+ * Note: The Interactions API is currently in beta.
+ */
+public final class InteractionsVideoContent {
+
+ public static void main(String[] args) {
+ Client client = new Client();
+
+ System.out.println("=== Interactions API: Video Content Example ===\n");
+
+ try {
+ // ===== Video from URI =====
+ System.out.println("--- Video from URI ---\n");
+
+ String videoUri = "https://storage.googleapis.com/cloud-samples-data/generative-ai/video/pixel8.mp4";
+ VideoContent videoContent = VideoContent.fromUri(videoUri, "video/mp4");
+ TextContent textPrompt = TextContent.of("Describe what happens in this video.");
+
+ Input input = Input.fromContents(textPrompt, videoContent);
+
+ Interaction response = client.interactions.create("gemini-3-flash-preview", input);
+
+ System.out.println("=== RESPONSE ===");
+ System.out.println(response.toJson());
+ System.out.println();
+
+ printResults(response);
+
+ System.out.println("\n=== Example completed ===");
+
+ } catch (Exception e) {
+ System.err.println("Error: " + e.getMessage());
+ e.printStackTrace();
+ }
+ }
+
+ private static void printResults(Interaction interaction) {
+ System.out.println("Results:");
+ System.out.println(" Interaction ID: " + interaction.id());
+ System.out.println(" Status: " + interaction.status());
+
+ if (interaction.outputs().isPresent() && !interaction.outputs().get().isEmpty()) {
+ for (Content output : interaction.outputs().get()) {
+ if (output instanceof TextContent) {
+ System.out.println(" Text: " + ((TextContent) output).text().orElse("(empty)"));
+ } else {
+ System.out.println(" " + output.getClass().getSimpleName());
+ }
+ }
+ }
+ }
+
+ private InteractionsVideoContent() {}
+}
diff --git a/pom.xml b/pom.xml
index 90a90201ab4..082489f5a2d 100644
--- a/pom.xml
+++ b/pom.xml
@@ -323,6 +323,7 @@
The Interactions API is available in both Vertex AI and Gemini API.
+ *
+ * Note: The Interactions API is in beta and subject to change.
+ */
+public final class AsyncInteractions {
+ Interactions interactions;
+ ApiClient apiClient;
+
+ public AsyncInteractions(ApiClient apiClient) {
+ this.apiClient = apiClient;
+ this.interactions = new Interactions(apiClient);
+ }
+
+ /**
+ * Asynchronously creates a new interaction with the specified configuration.
+ *
+ * Either {@code model} or {@code agent} must be specified in the config, but not both.
+ *
+ * Example usage for model-based interaction:
+ *
+ * Example usage for agent-based interaction:
+ *
+ * Note: The Interactions API is in beta and subject to change.
+ *
+ * @param config The configuration for creating the interaction
+ * @return A CompletableFuture containing the created Interaction with outputs
+ * @throws IllegalArgumentException if both model and agent are specified, or neither is specified
+ * @throws UnsupportedOperationException if using Vertex AI (not yet supported)
+ */
+ public CompletableFuture This is a convenience overload that wraps the text in a CreateInteractionConfig.
+ *
+ * Example usage:
+ *
+ * Note: The Interactions API is in beta and subject to change.
+ *
+ * @param model The model name (e.g., "gemini-2.5-flash")
+ * @param text The input text for the interaction
+ * @return A CompletableFuture containing the created Interaction with outputs
+ * @throws IllegalArgumentException if model or text is null or empty
+ */
+ public CompletableFuture This is a convenience overload for multi-turn conversations and complex inputs.
+ *
+ * Example usage:
+ *
+ * Note: The Interactions API is in beta and subject to change.
+ *
+ * @param model The model name (e.g., "gemini-2.5-flash")
+ * @param input The Input object (from turns, contents, or string)
+ * @return A CompletableFuture containing the created Interaction with outputs
+ * @throws IllegalArgumentException if model or input is null
+ */
+ public CompletableFuture Example usage:
+ *
+ * Note: The Interactions API is in beta and subject to change.
+ *
+ * @param id The ID of the interaction to retrieve
+ * @param config The configuration for the get request (can be null)
+ * @return A CompletableFuture containing the retrieved Interaction
+ */
+ public CompletableFuture Example usage:
+ *
+ * Note: The Interactions API is in beta and subject to change.
+ *
+ * @param id The ID of the interaction to cancel
+ * @param config The configuration for the cancel request (can be null)
+ * @return A CompletableFuture containing the updated Interaction
+ */
+ public CompletableFuture The API returns an empty response on successful deletion. Success is indicated by the
+ * CompletableFuture completing without exception.
+ *
+ * Example usage:
+ *
+ * Note: The Interactions API is in beta and subject to change.
+ *
+ * @param id The ID of the interaction to delete
+ * @param config The configuration for the delete request (can be null)
+ * @return A CompletableFuture that completes when the deletion is successful
+ */
+ public CompletableFuture This is a convenience overload equivalent to calling {@code get(id,
+ * GetInteractionConfig.builder().build())}.
+ *
+ * Example usage:
+ *
+ * This is a convenience overload equivalent to calling {@code cancel(id,
+ * CancelInteractionConfig.builder().build())}.
+ *
+ * Example usage:
+ *
+ * This is a convenience overload equivalent to calling {@code delete(id,
+ * DeleteInteractionConfig.builder().build())}.
+ *
+ * Example usage:
+ *
+ * Returns a CompletableFuture that resolves to a stream of events that can be iterated over to
+ * receive real-time updates as the model generates its response.
+ *
+ * Either {@code model} or {@code agent} must be specified in the config, but not both.
+ *
+ * Example usage:
+ *
+ * Note: The Interactions API is in beta and subject to change.
+ *
+ * @param config The configuration for creating the interaction
+ * @return A CompletableFuture containing a InteractionEventStream of InteractionSseEvent
+ * @throws IllegalArgumentException if both model and agent are specified, or neither is specified
+ */
+ public CompletableFuture This is a convenience overload that wraps the text in a CreateInteractionConfig.
+ *
+ * Example usage:
+ *
+ * Note: The Interactions API is in beta and subject to change.
+ *
+ * @param model The model name (e.g., "gemini-2.5-flash")
+ * @param text The input text for the interaction
+ * @return A CompletableFuture containing a InteractionEventStream of InteractionSseEvent
+ * @throws IllegalArgumentException if model or text is null or empty
+ */
+ public CompletableFuture This is a convenience overload for multi-turn conversations and complex inputs.
+ *
+ * Example usage:
+ *
+ * Note: The Interactions API is in beta and subject to change.
+ *
+ * @param model The model name (e.g., "gemini-2.5-flash")
+ * @param input The Input object (from turns, contents, or string)
+ * @return A CompletableFuture containing a InteractionEventStream of InteractionSseEvent
+ * @throws IllegalArgumentException if model or input is null
+ */
+ public CompletableFuture This method is primarily used for:
+ *
+ * Example usage for stream resumption:
+ *
+ * Note: The Interactions API is in beta and subject to change.
+ *
+ * @param id The ID of the interaction to retrieve as a stream
+ * @param config The configuration for the stream request (can be null)
+ * @return A CompletableFuture containing a InteractionEventStream of InteractionSseEvent
+ * @throws IllegalArgumentException if the ID is empty
+ */
+ public CompletableFuture This is a convenience method that calls {@link #getStream(String, GetInteractionConfig)}
+ * with an empty configuration.
+ *
+ * Use this when you don't need to specify additional configuration like lastEventId for
+ * stream resumption.
+ *
+ * @param id The ID of the interaction to retrieve as a stream
+ * @return A CompletableFuture containing a InteractionEventStream of InteractionSseEvent
+ * @throws IllegalArgumentException if the ID is empty
+ */
+ public CompletableFuture This class is similar to {@link ResponseStream} but supports polymorphic event types where
+ * the base type is an interface with Jackson {@code @JsonTypeInfo} and {@code @JsonSubTypes}
+ * annotations.
+ *
+ * This is used for streaming interactions where events are deserialized to their concrete types
+ * based on the "event_type" discriminator field.
+ *
+ * Example usage:
+ * Note: The Interactions API is in beta and subject to change.
+ */
+public final class Interactions {
+
+ final ApiClient apiClient;
+
+ // Constants for streaming mode clarity
+ static final boolean STREAMING = true;
+ static final boolean NON_STREAMING = false;
+
+ public Interactions(ApiClient apiClient) {
+ this.apiClient = apiClient;
+ }
+
+ /**
+ * Shared buildRequest method for both sync and async, streaming and non-streaming.
+ *
+ * @param config The interaction configuration
+ * @param stream Whether to enable streaming mode
+ * @return The built request ready for execution
+ */
+ BuiltRequest buildRequestForCreate(CreateInteractionConfig config, boolean stream) {
+
+ // Validation: exactly one of model or agent must be specified
+ boolean hasModel = config.model().isPresent() && !config.model().get().isEmpty();
+ boolean hasAgent = config.agent().isPresent() && !config.agent().get().isEmpty();
+
+ if (hasModel && hasAgent) {
+ throw new IllegalArgumentException(
+ "Cannot specify both 'model' and 'agent'. Please provide only one.");
+ }
+
+ if (!hasModel && !hasAgent) {
+ throw new IllegalArgumentException(
+ "Must specify either 'model' or 'agent' in CreateInteractionConfig.");
+ }
+
+ // Validation: agentConfig only with agent, generationConfig only with model
+ if (hasAgent && config.generationConfig().isPresent()) {
+ throw new IllegalArgumentException(
+ "Cannot use 'generationConfig' with agent-based interactions. "
+ + "Use 'agentConfig' instead.");
+ }
+
+ if (hasModel && config.agentConfig().isPresent()) {
+ throw new IllegalArgumentException(
+ "Cannot use 'agentConfig' with model-based interactions. "
+ + "Use 'generationConfig' instead.");
+ }
+
+ // Build request body - serialize config directly
+ ObjectNode body = (ObjectNode) JsonSerializable.toJsonNode(config);
+
+ // Add stream parameter if needed
+ if (stream) {
+ body.put("stream", true);
+ }
+
+ String path = "interactions";
+
+ // Build HTTP options with API version override if specified
+ Optional This method supports stream resumption via lastEventId.
+ */
+ BuiltRequest buildRequestForGetStream(String id, GetInteractionConfig config) {
+ validateInteractionId(id);
+
+ // Path construction - ApiClient handles Vertex AI or Gemini API prefixes
+ String basePath = "interactions/" + id;
+
+ // Build query parameters for streaming
+ ObjectNode queryParams = JsonSerializable.objectMapper().createObjectNode();
+ queryParams.put("stream", "true");
+
+ // Add last_event_id for stream resumption (optional)
+ if (config != null && config.lastEventId().isPresent()) {
+ queryParams.put("last_event_id", config.lastEventId().get());
+ }
+
+ // Combine path with query parameters (e.g., "interactions/abc?stream=true&last_event_id=xyz")
+ String path = String.format("%s?%s", basePath, Common.urlEncode(queryParams));
+
+ // Build HTTP options with API version override if specified
+ Optional Currently, only {@code apiVersion} is extracted from interaction configs to build {@link
+ * HttpOptions}. This method can be extended if additional parameters are required.
+ *
+ * @param apiVersion The optional API version from any interaction config
+ * @return Optional containing HttpOptions with apiVersion if present, empty otherwise
+ */
+ private Optional Either {@code model} or {@code agent} must be specified in the config, but not both.
+ *
+ * When using function calling tools, the application must handle the function execution loop
+ * manually. If the interaction returns {@code status: "requires_action"}, extract the function
+ * calls from the outputs, execute them, and create a new interaction with the results using
+ * {@code previousInteractionId}.
+ *
+ * Example usage for model-based interaction:
+ *
+ * Example usage for agent-based interaction:
+ *
+ * Example usage with manual function calling:
+ *
+ * Note: The Interactions API is in beta and subject to change.
+ *
+ * @param config The configuration for creating the interaction
+ * @return The created Interaction with outputs
+ * @throws IllegalArgumentException if both model and agent are specified, or neither is specified
+ * @throws GenAiIOException if the API request fails
+ */
+ public Interaction create(CreateInteractionConfig config) {
+ BuiltRequest builtRequest = buildRequestForCreate(config, NON_STREAMING);
+
+ try (ApiResponse response =
+ this.apiClient.request(
+ "post", builtRequest.path(), builtRequest.body(), builtRequest.httpOptions())) {
+ return processResponseForCreate(response, config);
+ }
+ }
+
+ /**
+ * Creates an interaction with a simple text input.
+ *
+ * This is a convenience method for the most common use case. For more complex scenarios, use
+ * {@link #create(CreateInteractionConfig)}.
+ *
+ * Example usage:
+ *
+ * Note: The Interactions API is in beta and subject to change.
+ *
+ * @param model The model name (e.g., "gemini-2.5-flash", "gemini-3-flash-preview")
+ * @param text The input text for the interaction
+ * @return The created Interaction with outputs
+ * @throws IllegalArgumentException if model or text is null or empty
+ * @throws GenAiIOException if the API request fails
+ */
+ public Interaction create(String model, String text) {
+ return create(CreateInteractionConfig.builder().model(model).input(text).build());
+ }
+
+ /**
+ * Creates an interaction with an Input object (turns, contents, or complex input).
+ *
+ * Use this for multi-turn conversations or complex input types.
+ *
+ * Example usage with multi-turn conversation:
+ *
+ * Example usage with multimodal content:
+ *
+ * Note: The Interactions API is in beta and subject to change.
+ *
+ * @param model The model name
+ * @param input The Input object (from turns, contents, or string)
+ * @return The created Interaction with outputs
+ * @throws IllegalArgumentException if model or input is null
+ * @throws GenAiIOException if the API request fails
+ */
+ public Interaction create(String model, Input input) {
+ return create(CreateInteractionConfig.builder().model(model).input(input).build());
+ }
+
+ /**
+ * Retrieves an interaction by its ID.
+ *
+ * Example usage:
+ *
+ * Note: The Interactions API is in beta and subject to change.
+ *
+ * @param id The ID of the interaction to retrieve
+ * @param config The configuration for the get request (can be null)
+ * @return The retrieved Interaction
+ * @throws IllegalArgumentException if the ID is empty
+ * @throws GenAiIOException if the API request fails
+ */
+ public Interaction get(String id, GetInteractionConfig config) {
+ BuiltRequest builtRequest = buildRequestForGet(id, config);
+
+ try (ApiResponse response =
+ this.apiClient.request(
+ "get", builtRequest.path(), builtRequest.body(), builtRequest.httpOptions())) {
+ return processResponseForGet(response, config);
+ }
+ }
+
+ /**
+ * Cancels a background interaction that is still in progress.
+ *
+ * Only applies to interactions created with background=true that are in IN_PROGRESS status.
+ *
+ * Example usage:
+ *
+ * Note: The Interactions API is in beta and subject to change.
+ *
+ * @param id The ID of the interaction to retrieve
+ * @param config The configuration for the cancel request (can be null)
+ * @return The updated Interaction with CANCELLED status
+ * @throws IllegalArgumentException if the ID is empty
+ * @throws GenAiIOException if the API request fails
+ */
+ public Interaction cancel(String id, CancelInteractionConfig config) {
+ BuiltRequest builtRequest = buildRequestForCancel(id, config);
+
+ try (ApiResponse response =
+ this.apiClient.request(
+ "post", builtRequest.path(), builtRequest.body(), builtRequest.httpOptions())) {
+ return processResponseForCancel(response, config);
+ }
+ }
+
+ /**
+ * Deletes an interaction by its ID.
+ *
+ * The API returns an empty response on successful deletion. Success is indicated by the
+ * method completing without throwing an exception.
+ *
+ * Example usage:
+ *
+ * Note: The Interactions API is in beta and subject to change.
+ *
+ * @param id The ID of the interaction to delete
+ * @param config The configuration for the delete request (can be null)
+ * @throws IllegalArgumentException if the ID is empty
+ * @throws GenAiIOException if the API request fails
+ */
+ public void delete(String id, DeleteInteractionConfig config) {
+ BuiltRequest builtRequest = buildRequestForDelete(id, config);
+
+ try (ApiResponse response =
+ this.apiClient.request(
+ "delete", builtRequest.path(), builtRequest.body(), builtRequest.httpOptions())) {
+ // Delete API returns empty JSON object {}
+ // Success is indicated by no exception thrown
+ }
+ }
+
+ /**
+ * Retrieves an interaction by its ID using default configuration.
+ *
+ * This is a convenience method equivalent to calling {@code get(id,
+ * GetInteractionConfig.builder().build())}. For advanced options like API version override or
+ * stream resumption, use {@link #get(String, GetInteractionConfig)}.
+ *
+ * Example usage:
+ *
+ * This is a convenience method equivalent to calling {@code cancel(id,
+ * CancelInteractionConfig.builder().build())}. Only applies to interactions created with
+ * background=true that are in IN_PROGRESS status.
+ *
+ * Example usage:
+ *
+ * This is a convenience method equivalent to calling {@code delete(id,
+ * DeleteInteractionConfig.builder().build())}. For API version override, use {@link
+ * #delete(String, DeleteInteractionConfig)}.
+ *
+ * Example usage:
+ *
+ * Returns a stream of events that can be iterated over to receive real-time updates as the
+ * model generates its response. This is useful for displaying responses incrementally or
+ * processing large outputs without waiting for the complete response.
+ *
+ * Either {@code model} or {@code agent} must be specified in the config, but not both.
+ *
+ * Example usage:
+ *
+ * Event sequence for a typical streaming interaction:
+ *
+ * Note: The Interactions API is in beta and subject to change.
+ *
+ * @param config The configuration for creating the interaction
+ * @return A InteractionEventStream of InteractionSseEvent that can be iterated over
+ * @throws IllegalArgumentException if both model and agent are specified, or neither is specified
+ * @throws GenAiIOException if the API request fails
+ */
+ public InteractionEventStream This is a convenience method for the most common streaming use case. For more complex
+ * scenarios, use {@link #createStream(CreateInteractionConfig)}.
+ *
+ * Example usage:
+ *
+ * Note: The Interactions API is in beta and subject to change.
+ *
+ * @param model The model name (e.g., "gemini-2.5-flash", "gemini-3-flash-preview")
+ * @param text The input text for the interaction
+ * @return A stream of InteractionSseEvent objects
+ * @throws IllegalArgumentException if model or text is null or empty
+ * @throws GenAiIOException if the API request fails
+ */
+ public InteractionEventStream Use this for streaming multi-turn conversations or complex input types.
+ *
+ * Example usage with multi-turn conversation:
+ *
+ * Example usage with multimodal content:
+ *
+ * Note: The Interactions API is in beta and subject to change.
+ *
+ * @param model The model name
+ * @param input The Input object (from turns, contents, or string)
+ * @return A stream of InteractionSseEvent objects
+ * @throws IllegalArgumentException if model or input is null
+ * @throws GenAiIOException if the API request fails
+ */
+ public InteractionEventStream This method is primarily used for:
+ *
+ * Example usage for stream resumption:
+ *
+ * Note: The Interactions API is in beta and subject to change.
+ *
+ * @param id The ID of the interaction to retrieve
+ * @param config The configuration for the stream request (can be null)
+ * @return A InteractionEventStream of InteractionSseEvent that can be iterated over
+ * @throws IllegalArgumentException if the ID is empty
+ * @throws GenAiIOException if the API request fails
+ */
+ public InteractionEventStream This is a convenience method that calls {@link #getStream(String, GetInteractionConfig)}
+ * with an empty configuration.
+ *
+ * Use this when you don't need to specify additional configuration like lastEventId for
+ * stream resumption.
+ *
+ * Example usage:
+ *
+ * This method is intended for types that use Jackson's {@code @JsonTypeInfo} and
+ * {@code @JsonSubTypes} annotations for polymorphic deserialization, where the base type may be
+ * an interface.
+ */
+ @InternalApi
+ public static content: The content of the turn as a list of Content objects.
+ */
+ @JsonProperty("content")
+ public abstract Builder content(List content: The content of the turn.
+ */
+ @CanIgnoreReturnValue
+ public Builder content(Content... content) {
+ return content(Arrays.asList(content));
+ }
+
+ /**
+ * Setter for content builder (varargs convenience method).
+ *
+ * content: The content of the turn.
+ */
+ @CanIgnoreReturnValue
+ public Builder content(Content.Builder... contentBuilders) {
+ return content(
+ Arrays.asList(contentBuilders).stream()
+ .map(Content.Builder::build)
+ .collect(toImmutableList()));
+ }
+
+ /** Internal setter for content with Optional. */
+ @ExcludeFromGeneratedCoverageReport
+ abstract Builder content(Optional Removes the content field.
+ */
+ @ExcludeFromGeneratedCoverageReport
+ @CanIgnoreReturnValue
+ public Builder clearContent() {
+ return content(Optional.empty());
+ }
+
+ /**
+ * Setter for role.
+ *
+ * role: The role in the conversation ('user' or 'model').
+ */
+ @JsonProperty("role")
+ public abstract Builder role(String role);
+
+ /** Internal setter for role with Optional. */
+ @ExcludeFromGeneratedCoverageReport
+ abstract Builder role(Optional Removes the role field.
+ */
+ @ExcludeFromGeneratedCoverageReport
+ @CanIgnoreReturnValue
+ public Builder clearRole() {
+ return role(Optional.empty());
+ }
+
+ /** Builds the Turn instance. */
+ public abstract Turn build();
+ }
+
+ /** Deserializes a Turn from a JSON string. */
+ @ExcludeFromGeneratedCoverageReport
+ public static Turn fromJson(String jsonString) {
+ return JsonSerializable.fromJsonString(jsonString, Turn.class);
+ }
+}
diff --git a/src/main/java/com/google/genai/types/interactions/AgentConfig.java b/src/main/java/com/google/genai/types/interactions/AgentConfig.java
new file mode 100644
index 00000000000..cc68fedbda1
--- /dev/null
+++ b/src/main/java/com/google/genai/types/interactions/AgentConfig.java
@@ -0,0 +1,59 @@
+/*
+ * Copyright 2025 Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.genai.types.interactions;
+
+import com.fasterxml.jackson.annotation.JsonSubTypes;
+import com.fasterxml.jackson.annotation.JsonTypeInfo;
+
+/**
+ * Base interface for agent configuration types using a type discriminator.
+ *
+ * AgentConfig is a polymorphic type that configures agent behavior. Alternative to {@code
+ * generation_config}. Only applicable when {@code agent} is set.
+ *
+ * Concrete subtypes:
+ *
+ * Example usage:
+ *
+ * This type matches the Python SDK's AllowedTools:
+ *
+ * Example usage:
+ *
+ * Valid values: "auto", "any", "none", "validated"
+ */
+ @JsonProperty("mode")
+ public abstract Optional mode: The mode of the tool choice. Valid values: "auto", "any", "none", "validated"
+ */
+ @JsonProperty("mode")
+ public abstract Builder mode(String mode);
+
+ @ExcludeFromGeneratedCoverageReport
+ abstract Builder mode(Optional tools: The names of the allowed tools.
+ */
+ @JsonProperty("tools")
+ public abstract Builder tools(List tools: The names of the allowed tools.
+ */
+ @CanIgnoreReturnValue
+ public Builder tools(String... tools) {
+ return tools(Arrays.asList(tools));
+ }
+
+ @ExcludeFromGeneratedCoverageReport
+ abstract Builder tools(Optional Annotations provide attribution for specific segments of text by mapping byte indices to their
+ * source references (such as URLs or titles). This enables proper citation and source tracking for
+ * content generated by the model.
+ *
+ * Example usage:
+ *
+ * The Interactions API is available in both Vertex AI and Gemini API.
+ *
+ * Note: The Interactions API is in beta and subject to change.
+ */
+@AutoValue
+@JsonDeserialize(builder = Annotation.Builder.class)
+public abstract class Annotation extends JsonSerializable {
+
+ /**
+ * Start of segment of the response that is attributed to this source. Index indicates the start
+ * of the segment, measured in bytes.
+ */
+ @JsonProperty("start_index")
+ public abstract Optional startIndex: Start of segment of the response that is attributed to this source.
+ */
+ @JsonProperty("start_index")
+ public abstract Builder startIndex(Integer startIndex);
+
+ @ExcludeFromGeneratedCoverageReport
+ abstract Builder startIndex(Optional endIndex: End of the attributed segment, exclusive.
+ */
+ @JsonProperty("end_index")
+ public abstract Builder endIndex(Integer endIndex);
+
+ @ExcludeFromGeneratedCoverageReport
+ abstract Builder endIndex(Optional source: Source attributed for a portion of the text.
+ */
+ @JsonProperty("source")
+ public abstract Builder source(String source);
+
+ @ExcludeFromGeneratedCoverageReport
+ abstract Builder source(Optional Supports known audio MIME types with extensibility for future formats.
+ */
+public class AudioMimeType {
+
+ /** Enum representing the known audio MIME types. */
+ public enum Known {
+ /** Unspecified or unknown audio MIME type. */
+ AUDIO_MIME_TYPE_UNSPECIFIED("unspecified"),
+
+ /** WAV audio format. */
+ AUDIO_WAV("audio/wav"),
+
+ /** MP3 audio format. */
+ AUDIO_MP3("audio/mp3"),
+
+ /** AIFF audio format. */
+ AUDIO_AIFF("audio/aiff"),
+
+ /** AAC audio format. */
+ AUDIO_AAC("audio/aac"),
+
+ /** OGG audio format. */
+ AUDIO_OGG("audio/ogg"),
+
+ /** FLAC audio format. */
+ AUDIO_FLAC("audio/flac");
+
+ private final String value;
+
+ Known(String value) {
+ this.value = value;
+ }
+
+ @Override
+ public String toString() {
+ return this.value;
+ }
+ }
+
+ private Known mimeTypeEnum;
+ private final String value;
+
+ /**
+ * Constructs an AudioMimeType from a string value.
+ *
+ * @param value The MIME type string (e.g., "audio/mp3")
+ */
+ @JsonCreator
+ public AudioMimeType(String value) {
+ this.value = value;
+ for (Known mimeTypeEnum : Known.values()) {
+ if (Ascii.equalsIgnoreCase(mimeTypeEnum.toString(), value)) {
+ this.mimeTypeEnum = mimeTypeEnum;
+ break;
+ }
+ }
+ if (this.mimeTypeEnum == null) {
+ this.mimeTypeEnum = Known.AUDIO_MIME_TYPE_UNSPECIFIED;
+ }
+ }
+
+ /**
+ * Constructs an AudioMimeType from a known enum value.
+ *
+ * @param knownValue The known MIME type
+ */
+ public AudioMimeType(Known knownValue) {
+ this.mimeTypeEnum = knownValue;
+ this.value = knownValue.toString();
+ }
+
+ @ExcludeFromGeneratedCoverageReport
+ @Override
+ @JsonValue
+ public String toString() {
+ return this.value;
+ }
+
+ @ExcludeFromGeneratedCoverageReport
+ @SuppressWarnings("PatternMatchingInstanceof")
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null) {
+ return false;
+ }
+
+ if (!(o instanceof AudioMimeType)) {
+ return false;
+ }
+
+ AudioMimeType other = (AudioMimeType) o;
+
+ if (this.mimeTypeEnum != Known.AUDIO_MIME_TYPE_UNSPECIFIED
+ && other.mimeTypeEnum != Known.AUDIO_MIME_TYPE_UNSPECIFIED) {
+ return this.mimeTypeEnum == other.mimeTypeEnum;
+ } else if (this.mimeTypeEnum == Known.AUDIO_MIME_TYPE_UNSPECIFIED
+ && other.mimeTypeEnum == Known.AUDIO_MIME_TYPE_UNSPECIFIED) {
+ return this.value.equals(other.value);
+ }
+ return false;
+ }
+
+ @ExcludeFromGeneratedCoverageReport
+ @Override
+ public int hashCode() {
+ if (this.mimeTypeEnum != Known.AUDIO_MIME_TYPE_UNSPECIFIED) {
+ return this.mimeTypeEnum.hashCode();
+ } else {
+ return Objects.hashCode(this.value);
+ }
+ }
+
+ /**
+ * Returns the known enum value if this is a recognized MIME type.
+ *
+ * @return The known enum value
+ */
+ @ExcludeFromGeneratedCoverageReport
+ public Known knownEnum() {
+ return this.mimeTypeEnum;
+ }
+}
diff --git a/src/main/java/com/google/genai/types/interactions/CancelInteractionConfig.java b/src/main/java/com/google/genai/types/interactions/CancelInteractionConfig.java
new file mode 100644
index 00000000000..af6465cb514
--- /dev/null
+++ b/src/main/java/com/google/genai/types/interactions/CancelInteractionConfig.java
@@ -0,0 +1,97 @@
+/*
+ * Copyright 2025 Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.genai.types.interactions;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
+import com.google.auto.value.AutoValue;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
+import com.google.genai.JsonSerializable;
+import com.google.genai.types.ExcludeFromGeneratedCoverageReport;
+import java.util.Optional;
+
+/**
+ * Configuration for canceling an interaction in the Interactions API.
+ *
+ * Optional parameters for the interactions.cancel method.
+ *
+ * Example usage:
+ *
+ * The Interactions API is available in both Vertex AI and Gemini API.
+ *
+ * Note: The Interactions API is in beta and subject to change.
+ */
+@AutoValue
+@JsonDeserialize(builder = CancelInteractionConfig.Builder.class)
+public abstract class CancelInteractionConfig extends JsonSerializable {
+ /** Optional API version to use for this request. Overrides client-level api_version. */
+ @JsonProperty("api_version")
+ public abstract Optional api_version: Optional API version to use for this request.
+ */
+ @JsonProperty("api_version")
+ public abstract Builder apiVersion(String apiVersion);
+
+ @ExcludeFromGeneratedCoverageReport
+ abstract Builder apiVersion(Optional The Interactions API is available in both Vertex AI and Gemini API.
+ *
+ * When to use CreateInteractionConfig:
+ *
+ * For simple use cases, prefer the convenience methods:
+ *
+ * Use CreateInteractionConfig when you need:
+ *
+ * Note: The Interactions API is in beta and subject to change.
+ *
+ * @see com.google.genai.Interactions#create(CreateInteractionConfig)
+ */
+@AutoValue
+@JsonDeserialize(builder = CreateInteractionConfig.Builder.class)
+public abstract class CreateInteractionConfig extends JsonSerializable {
+ /** Optional API version to use for this request. Overrides client-level api_version. */
+ @JsonProperty("api_version")
+ public abstract Optional
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ * {@code
+ * export GOOGLE_API_KEY="YOUR_API_KEY"
+ * unset GOOGLE_CLOUD_PROJECT GOOGLE_CLOUD_LOCATION GOOGLE_GENAI_USE_VERTEXAI
+ * mvn exec:java -Dexec.mainClass="com.google.genai.examples.InteractionsStreamingAgent"
+ * }
+ */
+public class InteractionsStreamingAgent {
+
+ public static void main(String[] args) {
+ try {
+ // Initialize the client
+ Client client = new Client.Builder().build();
+
+ System.out.println("Creating background agent interaction...");
+
+ // Create a background agent interaction
+ CreateInteractionConfig config =
+ CreateInteractionConfig.builder()
+ .agent("deep-research-pro-preview-12-2025")
+ .input("Write a brief summary of quantum computing.")
+ .background(true) // Returns immediately; agent runs in background
+ .build();
+
+ Interaction interaction = client.interactions.create(config);
+
+ System.out.println("Agent started. ID: " + interaction.id());
+ System.out.println("Status: " + interaction.status());
+ System.out.println("\nStreaming output:\n");
+
+ StringBuilder output = new StringBuilder();
+
+ // Stream the agent's progress
+ try (InteractionEventStream
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ * {@code
+ * CreateInteractionConfig config = CreateInteractionConfig.builder()
+ * .model("gemini-2.5-flash")
+ * .input("What is the capital of France?")
+ * .build();
+ * CompletableFuture
+ *
+ * {@code
+ * CreateInteractionConfig config = CreateInteractionConfig.builder()
+ * .agent("deep-research-pro-preview-12-2025")
+ * .input("Research the history of quantum computing")
+ * .build();
+ * CompletableFuture
+ *
+ * {@code
+ * CompletableFuture
+ *
+ * {@code
+ * Input conversation = Input.fromTurns(
+ * Turn.user("What's the weather?"),
+ * Turn.model("I don't have access to weather data."),
+ * Turn.user("Then tell me a joke."));
+ *
+ * CompletableFuture
+ *
+ * {@code
+ * GetInteractionConfig config = GetInteractionConfig.builder().build();
+ * CompletableFuture
+ *
+ * {@code
+ * CancelInteractionConfig config = CancelInteractionConfig.builder().build();
+ * CompletableFuture
+ *
+ * {@code
+ * DeleteInteractionConfig config = DeleteInteractionConfig.builder().build();
+ * CompletableFuture
+ *
+ * {@code
+ * CompletableFuture
+ *
+ * @param id The ID of the interaction to retrieve
+ * @return A CompletableFuture containing the retrieved Interaction
+ */
+ public CompletableFuture{@code
+ * CompletableFuture
+ *
+ * @param id The ID of the interaction to cancel
+ * @return A CompletableFuture containing the updated Interaction
+ */
+ public CompletableFuture{@code
+ * CompletableFuture
+ *
+ * @param id The ID of the interaction to delete
+ * @return A CompletableFuture that completes when the deletion is successful
+ */
+ public CompletableFuture{@code
+ * CreateInteractionConfig config = CreateInteractionConfig.builder()
+ * .model("gemini-2.5-flash")
+ * .input("Tell me a story")
+ * .build();
+ *
+ * client.async.interactions.createStream(config)
+ * .thenAccept(stream -> {
+ * try (stream) {
+ * for (InteractionSseEvent event : stream) {
+ * if (event instanceof ContentDelta deltaEvent) {
+ * Delta delta = deltaEvent.delta().orElse(null);
+ * if (delta instanceof TextDelta textDelta) {
+ * System.out.print(textDelta.text().orElse(""));
+ * }
+ * }
+ * }
+ * }
+ * });
+ * }
+ *
+ * {@code
+ * client.async.interactions.createStream("gemini-2.5-flash", "Tell me a story")
+ * .thenAccept(stream -> {
+ * try (stream) {
+ * for (InteractionSseEvent event : stream) {
+ * if (event instanceof ContentDelta deltaEvent) {
+ * Delta delta = deltaEvent.delta().orElse(null);
+ * if (delta instanceof TextDelta textDelta) {
+ * System.out.print(textDelta.text().orElse(""));
+ * }
+ * }
+ * }
+ * }
+ * });
+ * }
+ *
+ * {@code
+ * Input conversation = Input.fromTurns(
+ * Turn.user("What's the weather?"),
+ * Turn.model("I don't have access to weather data."),
+ * Turn.user("Then tell me a joke."));
+ *
+ * client.async.interactions.createStream("gemini-2.5-flash", conversation)
+ * .thenAccept(stream -> {
+ * // Process streaming events...
+ * });
+ * }
+ *
+ *
+ *
+ *
+ * {@code
+ * GetInteractionConfig resumeConfig = GetInteractionConfig.builder()
+ * .lastEventId(lastEventId)
+ * .build();
+ *
+ * client.async.interactions.getStream(interactionId, resumeConfig)
+ * .thenAccept(stream -> {
+ * try (stream) {
+ * for (InteractionSseEvent event : stream) {
+ * // Continue processing from where we left off...
+ * }
+ * }
+ * });
+ * }
+ *
+ * {@code
+ * try (InteractionEventStream
+ */
+public class InteractionEventStream{@code
+ * CreateInteractionConfig config = CreateInteractionConfig.builder()
+ * .model("gemini-2.5-flash")
+ * .input("What is the capital of France?")
+ * .build();
+ * Interaction response = client.interactions.create(config);
+ * }
+ *
+ * {@code
+ * CreateInteractionConfig config = CreateInteractionConfig.builder()
+ * .agent("deep-research-pro-preview-12-2025")
+ * .input("Research the history of quantum computing")
+ * .build();
+ * Interaction response = client.interactions.create(config);
+ * }
+ *
+ * {@code
+ * CreateInteractionConfig config = CreateInteractionConfig.builder()
+ * .model("gemini-2.5-flash")
+ * .input("What's the weather in Paris?")
+ * .tools(Function.of("getWeather", "Gets weather for a city", schema))
+ * .build();
+ *
+ * Interaction interaction = client.interactions.create(config);
+ *
+ * // Manual loop for function calling
+ * while ("requires_action".equals(interaction.status().toString())) {
+ * // Extract and execute functions manually
+ * List
+ *
+ * {@code
+ * Interaction response = client.interactions.create("gemini-2.5-flash", "What is 2+2?");
+ * System.out.println(response.outputs());
+ * }
+ *
+ * {@code
+ * Input conversation = Input.fromTurns(
+ * Turn.user("Hello! My name is Alice."),
+ * Turn.model("Hello Alice! Nice to meet you."),
+ * Turn.user("What's my name?")
+ * );
+ * Interaction response = client.interactions.create("gemini-2.5-flash", conversation);
+ * }
+ *
+ * {@code
+ * Input input = Input.fromContents(
+ * TextContent.of("Describe this image in detail."),
+ * ImageContent.fromUri("https://example.com/image.jpg", "image/jpeg")
+ * );
+ * Interaction response = client.interactions.create("gemini-2.5-flash", input);
+ * }
+ *
+ * {@code
+ * GetInteractionConfig config = GetInteractionConfig.builder().build();
+ * Interaction interaction = client.interactions.get("interaction-id-123", config);
+ * System.out.println("Status: " + interaction.status());
+ * }
+ *
+ * {@code
+ * CancelInteractionConfig config = CancelInteractionConfig.builder().build();
+ * Interaction cancelled = client.interactions.cancel("interaction-id-123", config);
+ * System.out.println("New status: " + cancelled.status()); // Should be CANCELLED
+ * }
+ *
+ * {@code
+ * DeleteInteractionConfig config = DeleteInteractionConfig.builder().build();
+ * client.interactions.delete("interaction-id-123", config);
+ * System.out.println("Interaction deleted successfully.");
+ * }
+ *
+ * {@code
+ * Interaction interaction = client.interactions.get("interaction-id-123");
+ * System.out.println("Status: " + interaction.status());
+ * }
+ *
+ * @param id The ID of the interaction to retrieve
+ * @return The retrieved Interaction
+ * @throws IllegalArgumentException if the ID is empty
+ * @throws GenAiIOException if the API request fails
+ */
+ public Interaction get(String id) {
+ return get(id, GetInteractionConfig.builder().build());
+ }
+
+ /**
+ * Cancels a background interaction that is still in progress using default configuration.
+ *
+ * {@code
+ * Interaction cancelled = client.interactions.cancel("interaction-id-123");
+ * System.out.println("New status: " + cancelled.status());
+ * }
+ *
+ * @param id The ID of the interaction to cancel
+ * @return The updated Interaction with CANCELLED status
+ * @throws IllegalArgumentException if the ID is empty
+ * @throws GenAiIOException if the API request fails
+ */
+ public Interaction cancel(String id) {
+ return cancel(id, CancelInteractionConfig.builder().build());
+ }
+
+ /**
+ * Deletes an interaction by its ID using default configuration.
+ *
+ * {@code
+ * client.interactions.delete("interaction-id-123");
+ * System.out.println("Interaction deleted successfully.");
+ * }
+ *
+ * @param id The ID of the interaction to delete
+ * @throws IllegalArgumentException if the ID is empty
+ * @throws GenAiIOException if the API request fails
+ */
+ public void delete(String id) {
+ delete(id, DeleteInteractionConfig.builder().build());
+ }
+
+ /**
+ * Creates a new streaming interaction with the specified configuration.
+ *
+ * {@code
+ * CreateInteractionConfig config = CreateInteractionConfig.builder()
+ * .model("gemini-2.5-flash")
+ * .input("Tell me a story")
+ * .build();
+ *
+ * try (ResponseStream
+ *
+ *
+ *
+ *
+ * {@code
+ * try (InteractionEventStream
+ *
+ * {@code
+ * Input conversation = Input.fromTurns(
+ * Turn.user("You are a helpful assistant."),
+ * Turn.model("I'm here to help!"),
+ * Turn.user("Tell me about Java.")
+ * );
+ * try (InteractionEventStream
+ *
+ * {@code
+ * Input input = Input.fromContents(
+ * TextContent.of("Describe this image."),
+ * ImageContent.fromUri("https://example.com/image.jpg", "image/jpeg")
+ * );
+ * try (InteractionEventStream
+ *
+ *
+ *
+ *
+ * {@code
+ * String lastEventId = null;
+ * String interactionId = null;
+ *
+ * // First attempt - connection may be interrupted
+ * try (var stream = client.interactions.createStream(config)) {
+ * for (InteractionSseEvent event : stream) {
+ * lastEventId = event.eventId().orElse(lastEventId);
+ * if (event instanceof InteractionEvent interactionEvent && interactionEvent.isStart()) {
+ * interactionId = interactionEvent.interaction()
+ * .map(Interaction::id)
+ * .orElse(null);
+ * }
+ * // Process event...
+ * }
+ * } catch (Exception e) {
+ * // Connection lost - resume from last known event
+ * GetInteractionConfig resumeConfig = GetInteractionConfig.builder()
+ * .lastEventId(lastEventId)
+ * .build();
+ * try (var stream = client.interactions.getStream(interactionId, resumeConfig)) {
+ * for (InteractionSseEvent event : stream) {
+ * // Continue processing from where we left off...
+ * }
+ * }
+ * }
+ * }
+ *
+ * {@code
+ * // Stream a background interaction
+ * try (var stream = client.interactions.getStream(interactionId)) {
+ * for (InteractionSseEvent event : stream) {
+ * // Process streaming events...
+ * }
+ * }
+ * }
+ *
+ * @param id The ID of the interaction to retrieve as a stream
+ * @return A InteractionEventStream of InteractionSseEvent that can be iterated over
+ * @throws IllegalArgumentException if the ID is empty
+ * @throws GenAiIOException if the API request fails
+ */
+ public InteractionEventStream> content();
+
+ /** Optional. The role in the conversation ('user' or 'model'). */
+ @JsonProperty("role")
+ public abstract Optional
> content);
+
+ /**
+ * Clear method for content.
+ *
+ *
+ *
+ *
+ * {@code
+ * // Dynamic agent configuration
+ * AgentConfig config = DynamicAgentConfig.create();
+ *
+ * // Deep Research agent with thinking summaries
+ * AgentConfig config = DeepResearchAgentConfig.builder()
+ * .thinkingSummaries(new ThinkingSummaries(ThinkingSummaries.Known.AUTO))
+ * .build();
+ *
+ * // Use in CreateInteractionConfig
+ * CreateInteractionConfig interactionConfig = CreateInteractionConfig.builder()
+ * .agent("agent-name")
+ * .input("Your input")
+ * .agentConfig(config)
+ * .build();
+ * }
+ */
+@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
+@JsonSubTypes({
+ @JsonSubTypes.Type(value = DynamicAgentConfig.class, name = "dynamic"),
+ @JsonSubTypes.Type(value = DeepResearchAgentConfig.class, name = "deep-research")
+})
+public interface AgentConfig {}
diff --git a/src/main/java/com/google/genai/types/interactions/AllowedTools.java b/src/main/java/com/google/genai/types/interactions/AllowedTools.java
new file mode 100644
index 00000000000..cc88aa86901
--- /dev/null
+++ b/src/main/java/com/google/genai/types/interactions/AllowedTools.java
@@ -0,0 +1,150 @@
+/*
+ * Copyright 2025 Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.genai.types.interactions;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
+import com.google.auto.value.AutoValue;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
+import com.google.genai.JsonSerializable;
+import com.google.genai.types.ExcludeFromGeneratedCoverageReport;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Optional;
+
+/**
+ * Configuration for allowed tools in an MCP server.
+ *
+ *
+ * class AllowedTools(BaseModel):
+ * mode: Optional[ToolChoiceType] = None # Literal["auto", "any", "none", "validated"]
+ * tools: Optional[List[str]] = None
+ *
+ *
+ * {@code
+ * AllowedTools allowedTools = AllowedTools.builder()
+ * .mode("auto")
+ * .tools("get_weather", "get_forecast")
+ * .build();
+ * }
+ */
+@AutoValue
+@JsonDeserialize(builder = AllowedTools.Builder.class)
+public abstract class AllowedTools extends JsonSerializable {
+
+ /**
+ * The mode of the tool choice.
+ *
+ * > tools();
+
+ /** Instantiates a builder for AllowedTools. */
+ @ExcludeFromGeneratedCoverageReport
+ public static Builder builder() {
+ return new AutoValue_AllowedTools.Builder();
+ }
+
+ /** Creates a builder with the same values as this instance. */
+ public abstract Builder toBuilder();
+
+ /** Builder for AllowedTools. */
+ @AutoValue.Builder
+ public abstract static class Builder {
+ /** For internal usage. Please use {@code AllowedTools.builder()} for instantiation. */
+ @JsonCreator
+ private static Builder create() {
+ return new AutoValue_AllowedTools.Builder();
+ }
+
+ /**
+ * Setter for mode.
+ *
+ *
> tools);
+
+ /** Clears the value of tools field. */
+ @ExcludeFromGeneratedCoverageReport
+ @CanIgnoreReturnValue
+ public Builder clearTools() {
+ return tools(Optional.empty());
+ }
+
+ public abstract AllowedTools build();
+ }
+
+ /** Deserializes a JSON string to an AllowedTools object. */
+ @ExcludeFromGeneratedCoverageReport
+ public static AllowedTools fromJson(String jsonString) {
+ return JsonSerializable.fromJsonString(jsonString, AllowedTools.class);
+ }
+
+ /** Convenience factory method. */
+ @ExcludeFromGeneratedCoverageReport
+ public static AllowedTools of(String mode, List
{@code
+ * Annotation citation = Annotation.builder()
+ * .startIndex(0)
+ * .endIndex(50)
+ * .source("https://example.com/research-paper")
+ * .build();
+ *
+ * // Or using the convenience factory method
+ * Annotation citation2 = Annotation.of(51, 100, "Wikipedia: Machine Learning");
+ * }
+ *
+ * {@code
+ * CancelInteractionConfig config = CancelInteractionConfig.builder()
+ * .apiVersion("v1alpha")
+ * .build();
+ * client.interactions.cancel("interaction-id", config);
+ * }
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *