diff --git a/GEMINI.md b/GEMINI.md new file mode 100644 index 00000000000..c2c2e40f9f2 --- /dev/null +++ b/GEMINI.md @@ -0,0 +1,83 @@ +--- +trigger: always_on +description: Read this file when working on the GenAI Java SDK +--- + +> [!IMPORTANT] When working in this directory, you must also read the +> generator's context file at `google3/google/cloud/aiplatform/sdk/GEMINI.md`. + +# Java SDK for Google GenAI + +This directory contains the Java SDK for the Google GenAI project. It is designed to provide a Java interface for interacting with Gemini models, supporting both the Gemini Developer API (MLDev) and Gemini Enterprise Agent Platform API (Vertex AI). + +## Project Overview + +The Java SDK is largely auto-generated based on API discovery documents. However, it also includes hand-written core infrastructure to support authentication, HTTP communication, and custom serialization needs. + +### Relationship to the Central Generator + +As described in `google3/google/cloud/aiplatform/sdk/GEMINI.md`, this SDK is produced by the central Python-based multi-language SDK generator located at `//google/cloud/aiplatform/sdk/generator`. +- Language-specific logic for Java is contained in `java_generator.py` and `java_datatypes.py` (in the generator directory). +- The generator produces data classes and API methods based on discovery docs and configuration. +- **Important**: The generator updates files in `src/private` from files in `src/main`. Do NOT edit files in `src/private` directly. + +## Architecture and Key Components + +### Hand-written Core Files + +The following files in `src/main/java/com/google/genai/` are hand-written and form the core infrastructure of the SDK: + +- **`Client.java`**: The main entry point for the SDK. It provides access to all services (Models, Chats, Files, etc.) in both synchronous and asynchronous modes. Handles initialization with API keys or credentials. +- **`ApiClient.java`**: An abstract base class for issuing HTTP requests. It handles request building, URL construction, header execution (including auth), and OkHttpClient configuration. +- **`HttpApiClient.java`**: The default concrete implementation of `ApiClient` that uses OkHttp to make real network calls. +- **`ApiResponse.java`**: A simple wrapper around the HTTP response, providing access to status code, headers, and body content. +- **`Common.java`**: Contains utility methods for setting and getting values by path in JSON objects, URL encoding, and other common tasks. +- **`JsonSerializable.java`**: Provides base functionality for JSON serialization and deserialization using Jackson. +- **`Transformers.java`**: Contains static methods to transform parameters and types to match API expectations (e.g., converting model names to resource paths). +- **`ResponseStream.java`**: Manages streaming responses, ensuring SSE compliance and detecting application-level errors. +- **`ReplayApiClient.java`**: A testing-specific implementation of `ApiClient` that reads responses from replay files instead of making network calls. +- **`ReplayApiResponse.java`**: Used with `ReplayApiClient` to represent mocked responses. +- **`Chat.java`, `AsyncChat.java`, `ChatBase.java`**: Manage multi-turn chat sessions and history. +- **`UploadClient.java`**: Handles resumable file uploads to the File API. +- **`GoogleCredentialsHttpClient.java`**: Handles authentication using Google Credentials (typically for Vertex AI). +- **`AfcUtil.java`**: Utilities for Auto-Function Calling. + +### Custom Serialization (`CustomDurationDeserializer`) + +To handle API response fields that return duration as a string with an 's' suffix (e.g., "3.5s"), the SDK uses a custom deserializer in `JsonSerializable.java`: `CustomDurationDeserializer`. +- This deserializer ensures that fields mapped to `java.time.Duration` in Java can be successfully decoded from JSON. +- It parses the numeric part and creates a `Duration` instance. +- `JsonSerializable` also includes a `CustomDurationSerializer` to output the same format when serializing. + +## Development and Testing + +### Running Tests + +The project uses Maven for building and testing. + +To run all unit tests, you must set the environment variable for replay tests: + +```bash +export GOOGLE_GENAI_REPLAYS_DIRECTORY="`blaze info workspace`/google/cloud/aiplatform/sdk/genai/replays" +mvn clean test +``` + +### Running Examples + +Examples are located in `examples/`. To run all examples (recommended before release): +```bash +./run_examples.sh +``` + +## Modifying the SDK + +- **For changes to generated code**: Do NOT edit the generated files directly in `src/private`. Modify the generator configuration or templates in `//google/cloud/aiplatform/sdk/` or modify files in `src/main` and then run the generator: + ```bash + google/cloud/aiplatform/sdk/generator/run_generator.sh --langs java + ``` +- **For changes to core infrastructure**: Modify the hand-written files in `src/main`. +- **Knowledge Sharing**: Every time you make a code change in this Java GenAI SDK, try to add useful knowledge into this `GEMINI.md` file if it is necessary or helpful for future maintainers (e.g., documenting new hand-written files, custom serialization patterns, or specific workflow gotchas). + +## Legacy Names + +- Similar to other SDKs, you might still find legacy names like "mldev" (representing Gemini API) or "vertex" (representing Gemini Enterprise Agent Platform API) in generator code and test files. diff --git a/README.md b/README.md index de01de37a6c..47233672678 100644 --- a/README.md +++ b/README.md @@ -3,8 +3,6 @@ Java idiomatic SDK for the [Gemini Developer APIs][gemini-api-doc] and [Gemini Enterprise Agent Platform][gemini-enterprise-agent-platform-doc] APIs. -**Note:** The SDK now has experimental support for the [Interactions API](#interactions-experimental). - [![Maven][maven-version-image]][maven-version-link] [![Javadoc][javadoc-image]][javadoc-link] @@ -18,7 +16,7 @@ If you're using Maven, add the following to your dependencies: com.google.genai google-genai - 1.53.0 + 1.47.0 ``` @@ -31,8 +29,8 @@ SDK for Java. ### Create a client The Google Gen AI Java SDK provides a Client class, simplifying interaction -with both the Gemini API and Gemini Enterprise Agent Platform API. With minimal -configuration, you can seamlessly switch between the 2 backends without rewriting +with both the Gemini API and Vertex AI API. With minimal configuration, +you can seamlessly switch between the 2 backends without rewriting your code. #### Instantiate a client that uses Gemini API @@ -44,7 +42,7 @@ import com.google.genai.Client; Client client = Client.builder().apiKey("your-api-key").build(); ``` -#### Instantiate a client that uses Gemini Enterprise Agent Platform API +#### Instantiate a client that uses Vertex AI API ##### Using project and location @@ -52,24 +50,24 @@ Client client = Client.builder().apiKey("your-api-key").build(); import com.google.genai.Client; // Use Builder class for instantiation. Explicitly set the project and location, -// and set `enterprise(true)` to use Gemini Enterprise Agent Platform backend. +// and set `vertexAI(true)` to use Vertex AI backend. Client client = Client.builder() .project("your-project") .location("your-location") - .enterprise(true) + .vertexAI(true) .build(); ``` -##### Using API key on Gemini Enterprise Agent Platform (GCP Express Mode) +##### Using API key on Vertex AI (GCP Express Mode) ```java import com.google.genai.Client; -// Explicitly set the `apiKey` and `enterprise(true)` to use Gemini Enterprise Agent Platform backend +// Explicitly set the `apiKey` and `vertexAI(true)` to use Vertex AI backend // in express mode. Client client = Client.builder() .apiKey("your-api-key") - .enterprise(true) + .vertexAI(true) .build(); ``` @@ -77,7 +75,7 @@ Client client = Client.builder() You can create a client by configuring the necessary environment variables. Configuration setup instructions depends on whether you're using the Gemini -Developer API or the Gemini API in Gemini Enterprise Agent Platform. +Developer API or the Gemini API in Vertex AI. **Gemini Developer API:** Set the `GOOGLE_API_KEY`. It will automatically be picked up by the client. Note that `GEMINI_API_KEY` is a legacy environment @@ -88,16 +86,15 @@ variable, it's recommended to use `GOOGLE_API_KEY` only. But if both are set, export GOOGLE_API_KEY='your-api-key' ``` -**Gemini API on Gemini Enterprise Agent Platform:** Set `GOOGLE_GENAI_USE_ENTERPRISE`, +**Gemini API on Vertex AI:** Set `GOOGLE_GENAI_USE_VERTEXAI`, `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION`, or `GOOGLE_API_KEY` for -Gemini Enterprise Agent Platform express mode. It's recommended that you set -only project & location, or API key. But if both are set, project & location -takes precedence. +Vertex AI express mode. It's recommended that you set only project & location, +or API key. But if both are set, project & location takes precedence. ```bash -export GOOGLE_GENAI_USE_ENTERPRISE=true +export GOOGLE_GENAI_USE_VERTEXAI=true -// Set project and location for Gemini Enterprise Agent Platform authentication +// Set project and location for Vertex AI authentication export GOOGLE_CLOUD_PROJECT='your-project-id' export GOOGLE_CLOUD_LOCATION='us-central1' // or API key for express mode @@ -120,7 +117,7 @@ preview features in the APIs. The stable API endpoints can be selected by setting the API version to `v1`. To set the API version use `HttpOptions`. For example, to set the API version to -`v1` for Gemini Enterprise Agent Platform: +`v1` for Vertex AI: ```java import com.google.genai.Client; @@ -129,7 +126,7 @@ import com.google.genai.types.HttpOptions; Client client = Client.builder() .project("your-project") .location("your-location") - .enterprise(true) + .vertexAI(true) .httpOptions(HttpOptions.builder().apiVersion("v1")) .build(); ``` @@ -287,10 +284,10 @@ import com.google.genai.types.Part; public class GenerateContentWithImageInput { public static void main(String[] args) { - // Instantiate the client using Gemini Enterprise Agent Platform API. The client gets the project and + // Instantiate the client using Vertex API. The client gets the project and // location from the environment variables `GOOGLE_CLOUD_PROJECT` and // `GOOGLE_CLOUD_LOCATION`. - Client client = Client.builder().enterprise(true).build(); + Client client = Client.builder().vertexAI(true).build(); // Construct a multimodal content with quick constructors Content content = @@ -566,7 +563,7 @@ public class CountTokens { ``` The `computeTokens` method returns the Tokens Info that contains tokens and -token IDs given your prompt. This method is only supported in Gemini Enterprise Agent Platform. +token IDs given your prompt. This method is only supported in Vertex AI. ```java package ; @@ -576,7 +573,7 @@ import com.google.genai.types.ComputeTokensResponse; public class ComputeTokens { public static void main(String[] args) { - Client client = Client.builder().enterprise(true).build(); + Client client = Client.builder().vertexAI(true).build(); ComputeTokensResponse response = client.models.computeTokens("gemini-2.5-flash", "What is your name?", null); @@ -589,7 +586,7 @@ public class ComputeTokens { #### Embed Content The `embedContent` method allows you to generate embeddings for words, phrases, -sentences, and code, as well as multimodal content like images or videos via Gemini Enterprise Agent Platform. +sentences, and code, as well as multimodal content like images or videos via Vertex AI. ```java package ; @@ -607,8 +604,8 @@ public class EmbedContent { System.out.println("Embedding response: " + response); - // Multimodal embedding with Gemini Enterprise Agent Platform - Client enterpriseClient = Client.builder().enterprise(true).build(); + // Multimodal embedding with Vertex AI + Client vertexClient = Client.builder().vertexAI(true).build(); EmbedContentConfig config = EmbedContentConfig.builder() .outputDimensionality(10) @@ -617,7 +614,7 @@ public class EmbedContent { .build(); EmbedContentResponse mmResponse = - enterpriseClient.models.embedContent( + vertexClient.models.embedContent( "gemini-embedding-2-exp-11-2025", Content.fromParts( Part.fromText("Hello"), @@ -672,7 +669,7 @@ public class GenerateImages { #### Upscale Image The `upscaleImage` method allows you to upscale an image. This feature is only -supported in Gemini Enterprise Agent Platform. +supported in Vertex AI. ```java package ; @@ -684,7 +681,7 @@ import com.google.genai.types.UpscaleImageResponse; public class UpscaleImage { public static void main(String[] args) { - Client client = Client.builder().enterprise(true).build(); + Client client = Client.builder().vertexAI(true).build(); Image image = Image.fromFile("path/to/your/image"); @@ -715,7 +712,7 @@ The `editImage` method lets you edit an image. You can input reference images addition to a text prompt to guide the editing. This feature uses a different model than `generateImages` and `upscaleImage`. It -is only supported in Gemini Enterprise Agent Platform. +is only supported in Vertex AI. ```java package ; @@ -734,7 +731,7 @@ import java.util.ArrayList; public class EditImage { public static void main(String[] args) { - Client client = Client.builder().enterprise(true).build(); + Client client = Client.builder().vertexAI(true).build(); Image image = Image.fromFile("path/to/your/image"); @@ -975,57 +972,6 @@ public final class FileOperations { } ``` -### Interactions (Experimental) - -The `interactions` service provides access to experimental features. - -> [!WARNING] -> This service is experimental and subject to change or removal in future releases. - -You can access it via the client: -```java -client.interactions -``` -or asynchronously: -```java -client.async.interactions -``` - -### Example: Create Interaction - -This example demonstrates creating a simple model interaction. - -```java -import com.google.genai.Client; -import com.google.genai.interactions.models.interactions.Content; -import com.google.genai.interactions.models.interactions.CreateModelInteractionParams; -import com.google.genai.interactions.models.interactions.Interaction; -import com.google.genai.interactions.models.interactions.Model; - -Client client = new Client(); - -CreateModelInteractionParams params = - CreateModelInteractionParams.builder() - .input("Why is the sky blue?") - .model(Model.GEMINI_2_5_FLASH) - .build(); - -Interaction interaction = client.interactions.create(params); - -System.out.println("Interaction ID: " + interaction.id()); -System.out.println("Status: " + interaction.status()); - -// Print the text outputs from the interaction. -interaction.outputs().ifPresent(outputs -> { - for (Content output : outputs) { - output.text().ifPresent(text -> System.out.println("Output: " + text.text())); - } -}); -``` - -For more examples, see `interactions*` in the [examples directory](https://github.com/googleapis/java-genai/tree/main/examples/). - - ## Versioning @@ -1040,7 +986,7 @@ The Google Gen AI Java SDK will accept contributions in the future. Apache 2.0 - See [LICENSE][license] for more information. [gemini-api-doc]: https://ai.google.dev/gemini-api/docs -[gemini-enterprise-agent-platform-doc]: https://docs.cloud.google.com/gemini-enterprise-agent-platform +[vertex-api-doc]: https://cloud.google.com/vertex-ai/generative-ai/docs/learn/overview [maven-version-image]: https://img.shields.io/maven-central/v/com.google.genai/google-genai.svg [maven-version-link]: https://central.sonatype.com/artifact/com.google.genai/google-genai [javadoc-image]: https://img.shields.io/badge/JavaDoc-Online-green diff --git a/examples/src/main/java/com/google/genai/examples/InteractionBasic.java b/examples/src/main/java/com/google/genai/examples/InteractionBasic.java deleted file mode 100644 index 1cd3d78dcdc..00000000000 --- a/examples/src/main/java/com/google/genai/examples/InteractionBasic.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright 2026 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: - * - *

1a. If you are using Vertex AI, setup ADC to get credentials: - * https://cloud.google.com/docs/authentication/provide-credentials-adc#google-idp - * - *

Then set Project, Location, and USE_VERTEXAI flag as environment variables: - * - *

export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT - * - *

export GOOGLE_CLOUD_LOCATION=YOUR_LOCATION - * - *

export GOOGLE_GENAI_USE_VERTEXAI=true - * - *

1b. If you are using Gemini Developer API, 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 exec:java -Dexec.mainClass="com.google.genai.examples.InteractionBasic" - */ -package com.google.genai.examples; - -import com.google.genai.Client; -import com.google.genai.interactions.models.interactions.Content; -import com.google.genai.interactions.models.interactions.CreateModelInteractionParams; -import com.google.genai.interactions.models.interactions.Interaction; -import com.google.genai.interactions.models.interactions.Model; -import com.google.genai.interactions.models.interactions.Step; - -/** An example of using the Unified Gen AI Java SDK to create a basic interaction. */ -public final class InteractionBasic { - public static void main(String[] args) { - Client client = new Client(); - - if (client.vertexAI()) { - System.out.println("Interactions API is not yet supported on Vertex"); - return; - } - - System.out.println("Using Gemini Developer API"); - - CreateModelInteractionParams params = - CreateModelInteractionParams.builder() - .input("Why is the sky blue?") - .model(Model.GEMINI_2_5_FLASH) - .build(); - - Interaction interaction = client.interactions.create(params); - - System.out.println("Interaction ID: " + interaction.id()); - System.out.println("Status: " + interaction.status()); - - // Print the text outputs from the interaction. - for (Step step : interaction.steps()) { - if (step.isModelOutput()) { - step.asModelOutput() - .content() - .ifPresent( - contents -> { - for (Content content : contents) { - content - .text() - .ifPresent(text -> System.out.println("Output: " + text.text())); - } - }); - } - } - } - - private InteractionBasic() {} -} diff --git a/examples/src/main/java/com/google/genai/examples/InteractionCreate.java b/examples/src/main/java/com/google/genai/examples/InteractionCreate.java deleted file mode 100644 index 52f4597c5b6..00000000000 --- a/examples/src/main/java/com/google/genai/examples/InteractionCreate.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright 2026 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: - * - *

1a. If you are using Vertex AI, setup ADC to get credentials: - * https://cloud.google.com/docs/authentication/provide-credentials-adc#google-idp - * - *

Then set Project, Location, and USE_VERTEXAI flag as environment variables: - * - *

export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT - * - *

export GOOGLE_CLOUD_LOCATION=YOUR_LOCATION - * - *

export GOOGLE_GENAI_USE_VERTEXAI=true - * - *

1b. If you are using Gemini Developer API, 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 exec:java -Dexec.mainClass="com.google.genai.examples.InteractionCreate" - */ -package com.google.genai.examples; - -import com.google.genai.Client; -import com.google.genai.interactions.models.interactions.Content; -import com.google.genai.interactions.models.interactions.CreateModelInteractionParams; -import com.google.genai.interactions.models.interactions.Interaction; -import com.google.genai.interactions.models.interactions.Model; -import com.google.genai.interactions.models.interactions.Step; - -/** An example of using the Unified Gen AI Java SDK to create an interaction. */ -public final class InteractionCreate { - public static void main(String[] args) { - // Instantiate the client. The client by default uses the Gemini Developer API. It gets the API - // key from the environment variable `GOOGLE_API_KEY`. Vertex AI API can be used by setting the - // environment variables `GOOGLE_CLOUD_LOCATION` and `GOOGLE_CLOUD_PROJECT`, as well as setting - // `GOOGLE_GENAI_USE_VERTEXAI` to "true". - // - // Note: Some services are only available in a specific API backend (Gemini or Vertex), you will - // get a `UnsupportedOperationException` if you try to use a service that is not available in - // the backend you are using. - Client client = new Client(); - - if (client.vertexAI()) { - System.out.println("Using Vertex AI"); - } else { - System.out.println("Using Gemini Developer API"); - } - - CreateModelInteractionParams params = - CreateModelInteractionParams.builder() - .input("What is your name?") - .model(Model.GEMINI_2_5_FLASH) - .build(); - - Interaction interaction = client.interactions.create(params); - - System.out.println("Interaction ID: " + interaction.id()); - System.out.println("Status: " + interaction.status()); - - // Print the text outputs from the interaction. - for (Step step : interaction.steps()) { - if (step.isModelOutput()) { - step.asModelOutput() - .content() - .ifPresent( - contents -> { - for (Content content : contents) { - content - .text() - .ifPresent(text -> System.out.println("Output: " + text.text())); - } - }); - } - } - } - - private InteractionCreate() {} -} diff --git a/examples/src/main/java/com/google/genai/examples/InteractionCreateAsync.java b/examples/src/main/java/com/google/genai/examples/InteractionCreateAsync.java deleted file mode 100644 index 19b5144a602..00000000000 --- a/examples/src/main/java/com/google/genai/examples/InteractionCreateAsync.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright 2026 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: - * - *

1a. If you are using Vertex AI, setup ADC to get credentials: - * https://cloud.google.com/docs/authentication/provide-credentials-adc#google-idp - * - *

Then set Project, Location, and USE_VERTEXAI flag as environment variables: - * - *

export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT - * - *

export GOOGLE_CLOUD_LOCATION=YOUR_LOCATION - * - *

export GOOGLE_GENAI_USE_VERTEXAI=true - * - *

1b. If you are using Gemini Developer API, 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 exec:java - * -Dexec.mainClass="com.google.genai.examples.InteractionCreateAsync" - */ -package com.google.genai.examples; - -import com.google.genai.Client; -import com.google.genai.interactions.models.interactions.Content; -import com.google.genai.interactions.models.interactions.CreateModelInteractionParams; -import com.google.genai.interactions.models.interactions.Interaction; -import com.google.genai.interactions.models.interactions.Model; -import com.google.genai.interactions.models.interactions.Step; -import java.util.concurrent.CompletableFuture; - -/** An example of using the Unified Gen AI Java SDK to create an interaction asynchronously. */ -public final class InteractionCreateAsync { - public static void main(String[] args) { - // Instantiate the client. The client by default uses the Gemini Developer API. It gets the API - // key from the environment variable `GOOGLE_API_KEY`. Vertex AI API can be used by setting the - // environment variables `GOOGLE_CLOUD_LOCATION` and `GOOGLE_CLOUD_PROJECT`, as well as setting - // `GOOGLE_GENAI_USE_VERTEXAI` to "true". - // - // Note: Some services are only available in a specific API backend (Gemini or Vertex), you will - // get a `UnsupportedOperationException` if you try to use a service that is not available in - // the backend you are using. - Client client = new Client(); - - if (client.vertexAI()) { - System.out.println("Using Vertex AI"); - } else { - System.out.println("Using Gemini Developer API"); - } - - CreateModelInteractionParams params = - CreateModelInteractionParams.builder() - .input("What is your name?") - .model(Model.GEMINI_2_5_FLASH) - .build(); - - CompletableFuture interactionFuture = client.async.interactions.create(params); - - interactionFuture - .thenAccept( - interaction -> { - System.out.println("Interaction ID: " + interaction.id()); - System.out.println("Status: " + interaction.status()); - - // Print the text outputs from the interaction. - for (Step step : interaction.steps()) { - if (step.isModelOutput()) { - step.asModelOutput() - .content() - .ifPresent( - contents -> { - for (Content content : contents) { - content - .text() - .ifPresent( - text -> System.out.println("Output: " + text.text())); - } - }); - } - } - }) - .join(); - } - - private InteractionCreateAsync() {} -} diff --git a/examples/src/main/java/com/google/genai/examples/InteractionCreateAsyncStreaming.java b/examples/src/main/java/com/google/genai/examples/InteractionCreateAsyncStreaming.java deleted file mode 100644 index 254b6c86d0d..00000000000 --- a/examples/src/main/java/com/google/genai/examples/InteractionCreateAsyncStreaming.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright 2026 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: - * - *

1a. If you are using Vertex AI, setup ADC to get credentials: - * https://cloud.google.com/docs/authentication/provide-credentials-adc#google-idp - * - *

Then set Project, Location, and USE_VERTEXAI flag as environment variables: - * - *

export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT - * - *

export GOOGLE_CLOUD_LOCATION=YOUR_LOCATION - * - *

export GOOGLE_GENAI_USE_VERTEXAI=true - * - *

1b. If you are using Gemini Developer API, 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 exec:java - * -Dexec.mainClass="com.google.genai.examples.InteractionCreateAsyncStreaming" - */ -package com.google.genai.examples; - -import com.google.genai.Client; -import com.google.genai.interactions.models.interactions.CreateModelInteractionParams; -import com.google.genai.interactions.models.interactions.Model; - -/** - * An example of using the Unified Gen AI Java SDK to create a streaming interaction asynchronously. - */ -public final class InteractionCreateAsyncStreaming { - public static void main(String[] args) { - // Instantiate the client. The client by default uses the Gemini Developer API. It gets the API - // key from the environment variable `GOOGLE_API_KEY`. Vertex AI API can be used by setting the - // environment variables `GOOGLE_CLOUD_LOCATION` and `GOOGLE_CLOUD_PROJECT`, as well as setting - // `GOOGLE_GENAI_USE_VERTEXAI` to "true". - // - // Note: Some services are only available in a specific API backend (Gemini or Vertex), you will - // get a `UnsupportedOperationException` if you try to use a service that is not available in - // the backend you are using. - Client client = new Client(); - - if (client.vertexAI()) { - System.out.println("Using Vertex AI"); - } else { - System.out.println("Using Gemini Developer API"); - } - - CreateModelInteractionParams params = - CreateModelInteractionParams.builder() - .input("Tell me a story in 300 words.") - .model(Model.GEMINI_2_5_FLASH) - .build(); - - System.out.println("Streaming response:"); - client - .async - .interactions - .createStreaming(params) - .subscribe( - event -> - event - .stepDelta() - .map(stepDelta -> stepDelta.delta()) - .flatMap(delta -> delta.text()) - .map(text -> text.text()) - .ifPresent(System.out::print)) - // Wait for the stream to complete. - .onCompleteFuture() - .join(); - System.out.println(); - - client.close(); - } - - private InteractionCreateAsyncStreaming() {} -} diff --git a/examples/src/main/java/com/google/genai/examples/InteractionCreateStreaming.java b/examples/src/main/java/com/google/genai/examples/InteractionCreateStreaming.java deleted file mode 100644 index 24e1f175262..00000000000 --- a/examples/src/main/java/com/google/genai/examples/InteractionCreateStreaming.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright 2026 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: - * - *

1a. If you are using Vertex AI, setup ADC to get credentials: - * https://cloud.google.com/docs/authentication/provide-credentials-adc#google-idp - * - *

Then set Project, Location, and USE_VERTEXAI flag as environment variables: - * - *

export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT - * - *

export GOOGLE_CLOUD_LOCATION=YOUR_LOCATION - * - *

export GOOGLE_GENAI_USE_VERTEXAI=true - * - *

1b. If you are using Gemini Developer API, 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 exec:java - * -Dexec.mainClass="com.google.genai.examples.InteractionCreateStreaming" - */ -package com.google.genai.examples; - -import com.google.genai.Client; -import com.google.genai.interactions.core.http.StreamResponse; -import com.google.genai.interactions.models.interactions.CreateModelInteractionParams; -import com.google.genai.interactions.models.interactions.InteractionSseEvent; -import com.google.genai.interactions.models.interactions.Model; - -/** - * An example of using the Unified Gen AI Java SDK to create a streaming interaction synchronously. - */ -public final class InteractionCreateStreaming { - public static void main(String[] args) { - // Instantiate the client. The client by default uses the Gemini Developer API. It gets the API - // key from the environment variable `GOOGLE_API_KEY`. Vertex AI API can be used by setting the - // environment variables `GOOGLE_CLOUD_LOCATION` and `GOOGLE_CLOUD_PROJECT`, as well as setting - // `GOOGLE_GENAI_USE_VERTEXAI` to "true". - // - // Note: Some services are only available in a specific API backend (Gemini or Vertex), you will - // get a `UnsupportedOperationException` if you try to use a service that is not available in - // the backend you are using. - Client client = new Client(); - - if (client.vertexAI()) { - System.out.println("Using Vertex AI"); - } else { - System.out.println("Using Gemini Developer API"); - } - - CreateModelInteractionParams params = - CreateModelInteractionParams.builder() - .input("Tell me a story in 300 words.") - .model(Model.GEMINI_2_5_FLASH) - .build(); - - try (StreamResponse streamResponse = - client.interactions.createStreaming(params)) { - System.out.println("Streaming response:"); - streamResponse.stream() - .flatMap(event -> event.stepDelta().stream()) - .map(stepDelta -> stepDelta.delta()) - .flatMap(delta -> delta.text().stream()) - .map(text -> text.text()) - .forEach(System.out::print); - System.out.println(); - } - } - - private InteractionCreateStreaming() {} -} diff --git a/examples/src/main/java/com/google/genai/examples/InteractionDeepResearch.java b/examples/src/main/java/com/google/genai/examples/InteractionDeepResearch.java deleted file mode 100644 index 8653f287249..00000000000 --- a/examples/src/main/java/com/google/genai/examples/InteractionDeepResearch.java +++ /dev/null @@ -1,167 +0,0 @@ -/* - * Copyright 2026 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: - * - *

Deep Research is currently only available on Vertex AI. - * - *

1. Setup ADC to get credentials: - * https://cloud.google.com/docs/authentication/provide-credentials-adc#google-idp - * - *

2. Set Project, Location, and USE_VERTEXAI flag as environment variables: - * - *

export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT - * - *

export GOOGLE_CLOUD_LOCATION=global - * - *

export GOOGLE_GENAI_USE_VERTEXAI=true - * - *

3. Compile the java package and run the sample code. - * - *

mvn clean compile exec:java - * -Dexec.mainClass="com.google.genai.examples.InteractionDeepResearch" - */ -package com.google.genai.examples; - -import com.google.genai.Client; -import com.google.genai.interactions.core.ClientOptions; -import com.google.genai.interactions.core.RequestOptions; -import com.google.genai.interactions.core.http.StreamResponse; -import com.google.genai.interactions.models.interactions.CreateAgentInteractionParams; -import com.google.genai.interactions.models.interactions.InteractionSseEvent; -import com.google.genai.interactions.services.blocking.InteractionService; -import java.time.Duration; -import java.util.concurrent.atomic.AtomicReference; - -/** - * An example of using the Unified Gen AI Java SDK to run a Deep Research interaction on Vertex AI. - */ -public final class InteractionDeepResearch { - public static void main(String[] args) { - // Instantiate the client. Deep Research requires Vertex AI. - // Ensure GOOGLE_CLOUD_PROJECT, GOOGLE_CLOUD_LOCATION=global, and - // GOOGLE_GENAI_USE_VERTEXAI=true are set in your environment. - Client client = new Client(); - - if (!client.vertexAI()) { - System.err.println("Deep Research is only supported on Vertex AI. " - + "Please set GOOGLE_GENAI_USE_VERTEXAI=true."); - return; - } - - System.out.println( - "Using Vertex AI Project: " + (client.project() != null ? client.project() : "unknown")); - - CreateAgentInteractionParams params = - CreateAgentInteractionParams.builder() - .agent("deep-research-pro-preview-12-2025") - .input("I want to learn more about the history of Hadrian's Wall") - .background(true) - .stream(true) - .build(); - - AtomicReference interactionId = new AtomicReference<>(); - RequestOptions options = RequestOptions.builder().timeout(Duration.ofHours(1)).build(); - - System.out.println("--- Starting Deep Research Interaction ---"); - InteractionService interactions = - client.interactions.withOptions( - b -> { - ClientOptions.Builder unused = - b.apiVersion("v1beta1"); - }); - - try (StreamResponse streamResponse = - interactions.createStreaming(params, options)) { - // We consume the first few events to capture the Interaction ID and see progress. - streamResponse.stream() - .limit(1) - .forEach( - event -> { - if (event.isCreated()) { - String id = event.asCreated().interaction().id(); - interactionId.set(id); - System.out.println("Started Interaction ID: " + id); - } - String eventType = "unknown"; - if (event.isCreated()) { - eventType = "interaction.created"; - } else if (event.isCompleted()) { - eventType = "interaction.completed"; - } else if (event.isStatusUpdate()) { - eventType = "interaction.status_update"; - } else if (event.isStepStart()) { - eventType = "step.start"; - } else if (event.isStepDelta()) { - eventType = "step.delta"; - } else if (event.isStepStop()) { - eventType = "step.stop"; - } else if (event.isError()) { - eventType = "error"; - } - - System.out.println("Event type: " + eventType); - }); - } - - String id = interactionId.get(); - if (id == null) { - System.err.println("Failed to capture interaction ID."); - return; - } - - // Deep research can take a long time. In a real application, you might poll or resume later. - // Here we resume the stream to wait for more output. - System.out.println("\n--- Resuming Interaction: " + id + " ---"); - try (StreamResponse getStream = - interactions.getStreaming(id, options)) { - getStream.stream() - .forEach( - event -> { - if (event.isStatusUpdate()) { - System.out.println( - "\n[Status update: " + event.asStatusUpdate().status().known() + "]"); - } - - event - .stepDelta() - .ifPresent( - delta -> { - delta - .delta() - .text() - .ifPresentOrElse( - text -> System.out.print(text.text()), - () -> { - // If it's a content delta but doesn't have text (e.g. tool call - // or thought), print it. - System.out.println( - "\n[Agent Activity]: " - + delta - .delta() - ._json() - .map(Object::toString) - .orElse("Unknown activity")); - }); - }); - }); - System.out.println(); - } - } - - private InteractionDeepResearch() {} -} diff --git a/examples/src/main/java/com/google/genai/examples/InteractionFunctionCallingClientState.java b/examples/src/main/java/com/google/genai/examples/InteractionFunctionCallingClientState.java deleted file mode 100644 index a3f87d86326..00000000000 --- a/examples/src/main/java/com/google/genai/examples/InteractionFunctionCallingClientState.java +++ /dev/null @@ -1,215 +0,0 @@ -/* - * Copyright 2026 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: - * - *

1a. If you are using Vertex AI, setup ADC to get credentials: - * https://cloud.google.com/docs/authentication/provide-credentials-adc#google-idp - * - *

Then set Project, Location, and USE_VERTEXAI flag as environment variables: - * - *

export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT - * - *

export GOOGLE_CLOUD_LOCATION=YOUR_LOCATION - * - *

export GOOGLE_GENAI_USE_VERTEXAI=true - * - *

1b. If you are using Gemini Developer API, 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 exec:java - * -Dexec.mainClass="com.google.genai.examples.InteractionFunctionCallingClientState" - */ -package com.google.genai.examples; - -import com.google.common.collect.ImmutableMap; -import com.google.genai.Client; -import com.google.genai.interactions.core.JsonValue; -import com.google.genai.interactions.models.interactions.Content; -import com.google.genai.interactions.models.interactions.CreateModelInteractionParams; -import com.google.genai.interactions.models.interactions.Function; -import com.google.genai.interactions.models.interactions.FunctionCallStep; -import com.google.genai.interactions.models.interactions.FunctionResultStep; -import com.google.genai.interactions.models.interactions.Interaction; -import com.google.genai.interactions.models.interactions.Model; -import com.google.genai.interactions.models.interactions.Step; -import com.google.genai.interactions.models.interactions.TextContent; -import com.google.genai.interactions.models.interactions.Tool; -import com.google.genai.interactions.models.interactions.UserInputStep; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * An example of using the Interactions API for multi-turn function calling where the state is - * managed by the client. - */ -public final class InteractionFunctionCallingClientState { - public static void main(String[] args) { - Client client = new Client(); - - if (client.vertexAI()) { - System.out.println("Interactions API is not yet supported on Vertex"); - return; - } - - System.out.println("Using Gemini Developer API"); - - // 1. Define the function (tool) - Map attendeesSchema = new HashMap<>(); - attendeesSchema.put("type", "array"); - attendeesSchema.put("items", ImmutableMap.of("type", "string")); - attendeesSchema.put("description", "List of people attending the meeting."); - - Map dateSchema = new HashMap<>(); - dateSchema.put("type", "string"); - dateSchema.put("description", "Date of the meeting (e.g., 2024-07-29)"); - - Map timeSchema = new HashMap<>(); - timeSchema.put("type", "string"); - timeSchema.put("description", "Time of the meeting (e.g., 15:00)"); - - Map topicSchema = new HashMap<>(); - topicSchema.put("type", "string"); - topicSchema.put("description", "The subject or topic of the meeting."); - - Map properties = new HashMap<>(); - properties.put("attendees", attendeesSchema); - properties.put("date", dateSchema); - properties.put("time", timeSchema); - properties.put("topic", topicSchema); - - Map parametersSchema = new HashMap<>(); - parametersSchema.put("type", "object"); - parametersSchema.put("properties", properties); - parametersSchema.put("required", Arrays.asList("attendees", "date", "time", "topic")); - - Function function = - Function.builder() - .name("schedule_meeting") - .description("Schedules a meeting with specified attendees at a given time and date.") - .parameters(JsonValue.from(parametersSchema)) - .build(); - - // 2. Initialize conversation history - List conversationHistory = new ArrayList<>(); - conversationHistory.add( - Step.ofUserInput( - UserInputStep.builder() - .content( - List.of( - Content.ofText( - TextContent.builder() - .text( - "Schedule a meeting for 2025-11-01 at 10 am with Peter and Amir" - + " about the Next Gen API") - .build()))) - .build())); - - // 3. First turn: Model decides to call the function - CreateModelInteractionParams params = - CreateModelInteractionParams.builder() - .model(Model.GEMINI_2_5_FLASH) - .inputOfStepList(conversationHistory) - .tools(Arrays.asList(Tool.ofFunction(function))) - .build(); - - Interaction response = client.interactions.create(params); - - String functionCallId = null; - String functionName = null; - - List steps = response.steps(); - if (steps != null) { - for (Step step : steps) { - if (step.isFunctionCall()) { - FunctionCallStep functionCall = step.asFunctionCall(); - functionCallId = functionCall.id(); - functionName = functionCall.name(); - System.out.println("Model requested function call: " + functionName); - System.out.println("Arguments: " + functionCall.arguments()); - } else if (step.isModelOutput()) { - step.asModelOutput() - .content() - .ifPresent( - contents -> { - for (Content output : contents) { - output - .text() - .ifPresent(text -> System.out.println("Output Text: " + text.text())); - } - }); - } - } - - // Add model response back to history - for (Step step : steps) { - conversationHistory.add(step); - } - } - - // 4. Second turn: Send the function result back to the model - if (functionCallId != null) { - System.out.println("Sending function result back..."); - - FunctionResultStep functionResult = - FunctionResultStep.builder() - .callId(functionCallId) - .name(functionName) - .result(FunctionResultStep.Result.ofString("Meeting scheduled successfully.")) - .build(); - - // Create a step with function result - conversationHistory.add(Step.ofFunctionResult(functionResult)); - - CreateModelInteractionParams followUpParams = - CreateModelInteractionParams.builder() - .model(Model.GEMINI_2_5_FLASH) - .inputOfStepList(conversationHistory) - .build(); - - Interaction followUpResponse = client.interactions.create(followUpParams); - - System.out.println("Final response status: " + followUpResponse.status()); - for (Step step : followUpResponse.steps()) { - if (step.isModelOutput()) { - step.asModelOutput() - .content() - .ifPresent( - contents -> { - for (Content output : contents) { - output - .text() - .ifPresent( - text -> System.out.println("Final Output: " + text.text())); - } - }); - } - } - } else { - System.out.println("No function call requested by the model."); - } - } - - private InteractionFunctionCallingClientState() {} -} diff --git a/examples/src/main/java/com/google/genai/examples/InteractionFunctionCallingServerState.java b/examples/src/main/java/com/google/genai/examples/InteractionFunctionCallingServerState.java deleted file mode 100644 index 7652c71270d..00000000000 --- a/examples/src/main/java/com/google/genai/examples/InteractionFunctionCallingServerState.java +++ /dev/null @@ -1,194 +0,0 @@ -/* - * Copyright 2026 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: - * - *

1a. If you are using Vertex AI, setup ADC to get credentials: - * https://cloud.google.com/docs/authentication/provide-credentials-adc#google-idp - * - *

Then set Project, Location, and USE_VERTEXAI flag as environment variables: - * - *

export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT - * - *

export GOOGLE_CLOUD_LOCATION=YOUR_LOCATION - * - *

export GOOGLE_GENAI_USE_VERTEXAI=true - * - *

1b. If you are using Gemini Developer API, 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 exec:java - * -Dexec.mainClass="com.google.genai.examples.InteractionFunctionCallingServerState" - */ -package com.google.genai.examples; - -import com.google.common.collect.ImmutableMap; -import com.google.genai.Client; -import com.google.genai.interactions.core.JsonValue; -import com.google.genai.interactions.models.interactions.Content; -import com.google.genai.interactions.models.interactions.CreateModelInteractionParams; -import com.google.genai.interactions.models.interactions.Function; -import com.google.genai.interactions.models.interactions.FunctionCallStep; -import com.google.genai.interactions.models.interactions.FunctionResultStep; -import com.google.genai.interactions.models.interactions.Interaction; -import com.google.genai.interactions.models.interactions.Model; -import com.google.genai.interactions.models.interactions.Step; -import com.google.genai.interactions.models.interactions.Tool; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * An example of using the Interactions API for multi-turn function calling where the state is - * managed by the server. - */ -public final class InteractionFunctionCallingServerState { - public static void main(String[] args) { - Client client = new Client(); - - if (client.vertexAI()) { - System.out.println("Interactions API is not yet supported on Vertex"); - return; - } - - System.out.println("Using Gemini Developer API"); - - // 1. Define the function (tool) - Map attendeesSchema = new HashMap<>(); - attendeesSchema.put("type", "array"); - attendeesSchema.put("items", ImmutableMap.of("type", "string")); - attendeesSchema.put("description", "List of people attending the meeting."); - - Map dateSchema = new HashMap<>(); - dateSchema.put("type", "string"); - dateSchema.put("description", "Date of the meeting (e.g., 2024-07-29)"); - - Map timeSchema = new HashMap<>(); - timeSchema.put("type", "string"); - timeSchema.put("description", "Time of the meeting (e.g., 15:00)"); - - Map topicSchema = new HashMap<>(); - topicSchema.put("type", "string"); - topicSchema.put("description", "The subject or topic of the meeting."); - - Map properties = new HashMap<>(); - properties.put("attendees", attendeesSchema); - properties.put("date", dateSchema); - properties.put("time", timeSchema); - properties.put("topic", topicSchema); - - Map parametersSchema = new HashMap<>(); - parametersSchema.put("type", "object"); - parametersSchema.put("properties", properties); - parametersSchema.put("required", Arrays.asList("attendees", "date", "time", "topic")); - - Function function = - Function.builder() - .name("schedule_meeting") - .description("Schedules a meeting with specified attendees at a given time and date.") - .parameters(JsonValue.from(parametersSchema)) - .build(); - - // 2. First turn: Model decides to call the function - CreateModelInteractionParams params = - CreateModelInteractionParams.builder() - .input( - "Schedule a meeting for 2025-11-01 at 10 am with Peter and Amir about the Next Gen" - + " API") - .model(Model.GEMINI_2_5_FLASH) - .tools(Arrays.asList(Tool.ofFunction(function))) - .build(); - - Interaction response = client.interactions.create(params); - - String functionCallId = null; - String functionName = null; - - List steps = response.steps(); - if (steps != null) { - for (Step step : steps) { - if (step.isFunctionCall()) { - FunctionCallStep functionCall = step.asFunctionCall(); - functionCallId = functionCall.id(); - functionName = functionCall.name(); - System.out.println("Model requested function call: " + functionName); - System.out.println("Arguments: " + functionCall.arguments()); - } else if (step.isModelOutput()) { - step.asModelOutput() - .content() - .ifPresent( - contents -> { - for (Content output : contents) { - output - .text() - .ifPresent(text -> System.out.println("Output Text: " + text.text())); - } - }); - } - } - } - - // 3. Second turn: Send the function result back to the model - if (functionCallId != null) { - System.out.println("Sending function result back..."); - - FunctionResultStep functionResult = - FunctionResultStep.builder() - .callId(functionCallId) - .name(functionName) - .result(FunctionResultStep.Result.ofString("Meeting scheduled successfully.")) - .build(); - - CreateModelInteractionParams followUpParams = - CreateModelInteractionParams.builder() - .model(Model.GEMINI_2_5_FLASH) - .previousInteractionId(response.id()) - .input( - CreateModelInteractionParams.Input.ofStepList( - java.util.Arrays.asList(Step.ofFunctionResult(functionResult)))) - .build(); - - Interaction followUpResponse = client.interactions.create(followUpParams); - - System.out.println("Final response status: " + followUpResponse.status()); - for (Step step : followUpResponse.steps()) { - if (step.isModelOutput()) { - step.asModelOutput() - .content() - .ifPresent( - contents -> { - for (Content output : contents) { - output - .text() - .ifPresent( - text -> System.out.println("Final Output: " + text.text())); - } - }); - } - } - } else { - System.out.println("No function call requested by the model."); - } - } - - private InteractionFunctionCallingServerState() {} -} diff --git a/examples/src/main/java/com/google/genai/examples/InteractionGet.java b/examples/src/main/java/com/google/genai/examples/InteractionGet.java deleted file mode 100644 index f19f5566741..00000000000 --- a/examples/src/main/java/com/google/genai/examples/InteractionGet.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright 2026 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: - * - *

1a. If you are using Vertex AI, setup ADC to get credentials: - * https://cloud.google.com/docs/authentication/provide-credentials-adc#google-idp - * - *

Then set Project, Location, and USE_VERTEXAI flag as environment variables: - * - *

export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT - * - *

export GOOGLE_CLOUD_LOCATION=YOUR_LOCATION - * - *

export GOOGLE_GENAI_USE_VERTEXAI=true - * - *

1b. If you are using Gemini Developer API, 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 exec:java -Dexec.mainClass="com.google.genai.examples.InteractionGet" - */ -package com.google.genai.examples; - -import com.google.genai.Client; -import com.google.genai.interactions.models.interactions.Content; -import com.google.genai.interactions.models.interactions.CreateModelInteractionParams; -import com.google.genai.interactions.models.interactions.Interaction; -import com.google.genai.interactions.models.interactions.Model; -import com.google.genai.interactions.models.interactions.Step; - -/** An example of using the Unified Gen AI Java SDK to retrieve an interaction. */ -public final class InteractionGet { - public static void main(String[] args) { - Client client = new Client(); - - if (client.vertexAI()) { - System.out.println("Interactions API is not yet supported on Vertex"); - return; - } - - System.out.println("Using Gemini Developer API"); - - // First, create an interaction to get an ID. - CreateModelInteractionParams createParams = - CreateModelInteractionParams.builder() - .input("Why is the sky blue?") - .model(Model.GEMINI_2_5_FLASH) - .build(); - - Interaction createdInteraction = client.interactions.create(createParams); - String id = createdInteraction.id(); - System.out.println("Created Interaction ID: " + id); - - // Now, retrieve the interaction using the ID. - Interaction retrievedInteraction = client.interactions.get(id); - System.out.println("Retrieved Interaction ID: " + retrievedInteraction.id()); - System.out.println("Status: " + retrievedInteraction.status()); - - // Print the text outputs from the retrieved interaction. - for (Step step : retrievedInteraction.steps()) { - if (step.isModelOutput()) { - step.asModelOutput() - .content() - .ifPresent( - contents -> { - for (Content content : contents) { - content - .text() - .ifPresent(text -> System.out.println("Output: " + text.text())); - } - }); - } - } - } - - private InteractionGet() {} -} diff --git a/examples/src/main/java/com/google/genai/examples/InteractionMultimodalInputTextAndAudio.java b/examples/src/main/java/com/google/genai/examples/InteractionMultimodalInputTextAndAudio.java deleted file mode 100644 index 1e5b582b0b9..00000000000 --- a/examples/src/main/java/com/google/genai/examples/InteractionMultimodalInputTextAndAudio.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright 2026 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 - * - * http://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: - * - *

1a. If you are using Vertex AI, setup ADC to get credentials: - * https://cloud.google.com/docs/authentication/provide-credentials-adc#google-idp - * - *

Then set Project, Location, and USE_VERTEXAI flag as environment variables: - * - *

export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT - * - *

export GOOGLE_CLOUD_LOCATION=YOUR_LOCATION - * - *

export GOOGLE_GENAI_USE_VERTEXAI=true - * - *

1b. If you are using Gemini Developer API, 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 exec:java - * -Dexec.mainClass="com.google.genai.examples.InteractionMultimodalInputTextAndAudio" - */ -package com.google.genai.examples; - -import com.google.genai.Client; -import com.google.genai.interactions.models.interactions.AudioContent; -import com.google.genai.interactions.models.interactions.Content; -import com.google.genai.interactions.models.interactions.CreateModelInteractionParams; -import com.google.genai.interactions.models.interactions.Interaction; -import com.google.genai.interactions.models.interactions.Step; -import com.google.genai.interactions.models.interactions.TextContent; -import java.util.Arrays; -import java.util.List; - -/** Example of using the Interactions API with multimodal input (text and audio). */ -public class InteractionMultimodalInputTextAndAudio { - - private InteractionMultimodalInputTextAndAudio() {} - - private static void createInteractions(Client client) { - Content textContent = - Content.ofText(TextContent.builder().text("Summarize this audio clip.").build()); - Content audioContent = - Content.ofAudio( - AudioContent.builder() - .uri("gs://cloud-samples-data/generative-ai/audio/pixel.mp3") - .mimeType(AudioContent.MimeType.AUDIO_MP3) - .build()); - - List contents = Arrays.asList(textContent, audioContent); - - CreateModelInteractionParams params = - CreateModelInteractionParams.builder() - .model("gemini-2.5-flash") - .inputOfContentList(contents) - .build(); - - Interaction interaction = client.interactions.create(params); - - List steps = interaction.steps(); - for (int i = 0; i < steps.size(); i++) { - System.out.println("Step " + (i + 1) + ": " + steps.get(i)); - } - } - - public static void main(String[] args) { - Client client = new Client(); - if (client.vertexAI()) { - System.out.println("Interactions API is not yet supported on Vertex"); - return; - } - try { - createInteractions(client); - } catch (RuntimeException e) { - System.err.println("Got error: " + e.getMessage()); - e.printStackTrace(); - } - } -} diff --git a/examples/src/main/java/com/google/genai/examples/InteractionMultimodalInputTextAndImage.java b/examples/src/main/java/com/google/genai/examples/InteractionMultimodalInputTextAndImage.java deleted file mode 100644 index 68bb9ab5e71..00000000000 --- a/examples/src/main/java/com/google/genai/examples/InteractionMultimodalInputTextAndImage.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright 2026 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 - * - * http://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: - * - *

1a. If you are using Vertex AI, setup ADC to get credentials: - * https://cloud.google.com/docs/authentication/provide-credentials-adc#google-idp - * - *

Then set Project, Location, and USE_VERTEXAI flag as environment variables: - * - *

export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT - * - *

export GOOGLE_CLOUD_LOCATION=YOUR_LOCATION - * - *

export GOOGLE_GENAI_USE_VERTEXAI=true - * - *

1b. If you are using Gemini Developer API, 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 exec:java - * -Dexec.mainClass="com.google.genai.examples.InteractionMultimodalInputTextAndImage" - */ -package com.google.genai.examples; - -import com.google.genai.Client; -import com.google.genai.interactions.models.interactions.Content; -import com.google.genai.interactions.models.interactions.CreateModelInteractionParams; -import com.google.genai.interactions.models.interactions.ImageContent; -import com.google.genai.interactions.models.interactions.Interaction; -import com.google.genai.interactions.models.interactions.Step; -import com.google.genai.interactions.models.interactions.TextContent; -import java.util.Arrays; -import java.util.List; - -/** Example of using the Interactions API with multimodal input (text and image). */ -public class InteractionMultimodalInputTextAndImage { - - private InteractionMultimodalInputTextAndImage() {} - - private static void createInteractions(Client client) { - Content textContent = - Content.ofText(TextContent.builder().text("What is shown in this image?").build()); - Content imageContent = - Content.ofImage( - ImageContent.builder() - .uri("gs://cloud-samples-data/generative-ai/image/scones.jpg") - .mimeType(ImageContent.MimeType.IMAGE_JPEG) - .build()); - - List contents = Arrays.asList(textContent, imageContent); - - CreateModelInteractionParams params = - CreateModelInteractionParams.builder() - .model("gemini-2.5-flash") - .inputOfContentList(contents) - .build(); - - Interaction interaction = client.interactions.create(params); - - List steps = interaction.steps(); - for (int i = 0; i < steps.size(); i++) { - System.out.println("Step " + (i + 1) + ": " + steps.get(i)); - } - } - - public static void main(String[] args) { - Client client = new Client(); - if (client.vertexAI()) { - System.out.println("Interactions API is not yet supported on Vertex"); - return; - } - try { - createInteractions(client); - } catch (RuntimeException e) { - System.err.println("Got error: " + e.getMessage()); - e.printStackTrace(); - } - } -} diff --git a/examples/src/main/java/com/google/genai/examples/InteractionMultimodalResponseAudio.java b/examples/src/main/java/com/google/genai/examples/InteractionMultimodalResponseAudio.java deleted file mode 100644 index 8083d9735b8..00000000000 --- a/examples/src/main/java/com/google/genai/examples/InteractionMultimodalResponseAudio.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright 2026 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 - * - * http://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: - * - *

1a. If you are using Vertex AI, setup ADC to get credentials: - * https://cloud.google.com/docs/authentication/provide-credentials-adc#google-idp - * - *

Then set Project, Location, and USE_VERTEXAI flag as environment variables: - * - *

export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT - * - *

export GOOGLE_CLOUD_LOCATION=YOUR_LOCATION - * - *

export GOOGLE_GENAI_USE_VERTEXAI=true - * - *

1b. If you are using Gemini Developer API, 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 exec:java - * -Dexec.mainClass="com.google.genai.examples.InteractionMultimodalResponseAudio" - */ -package com.google.genai.examples; - -import com.google.genai.Client; -import com.google.genai.interactions.models.interactions.CreateModelInteractionParams; -import com.google.genai.interactions.models.interactions.CreateModelInteractionParams.ResponseModality; -import com.google.genai.interactions.models.interactions.GenerationConfig; -import com.google.genai.interactions.models.interactions.Interaction; -import com.google.genai.interactions.models.interactions.SpeechConfig; -import com.google.genai.interactions.models.interactions.Step; -import java.util.Arrays; - -/** Example of generating audio using the Interactions API. */ -public final class InteractionMultimodalResponseAudio { - - private static void createInteractions(Client client) { - - SpeechConfig speechConfig = SpeechConfig.builder().voice("achernar").language("en-US").build(); - - GenerationConfig generationConfig = - GenerationConfig.builder().speechConfig(Arrays.asList(speechConfig)).build(); - - CreateModelInteractionParams params = - CreateModelInteractionParams.builder() - .model("gemini-2.5-flash-preview-tts") - .responseModalities(Arrays.asList(ResponseModality.AUDIO)) - .generationConfig(generationConfig) - .input("Say cheerfully: Have a wonderful day!") - .build(); - - Interaction interaction = client.interactions.create(params); - - int i = 1; - for (Step step : interaction.steps()) { - System.out.println("Output " + i + ": " + step); - i++; - } - } - - public static void main(String[] args) { - Client client = new Client(); - if (client.vertexAI()) { - System.out.println("Interactions API is not yet supported on Vertex"); - return; - } - try { - createInteractions(client); - } catch (RuntimeException e) { - System.err.println("Got error: " + e.getMessage()); - e.printStackTrace(); - } - } - - private InteractionMultimodalResponseAudio() {} -} diff --git a/examples/src/main/java/com/google/genai/examples/InteractionMultimodalResponseAudioWithGenerateContent.java b/examples/src/main/java/com/google/genai/examples/InteractionMultimodalResponseAudioWithGenerateContent.java deleted file mode 100644 index f6a5c2f39c1..00000000000 --- a/examples/src/main/java/com/google/genai/examples/InteractionMultimodalResponseAudioWithGenerateContent.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright 2026 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: - * - *

1a. If you are using Vertex AI, setup ADC to get credentials: - * https://cloud.google.com/docs/authentication/provide-credentials-adc#google-idp - * - *

Then set Project, Location, and USE_VERTEXAI flag as environment variables: - * - *

export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT - * - *

export GOOGLE_CLOUD_LOCATION=YOUR_LOCATION - * - *

export GOOGLE_GENAI_USE_VERTEXAI=true - * - *

1b. If you are using Gemini Developer API, 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 exec:java - * -Dexec.mainClass="com.google.genai.examples.InteractionMultimodalResponseAudioWithGenerateContent" - */ -package com.google.genai.examples; - -import com.google.genai.Client; -import com.google.genai.JsonSerializable; -import com.google.genai.interactions.models.interactions.Content; -import com.google.genai.interactions.models.interactions.CreateModelInteractionParams; -import com.google.genai.interactions.models.interactions.CreateModelInteractionParams.ResponseModality; -import com.google.genai.interactions.models.interactions.GenerationConfig; -import com.google.genai.interactions.models.interactions.Interaction; -import com.google.genai.interactions.models.interactions.Model; -import com.google.genai.interactions.models.interactions.SpeechConfig; -import com.google.genai.interactions.models.interactions.Step; -import com.google.genai.types.GenerateContentConfig; -import com.google.genai.types.GenerateContentResponse; -import java.util.Collections; - -/** - * An example of using the Unified Gen AI Java SDK to create an interaction with audio response and - * generate content with audio response. - */ -public final class InteractionMultimodalResponseAudioWithGenerateContent { - public static void main(String[] args) { - Client client = new Client(); - - if (client.vertexAI()) { - System.out.println("Interactions API is not yet supported on Vertex"); - return; - } - - System.out.println("[Interactions] Start interactions multimodal response audio"); - - SpeechConfig speechConfig = SpeechConfig.builder().voice("achernar").language("en-US").build(); - - GenerationConfig generationConfig = - GenerationConfig.builder().speechConfig(Collections.singletonList(speechConfig)).build(); - - CreateModelInteractionParams params = - CreateModelInteractionParams.builder() - .model(Model.GEMINI_2_5_FLASH_PREVIEW_TTS) - .responseModalities(Collections.singletonList(ResponseModality.AUDIO)) - .generationConfig(generationConfig) - .input("Say cheerfully: Have a wonderful day!") - .build(); - - Interaction interaction = client.interactions.create(params); - - System.out.println("Interaction ID: " + interaction.id()); - System.out.println("Status: " + interaction.status()); - - int i = 1; - for (Step step : interaction.steps()) { - System.out.println("Step " + i + ": " + step); - i++; - } - - System.out.println("[Generate Content] Start generate content"); - GenerateContentConfig config = - GenerateContentConfig.builder().responseModalities("AUDIO").build(); - - GenerateContentResponse generateContentResponse = - client.models.generateContent( - "gemini-2.5-flash-preview-tts", "Say cheerfully: Have a wonderful day!", config); - - System.out.println( - "Generate Content response: " + JsonSerializable.toJsonString(generateContentResponse)); - } - - private InteractionMultimodalResponseAudioWithGenerateContent() {} -} diff --git a/examples/src/main/java/com/google/genai/examples/InteractionMultimodalResponseImage.java b/examples/src/main/java/com/google/genai/examples/InteractionMultimodalResponseImage.java deleted file mode 100644 index 2476809c5ee..00000000000 --- a/examples/src/main/java/com/google/genai/examples/InteractionMultimodalResponseImage.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright 2026 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 - * - * http://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: - * - *

1a. If you are using Vertex AI, setup ADC to get credentials: - * https://cloud.google.com/docs/authentication/provide-credentials-adc#google-idp - * - *

Then set Project, Location, and USE_VERTEXAI flag as environment variables: - * - *

export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT - * - *

export GOOGLE_CLOUD_LOCATION=YOUR_LOCATION - * - *

export GOOGLE_GENAI_USE_VERTEXAI=true - * - *

1b. If you are using Gemini Developer API, 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 exec:java - * -Dexec.mainClass="com.google.genai.examples.InteractionMultimodalResponseImage" - */ -package com.google.genai.examples; - -import com.google.genai.Client; -import com.google.genai.interactions.models.interactions.CreateModelInteractionParams; -import com.google.genai.interactions.models.interactions.CreateModelInteractionParams.ResponseModality; -import com.google.genai.interactions.models.interactions.Interaction; -import com.google.genai.interactions.models.interactions.Step; -import java.util.Arrays; - -/** Example of generating an image using the Interactions API. */ -public class InteractionMultimodalResponseImage { - - private static void createInteractions(Client client) { - - CreateModelInteractionParams params = - CreateModelInteractionParams.builder() - .model("gemini-2.5-flash-image-preview") - .responseModalities(Arrays.asList(ResponseModality.IMAGE)) - .input("Generate an image of a futuristic cityscape at sunset.") - .build(); - - Interaction interaction = client.interactions.create(params); - - int i = 1; - for (Step step : interaction.steps()) { - System.out.println("Output " + i + ": " + step); - i++; - } - } - - public static void main(String[] args) { - Client client = new Client(); - if (client.vertexAI()) { - System.out.println("Interactions API is not yet supported on Vertex"); - return; - } - try { - createInteractions(client); - } catch (RuntimeException e) { - System.err.println("Got error: " + e.getMessage()); - e.printStackTrace(); - } - } - - private InteractionMultimodalResponseImage() {} -} diff --git a/examples/src/main/java/com/google/genai/examples/InteractionMultimodalResponseImageWithGenerateContent.java b/examples/src/main/java/com/google/genai/examples/InteractionMultimodalResponseImageWithGenerateContent.java deleted file mode 100644 index 6927477b9ea..00000000000 --- a/examples/src/main/java/com/google/genai/examples/InteractionMultimodalResponseImageWithGenerateContent.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright 2026 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: - * - *

1a. If you are using Vertex AI, setup ADC to get credentials: - * https://cloud.google.com/docs/authentication/provide-credentials-adc#google-idp - * - *

Then set Project, Location, and USE_VERTEXAI flag as environment variables: - * - *

export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT - * - *

export GOOGLE_CLOUD_LOCATION=YOUR_LOCATION - * - *

export GOOGLE_GENAI_USE_VERTEXAI=true - * - *

1b. If you are using Gemini Developer API, 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 exec:java - * -Dexec.mainClass="com.google.genai.examples.InteractionMultimodalResponseImageWithGenerateContent" - */ -package com.google.genai.examples; - -import com.google.genai.Client; -import com.google.genai.JsonSerializable; -import com.google.genai.interactions.models.interactions.Content; -import com.google.genai.interactions.models.interactions.CreateModelInteractionParams; -import com.google.genai.interactions.models.interactions.CreateModelInteractionParams.ResponseModality; -import com.google.genai.interactions.models.interactions.Interaction; -import com.google.genai.interactions.models.interactions.Model; -import com.google.genai.interactions.models.interactions.Step; -import com.google.genai.types.GenerateContentConfig; -import com.google.genai.types.GenerateContentResponse; -import java.util.Collections; - -/** - * An example of using the Unified Gen AI Java SDK to create an interaction with image response and - * generate content with image response. - */ -public final class InteractionMultimodalResponseImageWithGenerateContent { - public static void main(String[] args) { - Client client = new Client(); - - if (client.vertexAI()) { - System.out.println("Interactions API is not yet supported on Vertex"); - return; - } - - System.out.println("[Interactions] Start interactions multimodal response image"); - - CreateModelInteractionParams params = - CreateModelInteractionParams.builder() - .model(Model.GEMINI_2_5_FLASH_IMAGE) - .responseModalities(Collections.singletonList(ResponseModality.IMAGE)) - .input("Generate an image of a futuristic cityscape at sunset.") - .build(); - - Interaction interaction = client.interactions.create(params); - - System.out.println("Interaction ID: " + interaction.id()); - System.out.println("Status: " + interaction.status()); - - int i = 1; - for (Step step : interaction.steps()) { - System.out.println("Step " + i + ": " + step); - i++; - } - - System.out.println("[Generate Content] Start generate content"); - GenerateContentConfig config = - GenerateContentConfig.builder().responseModalities("TEXT", "IMAGE").build(); - - GenerateContentResponse generateContentResponse = - client.models.generateContent( - "gemini-2.5-flash-image", - "Generate an image of a futuristic cityscape at sunset.", - config); - - System.out.println( - "Generate Content response: " + JsonSerializable.toJsonString(generateContentResponse)); - } - - private InteractionMultimodalResponseImageWithGenerateContent() {} -} diff --git a/examples/src/main/java/com/google/genai/examples/InteractionStateful.java b/examples/src/main/java/com/google/genai/examples/InteractionStateful.java deleted file mode 100644 index a74def6597d..00000000000 --- a/examples/src/main/java/com/google/genai/examples/InteractionStateful.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright 2026 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: - * - *

1a. If you are using Vertex AI, setup ADC to get credentials: - * https://cloud.google.com/docs/authentication/provide-credentials-adc#google-idp - * - *

Then set Project, Location, and USE_VERTEXAI flag as environment variables: - * - *

export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT - * - *

export GOOGLE_CLOUD_LOCATION=YOUR_LOCATION - * - *

export GOOGLE_GENAI_USE_VERTEXAI=true - * - *

1b. If you are using Gemini Developer API, 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 exec:java -Dexec.mainClass="com.google.genai.examples.InteractionStateful" - */ -package com.google.genai.examples; - -import com.google.genai.Client; -import com.google.genai.interactions.models.interactions.Content; -import com.google.genai.interactions.models.interactions.CreateModelInteractionParams; -import com.google.genai.interactions.models.interactions.Interaction; -import com.google.genai.interactions.models.interactions.Model; -import com.google.genai.interactions.models.interactions.Step; - -/** An example of using the Unified Gen AI Java SDK to create a stateful interaction. */ -public final class InteractionStateful { - public static void main(String[] args) { - Client client = new Client(); - - if (client.vertexAI()) { - System.out.println("Interactions API is not yet supported on Vertex AI"); - return; - } - - System.out.println("Using Gemini Developer API"); - - System.out.println("User: What are the three largest cities in Spain?"); - CreateModelInteractionParams params1 = - CreateModelInteractionParams.builder() - .input("What are the three largest cities in Spain?") - .model(Model.GEMINI_2_5_FLASH) - .build(); - - Interaction interaction1 = client.interactions.create(params1); - System.out.println("Model: "); - printOutput(interaction1); - - System.out.println("\nUser: What is the most famous landmark in the second one?"); - CreateModelInteractionParams params2 = - CreateModelInteractionParams.builder() - .input("What is the most famous landmark in the second one?") - .model(Model.GEMINI_2_5_FLASH) - .previousInteractionId(interaction1.id()) - .build(); - - Interaction interaction2 = client.interactions.create(params2); - System.out.println("Model: "); - printOutput(interaction2); - } - - private static void printOutput(Interaction interaction) { - for (Step step : interaction.steps()) { - if (step.isModelOutput()) { - step.asModelOutput() - .content() - .ifPresent( - contents -> { - for (Content content : contents) { - content.text().ifPresent(text -> System.out.println(text.text())); - } - }); - } - } - } - - private InteractionStateful() {} -} diff --git a/examples/src/main/java/com/google/genai/examples/InteractionStateless.java b/examples/src/main/java/com/google/genai/examples/InteractionStateless.java deleted file mode 100644 index af0037da85f..00000000000 --- a/examples/src/main/java/com/google/genai/examples/InteractionStateless.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * Copyright 2026 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: - * - *

1a. If you are using Vertex AI, setup ADC to get credentials: - * https://cloud.google.com/docs/authentication/provide-credentials-adc#google-idp - * - *

Then set Project, Location, and USE_VERTEXAI flag as environment variables: - * - *

export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT - * - *

export GOOGLE_CLOUD_LOCATION=YOUR_LOCATION - * - *

export GOOGLE_GENAI_USE_VERTEXAI=true - * - *

1b. If you are using Gemini Developer API, 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 exec:java -Dexec.mainClass="com.google.genai.examples.InteractionStateless" - */ -package com.google.genai.examples; - -import com.google.genai.Client; -import com.google.genai.interactions.models.interactions.Content; -import com.google.genai.interactions.models.interactions.CreateModelInteractionParams; -import com.google.genai.interactions.models.interactions.Interaction; -import com.google.genai.interactions.models.interactions.Model; -import com.google.genai.interactions.models.interactions.ModelOutputStep; -import com.google.genai.interactions.models.interactions.Step; -import com.google.genai.interactions.models.interactions.TextContent; -import com.google.genai.interactions.models.interactions.UserInputStep; -import java.util.ArrayList; -import java.util.List; - -/** - * An example of using the Unified Gen AI Java SDK to create a stateless interaction (multi-turn - * chat). - */ -public final class InteractionStateless { - public static void main(String[] args) { - Client client = new Client(); - - if (client.vertexAI()) { - System.out.println("Interactions API is not yet supported on Vertex"); - return; - } else { - System.out.println("Using Gemini Developer API"); - } - - List conversationHistory = new ArrayList<>(); - conversationHistory.add( - Step.ofUserInput( - UserInputStep.builder() - .content( - List.of( - Content.ofText( - TextContent.builder() - .text("What are the three largest cities in Spain?") - .build()))) - .build())); - - System.out.println("User: What are the three largest cities in Spain?"); - - CreateModelInteractionParams params1 = - CreateModelInteractionParams.builder() - .inputOfStepList(conversationHistory) - .model(Model.GEMINI_2_5_FLASH) - .store(false) - .build(); - - Interaction response1 = client.interactions.create(params1); - - System.out.println("Model: "); - // Add model response to history - for (Step step : response1.steps()) { - if (step.isModelOutput()) { - step.asModelOutput() - .content() - .ifPresent( - contents -> { - for (Content output : contents) { - output.text().ifPresent(text -> System.out.println(text.text())); - } - }); - } - conversationHistory.add(step); - } - - // Add next user message - conversationHistory.add( - Step.ofUserInput( - UserInputStep.builder() - .content( - List.of( - Content.ofText( - TextContent.builder() - .text("What is the most famous landmark in the second one?") - .build()))) - .build())); - - System.out.println("\nUser: What is the most famous landmark in the second one?"); - - CreateModelInteractionParams params2 = - CreateModelInteractionParams.builder() - .inputOfStepList(conversationHistory) - .model(Model.GEMINI_2_5_FLASH) - .store(false) - .build(); - - Interaction response2 = client.interactions.create(params2); - - System.out.println("Model: "); - for (Step step : response2.steps()) { - if (step.isModelOutput()) { - step.asModelOutput() - .content() - .ifPresent( - contents -> { - for (Content output : contents) { - output.text().ifPresent(text -> System.out.println(text.text())); - } - }); - } - } - } - - private InteractionStateless() {} -} diff --git a/examples/src/main/java/com/google/genai/examples/InteractionStreaming.java b/examples/src/main/java/com/google/genai/examples/InteractionStreaming.java deleted file mode 100644 index efc3079aabe..00000000000 --- a/examples/src/main/java/com/google/genai/examples/InteractionStreaming.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright 2026 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: - * - *

1a. If you are using Vertex AI, setup ADC to get credentials: - * https://cloud.google.com/docs/authentication/provide-credentials-adc#google-idp - * - *

Then set Project, Location, and USE_VERTEXAI flag as environment variables: - * - *

export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT - * - *

export GOOGLE_CLOUD_LOCATION=YOUR_LOCATION - * - *

export GOOGLE_GENAI_USE_VERTEXAI=true - * - *

1b. If you are using Gemini Developer API, 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 exec:java -Dexec.mainClass="com.google.genai.examples.InteractionStreaming" - */ -package com.google.genai.examples; - -import com.google.genai.Client; -import com.google.genai.interactions.core.http.StreamResponse; -import com.google.genai.interactions.models.interactions.CreateModelInteractionParams; -import com.google.genai.interactions.models.interactions.InteractionSseEvent; -import com.google.genai.interactions.models.interactions.Model; - -/** An example of using the Unified Gen AI Java SDK to stream an interaction. */ -public final class InteractionStreaming { - public static void main(String[] args) { - Client client = new Client(); - - if (client.vertexAI()) { - System.out.println("Interactions API is not yet supported on Vertex AI"); - return; - } - - System.out.println("Using Gemini Developer API"); - - CreateModelInteractionParams params = - CreateModelInteractionParams.builder() - .input("Tell me a story") - .model(Model.GEMINI_2_5_FLASH) - .build(); - - try (StreamResponse response = - client.interactions.createStreaming(params)) { - response.stream() - .forEach( - event -> { - if (event.isStepDelta()) { - event - .asStepDelta() - .delta() - .text() - .ifPresent( - t -> { - System.out.print(t.text()); - System.out.flush(); - }); - } - }); - System.out.println(); - } catch (RuntimeException e) { - System.err.println("Error during streaming: " + e.getMessage()); - e.printStackTrace(); - } - } - - private InteractionStreaming() {} -} diff --git a/examples/src/main/java/com/google/genai/examples/InteractionStructuredOutputJson.java b/examples/src/main/java/com/google/genai/examples/InteractionStructuredOutputJson.java deleted file mode 100644 index 5bbc2d606f1..00000000000 --- a/examples/src/main/java/com/google/genai/examples/InteractionStructuredOutputJson.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright 2026 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 - * - * http://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: - * - *

1a. If you are using Vertex AI, setup ADC to get credentials: - * https://cloud.google.com/docs/authentication/provide-credentials-adc#google-idp - * - *

Then set Project, Location, and USE_VERTEXAI flag as environment variables: - * - *

export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT - * - *

export GOOGLE_CLOUD_LOCATION=YOUR_LOCATION - * - *

export GOOGLE_GENAI_USE_VERTEXAI=true - * - *

1b. If you are using Gemini Developer API, 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 exec:java - * -Dexec.mainClass="com.google.genai.examples.InteractionStructuredOutputJson" - */ -package com.google.genai.examples; - -import com.google.genai.Client; -import com.google.genai.interactions.core.JsonValue; -import com.google.genai.interactions.models.interactions.CreateModelInteractionParams; -import com.google.genai.interactions.models.interactions.CreateModelInteractionParams.ResponseFormat; -import com.google.genai.interactions.models.interactions.Interaction; -import java.util.HashMap; -import java.util.Map; - -/** Example of requesting structured JSON output using the Interactions API. */ -public class InteractionStructuredOutputJson { - - private static void createInteractions(Client client) { - - Map format = new HashMap<>(); - format.put("type", "array"); - format.put("description", "A list of colors"); - JsonValue responseFormat = JsonValue.from(format); - - CreateModelInteractionParams params = - CreateModelInteractionParams.builder() - .model("gemini-2.5-flash") - .input("Which are the colors of a rainbow") - .responseMimeType("application/json") - .responseFormat(ResponseFormat.ofJsonValue(responseFormat)) - .build(); - - Interaction interaction = client.interactions.create(params); - - System.out.println(interaction); - } - - public static void main(String[] args) { - Client client = new Client(); - if (client.vertexAI()) { - System.out.println("Interactions API is not yet supported on Vertex"); - return; - } - try { - createInteractions(client); - } catch (RuntimeException e) { - System.err.println("Got error: " + e.getMessage()); - e.printStackTrace(); - } - } - - private InteractionStructuredOutputJson() {} -} diff --git a/examples/src/main/java/com/google/genai/examples/InteractionToolCallWithCodeExecution.java b/examples/src/main/java/com/google/genai/examples/InteractionToolCallWithCodeExecution.java deleted file mode 100644 index 79cbffc508a..00000000000 --- a/examples/src/main/java/com/google/genai/examples/InteractionToolCallWithCodeExecution.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright 2026 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: - * - *

1a. If you are using Vertex AI, setup ADC to get credentials: - * https://cloud.google.com/docs/authentication/provide-credentials-adc#google-idp - * - *

Then set Project, Location, and USE_VERTEXAI flag as environment variables: - * - *

export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT - * - *

export GOOGLE_CLOUD_LOCATION=YOUR_LOCATION - * - *

export GOOGLE_GENAI_USE_VERTEXAI=true - * - *

1b. If you are using Gemini Developer API, 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 exec:java - * -Dexec.mainClass="com.google.genai.examples.InteractionToolCallWithCodeExecution" - */ -package com.google.genai.examples; - -import com.google.genai.Client; -import com.google.genai.interactions.models.interactions.Content; -import com.google.genai.interactions.models.interactions.CreateModelInteractionParams; -import com.google.genai.interactions.models.interactions.Interaction; -import com.google.genai.interactions.models.interactions.Model; -import com.google.genai.interactions.models.interactions.Step; -import com.google.genai.interactions.models.interactions.Tool; - -/** An example of using the Interactions API with code execution tool. */ -public final class InteractionToolCallWithCodeExecution { - public static void main(String[] args) { - Client client = new Client(); - - if (client.vertexAI()) { - System.out.println("Interactions API is not yet supported on Vertex"); - return; - } - - System.out.println("Using Gemini Developer API"); - - CreateModelInteractionParams params = - CreateModelInteractionParams.builder() - .input("What is the sum of the first 100 integers?") - .model(Model.GEMINI_2_5_FLASH) - .addTool(Tool.ofCodeExecution()) - .build(); - - try { - Interaction interaction = client.interactions.create(params); - - System.out.println("Interaction ID: " + interaction.id()); - System.out.println("Status: " + interaction.status()); - - // Print the text outputs from the interaction. - for (Step step : interaction.steps()) { - if (step.isModelOutput()) { - step.asModelOutput() - .content() - .ifPresent( - contents -> { - for (Content content : contents) { - content - .text() - .ifPresent( - text -> System.out.println("Output: " + text.text())); - } - }); - } - } - } catch (RuntimeException e) { - System.err.println("Error creating interaction: " + e.getMessage()); - e.printStackTrace(); - } - } - - private InteractionToolCallWithCodeExecution() {} -} diff --git a/examples/src/main/java/com/google/genai/examples/InteractionToolCallWithComputerUse.java b/examples/src/main/java/com/google/genai/examples/InteractionToolCallWithComputerUse.java deleted file mode 100644 index 83c32cb8561..00000000000 --- a/examples/src/main/java/com/google/genai/examples/InteractionToolCallWithComputerUse.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright 2026 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: - * - *

1a. If you are using Vertex AI, setup ADC to get credentials: - * https://cloud.google.com/docs/authentication/provide-credentials-adc#google-idp - * - *

Then set Project, Location, and USE_VERTEXAI flag as environment variables: - * - *

export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT - * - *

export GOOGLE_CLOUD_LOCATION=YOUR_LOCATION - * - *

export GOOGLE_GENAI_USE_VERTEXAI=true - * - *

1b. If you are using Gemini Developer API, 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 exec:java - * -Dexec.mainClass="com.google.genai.examples.InteractionToolCallWithComputerUse" - */ -package com.google.genai.examples; - -import com.google.genai.Client; -import com.google.genai.interactions.models.interactions.Content; -import com.google.genai.interactions.models.interactions.CreateModelInteractionParams; -import com.google.genai.interactions.models.interactions.Interaction; -import com.google.genai.interactions.models.interactions.Step; -import com.google.genai.interactions.models.interactions.Tool; - -/** - * An example of using the Unified Gen AI Java SDK to create an interaction with computer use tool. - */ -public final class InteractionToolCallWithComputerUse { - public static void main(String[] args) { - Client client = new Client(); - - if (client.vertexAI()) { - System.out.println("Interactions API is not yet supported on Vertex"); - return; - } else { - System.out.println("Using Gemini Developer API"); - } - - CreateModelInteractionParams params = - CreateModelInteractionParams.builder() - .model("gemini-2.5-computer-use-preview-10-2025") - .input( - "Search for highly rated smart fridges with touchscreen, 2 doors, around 25 cu ft," - + " priced below 4000 dollars on Google Shopping. Create a bulleted list of the" - + " 3 cheapest options in the format of name, description, price in an" - + " easy-to-read layout.") - .addTool( - Tool.ComputerUse.builder() - .environment(Tool.ComputerUse.Environment.BROWSER) - .build()) - .build(); - - Interaction interaction = client.interactions.create(params); - - System.out.println("Interaction ID: " + interaction.id()); - System.out.println("Status: " + interaction.status()); - - // Print the text outputs from the interaction. - for (Step step : interaction.steps()) { - if (step.isModelOutput()) { - step.asModelOutput() - .content() - .ifPresent( - contents -> { - for (Content content : contents) { - content - .text() - .ifPresent(text -> System.out.println("Output: " + text.text())); - } - }); - } - } - } - - private InteractionToolCallWithComputerUse() {} -} diff --git a/examples/src/main/java/com/google/genai/examples/InteractionToolCallWithFunctions.java b/examples/src/main/java/com/google/genai/examples/InteractionToolCallWithFunctions.java deleted file mode 100644 index 9705ca33253..00000000000 --- a/examples/src/main/java/com/google/genai/examples/InteractionToolCallWithFunctions.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - * Copyright 2026 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: - * - *

1a. If you are using Vertex AI, setup ADC to get credentials: - * https://cloud.google.com/docs/authentication/provide-credentials-adc#google-idp - * - *

Then set Project, Location, and USE_VERTEXAI flag as environment variables: - * - *

export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT - * - *

export GOOGLE_CLOUD_LOCATION=YOUR_LOCATION - * - *

export GOOGLE_GENAI_USE_VERTEXAI=true - * - *

1b. If you are using Gemini Developer API, 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 exec:java - * -Dexec.mainClass="com.google.genai.examples.InteractionToolCallWithFunctions" - */ -package com.google.genai.examples; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.genai.Client; -import com.google.genai.interactions.core.JsonValue; -import com.google.genai.interactions.models.interactions.Content; -import com.google.genai.interactions.models.interactions.CreateModelInteractionParams; -import com.google.genai.interactions.models.interactions.Function; -import com.google.genai.interactions.models.interactions.FunctionCallStep; -import com.google.genai.interactions.models.interactions.Interaction; -import com.google.genai.interactions.models.interactions.Model; -import com.google.genai.interactions.models.interactions.Step; -import com.google.genai.interactions.models.interactions.Tool; - -/** An example of using the Unified Gen AI Java SDK to perform tool calling with functions. */ -public final class InteractionToolCallWithFunctions { - public static void main(String[] args) { - Client client = new Client(); - - if (client.vertexAI()) { - System.out.println("Interactions API is not yet supported on Vertex AI"); - return; - } - - System.out.println("Using Gemini Developer API"); - - ImmutableMap attendeesSchema = - ImmutableMap.of( - "type", - "array", - "items", - ImmutableMap.of("type", "string"), - "description", - "List of people attending the meeting."); - ImmutableMap dateSchema = - ImmutableMap.of("type", "string", "description", "Date of the meeting (e.g., 2024-07-29)"); - ImmutableMap timeSchema = - ImmutableMap.of("type", "string", "description", "Time of the meeting (e.g., 15:00)"); - ImmutableMap topicSchema = - ImmutableMap.of("type", "string", "description", "The subject or topic of the meeting."); - - ImmutableMap properties = - ImmutableMap.of( - "attendees", - attendeesSchema, - "date", - dateSchema, - "time", - timeSchema, - "topic", - topicSchema); - - ImmutableMap parametersSchema = - ImmutableMap.of( - "type", - "object", - "properties", - properties, - "required", - ImmutableList.of("attendees", "date", "time", "topic")); - - Function function = - Function.builder() - .name("schedule_meeting") - .description("Schedules a meeting with specified attendees at a given time and date.") - .parameters(JsonValue.from(parametersSchema)) - .build(); - - Tool tool = Tool.ofFunction(function); - - CreateModelInteractionParams params = - CreateModelInteractionParams.builder() - .input( - "Schedule a meeting for 10/06/2028 at 10 am with Peter and Amir about the Next Gen" - + " API") - .model(Model.GEMINI_2_5_FLASH) - .tools(ImmutableList.of(tool)) - .build(); - - Interaction interaction = client.interactions.create(params); - - System.out.println("Interaction ID: " + interaction.id()); - System.out.println("Status: " + interaction.status()); - - for (Step step : interaction.steps()) { - if (step.isFunctionCall()) { - FunctionCallStep fc = step.asFunctionCall(); - System.out.println("Function Call: " + fc.name()); - System.out.println("Arguments: " + fc.arguments()); - } else if (step.isModelOutput()) { - step.asModelOutput() - .content() - .ifPresent( - contents -> { - for (Content output : contents) { - output - .text() - .ifPresent( - text -> - System.out.println("Output Text: " + text.text())); - } - }); - } - } - } - - private InteractionToolCallWithFunctions() {} -} diff --git a/examples/src/main/java/com/google/genai/examples/InteractionToolCallWithGoogleSearch.java b/examples/src/main/java/com/google/genai/examples/InteractionToolCallWithGoogleSearch.java deleted file mode 100644 index 4520ee36e63..00000000000 --- a/examples/src/main/java/com/google/genai/examples/InteractionToolCallWithGoogleSearch.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright 2026 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: - * - *

1a. If you are using Vertex AI, setup ADC to get credentials: - * https://cloud.google.com/docs/authentication/provide-credentials-adc#google-idp - * - *

Then set Project, Location, and USE_VERTEXAI flag as environment variables: - * - *

export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT - * - *

export GOOGLE_CLOUD_LOCATION=YOUR_LOCATION - * - *

export GOOGLE_GENAI_USE_VERTEXAI=true - * - *

1b. If you are using Gemini Developer API, 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 exec:java - * -Dexec.mainClass="com.google.genai.examples.InteractionToolCallWithGoogleSearch" - */ -package com.google.genai.examples; - -import com.google.common.collect.ImmutableList; -import com.google.genai.Client; -import com.google.genai.interactions.models.interactions.Content; -import com.google.genai.interactions.models.interactions.CreateModelInteractionParams; -import com.google.genai.interactions.models.interactions.Interaction; -import com.google.genai.interactions.models.interactions.Model; -import com.google.genai.interactions.models.interactions.Step; -import com.google.genai.interactions.models.interactions.Tool; - -/** An example of using the Unified Gen AI Java SDK to perform tool calling with Google Search. */ -public final class InteractionToolCallWithGoogleSearch { - public static void main(String[] args) { - Client client = new Client(); - - if (client.vertexAI()) { - System.out.println("Interactions API is not yet supported on Vertex AI"); - return; - } - - System.out.println("Using Gemini Developer API"); - - Tool.GoogleSearch googleSearch = Tool.GoogleSearch.builder().build(); - Tool tool = Tool.ofGoogleSearch(googleSearch); - - CreateModelInteractionParams params = - CreateModelInteractionParams.builder() - .input("Why is the sky blue") - .model(Model.GEMINI_2_5_FLASH) - .tools(ImmutableList.of(tool)) - .build(); - - Interaction interaction = client.interactions.create(params); - - System.out.println("Interaction ID: " + interaction.id()); - System.out.println("Status: " + interaction.status()); - - for (Step step : interaction.steps()) { - if (step.isModelOutput()) { - step.asModelOutput() - .content() - .ifPresent( - contents -> { - for (Content content : contents) { - content - .text() - .ifPresent( - text -> System.out.println("Output Text: " + text.text())); - } - }); - } - } - } - - private InteractionToolCallWithGoogleSearch() {} -} diff --git a/examples/src/main/java/com/google/genai/examples/InteractionToolCallWithMcpServer.java b/examples/src/main/java/com/google/genai/examples/InteractionToolCallWithMcpServer.java deleted file mode 100644 index e554058a3b8..00000000000 --- a/examples/src/main/java/com/google/genai/examples/InteractionToolCallWithMcpServer.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright 2026 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: - * - *

1a. If you are using Vertex AI, setup ADC to get credentials: - * https://cloud.google.com/docs/authentication/provide-credentials-adc#google-idp - * - *

Then set Project, Location, and USE_VERTEXAI flag as environment variables: - * - *

export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT - * - *

export GOOGLE_CLOUD_LOCATION=YOUR_LOCATION - * - *

export GOOGLE_GENAI_USE_VERTEXAI=true - * - *

1b. If you are using Gemini Developer API, 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 exec:java - * -Dexec.mainClass="com.google.genai.examples.InteractionToolCallWithMcpServer" - */ -package com.google.genai.examples; - -import com.google.genai.Client; -import com.google.genai.interactions.models.interactions.Content; -import com.google.genai.interactions.models.interactions.CreateModelInteractionParams; -import com.google.genai.interactions.models.interactions.Interaction; -import com.google.genai.interactions.models.interactions.Model; -import com.google.genai.interactions.models.interactions.Step; -import com.google.genai.interactions.models.interactions.Tool; - -/** An example of using the Interactions API with an MCP server tool. */ -public final class InteractionToolCallWithMcpServer { - public static void main(String[] args) { - Client client = new Client(); - - if (client.vertexAI()) { - System.out.println("Interactions API is not yet supported on Vertex"); - return; - } - - System.out.println("Using Gemini Developer API"); - - Tool.McpServer mcpServer = - Tool.McpServer.builder() - .name("weather_service") - .url("https://gemini-api-demos.uc.r.appspot.com/mcp") - .build(); - - CreateModelInteractionParams params = - CreateModelInteractionParams.builder() - .input("What is the temperature today in London?") - .systemInstruction( - "Today is 9-23-2025. Any dates before this are in the past, and any dates after" - + " this are in the future.") - .model(Model.GEMINI_2_5_FLASH) - .addTool(Tool.ofMcpServer(mcpServer)) - .build(); - - try { - Interaction interaction = client.interactions.create(params); - - System.out.println("Interaction ID: " + interaction.id()); - System.out.println("Status: " + interaction.status()); - - // Print the text outputs from the interaction. - for (Step step : interaction.steps()) { - if (step.isModelOutput()) { - step.asModelOutput() - .content() - .ifPresent( - contents -> { - for (Content content : contents) { - content - .text() - .ifPresent( - text -> System.out.println("Output: " + text.text())); - } - }); - } - } - } catch (RuntimeException e) { - System.err.println("Error creating interaction: " + e.getMessage()); - e.printStackTrace(); - } - } - - private InteractionToolCallWithMcpServer() {} -} diff --git a/examples/src/main/java/com/google/genai/examples/InteractionToolCallWithUrlContext.java b/examples/src/main/java/com/google/genai/examples/InteractionToolCallWithUrlContext.java deleted file mode 100644 index c4b38865ef4..00000000000 --- a/examples/src/main/java/com/google/genai/examples/InteractionToolCallWithUrlContext.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright 2026 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: - * - *

1a. If you are using Vertex AI, setup ADC to get credentials: - * https://cloud.google.com/docs/authentication/provide-credentials-adc#google-idp - * - *

Then set Project, Location, and USE_VERTEXAI flag as environment variables: - * - *

export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT - * - *

export GOOGLE_CLOUD_LOCATION=YOUR_LOCATION - * - *

export GOOGLE_GENAI_USE_VERTEXAI=true - * - *

1b. If you are using Gemini Developer API, 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 exec:java - * -Dexec.mainClass="com.google.genai.examples.InteractionToolCallWithUrlContext" - */ -package com.google.genai.examples; - -import com.google.genai.Client; -import com.google.genai.interactions.models.interactions.Content; -import com.google.genai.interactions.models.interactions.CreateModelInteractionParams; -import com.google.genai.interactions.models.interactions.Interaction; -import com.google.genai.interactions.models.interactions.Model; -import com.google.genai.interactions.models.interactions.Step; -import com.google.genai.interactions.models.interactions.Tool; - -/** An example of using the Interactions API with URL context tool. */ -public final class InteractionToolCallWithUrlContext { - public static void main(String[] args) { - Client client = new Client(); - - if (client.vertexAI()) { - System.out.println("Interactions API is not yet supported on Vertex"); - return; - } - - System.out.println("Using Gemini Developer API"); - - CreateModelInteractionParams params = - CreateModelInteractionParams.builder() - .input( - "Compare the ingredients and cooking times from the recipes at" - + " https://www.foodnetwork.com/recipes/ina-garten/perfect-roast-chicken-recipe-1940592" - + " and https://www.allrecipes.com/recipe/21151/simple-whole-roast-chicken/") - .model(Model.GEMINI_2_5_FLASH) - .addTool(Tool.ofUrlContext()) - .build(); - - try { - Interaction interaction = client.interactions.create(params); - - System.out.println("Interaction ID: " + interaction.id()); - System.out.println("Status: " + interaction.status()); - - // Print the text outputs from the interaction. - for (Step step : interaction.steps()) { - if (step.isModelOutput()) { - step.asModelOutput() - .content() - .ifPresent( - contents -> { - for (Content content : contents) { - content - .text() - .ifPresent( - text -> System.out.println("Output: " + text.text())); - } - }); - } - } - } catch (RuntimeException e) { - System.err.println("Error creating interaction: " + e.getMessage()); - e.printStackTrace(); - } - } - - private InteractionToolCallWithUrlContext() {} -} diff --git a/examples/src/main/java/com/google/genai/examples/InteractionWithConfig.java b/examples/src/main/java/com/google/genai/examples/InteractionWithConfig.java deleted file mode 100644 index 0624c37bf5c..00000000000 --- a/examples/src/main/java/com/google/genai/examples/InteractionWithConfig.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright 2026 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: - * - *

1a. If you are using Vertex AI, setup ADC to get credentials: - * https://cloud.google.com/docs/authentication/provide-credentials-adc#google-idp - * - *

Then set Project, Location, and USE_VERTEXAI flag as environment variables: - * - *

export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT - * - *

export GOOGLE_CLOUD_LOCATION=YOUR_LOCATION - * - *

export GOOGLE_GENAI_USE_VERTEXAI=true - * - *

1b. If you are using Gemini Developer API, 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 exec:java -Dexec.mainClass="com.google.genai.examples.InteractionWithConfig" - */ -package com.google.genai.examples; - -import com.google.genai.Client; -import com.google.genai.interactions.models.interactions.Content; -import com.google.genai.interactions.models.interactions.CreateModelInteractionParams; -import com.google.genai.interactions.models.interactions.Interaction; -import com.google.genai.interactions.models.interactions.Model; -import com.google.genai.interactions.models.interactions.Step; - -/** An example of using the Unified Gen AI Java SDK to create an interaction with config. */ -public final class InteractionWithConfig { - public static void main(String[] args) { - Client client = new Client(); - - if (client.vertexAI()) { - System.out.println("Interactions API is not yet supported on Vertex AI"); - return; - } - - System.out.println("Using Gemini Developer API"); - - CreateModelInteractionParams params = - CreateModelInteractionParams.builder() - .input("Tell me a story") - .model(Model.GEMINI_2_5_FLASH) - .systemInstruction("You are a helpful assistant") - .build(); - - Interaction interaction = client.interactions.create(params); - - System.out.println("Interaction ID: " + interaction.id()); - System.out.println("Status: " + interaction.status()); - - for (Step step : interaction.steps()) { - if (step.isModelOutput()) { - step.asModelOutput() - .content() - .ifPresent( - contents -> { - for (Content content : contents) { - content - .text() - .ifPresent(text -> System.out.println("Output: " + text.text())); - } - }); - } - } - } - - private InteractionWithConfig() {} -} diff --git a/pom.xml b/pom.xml index 50d08c6c232..676ecb3b48c 100644 --- a/pom.xml +++ b/pom.xml @@ -55,7 +55,6 @@ 5.11.4 1.6.0 4.12.0 - 1.9.10 src/main/java src/test/java @@ -131,11 +130,6 @@ okhttp ${okhttp.version} - - com.squareup.okhttp3 - logging-interceptor - ${okhttp.version} - com.google.protobuf protobuf-java @@ -166,27 +160,10 @@ jspecify 1.0.0 - org.jetbrains.kotlin kotlin-stdlib-jdk8 - ${kotlin.version} - - - org.jetbrains.kotlin - kotlin-reflect - ${kotlin.version} - - - - com.fasterxml.jackson.module - jackson-module-kotlin - ${jackson.version} - - - com.google.errorprone - error_prone_annotations - 2.36.0 + 1.9.10 @@ -327,70 +304,6 @@ - - org.jetbrains.kotlin - kotlin-maven-plugin - ${kotlin.version} - - - compile - - compile - - - - ${project.basedir}/${main.java.src.dir} - - - - - test-compile - - test-compile - - - - ${project.basedir}/${test.java.src.dir} - - - - - - 1.8 - - -Xjvm-default=all - - - - - maven-compiler-plugin - - - - default-compile - none - - - - default-testCompile - none - - - java-compile - compile - - compile - - - - java-test-compile - test-compile - - testCompile - - - - org.jacoco jacoco-maven-plugin @@ -631,7 +544,6 @@ - maven-compiler-plugin diff --git a/src/main/java/com/google/genai/ApiClient.java b/src/main/java/com/google/genai/ApiClient.java index f763457f626..0e5bbc384df 100644 --- a/src/main/java/com/google/genai/ApiClient.java +++ b/src/main/java/com/google/genai/ApiClient.java @@ -26,10 +26,6 @@ import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.genai.errors.GenAiIOException; -// interactions:strip_begin -import com.google.genai.interactions.core.VertexInfo; -import com.google.genai.interactions.core.http.HttpClient; -// interactions:strip_end import com.google.genai.types.ClientOptions; import com.google.genai.types.HttpOptions; import com.google.genai.types.HttpRetryOptions; @@ -81,9 +77,6 @@ public abstract class ApiClient implements AutoCloseable { HttpOptions httpOptions; final boolean vertexAI; final Optional clientOptions; - // interactions:strip_begin - final com.google.genai.interactions.core.ClientOptions interactionsClientOptions; - // interactions:strip_end final Optional customBaseUrl; // For Google AI APIs final Optional apiKey; @@ -127,9 +120,6 @@ protected ApiClient( } this.httpClient = createHttpClient(httpOptions, clientOptions); - // interactions:strip_begin - this.interactionsClientOptions = createInteractionsClientOptions(); - // interactions:strip_end } ApiClient( @@ -284,9 +274,6 @@ protected ApiClient( } this.vertexAI = true; this.httpClient = createHttpClient(httpOptions, clientOptions); - // interactions:strip_begin - this.interactionsClientOptions = createInteractionsClientOptions(); - // interactions:strip_end } private OkHttpClient createHttpClient( @@ -377,67 +364,6 @@ private void applyProxyOptions(ProxyOptions proxyOptions, OkHttpClient.Builder b } } - // interactions:strip_begin - private com.google.genai.interactions.core.ClientOptions createInteractionsClientOptions() { - HttpClient httpClient = - // Wrap in a non-closing client so that we can call `.close()` on the client options - // below without closing twice. - new NonClosingDelegatingHttpClient( - new com.google.genai.interactions.client.okhttp.OkHttpClient(this.httpClient)); - if (credentials.isPresent()) { - httpClient = new GoogleCredentialsHttpClient(httpClient, credentials.get()); - } - - // NOTE: We purposefully DO NOT set the following: - // - `checkJacksonVersionCompatibility`, `jsonMapper`, `sleeper`, `clock`, - // `responseValidation`, and `queryParams` because the defaults are fine and there are no - // corresponding fields in - // the main client. - // - `timeout` because we override it by passing a custom `OkHttpClient`, which has timeouts - // configured. - // - `maxRetries` because we don't wrap in `RetryingHttpClient` because retries are configured - // on the `OkHttpClient` - // instead. - com.google.genai.interactions.core.ClientOptions.Builder builder = - com.google.genai.interactions.core.ClientOptions.builder() - .httpClient(httpClient) - .baseUrl(httpOptions.baseUrl()) - .apiKey(apiKey); - - // BEGIN_SDK_PRIVATE_ONLY - // clientOptions - // .flatMap(ClientOptions::streamHandlerExecutor) - // .ifPresent( - // streamHandlerExecutor -> { - // com.google.genai.interactions.core.ClientOptions.Builder unused = - // builder.streamHandlerExecutor(streamHandlerExecutor); - // }); - // END_SDK_PRIVATE_ONLY - - httpOptions - .apiVersion() - .ifPresent( - apiVersion -> { - com.google.genai.interactions.core.ClientOptions.Builder unused = - builder.apiVersion(apiVersion); - }); - if (vertexAI && project.isPresent() && location.isPresent()) { - com.google.genai.interactions.core.ClientOptions.Builder unused = - builder.vertexInfo(new VertexInfo(project.get(), location.get())); - } - httpOptions - .headers() - .ifPresent( - headers -> - headers.forEach( - (name, value) -> { - com.google.genai.interactions.core.ClientOptions.Builder unused = - builder.putHeader(name, value); - })); - return builder.build(); - } - // interactions:strip_end - /** Builds a HTTP request given the http method, path, and request json string. */ @SuppressWarnings("unchecked") protected Request buildRequest( @@ -965,9 +891,6 @@ public void close() { if (httpClient().cache() != null) { httpClient().cache().close(); } - // interactions:strip_begin - this.interactionsClientOptions.close(); - // interactions:strip_end } catch (IOException e) { throw new GenAiIOException("Failed to close the client.", e); } diff --git a/src/main/java/com/google/genai/Client.java b/src/main/java/com/google/genai/Client.java index ad236f80223..763d04507f8 100644 --- a/src/main/java/com/google/genai/Client.java +++ b/src/main/java/com/google/genai/Client.java @@ -19,14 +19,8 @@ import static com.google.common.base.Preconditions.checkNotNull; import com.google.auth.oauth2.GoogleCredentials; -import com.google.errorprone.annotations.CanIgnoreReturnValue; -// interactions:strip_begin -import com.google.genai.interactions.services.async.InteractionServiceAsync; -import com.google.genai.interactions.services.async.InteractionServiceAsyncImpl; -import com.google.genai.interactions.services.blocking.InteractionService; -import com.google.genai.interactions.services.blocking.InteractionServiceImpl; -// interactions:strip_end import com.google.common.collect.ImmutableMap; +import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.genai.types.ClientOptions; import com.google.genai.types.HttpOptions; import java.util.Optional; @@ -50,11 +44,6 @@ public final class Async { public final AsyncTunings tunings; public final AsyncFileSearchStores fileSearchStores; - // interactions:strip_begin - public final InteractionServiceAsync interactions; - - // interactions:strip_end - public Async(ApiClient apiClient) { this.models = new AsyncModels(apiClient); this.batches = new AsyncBatches(apiClient); @@ -66,9 +55,6 @@ public Async(ApiClient apiClient) { this.authTokens = new AsyncTokens(apiClient); this.tunings = new AsyncTunings(apiClient); this.fileSearchStores = new AsyncFileSearchStores(apiClient); - // interactions:strip_begin - this.interactions = new InteractionServiceAsyncImpl(apiClient.interactionsClientOptions); - // interactions:strip_end } } @@ -85,11 +71,6 @@ public Async(ApiClient apiClient) { public final Tunings tunings; public final FileSearchStores fileSearchStores; - // interactions:strip_begin - public final InteractionService interactions; - - // interactions:strip_end - /** Builder for {@link Client}. */ public static class Builder { private Optional apiKey = Optional.empty(); @@ -98,8 +79,8 @@ public static class Builder { private Optional credentials = Optional.empty(); private Optional clientOptions = Optional.empty(); private Optional httpOptions = Optional.empty(); - private Optional enterprise = Optional.empty(); private Optional vertexAI = Optional.empty(); + private Optional enterprise = Optional.empty(); private Optional debugConfig = Optional.empty(); /** Builds the {@link Client} instance. */ @@ -111,8 +92,8 @@ public Client build() { credentials, httpOptions, clientOptions, - enterprise, vertexAI, + enterprise, debugConfig); } @@ -173,9 +154,7 @@ public Builder enterprise(boolean enterprise) { return this; } - /** Sets whether to use Vertex AI APIs. - * When both enterprise and vertexAI are set, and they have different values, an IllegalArgumentException will be thrown. - */ + /** Sets whether to use Vertex AI APIs. */ @CanIgnoreReturnValue public Builder vertexAI(boolean vertexAI) { this.vertexAI = Optional.of(vertexAI); @@ -208,8 +187,8 @@ public Client() { /* credentials= */ Optional.empty(), /* httpOptions= */ Optional.empty(), /* clientOptions= */ Optional.empty(), - /* enterprise= */ Optional.empty(), /* vertexAI= */ Optional.empty(), + /* enterprise= */ Optional.empty(), /* debugConfig= */ Optional.empty()); } @@ -239,8 +218,8 @@ private Client( Optional credentials, Optional httpOptions, Optional clientOptions, - Optional enterprise, Optional vertexAI, + Optional enterprise, Optional debugConfig) { checkNotNull(vertexAI, "vertexAI cannot be null"); checkNotNull(enterprise, "enterprise cannot be null"); @@ -341,18 +320,15 @@ private Client( authTokens = new Tokens(this.apiClient); tunings = new Tunings(this.apiClient); fileSearchStores = new FileSearchStores(this.apiClient); - // interactions:strip_begin - interactions = new InteractionServiceImpl(this.apiClient.interactionsClientOptions); - // interactions:strip_end } - /** Returns whether the client is using Gemini Enterprise Agent Platform. */ - public boolean enterprise() { + /** Returns whether the client is using Vertex AI APIs. */ + public boolean vertexAI() { return apiClient.vertexAI(); } - /** Returns whether the client is using Vertex AI APIs. */ - public boolean vertexAI() { + /** Returns whether the client is using Gemini Enterprise Agent Platform. */ + public boolean enterprise() { return apiClient.vertexAI(); } diff --git a/src/main/java/com/google/genai/GoogleCredentialsHttpClient.java b/src/main/java/com/google/genai/GoogleCredentialsHttpClient.java deleted file mode 100644 index 99e7e6f2e38..00000000000 --- a/src/main/java/com/google/genai/GoogleCredentialsHttpClient.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright 2026 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; - -import com.google.auth.oauth2.GoogleCredentials; -import com.google.genai.errors.GenAiIOException; -import com.google.genai.interactions.core.RequestOptions; -import com.google.genai.interactions.core.http.HttpClient; -import com.google.genai.interactions.core.http.HttpRequest; -import com.google.genai.interactions.core.http.HttpResponse; - -import java.io.IOException; -import java.util.Set; -import java.util.concurrent.CompletableFuture; - -/** A wrapper {@link HttpClient} that adds request headers from {@link GoogleCredentials}. */ -final class GoogleCredentialsHttpClient implements HttpClient { - private final HttpClient delegate; - private final GoogleCredentials credentials; - - GoogleCredentialsHttpClient(HttpClient delegate, GoogleCredentials credentials) { - this.delegate = delegate; - this.credentials = credentials; - } - - @Override - public HttpResponse execute(HttpRequest request, RequestOptions requestOptions) { - return delegate.execute(withGoogleCredentialsHeaders(request), requestOptions); - } - - @Override - public HttpResponse execute(HttpRequest request) { - return delegate.execute(withGoogleCredentialsHeaders(request)); - } - - @Override - public CompletableFuture executeAsync(HttpRequest request, RequestOptions requestOptions) { - return CompletableFuture.supplyAsync(() -> withGoogleCredentialsHeaders(request)) - .thenCompose(newRequest -> delegate.executeAsync(newRequest, requestOptions)); - } - - @Override - public CompletableFuture executeAsync(HttpRequest request) { - return CompletableFuture.supplyAsync(() -> withGoogleCredentialsHeaders(request)) - .thenCompose(delegate::executeAsync); - } - - private HttpRequest withGoogleCredentialsHeaders(HttpRequest request) { - Set headerNames = request.headers().names(); - if (headerNames.contains("Authorization") || headerNames.contains("x-goog-api-key")) { - return request; - } - - try { - credentials.refreshIfExpired(); - } catch (IOException e) { - throw new GenAiIOException("Failed to refresh credentials.", e); - } - - String accessToken = credentials.getAccessToken().getTokenValue(); - HttpRequest.Builder builder = request.toBuilder().putHeader("Authorization", "Bearer " + accessToken); - if (credentials.getQuotaProjectId() != null && !headerNames.contains("x-goog-user-project")) { - builder = builder.putHeader("x-goog-user-project", credentials.getQuotaProjectId()); - } - return builder.build(); - } - - @Override - public void close() { - delegate.close(); - } -} - diff --git a/src/main/java/com/google/genai/NonClosingDelegatingHttpClient.java b/src/main/java/com/google/genai/NonClosingDelegatingHttpClient.java deleted file mode 100644 index 305e553a8ee..00000000000 --- a/src/main/java/com/google/genai/NonClosingDelegatingHttpClient.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright 2026 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; - -import com.google.genai.interactions.core.RequestOptions; -import com.google.genai.interactions.core.http.HttpClient; -import com.google.genai.interactions.core.http.HttpRequest; -import com.google.genai.interactions.core.http.HttpResponse; - -import java.util.concurrent.CompletableFuture; - -/** - * A wrapper {@link HttpClient} that does not close its delegate when the wrapper is closed. - * - *

This is used to pass the client to other classes that may try to close it, but we don't want them to because we - * want to retain ownership of the client. - */ -final class NonClosingDelegatingHttpClient implements HttpClient { - private final HttpClient delegate; - - NonClosingDelegatingHttpClient(HttpClient delegate) { - this.delegate = delegate; - } - - @Override - public HttpResponse execute(HttpRequest request, RequestOptions requestOptions) { - return delegate.execute(request, requestOptions); - } - - @Override - public HttpResponse execute(HttpRequest request) { - return delegate.execute(request); - } - - @Override - public CompletableFuture executeAsync(HttpRequest request, RequestOptions requestOptions) { - return delegate.executeAsync(request, requestOptions); - } - - @Override - public CompletableFuture executeAsync(HttpRequest request) { - return delegate.executeAsync(request); - } - - @Override - public void close() { - // Purposefully empty. - } -} diff --git a/src/main/java/com/google/genai/interactions/client/GeminiNextGenApiClient.kt b/src/main/java/com/google/genai/interactions/client/GeminiNextGenApiClient.kt deleted file mode 100644 index 3927f33e594..00000000000 --- a/src/main/java/com/google/genai/interactions/client/GeminiNextGenApiClient.kt +++ /dev/null @@ -1,93 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.client - -import com.google.genai.interactions.core.ClientOptions -import com.google.genai.interactions.services.blocking.InteractionService -import java.util.function.Consumer - -/** - * A client for interacting with the Gemini Next Gen API REST API synchronously. You can also switch - * to asynchronous execution via the [async] method. - * - * This client performs best when you create a single instance and reuse it for all interactions - * with the REST API. This is because each client holds its own connection pool and thread pools. - * Reusing connections and threads reduces latency and saves memory. The client also handles rate - * limiting per client. This means that creating and using multiple instances at the same time will - * not respect rate limits. - * - * The threads and connections that are held will be released automatically if they remain idle. But - * if you are writing an application that needs to aggressively release unused resources, then you - * may call [close]. - */ -interface GeminiNextGenApiClient { - - /** - * Returns a version of this client that uses asynchronous execution. - * - * The returned client shares its resources, like its connection pool and thread pools, with - * this client. - */ - fun async(): GeminiNextGenApiClientAsync - - /** - * Returns a view of this service that provides access to raw HTTP responses for each method. - */ - fun withRawResponse(): WithRawResponse - - /** - * Returns a view of this service with the given option modifications applied. - * - * The original service is not modified. - */ - fun withOptions(modifier: Consumer): GeminiNextGenApiClient - - fun interactions(): InteractionService - - /** - * Closes this client, relinquishing any underlying resources. - * - * This is purposefully not inherited from [AutoCloseable] because the client is long-lived and - * usually should not be synchronously closed via try-with-resources. - * - * It's also usually not necessary to call this method at all. the default HTTP client - * automatically releases threads and connections if they remain idle, but if you are writing an - * application that needs to aggressively release unused resources, then you may call this - * method. - */ - fun close() - - /** - * A view of [GeminiNextGenApiClient] that provides access to raw HTTP responses for each - * method. - */ - interface WithRawResponse { - - /** - * Returns a view of this service with the given option modifications applied. - * - * The original service is not modified. - */ - fun withOptions( - modifier: Consumer - ): GeminiNextGenApiClient.WithRawResponse - - fun interactions(): InteractionService.WithRawResponse - } -} diff --git a/src/main/java/com/google/genai/interactions/client/GeminiNextGenApiClientAsync.kt b/src/main/java/com/google/genai/interactions/client/GeminiNextGenApiClientAsync.kt deleted file mode 100644 index 458d18e858c..00000000000 --- a/src/main/java/com/google/genai/interactions/client/GeminiNextGenApiClientAsync.kt +++ /dev/null @@ -1,93 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.client - -import com.google.genai.interactions.core.ClientOptions -import com.google.genai.interactions.services.async.InteractionServiceAsync -import java.util.function.Consumer - -/** - * A client for interacting with the Gemini Next Gen API REST API asynchronously. You can also - * switch to synchronous execution via the [sync] method. - * - * This client performs best when you create a single instance and reuse it for all interactions - * with the REST API. This is because each client holds its own connection pool and thread pools. - * Reusing connections and threads reduces latency and saves memory. The client also handles rate - * limiting per client. This means that creating and using multiple instances at the same time will - * not respect rate limits. - * - * The threads and connections that are held will be released automatically if they remain idle. But - * if you are writing an application that needs to aggressively release unused resources, then you - * may call [close]. - */ -interface GeminiNextGenApiClientAsync { - - /** - * Returns a version of this client that uses synchronous execution. - * - * The returned client shares its resources, like its connection pool and thread pools, with - * this client. - */ - fun sync(): GeminiNextGenApiClient - - /** - * Returns a view of this service that provides access to raw HTTP responses for each method. - */ - fun withRawResponse(): WithRawResponse - - /** - * Returns a view of this service with the given option modifications applied. - * - * The original service is not modified. - */ - fun withOptions(modifier: Consumer): GeminiNextGenApiClientAsync - - fun interactions(): InteractionServiceAsync - - /** - * Closes this client, relinquishing any underlying resources. - * - * This is purposefully not inherited from [AutoCloseable] because the client is long-lived and - * usually should not be synchronously closed via try-with-resources. - * - * It's also usually not necessary to call this method at all. the default HTTP client - * automatically releases threads and connections if they remain idle, but if you are writing an - * application that needs to aggressively release unused resources, then you may call this - * method. - */ - fun close() - - /** - * A view of [GeminiNextGenApiClientAsync] that provides access to raw HTTP responses for each - * method. - */ - interface WithRawResponse { - - /** - * Returns a view of this service with the given option modifications applied. - * - * The original service is not modified. - */ - fun withOptions( - modifier: Consumer - ): GeminiNextGenApiClientAsync.WithRawResponse - - fun interactions(): InteractionServiceAsync.WithRawResponse - } -} diff --git a/src/main/java/com/google/genai/interactions/client/GeminiNextGenApiClientAsyncImpl.kt b/src/main/java/com/google/genai/interactions/client/GeminiNextGenApiClientAsyncImpl.kt deleted file mode 100644 index a82a5d38900..00000000000 --- a/src/main/java/com/google/genai/interactions/client/GeminiNextGenApiClientAsyncImpl.kt +++ /dev/null @@ -1,78 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.client - -import com.google.genai.interactions.core.ClientOptions -import com.google.genai.interactions.core.getPackageVersion -import com.google.genai.interactions.services.async.InteractionServiceAsync -import com.google.genai.interactions.services.async.InteractionServiceAsyncImpl -import java.util.function.Consumer - -class GeminiNextGenApiClientAsyncImpl(private val clientOptions: ClientOptions) : - GeminiNextGenApiClientAsync { - - private val clientOptionsWithUserAgent = - if (clientOptions.headers.names().contains("User-Agent")) clientOptions - else - clientOptions - .toBuilder() - .putHeader("User-Agent", "${javaClass.simpleName}/Java ${getPackageVersion()}") - .build() - - // Pass the original clientOptions so that this client sets its own User-Agent. - private val sync: GeminiNextGenApiClient by lazy { GeminiNextGenApiClientImpl(clientOptions) } - - private val withRawResponse: GeminiNextGenApiClientAsync.WithRawResponse by lazy { - WithRawResponseImpl(clientOptions) - } - - private val interactions: InteractionServiceAsync by lazy { - InteractionServiceAsyncImpl(clientOptionsWithUserAgent) - } - - override fun sync(): GeminiNextGenApiClient = sync - - override fun withRawResponse(): GeminiNextGenApiClientAsync.WithRawResponse = withRawResponse - - override fun withOptions( - modifier: Consumer - ): GeminiNextGenApiClientAsync = - GeminiNextGenApiClientAsyncImpl(clientOptions.toBuilder().apply(modifier::accept).build()) - - override fun interactions(): InteractionServiceAsync = interactions - - override fun close() = clientOptions.close() - - class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : - GeminiNextGenApiClientAsync.WithRawResponse { - - private val interactions: InteractionServiceAsync.WithRawResponse by lazy { - InteractionServiceAsyncImpl.WithRawResponseImpl(clientOptions) - } - - override fun withOptions( - modifier: Consumer - ): GeminiNextGenApiClientAsync.WithRawResponse = - GeminiNextGenApiClientAsyncImpl.WithRawResponseImpl( - clientOptions.toBuilder().apply(modifier::accept).build() - ) - - override fun interactions(): InteractionServiceAsync.WithRawResponse = interactions - } -} diff --git a/src/main/java/com/google/genai/interactions/client/GeminiNextGenApiClientImpl.kt b/src/main/java/com/google/genai/interactions/client/GeminiNextGenApiClientImpl.kt deleted file mode 100644 index a2c3de26ac5..00000000000 --- a/src/main/java/com/google/genai/interactions/client/GeminiNextGenApiClientImpl.kt +++ /dev/null @@ -1,78 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.client - -import com.google.genai.interactions.core.ClientOptions -import com.google.genai.interactions.core.getPackageVersion -import com.google.genai.interactions.services.blocking.InteractionService -import com.google.genai.interactions.services.blocking.InteractionServiceImpl -import java.util.function.Consumer - -class GeminiNextGenApiClientImpl(private val clientOptions: ClientOptions) : - GeminiNextGenApiClient { - - private val clientOptionsWithUserAgent = - if (clientOptions.headers.names().contains("User-Agent")) clientOptions - else - clientOptions - .toBuilder() - .putHeader("User-Agent", "${javaClass.simpleName}/Java ${getPackageVersion()}") - .build() - - // Pass the original clientOptions so that this client sets its own User-Agent. - private val async: GeminiNextGenApiClientAsync by lazy { - GeminiNextGenApiClientAsyncImpl(clientOptions) - } - - private val withRawResponse: GeminiNextGenApiClient.WithRawResponse by lazy { - WithRawResponseImpl(clientOptions) - } - - private val interactions: InteractionService by lazy { - InteractionServiceImpl(clientOptionsWithUserAgent) - } - - override fun async(): GeminiNextGenApiClientAsync = async - - override fun withRawResponse(): GeminiNextGenApiClient.WithRawResponse = withRawResponse - - override fun withOptions(modifier: Consumer): GeminiNextGenApiClient = - GeminiNextGenApiClientImpl(clientOptions.toBuilder().apply(modifier::accept).build()) - - override fun interactions(): InteractionService = interactions - - override fun close() = clientOptions.close() - - class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : - GeminiNextGenApiClient.WithRawResponse { - - private val interactions: InteractionService.WithRawResponse by lazy { - InteractionServiceImpl.WithRawResponseImpl(clientOptions) - } - - override fun withOptions( - modifier: Consumer - ): GeminiNextGenApiClient.WithRawResponse = - GeminiNextGenApiClientImpl.WithRawResponseImpl( - clientOptions.toBuilder().apply(modifier::accept).build() - ) - - override fun interactions(): InteractionService.WithRawResponse = interactions - } -} diff --git a/src/main/java/com/google/genai/interactions/client/okhttp/GeminiNextGenApiOkHttpClient.kt b/src/main/java/com/google/genai/interactions/client/okhttp/GeminiNextGenApiOkHttpClient.kt deleted file mode 100644 index 4e879f382d6..00000000000 --- a/src/main/java/com/google/genai/interactions/client/okhttp/GeminiNextGenApiOkHttpClient.kt +++ /dev/null @@ -1,408 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.client.okhttp - -import com.fasterxml.jackson.databind.json.JsonMapper -import com.google.genai.interactions.client.GeminiNextGenApiClient -import com.google.genai.interactions.client.GeminiNextGenApiClientImpl -import com.google.genai.interactions.core.ClientOptions -import com.google.genai.interactions.core.Sleeper -import com.google.genai.interactions.core.Timeout -import com.google.genai.interactions.core.http.AsyncStreamResponse -import com.google.genai.interactions.core.http.Headers -import com.google.genai.interactions.core.http.HttpClient -import com.google.genai.interactions.core.http.QueryParams -import com.google.genai.interactions.core.jsonMapper -import java.net.Proxy -import java.time.Clock -import java.time.Duration -import java.util.Optional -import java.util.concurrent.Executor -import java.util.concurrent.ExecutorService -import javax.net.ssl.HostnameVerifier -import javax.net.ssl.SSLSocketFactory -import javax.net.ssl.X509TrustManager -import kotlin.jvm.optionals.getOrNull - -/** - * A class that allows building an instance of [GeminiNextGenApiClient] with [OkHttpClient] as the - * underlying [HttpClient]. - */ -class GeminiNextGenApiOkHttpClient private constructor() { - - companion object { - - /** Returns a mutable builder for constructing an instance of [GeminiNextGenApiClient]. */ - @JvmStatic fun builder() = Builder() - - /** - * Returns a client configured using system properties and environment variables. - * - * @see ClientOptions.Builder.fromEnv - */ - @JvmStatic fun fromEnv(): GeminiNextGenApiClient = builder().fromEnv().build() - } - - /** A builder for [GeminiNextGenApiOkHttpClient]. */ - class Builder internal constructor() { - - private var clientOptions: ClientOptions.Builder = ClientOptions.builder() - private var dispatcherExecutorService: ExecutorService? = null - private var proxy: Proxy? = null - private var maxIdleConnections: Int? = null - private var keepAliveDuration: Duration? = null - private var sslSocketFactory: SSLSocketFactory? = null - private var trustManager: X509TrustManager? = null - private var hostnameVerifier: HostnameVerifier? = null - - /** - * The executor service to use for running HTTP requests. - * - * Defaults to OkHttp's - * [default executor service](https://github.com/square/okhttp/blob/ace792f443b2ffb17974f5c0d1cecdf589309f26/okhttp/src/commonJvmAndroid/kotlin/okhttp3/Dispatcher.kt#L98-L104). - * - * This class takes ownership of the executor service and shuts it down when closed. - */ - fun dispatcherExecutorService(dispatcherExecutorService: ExecutorService?) = apply { - this.dispatcherExecutorService = dispatcherExecutorService - } - - /** - * Alias for calling [Builder.dispatcherExecutorService] with - * `dispatcherExecutorService.orElse(null)`. - */ - fun dispatcherExecutorService(dispatcherExecutorService: Optional) = - dispatcherExecutorService(dispatcherExecutorService.getOrNull()) - - fun proxy(proxy: Proxy?) = apply { this.proxy = proxy } - - /** Alias for calling [Builder.proxy] with `proxy.orElse(null)`. */ - fun proxy(proxy: Optional) = proxy(proxy.getOrNull()) - - /** - * The maximum number of idle connections kept by the underlying OkHttp connection pool. - * - * If this is set, then [keepAliveDuration] must also be set. - * - * If unset, then OkHttp's default is used. - */ - fun maxIdleConnections(maxIdleConnections: Int?) = apply { - this.maxIdleConnections = maxIdleConnections - } - - /** - * Alias for [Builder.maxIdleConnections]. - * - * This unboxed primitive overload exists for backwards compatibility. - */ - fun maxIdleConnections(maxIdleConnections: Int) = - maxIdleConnections(maxIdleConnections as Int?) - - /** - * Alias for calling [Builder.maxIdleConnections] with `maxIdleConnections.orElse(null)`. - */ - fun maxIdleConnections(maxIdleConnections: Optional) = - maxIdleConnections(maxIdleConnections.getOrNull()) - - /** - * The keep-alive duration for idle connections in the underlying OkHttp connection pool. - * - * If this is set, then [maxIdleConnections] must also be set. - * - * If unset, then OkHttp's default is used. - */ - fun keepAliveDuration(keepAliveDuration: Duration?) = apply { - this.keepAliveDuration = keepAliveDuration - } - - /** Alias for calling [Builder.keepAliveDuration] with `keepAliveDuration.orElse(null)`. */ - fun keepAliveDuration(keepAliveDuration: Optional) = - keepAliveDuration(keepAliveDuration.getOrNull()) - - /** - * The socket factory used to secure HTTPS connections. - * - * If this is set, then [trustManager] must also be set. - * - * If unset, then the system default is used. Most applications should not call this method, - * and instead use the system default. The default include special optimizations that can be - * lost if the implementation is modified. - */ - fun sslSocketFactory(sslSocketFactory: SSLSocketFactory?) = apply { - this.sslSocketFactory = sslSocketFactory - } - - /** Alias for calling [Builder.sslSocketFactory] with `sslSocketFactory.orElse(null)`. */ - fun sslSocketFactory(sslSocketFactory: Optional) = - sslSocketFactory(sslSocketFactory.getOrNull()) - - /** - * The trust manager used to secure HTTPS connections. - * - * If this is set, then [sslSocketFactory] must also be set. - * - * If unset, then the system default is used. Most applications should not call this method, - * and instead use the system default. The default include special optimizations that can be - * lost if the implementation is modified. - */ - fun trustManager(trustManager: X509TrustManager?) = apply { - this.trustManager = trustManager - } - - /** Alias for calling [Builder.trustManager] with `trustManager.orElse(null)`. */ - fun trustManager(trustManager: Optional) = - trustManager(trustManager.getOrNull()) - - /** - * The verifier used to confirm that response certificates apply to requested hostnames for - * HTTPS connections. - * - * If unset, then a default hostname verifier is used. - */ - fun hostnameVerifier(hostnameVerifier: HostnameVerifier?) = apply { - this.hostnameVerifier = hostnameVerifier - } - - /** Alias for calling [Builder.hostnameVerifier] with `hostnameVerifier.orElse(null)`. */ - fun hostnameVerifier(hostnameVerifier: Optional) = - hostnameVerifier(hostnameVerifier.getOrNull()) - - /** - * Whether to throw an exception if any of the Jackson versions detected at runtime are - * incompatible with the SDK's minimum supported Jackson version (2.13.4). - * - * Defaults to true. Use extreme caution when disabling this option. There is no guarantee - * that the SDK will work correctly when using an incompatible Jackson version. - */ - fun checkJacksonVersionCompatibility(checkJacksonVersionCompatibility: Boolean) = apply { - clientOptions.checkJacksonVersionCompatibility(checkJacksonVersionCompatibility) - } - - /** - * The Jackson JSON mapper to use for serializing and deserializing JSON. - * - * Defaults to [com.google.genai.interactions.core.jsonMapper]. The default is usually - * sufficient and rarely needs to be overridden. - */ - fun jsonMapper(jsonMapper: JsonMapper) = apply { clientOptions.jsonMapper(jsonMapper) } - - /** - * The executor to use for running [AsyncStreamResponse.Handler] callbacks. - * - * Defaults to a dedicated cached thread pool. - * - * This class takes ownership of the executor and shuts it down, if possible, when closed. - */ - fun streamHandlerExecutor(streamHandlerExecutor: Executor) = apply { - clientOptions.streamHandlerExecutor(streamHandlerExecutor) - } - - /** - * The interface to use for delaying execution, like during retries. - * - * This is primarily useful for using fake delays in tests. - * - * Defaults to real execution delays. - * - * This class takes ownership of the sleeper and closes it when closed. - */ - fun sleeper(sleeper: Sleeper) = apply { clientOptions.sleeper(sleeper) } - - /** - * The clock to use for operations that require timing, like retries. - * - * This is primarily useful for using a fake clock in tests. - * - * Defaults to [Clock.systemUTC]. - */ - fun clock(clock: Clock) = apply { clientOptions.clock(clock) } - - /** - * The base URL to use for every request. - * - * Defaults to the production environment: `https://generativelanguage.googleapis.com`. - */ - fun baseUrl(baseUrl: String?) = apply { clientOptions.baseUrl(baseUrl) } - - /** Alias for calling [Builder.baseUrl] with `baseUrl.orElse(null)`. */ - fun baseUrl(baseUrl: Optional) = baseUrl(baseUrl.getOrNull()) - - /** - * Whether to call `validate` on every response before returning it. - * - * Defaults to false, which means the shape of the response will not be validated upfront. - * Instead, validation will only occur for the parts of the response that are accessed. - */ - fun responseValidation(responseValidation: Boolean) = apply { - clientOptions.responseValidation(responseValidation) - } - - /** - * Sets the maximum time allowed for various parts of an HTTP call's lifecycle, excluding - * retries. - * - * Defaults to [Timeout.default]. - */ - fun timeout(timeout: Timeout) = apply { clientOptions.timeout(timeout) } - - /** - * Sets the maximum time allowed for a complete HTTP call, not including retries. - * - * See [Timeout.request] for more details. - * - * For fine-grained control, pass a [Timeout] object. - */ - fun timeout(timeout: Duration) = apply { clientOptions.timeout(timeout) } - - /** - * The maximum number of times to retry failed requests, with a short exponential backoff - * between requests. - * - * Only the following error types are retried: - * - Connection errors (for example, due to a network connectivity problem) - * - 408 Request Timeout - * - 409 Conflict - * - 429 Rate Limit - * - 5xx Internal - * - * The API may also explicitly instruct the SDK to retry or not retry a request. - * - * Defaults to 2. - */ - fun maxRetries(maxRetries: Int) = apply { clientOptions.maxRetries(maxRetries) } - - fun apiKey(apiKey: String?) = apply { clientOptions.apiKey(apiKey) } - - /** Alias for calling [Builder.apiKey] with `apiKey.orElse(null)`. */ - fun apiKey(apiKey: Optional) = apiKey(apiKey.getOrNull()) - - /** Defaults to `"v1beta"`. */ - fun apiVersion(apiVersion: String) = apply { clientOptions.apiVersion(apiVersion) } - - fun headers(headers: Headers) = apply { clientOptions.headers(headers) } - - fun headers(headers: Map>) = apply { - clientOptions.headers(headers) - } - - fun putHeader(name: String, value: String) = apply { clientOptions.putHeader(name, value) } - - fun putHeaders(name: String, values: Iterable) = apply { - clientOptions.putHeaders(name, values) - } - - fun putAllHeaders(headers: Headers) = apply { clientOptions.putAllHeaders(headers) } - - fun putAllHeaders(headers: Map>) = apply { - clientOptions.putAllHeaders(headers) - } - - fun replaceHeaders(name: String, value: String) = apply { - clientOptions.replaceHeaders(name, value) - } - - fun replaceHeaders(name: String, values: Iterable) = apply { - clientOptions.replaceHeaders(name, values) - } - - fun replaceAllHeaders(headers: Headers) = apply { clientOptions.replaceAllHeaders(headers) } - - fun replaceAllHeaders(headers: Map>) = apply { - clientOptions.replaceAllHeaders(headers) - } - - fun removeHeaders(name: String) = apply { clientOptions.removeHeaders(name) } - - fun removeAllHeaders(names: Set) = apply { clientOptions.removeAllHeaders(names) } - - fun queryParams(queryParams: QueryParams) = apply { clientOptions.queryParams(queryParams) } - - fun queryParams(queryParams: Map>) = apply { - clientOptions.queryParams(queryParams) - } - - fun putQueryParam(key: String, value: String) = apply { - clientOptions.putQueryParam(key, value) - } - - fun putQueryParams(key: String, values: Iterable) = apply { - clientOptions.putQueryParams(key, values) - } - - fun putAllQueryParams(queryParams: QueryParams) = apply { - clientOptions.putAllQueryParams(queryParams) - } - - fun putAllQueryParams(queryParams: Map>) = apply { - clientOptions.putAllQueryParams(queryParams) - } - - fun replaceQueryParams(key: String, value: String) = apply { - clientOptions.replaceQueryParams(key, value) - } - - fun replaceQueryParams(key: String, values: Iterable) = apply { - clientOptions.replaceQueryParams(key, values) - } - - fun replaceAllQueryParams(queryParams: QueryParams) = apply { - clientOptions.replaceAllQueryParams(queryParams) - } - - fun replaceAllQueryParams(queryParams: Map>) = apply { - clientOptions.replaceAllQueryParams(queryParams) - } - - fun removeQueryParams(key: String) = apply { clientOptions.removeQueryParams(key) } - - fun removeAllQueryParams(keys: Set) = apply { - clientOptions.removeAllQueryParams(keys) - } - - /** - * Updates configuration using system properties and environment variables. - * - * @see ClientOptions.Builder.fromEnv - */ - fun fromEnv() = apply { clientOptions.fromEnv() } - - /** - * Returns an immutable instance of [GeminiNextGenApiClient]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): GeminiNextGenApiClient = - GeminiNextGenApiClientImpl( - clientOptions - .httpClient( - OkHttpClient.builder() - .timeout(clientOptions.timeout()) - .proxy(proxy) - .maxIdleConnections(maxIdleConnections) - .keepAliveDuration(keepAliveDuration) - .dispatcherExecutorService(dispatcherExecutorService) - .sslSocketFactory(sslSocketFactory) - .trustManager(trustManager) - .hostnameVerifier(hostnameVerifier) - .build() - ) - .build() - ) - } -} diff --git a/src/main/java/com/google/genai/interactions/client/okhttp/GeminiNextGenApiOkHttpClientAsync.kt b/src/main/java/com/google/genai/interactions/client/okhttp/GeminiNextGenApiOkHttpClientAsync.kt deleted file mode 100644 index 987c035a5c5..00000000000 --- a/src/main/java/com/google/genai/interactions/client/okhttp/GeminiNextGenApiOkHttpClientAsync.kt +++ /dev/null @@ -1,410 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.client.okhttp - -import com.fasterxml.jackson.databind.json.JsonMapper -import com.google.genai.interactions.client.GeminiNextGenApiClientAsync -import com.google.genai.interactions.client.GeminiNextGenApiClientAsyncImpl -import com.google.genai.interactions.core.ClientOptions -import com.google.genai.interactions.core.Sleeper -import com.google.genai.interactions.core.Timeout -import com.google.genai.interactions.core.http.AsyncStreamResponse -import com.google.genai.interactions.core.http.Headers -import com.google.genai.interactions.core.http.HttpClient -import com.google.genai.interactions.core.http.QueryParams -import com.google.genai.interactions.core.jsonMapper -import java.net.Proxy -import java.time.Clock -import java.time.Duration -import java.util.Optional -import java.util.concurrent.Executor -import java.util.concurrent.ExecutorService -import javax.net.ssl.HostnameVerifier -import javax.net.ssl.SSLSocketFactory -import javax.net.ssl.X509TrustManager -import kotlin.jvm.optionals.getOrNull - -/** - * A class that allows building an instance of [GeminiNextGenApiClientAsync] with [OkHttpClient] as - * the underlying [HttpClient]. - */ -class GeminiNextGenApiOkHttpClientAsync private constructor() { - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [GeminiNextGenApiClientAsync]. - */ - @JvmStatic fun builder() = Builder() - - /** - * Returns a client configured using system properties and environment variables. - * - * @see ClientOptions.Builder.fromEnv - */ - @JvmStatic fun fromEnv(): GeminiNextGenApiClientAsync = builder().fromEnv().build() - } - - /** A builder for [GeminiNextGenApiOkHttpClientAsync]. */ - class Builder internal constructor() { - - private var clientOptions: ClientOptions.Builder = ClientOptions.builder() - private var dispatcherExecutorService: ExecutorService? = null - private var proxy: Proxy? = null - private var maxIdleConnections: Int? = null - private var keepAliveDuration: Duration? = null - private var sslSocketFactory: SSLSocketFactory? = null - private var trustManager: X509TrustManager? = null - private var hostnameVerifier: HostnameVerifier? = null - - /** - * The executor service to use for running HTTP requests. - * - * Defaults to OkHttp's - * [default executor service](https://github.com/square/okhttp/blob/ace792f443b2ffb17974f5c0d1cecdf589309f26/okhttp/src/commonJvmAndroid/kotlin/okhttp3/Dispatcher.kt#L98-L104). - * - * This class takes ownership of the executor service and shuts it down when closed. - */ - fun dispatcherExecutorService(dispatcherExecutorService: ExecutorService?) = apply { - this.dispatcherExecutorService = dispatcherExecutorService - } - - /** - * Alias for calling [Builder.dispatcherExecutorService] with - * `dispatcherExecutorService.orElse(null)`. - */ - fun dispatcherExecutorService(dispatcherExecutorService: Optional) = - dispatcherExecutorService(dispatcherExecutorService.getOrNull()) - - fun proxy(proxy: Proxy?) = apply { this.proxy = proxy } - - /** Alias for calling [Builder.proxy] with `proxy.orElse(null)`. */ - fun proxy(proxy: Optional) = proxy(proxy.getOrNull()) - - /** - * The maximum number of idle connections kept by the underlying OkHttp connection pool. - * - * If this is set, then [keepAliveDuration] must also be set. - * - * If unset, then OkHttp's default is used. - */ - fun maxIdleConnections(maxIdleConnections: Int?) = apply { - this.maxIdleConnections = maxIdleConnections - } - - /** - * Alias for [Builder.maxIdleConnections]. - * - * This unboxed primitive overload exists for backwards compatibility. - */ - fun maxIdleConnections(maxIdleConnections: Int) = - maxIdleConnections(maxIdleConnections as Int?) - - /** - * Alias for calling [Builder.maxIdleConnections] with `maxIdleConnections.orElse(null)`. - */ - fun maxIdleConnections(maxIdleConnections: Optional) = - maxIdleConnections(maxIdleConnections.getOrNull()) - - /** - * The keep-alive duration for idle connections in the underlying OkHttp connection pool. - * - * If this is set, then [maxIdleConnections] must also be set. - * - * If unset, then OkHttp's default is used. - */ - fun keepAliveDuration(keepAliveDuration: Duration?) = apply { - this.keepAliveDuration = keepAliveDuration - } - - /** Alias for calling [Builder.keepAliveDuration] with `keepAliveDuration.orElse(null)`. */ - fun keepAliveDuration(keepAliveDuration: Optional) = - keepAliveDuration(keepAliveDuration.getOrNull()) - - /** - * The socket factory used to secure HTTPS connections. - * - * If this is set, then [trustManager] must also be set. - * - * If unset, then the system default is used. Most applications should not call this method, - * and instead use the system default. The default include special optimizations that can be - * lost if the implementation is modified. - */ - fun sslSocketFactory(sslSocketFactory: SSLSocketFactory?) = apply { - this.sslSocketFactory = sslSocketFactory - } - - /** Alias for calling [Builder.sslSocketFactory] with `sslSocketFactory.orElse(null)`. */ - fun sslSocketFactory(sslSocketFactory: Optional) = - sslSocketFactory(sslSocketFactory.getOrNull()) - - /** - * The trust manager used to secure HTTPS connections. - * - * If this is set, then [sslSocketFactory] must also be set. - * - * If unset, then the system default is used. Most applications should not call this method, - * and instead use the system default. The default include special optimizations that can be - * lost if the implementation is modified. - */ - fun trustManager(trustManager: X509TrustManager?) = apply { - this.trustManager = trustManager - } - - /** Alias for calling [Builder.trustManager] with `trustManager.orElse(null)`. */ - fun trustManager(trustManager: Optional) = - trustManager(trustManager.getOrNull()) - - /** - * The verifier used to confirm that response certificates apply to requested hostnames for - * HTTPS connections. - * - * If unset, then a default hostname verifier is used. - */ - fun hostnameVerifier(hostnameVerifier: HostnameVerifier?) = apply { - this.hostnameVerifier = hostnameVerifier - } - - /** Alias for calling [Builder.hostnameVerifier] with `hostnameVerifier.orElse(null)`. */ - fun hostnameVerifier(hostnameVerifier: Optional) = - hostnameVerifier(hostnameVerifier.getOrNull()) - - /** - * Whether to throw an exception if any of the Jackson versions detected at runtime are - * incompatible with the SDK's minimum supported Jackson version (2.13.4). - * - * Defaults to true. Use extreme caution when disabling this option. There is no guarantee - * that the SDK will work correctly when using an incompatible Jackson version. - */ - fun checkJacksonVersionCompatibility(checkJacksonVersionCompatibility: Boolean) = apply { - clientOptions.checkJacksonVersionCompatibility(checkJacksonVersionCompatibility) - } - - /** - * The Jackson JSON mapper to use for serializing and deserializing JSON. - * - * Defaults to [com.google.genai.interactions.core.jsonMapper]. The default is usually - * sufficient and rarely needs to be overridden. - */ - fun jsonMapper(jsonMapper: JsonMapper) = apply { clientOptions.jsonMapper(jsonMapper) } - - /** - * The executor to use for running [AsyncStreamResponse.Handler] callbacks. - * - * Defaults to a dedicated cached thread pool. - * - * This class takes ownership of the executor and shuts it down, if possible, when closed. - */ - fun streamHandlerExecutor(streamHandlerExecutor: Executor) = apply { - clientOptions.streamHandlerExecutor(streamHandlerExecutor) - } - - /** - * The interface to use for delaying execution, like during retries. - * - * This is primarily useful for using fake delays in tests. - * - * Defaults to real execution delays. - * - * This class takes ownership of the sleeper and closes it when closed. - */ - fun sleeper(sleeper: Sleeper) = apply { clientOptions.sleeper(sleeper) } - - /** - * The clock to use for operations that require timing, like retries. - * - * This is primarily useful for using a fake clock in tests. - * - * Defaults to [Clock.systemUTC]. - */ - fun clock(clock: Clock) = apply { clientOptions.clock(clock) } - - /** - * The base URL to use for every request. - * - * Defaults to the production environment: `https://generativelanguage.googleapis.com`. - */ - fun baseUrl(baseUrl: String?) = apply { clientOptions.baseUrl(baseUrl) } - - /** Alias for calling [Builder.baseUrl] with `baseUrl.orElse(null)`. */ - fun baseUrl(baseUrl: Optional) = baseUrl(baseUrl.getOrNull()) - - /** - * Whether to call `validate` on every response before returning it. - * - * Defaults to false, which means the shape of the response will not be validated upfront. - * Instead, validation will only occur for the parts of the response that are accessed. - */ - fun responseValidation(responseValidation: Boolean) = apply { - clientOptions.responseValidation(responseValidation) - } - - /** - * Sets the maximum time allowed for various parts of an HTTP call's lifecycle, excluding - * retries. - * - * Defaults to [Timeout.default]. - */ - fun timeout(timeout: Timeout) = apply { clientOptions.timeout(timeout) } - - /** - * Sets the maximum time allowed for a complete HTTP call, not including retries. - * - * See [Timeout.request] for more details. - * - * For fine-grained control, pass a [Timeout] object. - */ - fun timeout(timeout: Duration) = apply { clientOptions.timeout(timeout) } - - /** - * The maximum number of times to retry failed requests, with a short exponential backoff - * between requests. - * - * Only the following error types are retried: - * - Connection errors (for example, due to a network connectivity problem) - * - 408 Request Timeout - * - 409 Conflict - * - 429 Rate Limit - * - 5xx Internal - * - * The API may also explicitly instruct the SDK to retry or not retry a request. - * - * Defaults to 2. - */ - fun maxRetries(maxRetries: Int) = apply { clientOptions.maxRetries(maxRetries) } - - fun apiKey(apiKey: String?) = apply { clientOptions.apiKey(apiKey) } - - /** Alias for calling [Builder.apiKey] with `apiKey.orElse(null)`. */ - fun apiKey(apiKey: Optional) = apiKey(apiKey.getOrNull()) - - /** Defaults to `"v1beta"`. */ - fun apiVersion(apiVersion: String) = apply { clientOptions.apiVersion(apiVersion) } - - fun headers(headers: Headers) = apply { clientOptions.headers(headers) } - - fun headers(headers: Map>) = apply { - clientOptions.headers(headers) - } - - fun putHeader(name: String, value: String) = apply { clientOptions.putHeader(name, value) } - - fun putHeaders(name: String, values: Iterable) = apply { - clientOptions.putHeaders(name, values) - } - - fun putAllHeaders(headers: Headers) = apply { clientOptions.putAllHeaders(headers) } - - fun putAllHeaders(headers: Map>) = apply { - clientOptions.putAllHeaders(headers) - } - - fun replaceHeaders(name: String, value: String) = apply { - clientOptions.replaceHeaders(name, value) - } - - fun replaceHeaders(name: String, values: Iterable) = apply { - clientOptions.replaceHeaders(name, values) - } - - fun replaceAllHeaders(headers: Headers) = apply { clientOptions.replaceAllHeaders(headers) } - - fun replaceAllHeaders(headers: Map>) = apply { - clientOptions.replaceAllHeaders(headers) - } - - fun removeHeaders(name: String) = apply { clientOptions.removeHeaders(name) } - - fun removeAllHeaders(names: Set) = apply { clientOptions.removeAllHeaders(names) } - - fun queryParams(queryParams: QueryParams) = apply { clientOptions.queryParams(queryParams) } - - fun queryParams(queryParams: Map>) = apply { - clientOptions.queryParams(queryParams) - } - - fun putQueryParam(key: String, value: String) = apply { - clientOptions.putQueryParam(key, value) - } - - fun putQueryParams(key: String, values: Iterable) = apply { - clientOptions.putQueryParams(key, values) - } - - fun putAllQueryParams(queryParams: QueryParams) = apply { - clientOptions.putAllQueryParams(queryParams) - } - - fun putAllQueryParams(queryParams: Map>) = apply { - clientOptions.putAllQueryParams(queryParams) - } - - fun replaceQueryParams(key: String, value: String) = apply { - clientOptions.replaceQueryParams(key, value) - } - - fun replaceQueryParams(key: String, values: Iterable) = apply { - clientOptions.replaceQueryParams(key, values) - } - - fun replaceAllQueryParams(queryParams: QueryParams) = apply { - clientOptions.replaceAllQueryParams(queryParams) - } - - fun replaceAllQueryParams(queryParams: Map>) = apply { - clientOptions.replaceAllQueryParams(queryParams) - } - - fun removeQueryParams(key: String) = apply { clientOptions.removeQueryParams(key) } - - fun removeAllQueryParams(keys: Set) = apply { - clientOptions.removeAllQueryParams(keys) - } - - /** - * Updates configuration using system properties and environment variables. - * - * @see ClientOptions.Builder.fromEnv - */ - fun fromEnv() = apply { clientOptions.fromEnv() } - - /** - * Returns an immutable instance of [GeminiNextGenApiClientAsync]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): GeminiNextGenApiClientAsync = - GeminiNextGenApiClientAsyncImpl( - clientOptions - .httpClient( - OkHttpClient.builder() - .timeout(clientOptions.timeout()) - .proxy(proxy) - .maxIdleConnections(maxIdleConnections) - .keepAliveDuration(keepAliveDuration) - .dispatcherExecutorService(dispatcherExecutorService) - .sslSocketFactory(sslSocketFactory) - .trustManager(trustManager) - .hostnameVerifier(hostnameVerifier) - .build() - ) - .build() - ) - } -} diff --git a/src/main/java/com/google/genai/interactions/client/okhttp/OkHttpClient.kt b/src/main/java/com/google/genai/interactions/client/okhttp/OkHttpClient.kt deleted file mode 100644 index fc046ccaf5c..00000000000 --- a/src/main/java/com/google/genai/interactions/client/okhttp/OkHttpClient.kt +++ /dev/null @@ -1,308 +0,0 @@ -/* -* 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 -* -* http://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.interactions.client.okhttp - -import com.google.genai.interactions.core.RequestOptions -import com.google.genai.interactions.core.Timeout -import com.google.genai.interactions.core.http.Headers -import com.google.genai.interactions.core.http.HttpClient -import com.google.genai.interactions.core.http.HttpMethod -import com.google.genai.interactions.core.http.HttpRequest -import com.google.genai.interactions.core.http.HttpRequestBody -import com.google.genai.interactions.core.http.HttpResponse -import com.google.genai.interactions.errors.GeminiNextGenApiIoException -import java.io.IOException -import java.io.InputStream -import java.net.Proxy -import java.time.Duration -import java.util.concurrent.CancellationException -import java.util.concurrent.CompletableFuture -import java.util.concurrent.ExecutorService -import java.util.concurrent.TimeUnit -import javax.net.ssl.HostnameVerifier -import javax.net.ssl.SSLSocketFactory -import javax.net.ssl.X509TrustManager -import okhttp3.Call -import okhttp3.Callback -import okhttp3.ConnectionPool -import okhttp3.Dispatcher -import okhttp3.HttpUrl.Companion.toHttpUrl -import okhttp3.MediaType -import okhttp3.MediaType.Companion.toMediaType -import okhttp3.Request -import okhttp3.RequestBody -import okhttp3.RequestBody.Companion.toRequestBody -import okhttp3.Response -import okhttp3.logging.HttpLoggingInterceptor -import okio.BufferedSink - -class OkHttpClient constructor(@JvmSynthetic internal val okHttpClient: okhttp3.OkHttpClient) : - HttpClient { - - override fun execute(request: HttpRequest, requestOptions: RequestOptions): HttpResponse { - val call = newCall(request, requestOptions) - - return try { - call.execute().toResponse() - } catch (e: IOException) { - throw GeminiNextGenApiIoException("Request failed", e) - } finally { - request.body?.close() - } - } - - override fun executeAsync( - request: HttpRequest, - requestOptions: RequestOptions, - ): CompletableFuture { - val future = CompletableFuture() - - val call = newCall(request, requestOptions) - call.enqueue( - object : Callback { - override fun onResponse(call: Call, response: Response) { - future.complete(response.toResponse()) - } - - override fun onFailure(call: Call, e: IOException) { - future.completeExceptionally(GeminiNextGenApiIoException("Request failed", e)) - } - } - ) - - future.whenComplete { _, e -> - if (e is CancellationException) { - call.cancel() - } - request.body?.close() - } - - return future - } - - override fun close() { - okHttpClient.dispatcher.executorService.shutdown() - okHttpClient.connectionPool.evictAll() - okHttpClient.cache?.close() - } - - private fun newCall(request: HttpRequest, requestOptions: RequestOptions): Call { - val clientBuilder = okHttpClient.newBuilder() - - val logLevel = - when (System.getenv("GEMINI_NEXT_GEN_API_LOG")?.lowercase()) { - "info" -> HttpLoggingInterceptor.Level.BASIC - "debug" -> HttpLoggingInterceptor.Level.BODY - else -> null - } - if (logLevel != null) { - clientBuilder.addNetworkInterceptor( - HttpLoggingInterceptor().setLevel(logLevel).apply { redactHeader("x-goog-api-key") } - ) - } - - requestOptions.timeout?.let { - clientBuilder - .connectTimeout(it.connect()) - .readTimeout(it.read()) - .writeTimeout(it.write()) - .callTimeout(it.request()) - } - - val client = clientBuilder.build() - return client.newCall(request.toRequest(client)) - } - - private fun HttpRequest.toRequest(client: okhttp3.OkHttpClient): Request { - var body: RequestBody? = body?.toRequestBody() - if (body == null && requiresBody(method)) { - body = "".toRequestBody() - } - - val builder = Request.Builder().url(toUrl()).method(method.name, body) - headers.names().forEach { name -> - headers.values(name).forEach { builder.addHeader(name, it) } - } - - return builder.build() - } - - /** `OkHttpClient` always requires a request body for some methods. */ - private fun requiresBody(method: HttpMethod): Boolean = - when (method) { - HttpMethod.POST, - HttpMethod.PUT, - HttpMethod.PATCH -> true - else -> false - } - - private fun HttpRequest.toUrl(): String { - val builder = baseUrl.toHttpUrl().newBuilder() - pathSegments.forEach(builder::addPathSegment) - queryParams.keys().forEach { key -> - queryParams.values(key).forEach { builder.addQueryParameter(key, it) } - } - - return builder.toString() - } - - private fun HttpRequestBody.toRequestBody(): RequestBody { - val mediaType = contentType()?.toMediaType() - val length = contentLength() - - return object : RequestBody() { - override fun contentType(): MediaType? = mediaType - - override fun contentLength(): Long = length - - override fun isOneShot(): Boolean = !repeatable() - - override fun writeTo(sink: BufferedSink) = writeTo(sink.outputStream()) - } - } - - private fun Response.toResponse(): HttpResponse { - val headers = headers.toHeaders() - - return object : HttpResponse { - override fun statusCode(): Int = code - - override fun headers(): Headers = headers - - override fun body(): InputStream = body!!.byteStream() - - override fun close() = body!!.close() - } - } - - private fun okhttp3.Headers.toHeaders(): Headers { - val headersBuilder = Headers.builder() - for (i in 0 until size) { - headersBuilder.put(name(i), value(i)) - } - return headersBuilder.build() - } - - companion object { - @JvmStatic fun builder() = Builder() - } - - class Builder internal constructor() { - - private var timeout: Timeout = Timeout.default() - private var proxy: Proxy? = null - private var maxIdleConnections: Int? = null - private var keepAliveDuration: Duration? = null - private var dispatcherExecutorService: ExecutorService? = null - private var sslSocketFactory: SSLSocketFactory? = null - private var trustManager: X509TrustManager? = null - private var hostnameVerifier: HostnameVerifier? = null - - fun timeout(timeout: Timeout) = apply { this.timeout = timeout } - - fun timeout(timeout: Duration) = timeout(Timeout.builder().request(timeout).build()) - - fun proxy(proxy: Proxy?) = apply { this.proxy = proxy } - - /** - * Sets the maximum number of idle connections kept by the underlying [ConnectionPool]. - * - * If this is set, then [keepAliveDuration] must also be set. - * - * If unset, then OkHttp's default is used. - */ - fun maxIdleConnections(maxIdleConnections: Int?) = apply { - this.maxIdleConnections = maxIdleConnections - } - - /** - * Sets the keep-alive duration for idle connections in the underlying [ConnectionPool]. - * - * If this is set, then [maxIdleConnections] must also be set. - * - * If unset, then OkHttp's default is used. - */ - fun keepAliveDuration(keepAliveDuration: Duration?) = apply { - this.keepAliveDuration = keepAliveDuration - } - - fun dispatcherExecutorService(dispatcherExecutorService: ExecutorService?) = apply { - this.dispatcherExecutorService = dispatcherExecutorService - } - - fun sslSocketFactory(sslSocketFactory: SSLSocketFactory?) = apply { - this.sslSocketFactory = sslSocketFactory - } - - fun trustManager(trustManager: X509TrustManager?) = apply { - this.trustManager = trustManager - } - - fun hostnameVerifier(hostnameVerifier: HostnameVerifier?) = apply { - this.hostnameVerifier = hostnameVerifier - } - - fun build(): OkHttpClient = - OkHttpClient( - okhttp3.OkHttpClient.Builder() - // `RetryingHttpClient` handles retries if the user enabled them. - .retryOnConnectionFailure(false) - .connectTimeout(timeout.connect()) - .readTimeout(timeout.read()) - .writeTimeout(timeout.write()) - .callTimeout(timeout.request()) - .proxy(proxy) - .apply { - dispatcherExecutorService?.let { dispatcher(Dispatcher(it)) } - - val maxIdleConnections = maxIdleConnections - val keepAliveDuration = keepAliveDuration - if (maxIdleConnections != null && keepAliveDuration != null) { - connectionPool( - ConnectionPool( - maxIdleConnections, - keepAliveDuration.toNanos(), - TimeUnit.NANOSECONDS, - ) - ) - } else { - check((maxIdleConnections != null) == (keepAliveDuration != null)) { - "Both or none of `maxIdleConnections` and `keepAliveDuration` must be set, but only one was set" - } - } - - val sslSocketFactory = sslSocketFactory - val trustManager = trustManager - if (sslSocketFactory != null && trustManager != null) { - sslSocketFactory(sslSocketFactory, trustManager) - } else { - check((sslSocketFactory != null) == (trustManager != null)) { - "Both or none of `sslSocketFactory` and `trustManager` must be set, but only one was set" - } - } - - hostnameVerifier?.let(::hostnameVerifier) - } - .build() - .apply { - // We usually make all our requests to the same host so it makes sense to - // raise the per-host limit to the overall limit. - dispatcher.maxRequestsPerHost = dispatcher.maxRequests - } - ) - } -} diff --git a/src/main/java/com/google/genai/interactions/core/BaseDeserializer.kt b/src/main/java/com/google/genai/interactions/core/BaseDeserializer.kt deleted file mode 100644 index 24a8adf9430..00000000000 --- a/src/main/java/com/google/genai/interactions/core/BaseDeserializer.kt +++ /dev/null @@ -1,60 +0,0 @@ -/* -* 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 -* -* http://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.interactions.core - -import com.fasterxml.jackson.core.JsonParser -import com.fasterxml.jackson.core.ObjectCodec -import com.fasterxml.jackson.core.type.TypeReference -import com.fasterxml.jackson.databind.BeanProperty -import com.fasterxml.jackson.databind.DeserializationContext -import com.fasterxml.jackson.databind.JavaType -import com.fasterxml.jackson.databind.JsonDeserializer -import com.fasterxml.jackson.databind.JsonNode -import com.fasterxml.jackson.databind.deser.ContextualDeserializer -import com.fasterxml.jackson.databind.deser.std.StdDeserializer -import kotlin.reflect.KClass - -abstract class BaseDeserializer(type: KClass) : - StdDeserializer(type.java), ContextualDeserializer { - - override fun createContextual( - context: DeserializationContext, - property: BeanProperty?, - ): JsonDeserializer { - return this - } - - override fun deserialize(parser: JsonParser, context: DeserializationContext): T { - return parser.codec.deserialize(parser.readValueAsTree()) - } - - protected abstract fun ObjectCodec.deserialize(node: JsonNode): T - - protected fun ObjectCodec.tryDeserialize(node: JsonNode, type: TypeReference): T? = - try { - readValue(treeAsTokens(node), type) - } catch (e: Exception) { - null - } - - protected fun ObjectCodec.tryDeserialize(node: JsonNode, type: JavaType): T? = - try { - readValue(treeAsTokens(node), type) - } catch (e: Exception) { - null - } -} diff --git a/src/main/java/com/google/genai/interactions/core/BaseSerializer.kt b/src/main/java/com/google/genai/interactions/core/BaseSerializer.kt deleted file mode 100644 index 04ace38a7e6..00000000000 --- a/src/main/java/com/google/genai/interactions/core/BaseSerializer.kt +++ /dev/null @@ -1,22 +0,0 @@ -/* -* 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 -* -* http://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.interactions.core - -import com.fasterxml.jackson.databind.ser.std.StdSerializer -import kotlin.reflect.KClass - -abstract class BaseSerializer(type: KClass) : StdSerializer(type.java) diff --git a/src/main/java/com/google/genai/interactions/core/Check.kt b/src/main/java/com/google/genai/interactions/core/Check.kt deleted file mode 100644 index 2c0ef8fe77a..00000000000 --- a/src/main/java/com/google/genai/interactions/core/Check.kt +++ /dev/null @@ -1,112 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -@file:JvmName("Check") - -package com.google.genai.interactions.core - -import com.fasterxml.jackson.core.Version -import com.fasterxml.jackson.core.util.VersionUtil - -fun checkRequired(name: String, condition: Boolean) = - check(condition) { "`$name` is required, but was not set" } - -fun checkRequired(name: String, value: T?): T = - checkNotNull(value) { "`$name` is required, but was not set" } - -@JvmSynthetic -internal fun checkKnown(name: String, value: JsonField): T = - value.asKnown().orElseThrow { - IllegalStateException("`$name` is not a known type: ${value.javaClass.simpleName}") - } - -@JvmSynthetic -internal fun checkKnown(name: String, value: MultipartField): T = - value.value.asKnown().orElseThrow { - IllegalStateException("`$name` is not a known type: ${value.javaClass.simpleName}") - } - -@JvmSynthetic -internal fun checkLength(name: String, value: String, length: Int): String = - value.also { - check(it.length == length) { "`$name` must have length $length, but was ${it.length}" } - } - -@JvmSynthetic -internal fun checkMinLength(name: String, value: String, minLength: Int): String = - value.also { - check(it.length >= minLength) { - if (minLength == 1) "`$name` must be non-empty, but was empty" - else "`$name` must have at least length $minLength, but was ${it.length}" - } - } - -@JvmSynthetic -internal fun checkMaxLength(name: String, value: String, maxLength: Int): String = - value.also { - check(it.length <= maxLength) { - "`$name` must have at most length $maxLength, but was ${it.length}" - } - } - -@JvmSynthetic -internal fun checkJacksonVersionCompatibility() { - val incompatibleJacksonVersions = - RUNTIME_JACKSON_VERSIONS.mapNotNull { - val badVersionReason = BAD_JACKSON_VERSIONS[it.toString()] - when { - it.majorVersion != MINIMUM_JACKSON_VERSION.majorVersion -> - it to "incompatible major version" - it.minorVersion < MINIMUM_JACKSON_VERSION.minorVersion -> - it to "minor version too low" - it.minorVersion == MINIMUM_JACKSON_VERSION.minorVersion && - it.patchLevel < MINIMUM_JACKSON_VERSION.patchLevel -> - it to "patch version too low" - badVersionReason != null -> it to badVersionReason - else -> null - } - } - check(incompatibleJacksonVersions.isEmpty()) { - """ -This SDK requires a minimum Jackson version of $MINIMUM_JACKSON_VERSION, but the following incompatible Jackson versions were detected at runtime: - -${incompatibleJacksonVersions.asSequence().map { (version, incompatibilityReason) -> - "- `${version.toFullString().replace("/", ":")}` ($incompatibilityReason)" -}.joinToString("\n")} - -This can happen if you are either: -1. Directly depending on different Jackson versions -2. Depending on some library that depends on different Jackson versions, potentially transitively - -Double-check that you are depending on compatible Jackson versions. - -See https://www.github.com/stainless-sdks/gemini-next-gen-api-java#jackson for more information. - """ - .trimIndent() - } -} - -private val MINIMUM_JACKSON_VERSION: Version = VersionUtil.parseVersion("2.13.4", null, null) -private val BAD_JACKSON_VERSIONS: Map = - mapOf("2.18.1" to "due to https://github.com/FasterXML/jackson-databind/issues/4639") -private val RUNTIME_JACKSON_VERSIONS: List = - listOf( - com.fasterxml.jackson.core.json.PackageVersion.VERSION, - com.fasterxml.jackson.databind.cfg.PackageVersion.VERSION, - com.fasterxml.jackson.datatype.jdk8.PackageVersion.VERSION, - com.fasterxml.jackson.datatype.jsr310.PackageVersion.VERSION, - com.fasterxml.jackson.module.kotlin.PackageVersion.VERSION, - ) diff --git a/src/main/java/com/google/genai/interactions/core/ClientOptions.kt b/src/main/java/com/google/genai/interactions/core/ClientOptions.kt deleted file mode 100644 index 8887c91666e..00000000000 --- a/src/main/java/com/google/genai/interactions/core/ClientOptions.kt +++ /dev/null @@ -1,526 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.core - -import com.fasterxml.jackson.databind.json.JsonMapper -import com.google.genai.interactions.core.http.AsyncStreamResponse -import com.google.genai.interactions.core.http.Headers -import com.google.genai.interactions.core.http.HttpClient -import com.google.genai.interactions.core.http.PhantomReachableClosingHttpClient -import com.google.genai.interactions.core.http.QueryParams -import com.google.genai.interactions.core.http.RetryingHttpClient -import java.time.Clock -import java.time.Duration -import java.util.Optional -import java.util.concurrent.Executor -import java.util.concurrent.ExecutorService -import java.util.concurrent.Executors -import java.util.concurrent.ThreadFactory -import java.util.concurrent.atomic.AtomicLong -import kotlin.jvm.optionals.getOrNull - -/** A class representing the SDK client configuration. */ -class ClientOptions -private constructor( - private val originalHttpClient: HttpClient, - /** - * The HTTP client to use in the SDK. - * - * Use the one published in `gemini-next-gen-api-java-client-okhttp` or implement your own. - * - * This class takes ownership of the client and closes it when closed. - */ - @get:JvmName("httpClient") val httpClient: HttpClient, - /** - * Whether to throw an exception if any of the Jackson versions detected at runtime are - * incompatible with the SDK's minimum supported Jackson version (2.13.4). - * - * Defaults to true. Use extreme caution when disabling this option. There is no guarantee that - * the SDK will work correctly when using an incompatible Jackson version. - */ - @get:JvmName("checkJacksonVersionCompatibility") val checkJacksonVersionCompatibility: Boolean, - /** - * The Jackson JSON mapper to use for serializing and deserializing JSON. - * - * Defaults to [com.google.genai.interactions.core.jsonMapper]. The default is usually sufficient - * and rarely needs to be overridden. - */ - @get:JvmName("jsonMapper") val jsonMapper: JsonMapper, - /** - * The executor to use for running [AsyncStreamResponse.Handler] callbacks. - * - * Defaults to a dedicated cached thread pool. - * - * This class takes ownership of the executor and shuts it down, if possible, when closed. - */ - @get:JvmName("streamHandlerExecutor") val streamHandlerExecutor: Executor, - /** - * The interface to use for delaying execution, like during retries. - * - * This is primarily useful for using fake delays in tests. - * - * Defaults to real execution delays. - * - * This class takes ownership of the sleeper and closes it when closed. - */ - @get:JvmName("sleeper") val sleeper: Sleeper, - /** - * The clock to use for operations that require timing, like retries. - * - * This is primarily useful for using a fake clock in tests. - * - * Defaults to [Clock.systemUTC]. - */ - @get:JvmName("clock") val clock: Clock, - private val baseUrl: String?, - /** Headers to send with the request. */ - @get:JvmName("headers") val headers: Headers, - /** Query params to send with the request. */ - @get:JvmName("queryParams") val queryParams: QueryParams, - /** - * Whether to call `validate` on every response before returning it. - * - * Defaults to false, which means the shape of the response will not be validated upfront. - * Instead, validation will only occur for the parts of the response that are accessed. - */ - @get:JvmName("responseValidation") val responseValidation: Boolean, - /** - * Sets the maximum time allowed for various parts of an HTTP call's lifecycle, excluding - * retries. - * - * Defaults to [Timeout.default]. - */ - @get:JvmName("timeout") val timeout: Timeout, - /** - * The maximum number of times to retry failed requests, with a short exponential backoff - * between requests. - * - * Only the following error types are retried: - * - Connection errors (for example, due to a network connectivity problem) - * - 408 Request Timeout - * - 409 Conflict - * - 429 Rate Limit - * - 5xx Internal - * - * The API may also explicitly instruct the SDK to retry or not retry a request. - * - * Defaults to 2. - */ - @get:JvmName("maxRetries") val maxRetries: Int, - private val apiKey: String?, - /** Defaults to `"v1beta"`. */ - @get:JvmName("apiVersion") val apiVersion: String, - @JvmSynthetic internal val vertexInfo: VertexInfo?, -) { - - init { - if (checkJacksonVersionCompatibility) { - checkJacksonVersionCompatibility() - } - } - - /** - * The base URL to use for every request. - * - * Defaults to the production environment: `https://generativelanguage.googleapis.com`. - */ - fun baseUrl(): String = baseUrl ?: PRODUCTION_URL - - fun apiKey(): Optional = Optional.ofNullable(apiKey) - - fun toBuilder() = Builder().from(this) - - companion object { - - const val PRODUCTION_URL = "https://generativelanguage.googleapis.com" - - /** - * Returns a mutable builder for constructing an instance of [ClientOptions]. - * - * The following fields are required: - * ```java - * .httpClient() - * ``` - */ - @JvmStatic fun builder() = Builder() - - /** - * Returns options configured using system properties and environment variables. - * - * @see Builder.fromEnv - */ - @JvmStatic fun fromEnv(): ClientOptions = builder().fromEnv().build() - } - - /** A builder for [ClientOptions]. */ - class Builder internal constructor() { - - private var httpClient: HttpClient? = null - private var checkJacksonVersionCompatibility: Boolean = true - private var jsonMapper: JsonMapper = jsonMapper() - private var streamHandlerExecutor: Executor? = null - private var sleeper: Sleeper? = null - private var clock: Clock = Clock.systemUTC() - private var baseUrl: String? = null - private var headers: Headers.Builder = Headers.builder() - private var queryParams: QueryParams.Builder = QueryParams.builder() - private var responseValidation: Boolean = false - private var timeout: Timeout = Timeout.default() - private var maxRetries: Int = 2 - private var apiKey: String? = null - private var apiVersion: String = "v1beta" - private var vertexInfo: VertexInfo? = null - - @JvmSynthetic - internal fun from(clientOptions: ClientOptions) = apply { - httpClient = clientOptions.originalHttpClient - checkJacksonVersionCompatibility = clientOptions.checkJacksonVersionCompatibility - jsonMapper = clientOptions.jsonMapper - streamHandlerExecutor = clientOptions.streamHandlerExecutor - sleeper = clientOptions.sleeper - clock = clientOptions.clock - baseUrl = clientOptions.baseUrl - headers = clientOptions.headers.toBuilder() - queryParams = clientOptions.queryParams.toBuilder() - responseValidation = clientOptions.responseValidation - timeout = clientOptions.timeout - maxRetries = clientOptions.maxRetries - apiKey = clientOptions.apiKey - apiVersion = clientOptions.apiVersion - vertexInfo = clientOptions.vertexInfo - } - - /** - * The HTTP client to use in the SDK. - * - * Use the one published in `gemini-next-gen-api-java-client-okhttp` or implement your own. - * - * This class takes ownership of the client and closes it when closed. - */ - fun httpClient(httpClient: HttpClient) = apply { - this.httpClient = PhantomReachableClosingHttpClient(httpClient) - } - - /** - * Whether to throw an exception if any of the Jackson versions detected at runtime are - * incompatible with the SDK's minimum supported Jackson version (2.13.4). - * - * Defaults to true. Use extreme caution when disabling this option. There is no guarantee - * that the SDK will work correctly when using an incompatible Jackson version. - */ - fun checkJacksonVersionCompatibility(checkJacksonVersionCompatibility: Boolean) = apply { - this.checkJacksonVersionCompatibility = checkJacksonVersionCompatibility - } - - /** - * The Jackson JSON mapper to use for serializing and deserializing JSON. - * - * Defaults to [com.google.genai.interactions.core.jsonMapper]. The default is usually - * sufficient and rarely needs to be overridden. - */ - fun jsonMapper(jsonMapper: JsonMapper) = apply { this.jsonMapper = jsonMapper } - - /** - * The executor to use for running [AsyncStreamResponse.Handler] callbacks. - * - * Defaults to a dedicated cached thread pool. - * - * This class takes ownership of the executor and shuts it down, if possible, when closed. - */ - fun streamHandlerExecutor(streamHandlerExecutor: Executor) = apply { - this.streamHandlerExecutor = - if (streamHandlerExecutor is ExecutorService) - PhantomReachableExecutorService(streamHandlerExecutor) - else streamHandlerExecutor - } - - /** - * The interface to use for delaying execution, like during retries. - * - * This is primarily useful for using fake delays in tests. - * - * Defaults to real execution delays. - * - * This class takes ownership of the sleeper and closes it when closed. - */ - fun sleeper(sleeper: Sleeper) = apply { this.sleeper = PhantomReachableSleeper(sleeper) } - - /** - * The clock to use for operations that require timing, like retries. - * - * This is primarily useful for using a fake clock in tests. - * - * Defaults to [Clock.systemUTC]. - */ - fun clock(clock: Clock) = apply { this.clock = clock } - - /** - * The base URL to use for every request. - * - * Defaults to the production environment: `https://generativelanguage.googleapis.com`. - */ - fun baseUrl(baseUrl: String?) = apply { this.baseUrl = baseUrl } - - /** Alias for calling [Builder.baseUrl] with `baseUrl.orElse(null)`. */ - fun baseUrl(baseUrl: Optional) = baseUrl(baseUrl.getOrNull()) - - /** - * Whether to call `validate` on every response before returning it. - * - * Defaults to false, which means the shape of the response will not be validated upfront. - * Instead, validation will only occur for the parts of the response that are accessed. - */ - fun responseValidation(responseValidation: Boolean) = apply { - this.responseValidation = responseValidation - } - - /** - * Sets the maximum time allowed for various parts of an HTTP call's lifecycle, excluding - * retries. - * - * Defaults to [Timeout.default]. - */ - fun timeout(timeout: Timeout) = apply { this.timeout = timeout } - - /** - * Sets the maximum time allowed for a complete HTTP call, not including retries. - * - * See [Timeout.request] for more details. - * - * For fine-grained control, pass a [Timeout] object. - */ - fun timeout(timeout: Duration) = timeout(Timeout.builder().request(timeout).build()) - - /** - * The maximum number of times to retry failed requests, with a short exponential backoff - * between requests. - * - * Only the following error types are retried: - * - Connection errors (for example, due to a network connectivity problem) - * - 408 Request Timeout - * - 409 Conflict - * - 429 Rate Limit - * - 5xx Internal - * - * The API may also explicitly instruct the SDK to retry or not retry a request. - * - * Defaults to 2. - */ - fun maxRetries(maxRetries: Int) = apply { this.maxRetries = maxRetries } - - fun apiKey(apiKey: String?) = apply { this.apiKey = apiKey } - - /** Alias for calling [Builder.apiKey] with `apiKey.orElse(null)`. */ - fun apiKey(apiKey: Optional) = apiKey(apiKey.getOrNull()) - - /** Defaults to `"v1beta"`. */ - fun apiVersion(apiVersion: String) = apply { this.apiVersion = apiVersion } - - fun vertexInfo(vertexInfo: VertexInfo?) = apply { this.vertexInfo = vertexInfo } - - fun headers(headers: Headers) = apply { - this.headers.clear() - putAllHeaders(headers) - } - - fun headers(headers: Map>) = apply { - this.headers.clear() - putAllHeaders(headers) - } - - fun putHeader(name: String, value: String) = apply { headers.put(name, value) } - - fun putHeaders(name: String, values: Iterable) = apply { headers.put(name, values) } - - fun putAllHeaders(headers: Headers) = apply { this.headers.putAll(headers) } - - fun putAllHeaders(headers: Map>) = apply { - this.headers.putAll(headers) - } - - fun replaceHeaders(name: String, value: String) = apply { headers.replace(name, value) } - - fun replaceHeaders(name: String, values: Iterable) = apply { - headers.replace(name, values) - } - - fun replaceAllHeaders(headers: Headers) = apply { this.headers.replaceAll(headers) } - - fun replaceAllHeaders(headers: Map>) = apply { - this.headers.replaceAll(headers) - } - - fun removeHeaders(name: String) = apply { headers.remove(name) } - - fun removeAllHeaders(names: Set) = apply { headers.removeAll(names) } - - fun queryParams(queryParams: QueryParams) = apply { - this.queryParams.clear() - putAllQueryParams(queryParams) - } - - fun queryParams(queryParams: Map>) = apply { - this.queryParams.clear() - putAllQueryParams(queryParams) - } - - fun putQueryParam(key: String, value: String) = apply { queryParams.put(key, value) } - - fun putQueryParams(key: String, values: Iterable) = apply { - queryParams.put(key, values) - } - - fun putAllQueryParams(queryParams: QueryParams) = apply { - this.queryParams.putAll(queryParams) - } - - fun putAllQueryParams(queryParams: Map>) = apply { - this.queryParams.putAll(queryParams) - } - - fun replaceQueryParams(key: String, value: String) = apply { - queryParams.replace(key, value) - } - - fun replaceQueryParams(key: String, values: Iterable) = apply { - queryParams.replace(key, values) - } - - fun replaceAllQueryParams(queryParams: QueryParams) = apply { - this.queryParams.replaceAll(queryParams) - } - - fun replaceAllQueryParams(queryParams: Map>) = apply { - this.queryParams.replaceAll(queryParams) - } - - fun removeQueryParams(key: String) = apply { queryParams.remove(key) } - - fun removeAllQueryParams(keys: Set) = apply { queryParams.removeAll(keys) } - - fun timeout(): Timeout = timeout - - /** - * Updates configuration using system properties and environment variables. - * - * See this table for the available options: - * - * |Setter |System property |Environment variable |Required|Default value | - * |---------|-------------------------------|------------------------------|--------|---------------------------------------------| - * |`apiKey` |`gemininextgenapi.geminiApiKey`|`GEMINI_API_KEY` |false |- | - * |`baseUrl`|`gemininextgenapi.baseUrl` |`GEMINI_NEXT_GEN_API_BASE_URL`|true |`"https://generativelanguage.googleapis.com"`| - * - * System properties take precedence over environment variables. - */ - fun fromEnv() = apply { - (System.getProperty("gemininextgenapi.baseUrl") - ?: System.getenv("GEMINI_NEXT_GEN_API_BASE_URL")) - ?.let { baseUrl(it) } - (System.getProperty("gemininextgenapi.geminiApiKey") ?: System.getenv("GEMINI_API_KEY")) - ?.let { apiKey(it) } - } - - /** - * Returns an immutable instance of [ClientOptions]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .httpClient() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): ClientOptions { - val httpClient = checkRequired("httpClient", httpClient) - val streamHandlerExecutor = - streamHandlerExecutor - ?: PhantomReachableExecutorService( - Executors.newCachedThreadPool( - object : ThreadFactory { - - private val threadFactory: ThreadFactory = - Executors.defaultThreadFactory() - private val count = AtomicLong(0) - - override fun newThread(runnable: Runnable): Thread = - threadFactory.newThread(runnable).also { - it.name = - "gemini-next-gen-api-stream-handler-thread-${count.getAndIncrement()}" - } - } - ) - ) - val sleeper = sleeper ?: PhantomReachableSleeper(DefaultSleeper()) - - val headers = Headers.builder() - val queryParams = QueryParams.builder() - headers.put("Api-Revision", "2026-05-20") - // We replace after all the default headers to allow end-users to overwrite them. - headers.replaceAll(this.headers.build()) - queryParams.replaceAll(this.queryParams.build()) - apiKey?.let { - if (!it.isEmpty()) { - headers.replace("x-goog-api-key", it) - } - } - - return ClientOptions( - httpClient, - RetryingHttpClient.builder() - .httpClient(httpClient) - .sleeper(sleeper) - .clock(clock) - .maxRetries(maxRetries) - .build(), - checkJacksonVersionCompatibility, - jsonMapper, - streamHandlerExecutor, - sleeper, - clock, - baseUrl, - headers.build(), - queryParams.build(), - responseValidation, - timeout, - maxRetries, - apiKey, - apiVersion, - vertexInfo, - ) - } - } - - /** - * Closes these client options, relinquishing any underlying resources. - * - * This is purposefully not inherited from [AutoCloseable] because the client options are - * long-lived and usually should not be synchronously closed via try-with-resources. - * - * It's also usually not necessary to call this method at all. the default client automatically - * releases threads and connections if they remain idle, but if you are writing an application - * that needs to aggressively release unused resources, then you may call this method. - */ - fun close() { - httpClient.close() - (streamHandlerExecutor as? ExecutorService)?.shutdown() - sleeper.close() - } -} diff --git a/src/main/java/com/google/genai/interactions/core/DefaultSleeper.kt b/src/main/java/com/google/genai/interactions/core/DefaultSleeper.kt deleted file mode 100644 index 485c67612db..00000000000 --- a/src/main/java/com/google/genai/interactions/core/DefaultSleeper.kt +++ /dev/null @@ -1,44 +0,0 @@ -/* -* 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 -* -* http://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.interactions.core - -import java.time.Duration -import java.util.Timer -import java.util.TimerTask -import java.util.concurrent.CompletableFuture - -class DefaultSleeper : Sleeper { - - private val timer = Timer("DefaultSleeper", true) - - override fun sleep(duration: Duration) = Thread.sleep(duration.toMillis()) - - override fun sleepAsync(duration: Duration): CompletableFuture { - val future = CompletableFuture() - timer.schedule( - object : TimerTask() { - override fun run() { - future.complete(null) - } - }, - duration.toMillis(), - ) - return future - } - - override fun close() = timer.cancel() -} diff --git a/src/main/java/com/google/genai/interactions/core/ObjectMappers.kt b/src/main/java/com/google/genai/interactions/core/ObjectMappers.kt deleted file mode 100644 index 3b4c3b54663..00000000000 --- a/src/main/java/com/google/genai/interactions/core/ObjectMappers.kt +++ /dev/null @@ -1,194 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -@file:JvmName("ObjectMappers") - -package com.google.genai.interactions.core - -import com.fasterxml.jackson.annotation.JsonInclude -import com.fasterxml.jackson.core.JsonGenerator -import com.fasterxml.jackson.core.JsonParseException -import com.fasterxml.jackson.core.JsonParser -import com.fasterxml.jackson.databind.DeserializationContext -import com.fasterxml.jackson.databind.DeserializationFeature -import com.fasterxml.jackson.databind.MapperFeature -import com.fasterxml.jackson.databind.SerializationFeature -import com.fasterxml.jackson.databind.SerializerProvider -import com.fasterxml.jackson.databind.cfg.CoercionAction -import com.fasterxml.jackson.databind.cfg.CoercionInputShape -import com.fasterxml.jackson.databind.deser.std.StdDeserializer -import com.fasterxml.jackson.databind.json.JsonMapper -import com.fasterxml.jackson.databind.module.SimpleModule -import com.fasterxml.jackson.databind.type.LogicalType -import com.fasterxml.jackson.datatype.jdk8.Jdk8Module -import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule -import com.fasterxml.jackson.module.kotlin.kotlinModule -import java.io.InputStream -import java.time.DateTimeException -import java.time.LocalDate -import java.time.LocalDateTime -import java.time.OffsetDateTime -import java.time.ZoneId -import java.time.format.DateTimeFormatter -import java.time.temporal.ChronoField - -fun jsonMapper(): JsonMapper = - JsonMapper.builder() - .addModule(kotlinModule()) - .addModule(Jdk8Module()) - .addModule(JavaTimeModule()) - .addModule( - SimpleModule() - .addSerializer(InputStreamSerializer) - .addDeserializer(OffsetDateTime::class.java, LenientOffsetDateTimeDeserializer()) - ) - .withCoercionConfig(LogicalType.Boolean) { - it.setCoercion(CoercionInputShape.Integer, CoercionAction.Fail) - .setCoercion(CoercionInputShape.Float, CoercionAction.Fail) - .setCoercion(CoercionInputShape.String, CoercionAction.Fail) - .setCoercion(CoercionInputShape.Array, CoercionAction.Fail) - .setCoercion(CoercionInputShape.Object, CoercionAction.Fail) - } - .withCoercionConfig(LogicalType.Integer) { - it.setCoercion(CoercionInputShape.Boolean, CoercionAction.Fail) - .setCoercion(CoercionInputShape.Float, CoercionAction.Fail) - .setCoercion(CoercionInputShape.String, CoercionAction.Fail) - .setCoercion(CoercionInputShape.Array, CoercionAction.Fail) - .setCoercion(CoercionInputShape.Object, CoercionAction.Fail) - } - .withCoercionConfig(LogicalType.Float) { - it.setCoercion(CoercionInputShape.Boolean, CoercionAction.Fail) - .setCoercion(CoercionInputShape.String, CoercionAction.Fail) - .setCoercion(CoercionInputShape.Array, CoercionAction.Fail) - .setCoercion(CoercionInputShape.Object, CoercionAction.Fail) - } - .withCoercionConfig(LogicalType.Textual) { - it.setCoercion(CoercionInputShape.Boolean, CoercionAction.Fail) - .setCoercion(CoercionInputShape.Integer, CoercionAction.Fail) - .setCoercion(CoercionInputShape.Float, CoercionAction.Fail) - .setCoercion(CoercionInputShape.Array, CoercionAction.Fail) - .setCoercion(CoercionInputShape.Object, CoercionAction.Fail) - } - .withCoercionConfig(LogicalType.DateTime) { - it.setCoercion(CoercionInputShape.Integer, CoercionAction.Fail) - .setCoercion(CoercionInputShape.Float, CoercionAction.Fail) - .setCoercion(CoercionInputShape.Array, CoercionAction.Fail) - .setCoercion(CoercionInputShape.Object, CoercionAction.Fail) - } - .withCoercionConfig(LogicalType.Array) { - it.setCoercion(CoercionInputShape.Boolean, CoercionAction.Fail) - .setCoercion(CoercionInputShape.Integer, CoercionAction.Fail) - .setCoercion(CoercionInputShape.Float, CoercionAction.Fail) - .setCoercion(CoercionInputShape.String, CoercionAction.Fail) - .setCoercion(CoercionInputShape.Object, CoercionAction.Fail) - } - .withCoercionConfig(LogicalType.Collection) { - it.setCoercion(CoercionInputShape.Boolean, CoercionAction.Fail) - .setCoercion(CoercionInputShape.Integer, CoercionAction.Fail) - .setCoercion(CoercionInputShape.Float, CoercionAction.Fail) - .setCoercion(CoercionInputShape.String, CoercionAction.Fail) - .setCoercion(CoercionInputShape.Object, CoercionAction.Fail) - } - .withCoercionConfig(LogicalType.Map) { - it.setCoercion(CoercionInputShape.Boolean, CoercionAction.Fail) - .setCoercion(CoercionInputShape.Integer, CoercionAction.Fail) - .setCoercion(CoercionInputShape.Float, CoercionAction.Fail) - .setCoercion(CoercionInputShape.String, CoercionAction.Fail) - .setCoercion(CoercionInputShape.Object, CoercionAction.Fail) - } - .withCoercionConfig(LogicalType.POJO) { - it.setCoercion(CoercionInputShape.Boolean, CoercionAction.Fail) - .setCoercion(CoercionInputShape.Integer, CoercionAction.Fail) - .setCoercion(CoercionInputShape.Float, CoercionAction.Fail) - .setCoercion(CoercionInputShape.String, CoercionAction.Fail) - .setCoercion(CoercionInputShape.Array, CoercionAction.Fail) - } - .serializationInclusion(JsonInclude.Include.NON_ABSENT) - .disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE) - .disable(SerializationFeature.FLUSH_AFTER_WRITE_VALUE) - .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) - .disable(SerializationFeature.WRITE_DURATIONS_AS_TIMESTAMPS) - .disable(MapperFeature.ALLOW_COERCION_OF_SCALARS) - .disable(MapperFeature.AUTO_DETECT_CREATORS) - .disable(MapperFeature.AUTO_DETECT_FIELDS) - .disable(MapperFeature.AUTO_DETECT_GETTERS) - .disable(MapperFeature.AUTO_DETECT_IS_GETTERS) - .disable(MapperFeature.AUTO_DETECT_SETTERS) - .build() - -/** A serializer that serializes [InputStream] to bytes. */ -private object InputStreamSerializer : BaseSerializer(InputStream::class) { - - private fun readResolve(): Any = InputStreamSerializer - - override fun serialize( - value: InputStream?, - gen: JsonGenerator?, - serializers: SerializerProvider?, - ) { - if (value == null) { - gen?.writeNull() - } else { - value.use { gen?.writeBinary(it.readBytes()) } - } - } -} - -/** - * A deserializer that can deserialize [OffsetDateTime] from datetimes, dates, and zoned datetimes. - */ -private class LenientOffsetDateTimeDeserializer : - StdDeserializer(OffsetDateTime::class.java) { - - companion object { - - private val DATE_TIME_FORMATTERS = - listOf( - DateTimeFormatter.ISO_LOCAL_DATE_TIME, - DateTimeFormatter.ISO_LOCAL_DATE, - DateTimeFormatter.ISO_ZONED_DATE_TIME, - ) - } - - override fun logicalType(): LogicalType = LogicalType.DateTime - - override fun deserialize(p: JsonParser, context: DeserializationContext): OffsetDateTime { - val exceptions = mutableListOf() - - for (formatter in DATE_TIME_FORMATTERS) { - try { - val temporal = formatter.parse(p.text) - - return when { - !temporal.isSupported(ChronoField.HOUR_OF_DAY) -> - LocalDate.from(temporal) - .atStartOfDay() - .atZone(ZoneId.of("UTC")) - .toOffsetDateTime() - !temporal.isSupported(ChronoField.OFFSET_SECONDS) -> - LocalDateTime.from(temporal).atZone(ZoneId.of("UTC")).toOffsetDateTime() - else -> OffsetDateTime.from(temporal) - } - } catch (e: DateTimeException) { - exceptions.add(e) - } - } - - throw JsonParseException(p, "Cannot parse `OffsetDateTime` from value: ${p.text}").apply { - exceptions.forEach { addSuppressed(it) } - } - } -} diff --git a/src/main/java/com/google/genai/interactions/core/Params.kt b/src/main/java/com/google/genai/interactions/core/Params.kt deleted file mode 100644 index d9c986c75c9..00000000000 --- a/src/main/java/com/google/genai/interactions/core/Params.kt +++ /dev/null @@ -1,32 +0,0 @@ -/* -* 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 -* -* http://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.interactions.core - -import com.google.genai.interactions.core.http.Headers -import com.google.genai.interactions.core.http.QueryParams - -/** An interface representing parameters passed to a service method. */ -interface Params { - /** The full set of headers in the parameters, including both fixed and additional headers. */ - fun _headers(): Headers - - /** - * The full set of query params in the parameters, including both fixed and additional query - * params. - */ - fun _queryParams(): QueryParams -} diff --git a/src/main/java/com/google/genai/interactions/core/PhantomReachable.kt b/src/main/java/com/google/genai/interactions/core/PhantomReachable.kt deleted file mode 100644 index e45dd5a4b83..00000000000 --- a/src/main/java/com/google/genai/interactions/core/PhantomReachable.kt +++ /dev/null @@ -1,72 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -@file:JvmName("PhantomReachable") - -package com.google.genai.interactions.core - -import com.google.genai.interactions.errors.GeminiNextGenApiException -import java.lang.reflect.InvocationTargetException - -/** - * Closes [closeable] when [observed] becomes only phantom reachable. - * - * This is a wrapper around a Java 9+ [java.lang.ref.Cleaner], or a no-op in older Java versions. - */ -@JvmSynthetic -internal fun closeWhenPhantomReachable(observed: Any, closeable: AutoCloseable) { - check(observed !== closeable) { - "`observed` cannot be the same object as `closeable` because it would never become phantom reachable" - } - closeWhenPhantomReachable(observed, closeable::close) -} - -/** - * Calls [close] when [observed] becomes only phantom reachable. - * - * This is a wrapper around a Java 9+ [java.lang.ref.Cleaner], or a no-op in older Java versions. - */ -@JvmSynthetic -internal fun closeWhenPhantomReachable(observed: Any, close: () -> Unit) { - closeWhenPhantomReachable?.let { it(observed, close) } -} - -private val closeWhenPhantomReachable: ((Any, () -> Unit) -> Unit)? by lazy { - try { - val cleanerClass = Class.forName("java.lang.ref.Cleaner") - val cleanerCreate = cleanerClass.getMethod("create") - val cleanerRegister = - cleanerClass.getMethod("register", Any::class.java, Runnable::class.java) - val cleanerObject = cleanerCreate.invoke(null); - - { observed, close -> - try { - cleanerRegister.invoke(cleanerObject, observed, Runnable { close() }) - } catch (e: ReflectiveOperationException) { - if (e is InvocationTargetException) { - when (val cause = e.cause) { - is RuntimeException, - is Error -> throw cause - } - } - throw GeminiNextGenApiException("Unexpected reflective invocation failure", e) - } - } - } catch (e: ReflectiveOperationException) { - // We're running Java 8, which has no Cleaner. - null - } -} diff --git a/src/main/java/com/google/genai/interactions/core/PhantomReachableExecutorService.kt b/src/main/java/com/google/genai/interactions/core/PhantomReachableExecutorService.kt deleted file mode 100644 index c091e7f4eb3..00000000000 --- a/src/main/java/com/google/genai/interactions/core/PhantomReachableExecutorService.kt +++ /dev/null @@ -1,74 +0,0 @@ -/* -* 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 -* -* http://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.interactions.core - -import java.util.concurrent.Callable -import java.util.concurrent.ExecutorService -import java.util.concurrent.Future -import java.util.concurrent.TimeUnit - -/** - * A delegating wrapper around an [ExecutorService] that shuts it down once it's only phantom - * reachable. - * - * This class ensures the [ExecutorService] is shut down even if the user forgets to do it. - */ -internal class PhantomReachableExecutorService(private val executorService: ExecutorService) : - ExecutorService { - init { - closeWhenPhantomReachable(this) { executorService.shutdown() } - } - - override fun execute(command: Runnable) = executorService.execute(command) - - override fun shutdown() = executorService.shutdown() - - override fun shutdownNow(): MutableList = executorService.shutdownNow() - - override fun isShutdown(): Boolean = executorService.isShutdown - - override fun isTerminated(): Boolean = executorService.isTerminated - - override fun awaitTermination(timeout: Long, unit: TimeUnit): Boolean = - executorService.awaitTermination(timeout, unit) - - override fun submit(task: Callable): Future = executorService.submit(task) - - override fun submit(task: Runnable, result: T): Future = - executorService.submit(task, result) - - override fun submit(task: Runnable): Future<*> = executorService.submit(task) - - override fun invokeAll( - tasks: MutableCollection> - ): MutableList> = executorService.invokeAll(tasks) - - override fun invokeAll( - tasks: MutableCollection>, - timeout: Long, - unit: TimeUnit, - ): MutableList> = executorService.invokeAll(tasks, timeout, unit) - - override fun invokeAny(tasks: MutableCollection>): T = - executorService.invokeAny(tasks) - - override fun invokeAny( - tasks: MutableCollection>, - timeout: Long, - unit: TimeUnit, - ): T = executorService.invokeAny(tasks, timeout, unit) -} diff --git a/src/main/java/com/google/genai/interactions/core/PhantomReachableSleeper.kt b/src/main/java/com/google/genai/interactions/core/PhantomReachableSleeper.kt deleted file mode 100644 index 278ed9af1e2..00000000000 --- a/src/main/java/com/google/genai/interactions/core/PhantomReachableSleeper.kt +++ /dev/null @@ -1,39 +0,0 @@ -/* -* 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 -* -* http://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.interactions.core - -import java.time.Duration -import java.util.concurrent.CompletableFuture - -/** - * A delegating wrapper around a [Sleeper] that closes it once it's only phantom reachable. - * - * This class ensures the [Sleeper] is closed even if the user forgets to do it. - */ -internal class PhantomReachableSleeper(private val sleeper: Sleeper) : Sleeper { - - init { - closeWhenPhantomReachable(this, sleeper) - } - - override fun sleep(duration: Duration) = sleeper.sleep(duration) - - override fun sleepAsync(duration: Duration): CompletableFuture = - sleeper.sleepAsync(duration) - - override fun close() = sleeper.close() -} diff --git a/src/main/java/com/google/genai/interactions/core/PrepareRequest.kt b/src/main/java/com/google/genai/interactions/core/PrepareRequest.kt deleted file mode 100644 index 2a29fd3bee9..00000000000 --- a/src/main/java/com/google/genai/interactions/core/PrepareRequest.kt +++ /dev/null @@ -1,48 +0,0 @@ -/* - * 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 - * - * http://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. - */ - -@file:JvmName("PrepareRequest") - -package com.google.genai.interactions.core - -import com.google.genai.interactions.core.http.HttpRequest -import java.util.concurrent.CompletableFuture - -@JvmSynthetic -internal fun HttpRequest.prepare(clientOptions: ClientOptions, params: Params): HttpRequest = - toBuilder() - .pathSegments( - clientOptions.vertexInfo?.let { toVertexPathSegments(it, pathSegments) } ?: pathSegments - ) - .putAllQueryParams(clientOptions.queryParams) - .replaceAllQueryParams(params._queryParams()) - .putAllHeaders(clientOptions.headers) - .replaceAllHeaders(params._headers()) - .build() - -private fun toVertexPathSegments(vertexInfo: VertexInfo, pathSegments: List): List = - pathSegments.toMutableList().apply { - addAll(1, listOf("projects", vertexInfo.project, "locations", vertexInfo.location)) - } - -@JvmSynthetic -internal fun HttpRequest.prepareAsync( - clientOptions: ClientOptions, - params: Params, -): CompletableFuture = - // This async version exists to make it easier to add async specific preparation logic in the - // future. - CompletableFuture.completedFuture(prepare(clientOptions, params)) diff --git a/src/main/java/com/google/genai/interactions/core/Properties.kt b/src/main/java/com/google/genai/interactions/core/Properties.kt deleted file mode 100644 index dcc5cfee865..00000000000 --- a/src/main/java/com/google/genai/interactions/core/Properties.kt +++ /dev/null @@ -1,58 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -@file:JvmName("Properties") - -package com.google.genai.interactions.core - -import com.google.genai.interactions.client.GeminiNextGenApiClient - -fun getOsArch(): String { - val osArch = System.getProperty("os.arch") - - return when (osArch) { - null -> "unknown" - "i386", - "x32", - "x86" -> "x32" - "amd64", - "x86_64" -> "x64" - "arm" -> "arm" - "aarch64" -> "arm64" - else -> "other:$osArch" - } -} - -fun getOsName(): String { - val osName = System.getProperty("os.name") - val vendorUrl = System.getProperty("java.vendor.url") - - return when { - osName == null -> "Unknown" - osName.startsWith("Linux") && vendorUrl == "http://www.android.com/" -> "Android" - osName.startsWith("Linux") -> "Linux" - osName.startsWith("Mac OS") -> "MacOS" - osName.startsWith("Windows") -> "Windows" - else -> "Other:$osName" - } -} - -fun getOsVersion(): String = System.getProperty("os.version", "unknown") ?: "unknown" - -fun getPackageVersion(): String = - GeminiNextGenApiClient::class.java.`package`?.implementationVersion ?: "unknown" - -fun getJavaVersion(): String = System.getProperty("java.version", "unknown") ?: "unknown" diff --git a/src/main/java/com/google/genai/interactions/core/RequestOptions.kt b/src/main/java/com/google/genai/interactions/core/RequestOptions.kt deleted file mode 100644 index fbc569f2ec8..00000000000 --- a/src/main/java/com/google/genai/interactions/core/RequestOptions.kt +++ /dev/null @@ -1,62 +0,0 @@ -/* -* 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 -* -* http://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.interactions.core - -import java.time.Duration - -class RequestOptions private constructor(val responseValidation: Boolean?, val timeout: Timeout?) { - - companion object { - - private val NONE = builder().build() - - @JvmStatic fun none() = NONE - - @JvmSynthetic - internal fun from(clientOptions: ClientOptions): RequestOptions = - builder() - .responseValidation(clientOptions.responseValidation) - .timeout(clientOptions.timeout) - .build() - - @JvmStatic fun builder() = Builder() - } - - fun applyDefaults(options: RequestOptions): RequestOptions = - RequestOptions( - responseValidation = responseValidation ?: options.responseValidation, - timeout = - if (options.timeout != null && timeout != null) timeout.assign(options.timeout) - else timeout ?: options.timeout, - ) - - class Builder internal constructor() { - - private var responseValidation: Boolean? = null - private var timeout: Timeout? = null - - fun responseValidation(responseValidation: Boolean) = apply { - this.responseValidation = responseValidation - } - - fun timeout(timeout: Timeout) = apply { this.timeout = timeout } - - fun timeout(timeout: Duration) = timeout(Timeout.builder().request(timeout).build()) - - fun build(): RequestOptions = RequestOptions(responseValidation, timeout) - } -} diff --git a/src/main/java/com/google/genai/interactions/core/Sleeper.kt b/src/main/java/com/google/genai/interactions/core/Sleeper.kt deleted file mode 100644 index bdda52bd57d..00000000000 --- a/src/main/java/com/google/genai/interactions/core/Sleeper.kt +++ /dev/null @@ -1,37 +0,0 @@ -/* -* 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 -* -* http://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.interactions.core - -import java.time.Duration -import java.util.concurrent.CompletableFuture - -/** - * An interface for delaying execution for a specified amount of time. - * - * Useful for testing and cleaning up resources. - */ -interface Sleeper : AutoCloseable { - - /** Synchronously pauses execution for the given [duration]. */ - fun sleep(duration: Duration) - - /** Asynchronously pauses execution for the given [duration]. */ - fun sleepAsync(duration: Duration): CompletableFuture - - /** Overridden from [AutoCloseable] to not have a checked exception in its signature. */ - override fun close() -} diff --git a/src/main/java/com/google/genai/interactions/core/Timeout.kt b/src/main/java/com/google/genai/interactions/core/Timeout.kt deleted file mode 100644 index 0e96f6af764..00000000000 --- a/src/main/java/com/google/genai/interactions/core/Timeout.kt +++ /dev/null @@ -1,187 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.core - -import java.time.Duration -import java.util.Objects -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -/** A class containing timeouts for various processing phases of a request. */ -class Timeout -private constructor( - private val connect: Duration?, - private val read: Duration?, - private val write: Duration?, - private val request: Duration?, -) { - - /** - * The maximum time allowed to establish a connection with a host. - * - * A value of [Duration.ZERO] means there's no timeout. - * - * Defaults to `Duration.ofMinutes(1)`. - */ - fun connect(): Duration = connect ?: Duration.ofMinutes(1) - - /** - * The maximum time allowed between two data packets when waiting for the server’s response. - * - * A value of [Duration.ZERO] means there's no timeout. - * - * Defaults to `request()`. - */ - fun read(): Duration = read ?: request() - - /** - * The maximum time allowed between two data packets when sending the request to the server. - * - * A value of [Duration.ZERO] means there's no timeout. - * - * Defaults to `request()`. - */ - fun write(): Duration = write ?: request() - - /** - * The maximum time allowed for a complete HTTP call, not including retries. - * - * This includes resolving DNS, connecting, writing the request body, server processing, as well - * as reading the response body. - * - * A value of [Duration.ZERO] means there's no timeout. - * - * Defaults to `Duration.ofMinutes(1)`. - */ - fun request(): Duration = request ?: Duration.ofMinutes(1) - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun default() = builder().build() - - /** Returns a mutable builder for constructing an instance of [Timeout]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Timeout]. */ - class Builder internal constructor() { - - private var connect: Duration? = null - private var read: Duration? = null - private var write: Duration? = null - private var request: Duration? = null - - @JvmSynthetic - internal fun from(timeout: Timeout) = apply { - connect = timeout.connect - read = timeout.read - write = timeout.write - request = timeout.request - } - - /** - * The maximum time allowed to establish a connection with a host. - * - * A value of [Duration.ZERO] means there's no timeout. - * - * Defaults to `Duration.ofMinutes(1)`. - */ - fun connect(connect: Duration?) = apply { this.connect = connect } - - /** Alias for calling [Builder.connect] with `connect.orElse(null)`. */ - fun connect(connect: Optional) = connect(connect.getOrNull()) - - /** - * The maximum time allowed between two data packets when waiting for the server’s response. - * - * A value of [Duration.ZERO] means there's no timeout. - * - * Defaults to `request()`. - */ - fun read(read: Duration?) = apply { this.read = read } - - /** Alias for calling [Builder.read] with `read.orElse(null)`. */ - fun read(read: Optional) = read(read.getOrNull()) - - /** - * The maximum time allowed between two data packets when sending the request to the server. - * - * A value of [Duration.ZERO] means there's no timeout. - * - * Defaults to `request()`. - */ - fun write(write: Duration?) = apply { this.write = write } - - /** Alias for calling [Builder.write] with `write.orElse(null)`. */ - fun write(write: Optional) = write(write.getOrNull()) - - /** - * The maximum time allowed for a complete HTTP call, not including retries. - * - * This includes resolving DNS, connecting, writing the request body, server processing, as - * well as reading the response body. - * - * A value of [Duration.ZERO] means there's no timeout. - * - * Defaults to `Duration.ofMinutes(1)`. - */ - fun request(request: Duration?) = apply { this.request = request } - - /** Alias for calling [Builder.request] with `request.orElse(null)`. */ - fun request(request: Optional) = request(request.getOrNull()) - - /** - * Returns an immutable instance of [Timeout]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): Timeout = Timeout(connect, read, write, request) - } - - @JvmSynthetic - internal fun assign(target: Timeout): Timeout = - target - .toBuilder() - .apply { - connect?.let(this::connect) - read?.let(this::read) - write?.let(this::write) - request?.let(this::request) - } - .build() - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Timeout && - connect == other.connect && - read == other.read && - write == other.write && - request == other.request - } - - override fun hashCode(): Int = Objects.hash(connect, read, write, request) - - override fun toString() = - "Timeout{connect=$connect, read=$read, write=$write, request=$request}" -} diff --git a/src/main/java/com/google/genai/interactions/core/Utils.kt b/src/main/java/com/google/genai/interactions/core/Utils.kt deleted file mode 100644 index 9a9dec8ebdf..00000000000 --- a/src/main/java/com/google/genai/interactions/core/Utils.kt +++ /dev/null @@ -1,131 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -@file:JvmName("Utils") - -package com.google.genai.interactions.core - -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.util.Collections -import java.util.SortedMap -import java.util.concurrent.CompletableFuture -import java.util.concurrent.locks.Lock - -@JvmSynthetic -internal fun T?.getOrThrow(name: String): T = - this ?: throw GeminiNextGenApiInvalidDataException("`${name}` is not present") - -@JvmSynthetic -internal fun List.toImmutable(): List = - if (isEmpty()) Collections.emptyList() else Collections.unmodifiableList(toList()) - -@JvmSynthetic -internal fun Map.toImmutable(): Map = - if (isEmpty()) immutableEmptyMap() else Collections.unmodifiableMap(toMap()) - -@JvmSynthetic internal fun immutableEmptyMap(): Map = Collections.emptyMap() - -@JvmSynthetic -internal fun , V> SortedMap.toImmutable(): SortedMap = - if (isEmpty()) Collections.emptySortedMap() - else Collections.unmodifiableSortedMap(toSortedMap(comparator())) - -/** - * Returns all elements that yield the largest value for the given function, or an empty list if - * there are zero elements. - * - * This is similar to [Sequence.maxByOrNull] except it returns _all_ elements that yield the largest - * value; not just the first one. - */ -@JvmSynthetic -internal fun > Sequence.allMaxBy(selector: (T) -> R): List { - var maxValue: R? = null - val maxElements = mutableListOf() - - val iterator = iterator() - while (iterator.hasNext()) { - val element = iterator.next() - val value = selector(element) - if (maxValue == null || value > maxValue) { - maxValue = value - maxElements.clear() - maxElements.add(element) - } else if (value == maxValue) { - maxElements.add(element) - } - } - - return maxElements -} - -/** - * Returns whether [this] is equal to [other]. - * - * This differs from [Object.equals] because it also deeply equates arrays based on their contents, - * even when there are arrays directly nested within other arrays. - */ -@JvmSynthetic -internal infix fun Any?.contentEquals(other: Any?): Boolean = - arrayOf(this).contentDeepEquals(arrayOf(other)) - -/** - * Returns a hash of the given sequence of [values]. - * - * This differs from [java.util.Objects.hash] because it also deeply hashes arrays based on their - * contents, even when there are arrays directly nested within other arrays. - */ -@JvmSynthetic internal fun contentHash(vararg values: Any?): Int = values.contentDeepHashCode() - -/** - * Returns a [String] representation of [this]. - * - * This differs from [Object.toString] because it also deeply stringifies arrays based on their - * contents, even when there are arrays directly nested within other arrays. - */ -@JvmSynthetic -internal fun Any?.contentToString(): String { - var string = arrayOf(this).contentDeepToString() - if (string.startsWith('[')) { - string = string.substring(1) - } - if (string.endsWith(']')) { - string = string.substring(0, string.length - 1) - } - return string -} - -internal interface Enum - -/** - * Executes the given [action] while holding the lock, returning a [CompletableFuture] with the - * result. - * - * @param action The asynchronous action to execute while holding the lock - * @return A [CompletableFuture] that completes with the result of the action - */ -@JvmSynthetic -internal fun Lock.withLockAsync(action: () -> CompletableFuture): CompletableFuture { - lock() - val future = - try { - action() - } catch (e: Throwable) { - unlock() - throw e - } - future.whenComplete { _, _ -> unlock() } - return future -} diff --git a/src/main/java/com/google/genai/interactions/core/Values.kt b/src/main/java/com/google/genai/interactions/core/Values.kt deleted file mode 100644 index f80ec11fad4..00000000000 --- a/src/main/java/com/google/genai/interactions/core/Values.kt +++ /dev/null @@ -1,739 +0,0 @@ -/* -* 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 -* -* http://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.interactions.core - -import com.fasterxml.jackson.annotation.JacksonAnnotationsInside -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonInclude -import com.fasterxml.jackson.core.JsonGenerator -import com.fasterxml.jackson.core.ObjectCodec -import com.fasterxml.jackson.core.type.TypeReference -import com.fasterxml.jackson.databind.BeanProperty -import com.fasterxml.jackson.databind.DeserializationContext -import com.fasterxml.jackson.databind.JavaType -import com.fasterxml.jackson.databind.JsonDeserializer -import com.fasterxml.jackson.databind.JsonNode -import com.fasterxml.jackson.databind.SerializerProvider -import com.fasterxml.jackson.databind.annotation.JsonDeserialize -import com.fasterxml.jackson.databind.annotation.JsonSerialize -import com.fasterxml.jackson.databind.node.JsonNodeType.ARRAY -import com.fasterxml.jackson.databind.node.JsonNodeType.BINARY -import com.fasterxml.jackson.databind.node.JsonNodeType.BOOLEAN -import com.fasterxml.jackson.databind.node.JsonNodeType.MISSING -import com.fasterxml.jackson.databind.node.JsonNodeType.NULL -import com.fasterxml.jackson.databind.node.JsonNodeType.NUMBER -import com.fasterxml.jackson.databind.node.JsonNodeType.OBJECT -import com.fasterxml.jackson.databind.node.JsonNodeType.POJO -import com.fasterxml.jackson.databind.node.JsonNodeType.STRING -import com.fasterxml.jackson.databind.ser.std.NullSerializer -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.io.InputStream -import java.util.Objects -import java.util.Optional - -/** - * A class representing a serializable JSON field. - * - * It can either be a [KnownValue] value of type [T], matching the type the SDK expects, or an - * arbitrary JSON value that bypasses the type system (via [JsonValue]). - */ -@JsonDeserialize(using = JsonField.Deserializer::class) -sealed class JsonField { - - /** - * Returns whether this field is missing, which means it will be omitted from the serialized - * JSON entirely. - */ - fun isMissing(): Boolean = this is JsonMissing - - /** Whether this field is explicitly set to `null`. */ - fun isNull(): Boolean = this is JsonNull - - /** - * Returns an [Optional] containing this field's "known" value, meaning it matches the type the - * SDK expects, or an empty [Optional] if this field contains an arbitrary [JsonValue]. - * - * This is the opposite of [asUnknown]. - */ - fun asKnown(): - Optional< - // Safe because `Optional` is effectively covariant, but Kotlin doesn't know that. - @UnsafeVariance - T - > = Optional.ofNullable((this as? KnownValue)?.value) - - /** - * Returns an [Optional] containing this field's arbitrary [JsonValue], meaning it mismatches - * the type the SDK expects, or an empty [Optional] if this field contains a "known" value. - * - * This is the opposite of [asKnown]. - */ - fun asUnknown(): Optional = Optional.ofNullable(this as? JsonValue) - - /** - * Returns an [Optional] containing this field's boolean value, or an empty [Optional] if it - * doesn't contain a boolean. - * - * This method checks for both a [KnownValue] containing a boolean and for [JsonBoolean]. - */ - fun asBoolean(): Optional = - when (this) { - is JsonBoolean -> Optional.of(value) - is KnownValue -> Optional.ofNullable(value as? Boolean) - else -> Optional.empty() - } - - /** - * Returns an [Optional] containing this field's numerical value, or an empty [Optional] if it - * doesn't contain a number. - * - * This method checks for both a [KnownValue] containing a number and for [JsonNumber]. - */ - fun asNumber(): Optional = - when (this) { - is JsonNumber -> Optional.of(value) - is KnownValue -> Optional.ofNullable(value as? Number) - else -> Optional.empty() - } - - /** - * Returns an [Optional] containing this field's string value, or an empty [Optional] if it - * doesn't contain a string. - * - * This method checks for both a [KnownValue] containing a string and for [JsonString]. - */ - fun asString(): Optional = - when (this) { - is JsonString -> Optional.of(value) - is KnownValue -> Optional.ofNullable(value as? String) - else -> Optional.empty() - } - - fun asStringOrThrow(): String = - asString().orElseThrow { GeminiNextGenApiInvalidDataException("Value is not a string") } - - /** - * Returns an [Optional] containing this field's list value, or an empty [Optional] if it - * doesn't contain a list. - * - * This method checks for both a [KnownValue] containing a list and for [JsonArray]. - */ - fun asArray(): Optional> = - when (this) { - is JsonArray -> Optional.of(values) - is KnownValue -> - Optional.ofNullable( - (value as? List<*>)?.map { - try { - JsonValue.from(it) - } catch (e: IllegalArgumentException) { - // The known value is a list, but not all values are convertible to - // `JsonValue`. - return Optional.empty() - } - } - ) - else -> Optional.empty() - } - - /** - * Returns an [Optional] containing this field's map value, or an empty [Optional] if it doesn't - * contain a map. - * - * This method checks for both a [KnownValue] containing a map and for [JsonObject]. - */ - fun asObject(): Optional> = - when (this) { - is JsonObject -> Optional.of(values) - is KnownValue -> - Optional.ofNullable( - (value as? Map<*, *>) - ?.map { (key, value) -> - if (key !is String) { - return Optional.empty() - } - - val jsonValue = - try { - JsonValue.from(value) - } catch (e: IllegalArgumentException) { - // The known value is a map, but not all items are convertible - // to `JsonValue`. - return Optional.empty() - } - - key to jsonValue - } - ?.toMap() - ) - else -> Optional.empty() - } - - @JvmSynthetic - internal fun getRequired(name: String): T = - when (this) { - is KnownValue -> value - is JsonMissing -> throw GeminiNextGenApiInvalidDataException("`$name` is not set") - is JsonNull -> throw GeminiNextGenApiInvalidDataException("`$name` is null") - else -> throw GeminiNextGenApiInvalidDataException("`$name` is invalid, received $this") - } - - @JvmSynthetic - internal fun getOptional( - name: String - ): Optional< - // Safe because `Optional` is effectively covariant, but Kotlin doesn't know that. - @UnsafeVariance - T - > = - when (this) { - is KnownValue -> Optional.of(value) - is JsonMissing, - is JsonNull -> Optional.empty() - else -> throw GeminiNextGenApiInvalidDataException("`$name` is invalid, received $this") - } - - @JvmSynthetic - internal fun map(transform: (T) -> R): JsonField = - when (this) { - is KnownValue -> KnownValue.of(transform(value)) - is JsonValue -> this - } - - @JvmSynthetic internal fun accept(consume: (T) -> Unit) = asKnown().ifPresent(consume) - - /** Returns the result of calling the [visitor] method corresponding to this field's state. */ - fun accept(visitor: Visitor): R = - when (this) { - is KnownValue -> visitor.visitKnown(value) - is JsonValue -> accept(visitor as JsonValue.Visitor) - } - - /** - * An interface that defines how to map each possible state of a `JsonField` to a value of - * type [R]. - */ - interface Visitor : JsonValue.Visitor { - - fun visitKnown(value: T): R = visitDefault() - } - - companion object { - - /** Returns a [JsonField] containing the given "known" [value]. */ - @JvmStatic fun of(value: T): JsonField = KnownValue.of(value) - - /** - * Returns a [JsonField] containing the given "known" [value], or [JsonNull] if [value] is - * null. - */ - @JvmStatic - fun ofNullable(value: T?): JsonField = - when (value) { - null -> JsonNull.of() - else -> KnownValue.of(value) - } - } - - /** - * This class is a Jackson filter that can be used to exclude missing properties from objects. - * This filter should not be used directly and should instead use the @ExcludeMissing - * annotation. - */ - class IsMissing { - - override fun equals(other: Any?): Boolean = other is JsonMissing - - override fun hashCode(): Int = Objects.hash() - } - - class Deserializer(private val type: JavaType? = null) : - BaseDeserializer>(JsonField::class) { - - override fun createContextual( - context: DeserializationContext, - property: BeanProperty?, - ): JsonDeserializer> = Deserializer(context.contextualType?.containedType(0)) - - override fun ObjectCodec.deserialize(node: JsonNode): JsonField<*> = - type?.let { tryDeserialize(node, type) }?.let { of(it) } - ?: JsonValue.fromJsonNode(node) - - override fun getNullValue(context: DeserializationContext): JsonField<*> = JsonNull.of() - } -} - -/** - * A class representing an arbitrary JSON value. - * - * It is immutable and assignable to any [JsonField], regardless of its expected type (i.e. its - * generic type argument). - */ -@JsonDeserialize(using = JsonValue.Deserializer::class) -sealed class JsonValue : JsonField() { - - fun convert(type: TypeReference): R? = JSON_MAPPER.convertValue(this, type) - - fun convert(type: Class): R? = JSON_MAPPER.convertValue(this, type) - - /** Returns the result of calling the [visitor] method corresponding to this value's variant. */ - fun accept(visitor: Visitor): R = - when (this) { - is JsonMissing -> visitor.visitMissing() - is JsonNull -> visitor.visitNull() - is JsonBoolean -> visitor.visitBoolean(value) - is JsonNumber -> visitor.visitNumber(value) - is JsonString -> visitor.visitString(value) - is JsonArray -> visitor.visitArray(values) - is JsonObject -> visitor.visitObject(values) - } - - /** - * An interface that defines how to map each variant state of a [JsonValue] to a value of type - * [R]. - */ - interface Visitor { - - fun visitNull(): R = visitDefault() - - fun visitMissing(): R = visitDefault() - - fun visitBoolean(value: Boolean): R = visitDefault() - - fun visitNumber(value: Number): R = visitDefault() - - fun visitString(value: String): R = visitDefault() - - fun visitArray(values: List): R = visitDefault() - - fun visitObject(values: Map): R = visitDefault() - - /** - * The default implementation for unimplemented visitor methods. - * - * @throws IllegalArgumentException in the default implementation. - */ - fun visitDefault(): R = throw IllegalArgumentException("Unexpected value") - } - - companion object { - - private val JSON_MAPPER = jsonMapper() - - /** - * Converts the given [value] to a [JsonValue]. - * - * This method works best on primitive types, [List] values, [Map] values, and nested - * combinations of these. For example: - * ```java - * // Create primitive JSON values - * JsonValue nullValue = JsonValue.from(null); - * JsonValue booleanValue = JsonValue.from(true); - * JsonValue numberValue = JsonValue.from(42); - * JsonValue stringValue = JsonValue.from("Hello World!"); - * - * // Create a JSON array value equivalent to `["Hello", "World"]` - * JsonValue arrayValue = JsonValue.from(List.of("Hello", "World")); - * - * // Create a JSON object value equivalent to `{ "a": 1, "b": 2 }` - * JsonValue objectValue = JsonValue.from(Map.of( - * "a", 1, - * "b", 2 - * )); - * - * // Create an arbitrarily nested JSON equivalent to: - * // { - * // "a": [1, 2], - * // "b": [3, 4] - * // } - * JsonValue complexValue = JsonValue.from(Map.of( - * "a", List.of(1, 2), - * "b", List.of(3, 4) - * )); - * ``` - * - * @throws IllegalArgumentException if [value] is not JSON serializable. - */ - @JvmStatic - fun from(value: Any?): JsonValue = - when (value) { - null -> JsonNull.of() - is JsonValue -> value - else -> JSON_MAPPER.convertValue(value, JsonValue::class.java) - } - - /** - * Returns a [JsonValue] converted from the given Jackson [JsonNode]. - * - * @throws IllegalStateException for unsupported node types. - */ - @JvmStatic - fun fromJsonNode(node: JsonNode): JsonValue = - when (node.nodeType) { - MISSING -> JsonMissing.of() - NULL -> JsonNull.of() - BOOLEAN -> JsonBoolean.of(node.booleanValue()) - NUMBER -> JsonNumber.of(node.numberValue()) - STRING -> JsonString.of(node.textValue()) - ARRAY -> - JsonArray.of(node.elements().asSequence().map { fromJsonNode(it) }.toList()) - OBJECT -> - JsonObject.of( - node.fields().asSequence().map { it.key to fromJsonNode(it.value) }.toMap() - ) - BINARY, - POJO, - null -> throw IllegalStateException("Unexpected JsonNode type: ${node.nodeType}") - } - } - - class Deserializer : BaseDeserializer(JsonValue::class) { - - override fun ObjectCodec.deserialize(node: JsonNode): JsonValue = fromJsonNode(node) - - override fun getNullValue(context: DeserializationContext?): JsonValue = JsonNull.of() - } -} - -/** - * A class representing a "known" JSON serializable value of type [T], matching the type the SDK - * expects. - * - * It is assignable to `JsonField`. - */ -class KnownValue -private constructor( - @com.fasterxml.jackson.annotation.JsonValue @get:JvmName("value") val value: T -) : JsonField() { - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is KnownValue<*> && value contentEquals other.value - } - - override fun hashCode() = contentHash(value) - - override fun toString() = value.contentToString() - - companion object { - - /** Returns a [KnownValue] containing the given [value]. */ - @JsonCreator @JvmStatic fun of(value: T) = KnownValue(value) - } -} - -/** - * A [JsonValue] representing an omitted JSON field. - * - * An instance of this class will cause a JSON field to be omitted from the serialized JSON - * entirely. - */ -@JsonSerialize(using = JsonMissing.Serializer::class) -class JsonMissing : JsonValue() { - - override fun toString() = "" - - companion object { - - private val INSTANCE: JsonMissing = JsonMissing() - - /** Returns the singleton instance of [JsonMissing]. */ - @JvmStatic fun of() = INSTANCE - } - - class Serializer : BaseSerializer(JsonMissing::class) { - - override fun serialize( - value: JsonMissing, - generator: JsonGenerator, - provider: SerializerProvider, - ) { - throw IllegalStateException("JsonMissing cannot be serialized") - } - } -} - -/** A [JsonValue] representing a JSON `null` value. */ -@JsonSerialize(using = NullSerializer::class) -class JsonNull : JsonValue() { - - override fun toString() = "null" - - companion object { - - private val INSTANCE: JsonNull = JsonNull() - - /** Returns the singleton instance of [JsonMissing]. */ - @JsonCreator @JvmStatic fun of() = INSTANCE - } -} - -/** A [JsonValue] representing a JSON boolean value. */ -class JsonBoolean -private constructor( - @get:com.fasterxml.jackson.annotation.JsonValue @get:JvmName("value") val value: Boolean -) : JsonValue() { - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is JsonBoolean && value == other.value - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - - companion object { - - /** Returns a [JsonBoolean] containing the given [value]. */ - @JsonCreator @JvmStatic fun of(value: Boolean) = JsonBoolean(value) - } -} - -/** A [JsonValue] representing a JSON number value. */ -class JsonNumber -private constructor( - @get:com.fasterxml.jackson.annotation.JsonValue @get:JvmName("value") val value: Number -) : JsonValue() { - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is JsonNumber && value == other.value - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - - companion object { - - /** Returns a [JsonNumber] containing the given [value]. */ - @JsonCreator @JvmStatic fun of(value: Number) = JsonNumber(value) - } -} - -/** A [JsonValue] representing a JSON string value. */ -class JsonString -private constructor( - @get:com.fasterxml.jackson.annotation.JsonValue @get:JvmName("value") val value: String -) : JsonValue() { - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is JsonString && value == other.value - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value - - companion object { - - /** Returns a [JsonString] containing the given [value]. */ - @JsonCreator @JvmStatic fun of(value: String) = JsonString(value) - } -} - -/** A [JsonValue] representing a JSON array value. */ -class JsonArray -private constructor( - @get:com.fasterxml.jackson.annotation.JsonValue - @get:JvmName("values") - val values: List -) : JsonValue() { - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is JsonArray && values == other.values - } - - override fun hashCode() = values.hashCode() - - override fun toString() = values.toString() - - companion object { - - /** Returns a [JsonArray] containing the given [values]. */ - @JsonCreator @JvmStatic fun of(values: List) = JsonArray(values.toImmutable()) - } -} - -/** A [JsonValue] representing a JSON object value. */ -class JsonObject -private constructor( - @get:com.fasterxml.jackson.annotation.JsonValue - @get:JvmName("values") - val values: Map -) : JsonValue() { - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is JsonObject && values == other.values - } - - override fun hashCode() = values.hashCode() - - override fun toString() = values.toString() - - companion object { - - /** Returns a [JsonObject] containing the given [values]. */ - @JsonCreator - @JvmStatic - fun of(values: Map) = JsonObject(values.toImmutable()) - } -} - -/** A Jackson annotation for excluding fields set to [JsonMissing] from the serialized JSON. */ -@JacksonAnnotationsInside -@JsonInclude(JsonInclude.Include.CUSTOM, valueFilter = JsonField.IsMissing::class) -annotation class ExcludeMissing - -/** A class representing a field in a `multipart/form-data` request. */ -class MultipartField -private constructor( - /** A [JsonField] value, which will be serialized to zero or more parts. */ - @get:com.fasterxml.jackson.annotation.JsonValue @get:JvmName("value") val value: JsonField, - /** A content type for the serialized parts. */ - @get:JvmName("contentType") val contentType: String, - private val filename: String?, -) { - - companion object { - - /** - * Returns a [MultipartField] containing the given [value] as a [KnownValue]. - * - * [contentType] will be set to `application/octet-stream` if [value] is binary data, or - * `text/plain; charset=utf-8` otherwise. - */ - @JvmStatic fun of(value: T?) = builder().value(value).build() - - /** - * Returns a [MultipartField] containing the given [value]. - * - * [contentType] will be set to `application/octet-stream` if [value] is binary data, or - * `text/plain; charset=utf-8` otherwise. - */ - @JvmStatic fun of(value: JsonField) = builder().value(value).build() - - /** - * Returns a mutable builder for constructing an instance of [MultipartField]. - * - * The following fields are required: - * ```java - * .value() - * ``` - * - * If [contentType] is unset, then it will be set to `application/octet-stream` if [value] - * is binary data, or `text/plain; charset=utf-8` otherwise. - */ - @JvmStatic fun builder() = Builder() - } - - /** Returns the filename directive that will be included in the serialized field. */ - fun filename(): Optional = Optional.ofNullable(filename) - - @JvmSynthetic - internal fun map(transform: (T) -> R): MultipartField = - builder().value(value.map(transform)).contentType(contentType).filename(filename).build() - - /** A builder for [MultipartField]. */ - class Builder internal constructor() { - - private var value: JsonField? = null - private var contentType: String? = null - private var filename: String? = null - - fun value(value: JsonField) = apply { this.value = value } - - fun value(value: T?) = value(JsonField.ofNullable(value)) - - fun contentType(contentType: String) = apply { this.contentType = contentType } - - fun filename(filename: String?) = apply { this.filename = filename } - - /** Alias for calling [Builder.filename] with `filename.orElse(null)`. */ - fun filename(filename: Optional) = filename(filename.orElse(null)) - - /** - * Returns an immutable instance of [MultipartField]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .value() - * ``` - * - * If [contentType] is unset, then it will be set to `application/octet-stream` if [value] - * is binary data, or `text/plain; charset=utf-8` otherwise. - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): MultipartField { - val value = checkRequired("value", value) - return MultipartField( - value, - contentType - ?: if ( - value is KnownValue && - (value.value is InputStream || value.value is ByteArray) - ) - "application/octet-stream" - else "text/plain; charset=utf-8", - filename, - ) - } - } - - private val hashCode: Int by lazy { contentHash(value, contentType, filename) } - - override fun hashCode(): Int = hashCode - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is MultipartField<*> && - value == other.value && - contentType == other.contentType && - filename == other.filename - } - - override fun toString(): String = - "MultipartField{value=$value, contentType=$contentType, filename=$filename}" -} diff --git a/src/main/java/com/google/genai/interactions/core/VertexInfo.kt b/src/main/java/com/google/genai/interactions/core/VertexInfo.kt deleted file mode 100644 index 35e5a7a1134..00000000000 --- a/src/main/java/com/google/genai/interactions/core/VertexInfo.kt +++ /dev/null @@ -1,19 +0,0 @@ -/* - * 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 - * - * http://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.interactions.core - -data class VertexInfo(val project: String, val location: String) diff --git a/src/main/java/com/google/genai/interactions/core/handlers/ErrorHandler.kt b/src/main/java/com/google/genai/interactions/core/handlers/ErrorHandler.kt deleted file mode 100644 index 8cc5ca3180d..00000000000 --- a/src/main/java/com/google/genai/interactions/core/handlers/ErrorHandler.kt +++ /dev/null @@ -1,100 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -@file:JvmName("ErrorHandler") - -package com.google.genai.interactions.core.handlers - -import com.fasterxml.jackson.databind.json.JsonMapper -import com.google.genai.interactions.core.JsonMissing -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.core.http.HttpResponse -import com.google.genai.interactions.core.http.HttpResponse.Handler -import com.google.genai.interactions.errors.BadRequestException -import com.google.genai.interactions.errors.InternalServerException -import com.google.genai.interactions.errors.NotFoundException -import com.google.genai.interactions.errors.PermissionDeniedException -import com.google.genai.interactions.errors.RateLimitException -import com.google.genai.interactions.errors.UnauthorizedException -import com.google.genai.interactions.errors.UnexpectedStatusCodeException -import com.google.genai.interactions.errors.UnprocessableEntityException - -@JvmSynthetic -internal fun errorBodyHandler(jsonMapper: JsonMapper): Handler { - val handler = jsonHandler(jsonMapper) - - return object : Handler { - override fun handle(response: HttpResponse): JsonValue = - try { - handler.handle(response) - } catch (e: Exception) { - JsonMissing.of() - } - } -} - -@JvmSynthetic -internal fun errorHandler(errorBodyHandler: Handler): Handler = - object : Handler { - override fun handle(response: HttpResponse): HttpResponse = - when (val statusCode = response.statusCode()) { - in 200..299 -> response - 400 -> - throw BadRequestException.builder() - .headers(response.headers()) - .body(errorBodyHandler.handle(response)) - .build() - 401 -> - throw UnauthorizedException.builder() - .headers(response.headers()) - .body(errorBodyHandler.handle(response)) - .build() - 403 -> - throw PermissionDeniedException.builder() - .headers(response.headers()) - .body(errorBodyHandler.handle(response)) - .build() - 404 -> - throw NotFoundException.builder() - .headers(response.headers()) - .body(errorBodyHandler.handle(response)) - .build() - 422 -> - throw UnprocessableEntityException.builder() - .headers(response.headers()) - .body(errorBodyHandler.handle(response)) - .build() - 429 -> - throw RateLimitException.builder() - .headers(response.headers()) - .body(errorBodyHandler.handle(response)) - .build() - in 500..599 -> - throw InternalServerException.builder() - .statusCode(statusCode) - .headers(response.headers()) - .body(errorBodyHandler.handle(response)) - .build() - else -> - throw UnexpectedStatusCodeException.builder() - .statusCode(statusCode) - .headers(response.headers()) - .body(errorBodyHandler.handle(response)) - .build() - } - } diff --git a/src/main/java/com/google/genai/interactions/core/handlers/JsonHandler.kt b/src/main/java/com/google/genai/interactions/core/handlers/JsonHandler.kt deleted file mode 100644 index c452f2eb0b5..00000000000 --- a/src/main/java/com/google/genai/interactions/core/handlers/JsonHandler.kt +++ /dev/null @@ -1,36 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -@file:JvmName("JsonHandler") - -package com.google.genai.interactions.core.handlers - -import com.fasterxml.jackson.databind.json.JsonMapper -import com.fasterxml.jackson.module.kotlin.jacksonTypeRef -import com.google.genai.interactions.core.http.HttpResponse -import com.google.genai.interactions.core.http.HttpResponse.Handler -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException - -@JvmSynthetic -internal inline fun jsonHandler(jsonMapper: JsonMapper): Handler = - object : Handler { - override fun handle(response: HttpResponse): T = - try { - jsonMapper.readValue(response.body(), jacksonTypeRef()) - } catch (e: Exception) { - throw GeminiNextGenApiInvalidDataException("Error reading response", e) - } - } diff --git a/src/main/java/com/google/genai/interactions/core/handlers/SseHandler.kt b/src/main/java/com/google/genai/interactions/core/handlers/SseHandler.kt deleted file mode 100644 index 15da616f27b..00000000000 --- a/src/main/java/com/google/genai/interactions/core/handlers/SseHandler.kt +++ /dev/null @@ -1,133 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -@file:JvmName("SseHandler") - -package com.google.genai.interactions.core.handlers - -import com.fasterxml.jackson.databind.json.JsonMapper -import com.google.genai.interactions.core.http.HttpResponse -import com.google.genai.interactions.core.http.HttpResponse.Handler -import com.google.genai.interactions.core.http.SseMessage -import com.google.genai.interactions.core.http.StreamResponse -import com.google.genai.interactions.core.http.map - -@JvmSynthetic -internal fun sseHandler(jsonMapper: JsonMapper): Handler> = - streamHandler { response, lines -> - val state = SseState(jsonMapper) - var done = false - for (line in lines) { - // Stop emitting messages, but iterate through the full stream. - if (done) { - continue - } - - val message = state.decode(line) ?: continue - - if (message.data.startsWith("[DONE]")) { - // In this case we don't break because we still want to iterate through the full - // stream. - done = true - continue - } - - yield(message) - } - } - -private class SseState( - val jsonMapper: JsonMapper, - var event: String? = null, - val data: MutableList = mutableListOf(), - var lastId: String? = null, - var retry: Int? = null, -) { - // https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation - fun decode(line: String): SseMessage? { - if (line.isEmpty()) { - return flush() - } - - if (line.startsWith(':')) { - return null - } - - val fieldName: String - var value: String - - val colonIndex = line.indexOf(':') - if (colonIndex == -1) { - fieldName = line - value = "" - } else { - fieldName = line.substring(0, colonIndex) - value = line.substring(colonIndex + 1) - } - - if (value.startsWith(' ')) { - value = value.substring(1) - } - - when (fieldName) { - "event" -> event = value - "data" -> data.add(value) - "id" -> { - if (!value.contains('\u0000')) { - lastId = value - } - } - "retry" -> value.toIntOrNull()?.let { retry = it } - } - - return null - } - - private fun flush(): SseMessage? { - if (isEmpty()) { - return null - } - - val message = - SseMessage.builder() - .jsonMapper(jsonMapper) - .event(event) - .data(data.joinToString("\n")) - .id(lastId) - .retry(retry) - .build() - - // NOTE: Per the SSE spec, do not reset lastId. - event = null - data.clear() - retry = null - - return message - } - - private fun isEmpty(): Boolean = - event.isNullOrEmpty() && data.isEmpty() && lastId.isNullOrEmpty() && retry == null -} - -@JvmSynthetic -internal inline fun Handler>.mapJson(): - Handler> = - object : Handler> { - override fun handle(response: HttpResponse): StreamResponse = - this@mapJson.handle(response).map { it.json() } - } diff --git a/src/main/java/com/google/genai/interactions/core/handlers/StreamHandler.kt b/src/main/java/com/google/genai/interactions/core/handlers/StreamHandler.kt deleted file mode 100644 index 5c97a17e926..00000000000 --- a/src/main/java/com/google/genai/interactions/core/handlers/StreamHandler.kt +++ /dev/null @@ -1,118 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -@file:JvmName("StreamHandler") - -package com.google.genai.interactions.core.handlers - -import com.google.genai.interactions.core.http.HttpResponse -import com.google.genai.interactions.core.http.HttpResponse.Handler -import com.google.genai.interactions.core.http.PhantomReachableClosingStreamResponse -import com.google.genai.interactions.core.http.StreamResponse -import com.google.genai.interactions.errors.GeminiNextGenApiIoException -import java.io.IOException -import java.util.stream.Stream -import kotlin.streams.asStream - -@JvmSynthetic -internal fun streamHandler( - block: suspend SequenceScope.(response: HttpResponse, lines: Sequence) -> Unit -): Handler> = - object : Handler> { - - override fun handle(response: HttpResponse): StreamResponse { - val reader = response.body().bufferedReader() - val sequence = - // Wrap in a `CloseableSequence` to avoid performing a read on the `reader` - // after it has been closed, which would throw an `IOException`. - CloseableSequence( - sequence { - reader.useLines { lines -> - block( - response, - // We wrap the `lines` instead of the top-level sequence because - // we only want to catch `IOException` from the reader; not from - // the user's own code. - IOExceptionWrappingSequence(lines), - ) - } - } - .constrainOnce() - ) - - return PhantomReachableClosingStreamResponse( - object : StreamResponse { - - override fun stream(): Stream = sequence.asStream() - - override fun close() { - sequence.close() - reader.close() - response.close() - } - } - ) - } - } - -/** A sequence that catches, wraps, and rethrows [IOException] as [GeminiNextGenApiIoException]. */ -private class IOExceptionWrappingSequence(private val sequence: Sequence) : Sequence { - - override fun iterator(): Iterator { - val iterator = sequence.iterator() - return object : Iterator { - - override fun next(): T = - try { - iterator.next() - } catch (e: IOException) { - throw GeminiNextGenApiIoException("Stream failed", e) - } - - override fun hasNext(): Boolean = - try { - iterator.hasNext() - } catch (e: IOException) { - throw GeminiNextGenApiIoException("Stream failed", e) - } - } - } -} - -/** - * A sequence that can be closed. - * - * Once [close] is called, it will not yield more elements. It will also no longer consult the - * underlying [Iterator.hasNext] method. - */ -private class CloseableSequence(private val sequence: Sequence) : Sequence { - - private var isClosed: Boolean = false - - override fun iterator(): Iterator { - val iterator = sequence.iterator() - return object : Iterator { - - override fun next(): T = iterator.next() - - override fun hasNext(): Boolean = !isClosed && iterator.hasNext() - } - } - - fun close() { - isClosed = true - } -} diff --git a/src/main/java/com/google/genai/interactions/core/handlers/StringHandler.kt b/src/main/java/com/google/genai/interactions/core/handlers/StringHandler.kt deleted file mode 100644 index c3b50d149c7..00000000000 --- a/src/main/java/com/google/genai/interactions/core/handlers/StringHandler.kt +++ /dev/null @@ -1,29 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -@file:JvmName("StringHandler") - -package com.google.genai.interactions.core.handlers - -import com.google.genai.interactions.core.http.HttpResponse -import com.google.genai.interactions.core.http.HttpResponse.Handler - -@JvmSynthetic internal fun stringHandler(): Handler = StringHandlerInternal - -private object StringHandlerInternal : Handler { - override fun handle(response: HttpResponse): String = - response.body().readBytes().toString(Charsets.UTF_8) -} diff --git a/src/main/java/com/google/genai/interactions/core/http/AsyncStreamResponse.kt b/src/main/java/com/google/genai/interactions/core/http/AsyncStreamResponse.kt deleted file mode 100644 index b2c0e53dc81..00000000000 --- a/src/main/java/com/google/genai/interactions/core/http/AsyncStreamResponse.kt +++ /dev/null @@ -1,173 +0,0 @@ -/* -* 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 -* -* http://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.interactions.core.http - -import com.google.genai.interactions.core.http.AsyncStreamResponse.Handler -import java.util.Optional -import java.util.concurrent.CompletableFuture -import java.util.concurrent.Executor -import java.util.concurrent.atomic.AtomicReference - -/** - * A class providing access to an API response as an asynchronous stream of chunks of type [T], - * where each chunk can be individually processed as soon as it arrives instead of waiting on the - * full response. - */ -interface AsyncStreamResponse { - - /** - * Registers [handler] to be called for events of this stream. - * - * [handler]'s methods will be called in the client's configured or default thread pool. - * - * @throws IllegalStateException if [subscribe] has already been called. - */ - fun subscribe(handler: Handler): AsyncStreamResponse - - /** - * Registers [handler] to be called for events of this stream. - * - * [handler]'s methods will be called in the given [executor]. - * - * @throws IllegalStateException if [subscribe] has already been called. - */ - fun subscribe(handler: Handler, executor: Executor): AsyncStreamResponse - - /** - * Returns a future that completes when a stream is fully consumed, errors, or gets closed - * early. - */ - fun onCompleteFuture(): CompletableFuture - - /** - * Closes this resource, relinquishing any underlying resources. - * - * This is purposefully not inherited from [AutoCloseable] because this response should not be - * synchronously closed via try-with-resources. - */ - fun close() - - /** A class for handling streaming events. */ - fun interface Handler { - - /** Called whenever a chunk is received. */ - fun onNext(value: T) - - /** - * Called when a stream is fully consumed, errors, or gets closed early. - * - * [onNext] will not be called once this method is called. - * - * @param error Non-empty if the stream completed due to an error. - */ - fun onComplete(error: Optional) {} - } -} - -@JvmSynthetic -internal fun CompletableFuture>.toAsync(streamHandlerExecutor: Executor) = - PhantomReachableClosingAsyncStreamResponse( - object : AsyncStreamResponse { - - private val onCompleteFuture = CompletableFuture() - private val state = AtomicReference(State.NEW) - - init { - this@toAsync.whenComplete { _, error -> - // If an error occurs from the original future, then we should resolve the - // `onCompleteFuture` even if `subscribe` has not been called. - error?.let(onCompleteFuture::completeExceptionally) - } - } - - override fun subscribe(handler: Handler): AsyncStreamResponse = - subscribe(handler, streamHandlerExecutor) - - override fun subscribe( - handler: Handler, - executor: Executor, - ): AsyncStreamResponse = apply { - // TODO(JDK): Use `compareAndExchange` once targeting JDK 9. - check(state.compareAndSet(State.NEW, State.SUBSCRIBED)) { - if (state.get() == State.SUBSCRIBED) "Cannot subscribe more than once" - else "Cannot subscribe after the response is closed" - } - - this@toAsync.whenCompleteAsync( - { streamResponse, futureError -> - if (state.get() == State.CLOSED) { - // Avoid doing any work if `close` was called before the future - // completed. - return@whenCompleteAsync - } - - if (futureError != null) { - // An error occurred before we started passing chunks to the handler. - handler.onComplete(Optional.of(futureError)) - return@whenCompleteAsync - } - - var streamError: Throwable? = null - try { - streamResponse.stream().forEach(handler::onNext) - } catch (e: Throwable) { - streamError = e - } - - try { - handler.onComplete(Optional.ofNullable(streamError)) - } finally { - try { - // Notify completion via the `onCompleteFuture` as well. This is in - // a separate `try-finally` block so that we still complete the - // future if `handler.onComplete` throws. - if (streamError == null) { - onCompleteFuture.complete(null) - } else { - onCompleteFuture.completeExceptionally(streamError) - } - } finally { - close() - } - } - }, - executor, - ) - } - - override fun onCompleteFuture(): CompletableFuture = onCompleteFuture - - override fun close() { - val previousState = state.getAndSet(State.CLOSED) - if (previousState == State.CLOSED) { - return - } - - this@toAsync.whenComplete { streamResponse, error -> streamResponse?.close() } - // When the stream is closed, we should always consider it closed. If it closed due - // to an error, then we will have already completed the future earlier, and this - // will be a no-op. - onCompleteFuture.complete(null) - } - } - ) - -private enum class State { - NEW, - SUBSCRIBED, - CLOSED, -} diff --git a/src/main/java/com/google/genai/interactions/core/http/Headers.kt b/src/main/java/com/google/genai/interactions/core/http/Headers.kt deleted file mode 100644 index 5f927de08ba..00000000000 --- a/src/main/java/com/google/genai/interactions/core/http/Headers.kt +++ /dev/null @@ -1,131 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.core.http - -import com.google.genai.interactions.core.JsonArray -import com.google.genai.interactions.core.JsonBoolean -import com.google.genai.interactions.core.JsonMissing -import com.google.genai.interactions.core.JsonNull -import com.google.genai.interactions.core.JsonNumber -import com.google.genai.interactions.core.JsonObject -import com.google.genai.interactions.core.JsonString -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.core.toImmutable -import java.util.TreeMap - -class Headers -private constructor( - private val map: Map>, - @get:JvmName("size") val size: Int, -) { - - fun isEmpty(): Boolean = map.isEmpty() - - fun names(): Set = map.keys - - fun values(name: String): List = map[name].orEmpty() - - fun toBuilder(): Builder = Builder().putAll(map) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder internal constructor() { - - private val map: MutableMap> = - TreeMap(String.CASE_INSENSITIVE_ORDER) - private var size: Int = 0 - - fun put(name: String, value: JsonValue): Builder = apply { - when (value) { - is JsonMissing, - is JsonNull -> {} - is JsonBoolean -> put(name, value.value.toString()) - is JsonNumber -> put(name, value.value.toString()) - is JsonString -> put(name, value.value) - is JsonArray -> value.values.forEach { put(name, it) } - is JsonObject -> - value.values.forEach { (nestedName, value) -> put("$name.$nestedName", value) } - } - } - - fun put(name: String, value: String) = apply { - map.getOrPut(name) { mutableListOf() }.add(value) - size++ - } - - fun put(name: String, values: Iterable) = apply { values.forEach { put(name, it) } } - - fun putAll(headers: Map>) = apply { headers.forEach(::put) } - - fun putAll(headers: Headers) = apply { - headers.names().forEach { put(it, headers.values(it)) } - } - - fun replace(name: String, value: String) = apply { - remove(name) - put(name, value) - } - - fun replace(name: String, values: Iterable) = apply { - remove(name) - put(name, values) - } - - fun replaceAll(headers: Map>) = apply { - headers.forEach(::replace) - } - - fun replaceAll(headers: Headers) = apply { - headers.names().forEach { replace(it, headers.values(it)) } - } - - fun remove(name: String) = apply { size -= map.remove(name).orEmpty().size } - - fun removeAll(names: Set) = apply { names.forEach(::remove) } - - fun clear() = apply { - map.clear() - size = 0 - } - - fun build() = - Headers( - map.mapValuesTo(TreeMap(String.CASE_INSENSITIVE_ORDER)) { (_, values) -> - values.toImmutable() - } - .toImmutable(), - size, - ) - } - - override fun hashCode(): Int = map.hashCode() - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Headers && map == other.map - } - - override fun toString(): String = "Headers{map=$map}" -} diff --git a/src/main/java/com/google/genai/interactions/core/http/HttpClient.kt b/src/main/java/com/google/genai/interactions/core/http/HttpClient.kt deleted file mode 100644 index f559faca49e..00000000000 --- a/src/main/java/com/google/genai/interactions/core/http/HttpClient.kt +++ /dev/null @@ -1,42 +0,0 @@ -/* -* 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 -* -* http://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.interactions.core.http - -import com.google.genai.interactions.core.RequestOptions -import java.lang.AutoCloseable -import java.util.concurrent.CompletableFuture - -interface HttpClient : AutoCloseable { - - fun execute( - request: HttpRequest, - requestOptions: RequestOptions = RequestOptions.none(), - ): HttpResponse - - fun execute(request: HttpRequest): HttpResponse = execute(request, RequestOptions.none()) - - fun executeAsync( - request: HttpRequest, - requestOptions: RequestOptions = RequestOptions.none(), - ): CompletableFuture - - fun executeAsync(request: HttpRequest): CompletableFuture = - executeAsync(request, RequestOptions.none()) - - /** Overridden from [AutoCloseable] to not have a checked exception in its signature. */ - override fun close() -} diff --git a/src/main/java/com/google/genai/interactions/core/http/HttpMethod.kt b/src/main/java/com/google/genai/interactions/core/http/HttpMethod.kt deleted file mode 100644 index 86a92566278..00000000000 --- a/src/main/java/com/google/genai/interactions/core/http/HttpMethod.kt +++ /dev/null @@ -1,29 +0,0 @@ -/* -* 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 -* -* http://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.interactions.core.http - -enum class HttpMethod { - GET, - HEAD, - POST, - PUT, - DELETE, - CONNECT, - OPTIONS, - TRACE, - PATCH, -} diff --git a/src/main/java/com/google/genai/interactions/core/http/HttpRequest.kt b/src/main/java/com/google/genai/interactions/core/http/HttpRequest.kt deleted file mode 100644 index ab7e17d77cf..00000000000 --- a/src/main/java/com/google/genai/interactions/core/http/HttpRequest.kt +++ /dev/null @@ -1,196 +0,0 @@ -/* - * 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 - * - * http://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.interactions.core.http - -import com.google.genai.interactions.core.checkRequired -import com.google.genai.interactions.core.toImmutable -import java.net.URLEncoder - -class HttpRequest -private constructor( - @get:JvmName("method") val method: HttpMethod, - @get:JvmName("baseUrl") val baseUrl: String, - @get:JvmName("pathSegments") val pathSegments: List, - @get:JvmName("headers") val headers: Headers, - @get:JvmName("queryParams") val queryParams: QueryParams, - @get:JvmName("body") val body: HttpRequestBody?, -) { - - fun url(): String = buildString { - append(baseUrl) - - pathSegments.forEach { segment -> - if (!endsWith("/")) { - append("/") - } - append(URLEncoder.encode(segment, "UTF-8")) - } - - if (queryParams.isEmpty()) { - return@buildString - } - - append("?") - var isFirst = true - queryParams.keys().forEach { key -> - queryParams.values(key).forEach { value -> - if (!isFirst) { - append("&") - } - append(URLEncoder.encode(key, "UTF-8")) - append("=") - append(URLEncoder.encode(value, "UTF-8")) - isFirst = false - } - } - } - - fun toBuilder(): Builder = Builder().from(this) - - override fun toString(): String = - "HttpRequest{method=$method, baseUrl=$baseUrl, pathSegments=$pathSegments, headers=$headers, queryParams=$queryParams, body=$body}" - - companion object { - @JvmStatic fun builder() = Builder() - } - - class Builder internal constructor() { - - private var method: HttpMethod? = null - private var baseUrl: String? = null - private var pathSegments: MutableList = mutableListOf() - private var headers: Headers.Builder = Headers.builder() - private var queryParams: QueryParams.Builder = QueryParams.builder() - private var body: HttpRequestBody? = null - - @JvmSynthetic - internal fun from(request: HttpRequest) = apply { - method = request.method - baseUrl = request.baseUrl - pathSegments = request.pathSegments.toMutableList() - headers = request.headers.toBuilder() - queryParams = request.queryParams.toBuilder() - body = request.body - } - - fun method(method: HttpMethod) = apply { this.method = method } - - fun baseUrl(baseUrl: String) = apply { this.baseUrl = baseUrl } - - fun pathSegments(pathSegments: List) = apply { - this.pathSegments = pathSegments.toMutableList() - } - - fun addPathSegment(pathSegment: String) = apply { pathSegments.add(pathSegment) } - - fun addPathSegments(vararg pathSegments: String) = apply { - this.pathSegments.addAll(pathSegments) - } - - fun headers(headers: Headers) = apply { - this.headers.clear() - putAllHeaders(headers) - } - - fun headers(headers: Map>) = apply { - this.headers.clear() - putAllHeaders(headers) - } - - fun putHeader(name: String, value: String) = apply { headers.put(name, value) } - - fun putHeaders(name: String, values: Iterable) = apply { headers.put(name, values) } - - fun putAllHeaders(headers: Headers) = apply { this.headers.putAll(headers) } - - fun putAllHeaders(headers: Map>) = apply { - this.headers.putAll(headers) - } - - fun replaceHeaders(name: String, value: String) = apply { headers.replace(name, value) } - - fun replaceHeaders(name: String, values: Iterable) = apply { - headers.replace(name, values) - } - - fun replaceAllHeaders(headers: Headers) = apply { this.headers.replaceAll(headers) } - - fun replaceAllHeaders(headers: Map>) = apply { - this.headers.replaceAll(headers) - } - - fun removeHeaders(name: String) = apply { headers.remove(name) } - - fun removeAllHeaders(names: Set) = apply { headers.removeAll(names) } - - fun queryParams(queryParams: QueryParams) = apply { - this.queryParams.clear() - putAllQueryParams(queryParams) - } - - fun queryParams(queryParams: Map>) = apply { - this.queryParams.clear() - putAllQueryParams(queryParams) - } - - fun putQueryParam(key: String, value: String) = apply { queryParams.put(key, value) } - - fun putQueryParams(key: String, values: Iterable) = apply { - queryParams.put(key, values) - } - - fun putAllQueryParams(queryParams: QueryParams) = apply { - this.queryParams.putAll(queryParams) - } - - fun putAllQueryParams(queryParams: Map>) = apply { - this.queryParams.putAll(queryParams) - } - - fun replaceQueryParams(key: String, value: String) = apply { - queryParams.replace(key, value) - } - - fun replaceQueryParams(key: String, values: Iterable) = apply { - queryParams.replace(key, values) - } - - fun replaceAllQueryParams(queryParams: QueryParams) = apply { - this.queryParams.replaceAll(queryParams) - } - - fun replaceAllQueryParams(queryParams: Map>) = apply { - this.queryParams.replaceAll(queryParams) - } - - fun removeQueryParams(key: String) = apply { queryParams.remove(key) } - - fun removeAllQueryParams(keys: Set) = apply { queryParams.removeAll(keys) } - - fun body(body: HttpRequestBody) = apply { this.body = body } - - fun build(): HttpRequest = - HttpRequest( - checkRequired("method", method), - checkRequired("baseUrl", baseUrl), - pathSegments.toImmutable(), - headers.build(), - queryParams.build(), - body, - ) - } -} diff --git a/src/main/java/com/google/genai/interactions/core/http/HttpRequestBodies.kt b/src/main/java/com/google/genai/interactions/core/http/HttpRequestBodies.kt deleted file mode 100644 index 7f1bdfc00cb..00000000000 --- a/src/main/java/com/google/genai/interactions/core/http/HttpRequestBodies.kt +++ /dev/null @@ -1,284 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -@file:JvmName("HttpRequestBodies") - -package com.google.genai.interactions.core.http - -import com.fasterxml.jackson.databind.JsonNode -import com.fasterxml.jackson.databind.json.JsonMapper -import com.fasterxml.jackson.databind.node.JsonNodeType -import com.google.genai.interactions.core.MultipartField -import com.google.genai.interactions.core.toImmutable -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.io.ByteArrayInputStream -import java.io.InputStream -import java.io.OutputStream -import java.util.UUID -import kotlin.jvm.optionals.getOrNull - -@JvmSynthetic -internal inline fun json(jsonMapper: JsonMapper, value: T): HttpRequestBody = - object : HttpRequestBody { - private val bytes: ByteArray by lazy { jsonMapper.writeValueAsBytes(value) } - - override fun writeTo(outputStream: OutputStream) = outputStream.write(bytes) - - override fun contentType(): String = "application/json" - - override fun contentLength(): Long = bytes.size.toLong() - - override fun repeatable(): Boolean = true - - override fun close() {} - } - -@JvmSynthetic -internal fun multipartFormData( - jsonMapper: JsonMapper, - fields: Map>, -): HttpRequestBody = - MultipartBody.Builder() - .apply { - fields.forEach { (name, field) -> - val knownValue = field.value.asKnown().getOrNull() - val parts = - if (knownValue is InputStream) { - // Read directly from the `InputStream` instead of reading it all - // into memory due to the `jsonMapper` serialization below. - sequenceOf(name to knownValue) - } else { - val node = jsonMapper.valueToTree(field.value) - serializePart(name, node) - } - - parts.forEach { (name, bytes) -> - val partBody = - if (bytes is ByteArrayInputStream) { - val byteArray = bytes.readBytes() - - object : HttpRequestBody { - - override fun writeTo(outputStream: OutputStream) { - outputStream.write(byteArray) - } - - override fun contentType(): String = field.contentType - - override fun contentLength(): Long = byteArray.size.toLong() - - override fun repeatable(): Boolean = true - - override fun close() {} - } - } else { - object : HttpRequestBody { - - override fun writeTo(outputStream: OutputStream) { - bytes.copyTo(outputStream) - } - - override fun contentType(): String = field.contentType - - override fun contentLength(): Long = -1L - - override fun repeatable(): Boolean = false - - override fun close() = bytes.close() - } - } - - addPart( - MultipartBody.Part.create( - name, - field.filename().getOrNull(), - field.contentType, - partBody, - ) - ) - } - } - } - .build() - -private fun serializePart(name: String, node: JsonNode): Sequence> = - when (node.nodeType) { - JsonNodeType.MISSING, - JsonNodeType.NULL -> emptySequence() - JsonNodeType.BINARY -> sequenceOf(name to node.binaryValue().inputStream()) - JsonNodeType.STRING -> sequenceOf(name to node.textValue().byteInputStream()) - JsonNodeType.BOOLEAN -> sequenceOf(name to node.booleanValue().toString().byteInputStream()) - JsonNodeType.NUMBER -> sequenceOf(name to node.numberValue().toString().byteInputStream()) - JsonNodeType.ARRAY -> - sequenceOf( - name to - node - .elements() - .asSequence() - .mapNotNull { element -> - when (element.nodeType) { - JsonNodeType.MISSING, - JsonNodeType.NULL -> null - JsonNodeType.STRING -> element.textValue() - JsonNodeType.BOOLEAN -> element.booleanValue().toString() - JsonNodeType.NUMBER -> element.numberValue().toString() - null, - JsonNodeType.BINARY, - JsonNodeType.ARRAY, - JsonNodeType.OBJECT, - JsonNodeType.POJO -> - throw GeminiNextGenApiInvalidDataException( - "Unexpected JsonNode type in array: ${element.nodeType}" - ) - } - } - .joinToString(",") - .byteInputStream() - ) - JsonNodeType.OBJECT -> - node.fields().asSequence().flatMap { (key, value) -> - serializePart("$name[$key]", value) - } - JsonNodeType.POJO, - null -> - throw GeminiNextGenApiInvalidDataException("Unexpected JsonNode type: ${node.nodeType}") - } - -private class MultipartBody -private constructor(private val boundary: String, private val parts: List) : HttpRequestBody { - private val boundaryBytes: ByteArray = boundary.toByteArray() - private val contentType = "multipart/form-data; boundary=$boundary" - - // This must remain in sync with `contentLength`. - override fun writeTo(outputStream: OutputStream) { - parts.forEach { part -> - outputStream.write(DASHDASH) - outputStream.write(boundaryBytes) - outputStream.write(CRLF) - - outputStream.write(CONTENT_DISPOSITION) - outputStream.write(part.contentDisposition.toByteArray()) - outputStream.write(CRLF) - - outputStream.write(CONTENT_TYPE) - outputStream.write(part.contentType.toByteArray()) - outputStream.write(CRLF) - - outputStream.write(CRLF) - part.body.writeTo(outputStream) - outputStream.write(CRLF) - } - - outputStream.write(DASHDASH) - outputStream.write(boundaryBytes) - outputStream.write(DASHDASH) - outputStream.write(CRLF) - } - - override fun contentType(): String = contentType - - // This must remain in sync with `writeTo`. - override fun contentLength(): Long { - var byteCount = 0L - - parts.forEach { part -> - val contentLength = part.body.contentLength() - if (contentLength == -1L) { - return -1L - } - - byteCount += - DASHDASH.size + - boundaryBytes.size + - CRLF.size + - CONTENT_DISPOSITION.size + - part.contentDisposition.toByteArray().size + - CRLF.size + - CONTENT_TYPE.size + - part.contentType.toByteArray().size + - CRLF.size + - CRLF.size + - contentLength + - CRLF.size - } - - byteCount += DASHDASH.size + boundaryBytes.size + DASHDASH.size + CRLF.size - return byteCount - } - - override fun repeatable(): Boolean = parts.all { it.body.repeatable() } - - override fun close() { - parts.forEach { it.body.close() } - } - - class Builder { - private val boundary = UUID.randomUUID().toString() - private val parts: MutableList = mutableListOf() - - fun addPart(part: Part) = apply { parts.add(part) } - - fun build() = MultipartBody(boundary, parts.toImmutable()) - } - - class Part - private constructor( - val contentDisposition: String, - val contentType: String, - val body: HttpRequestBody, - ) { - companion object { - fun create( - name: String, - filename: String?, - contentType: String, - body: HttpRequestBody, - ): Part { - val disposition = buildString { - append("form-data; name=") - appendQuotedString(name) - if (filename != null) { - append("; filename=") - appendQuotedString(filename) - } - } - return Part(disposition, contentType, body) - } - } - } - - companion object { - private val CRLF = byteArrayOf('\r'.code.toByte(), '\n'.code.toByte()) - private val DASHDASH = byteArrayOf('-'.code.toByte(), '-'.code.toByte()) - private val CONTENT_DISPOSITION = "Content-Disposition: ".toByteArray() - private val CONTENT_TYPE = "Content-Type: ".toByteArray() - - private fun StringBuilder.appendQuotedString(key: String) { - append('"') - for (ch in key) { - when (ch) { - '\n' -> append("%0A") - '\r' -> append("%0D") - '"' -> append("%22") - else -> append(ch) - } - } - append('"') - } - } -} diff --git a/src/main/java/com/google/genai/interactions/core/http/HttpRequestBody.kt b/src/main/java/com/google/genai/interactions/core/http/HttpRequestBody.kt deleted file mode 100644 index 9f0be43b194..00000000000 --- a/src/main/java/com/google/genai/interactions/core/http/HttpRequestBody.kt +++ /dev/null @@ -1,41 +0,0 @@ -/* -* 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 -* -* http://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.interactions.core.http - -import java.io.OutputStream -import java.lang.AutoCloseable - -interface HttpRequestBody : AutoCloseable { - - fun writeTo(outputStream: OutputStream) - - fun contentType(): String? - - fun contentLength(): Long - - /** - * Determines if a request can be repeated in a meaningful way, for example before doing a - * retry. - * - * The most typical case when a request can't be retried is if the request body is being - * streamed. In this case the body data isn't available on subsequent attempts. - */ - fun repeatable(): Boolean - - /** Overridden from [AutoCloseable] to not have a checked exception in its signature. */ - override fun close() -} diff --git a/src/main/java/com/google/genai/interactions/core/http/HttpResponse.kt b/src/main/java/com/google/genai/interactions/core/http/HttpResponse.kt deleted file mode 100644 index 415c6010b02..00000000000 --- a/src/main/java/com/google/genai/interactions/core/http/HttpResponse.kt +++ /dev/null @@ -1,38 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.core.http - -import java.io.InputStream - -interface HttpResponse : AutoCloseable { - - fun statusCode(): Int - - fun headers(): Headers - - fun body(): InputStream - - /** Overridden from [AutoCloseable] to not have a checked exception in its signature. */ - override fun close() - - interface Handler { - - fun handle(response: HttpResponse): T - } -} diff --git a/src/main/java/com/google/genai/interactions/core/http/HttpResponseFor.kt b/src/main/java/com/google/genai/interactions/core/http/HttpResponseFor.kt deleted file mode 100644 index ff57f4d12bf..00000000000 --- a/src/main/java/com/google/genai/interactions/core/http/HttpResponseFor.kt +++ /dev/null @@ -1,41 +0,0 @@ -/* -* 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 -* -* http://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.interactions.core.http - -import java.io.InputStream - -interface HttpResponseFor : HttpResponse { - - fun parse(): T -} - -@JvmSynthetic -internal fun HttpResponse.parseable(parse: () -> T): HttpResponseFor = - object : HttpResponseFor { - - private val parsed: T by lazy { parse() } - - override fun parse(): T = parsed - - override fun statusCode(): Int = this@parseable.statusCode() - - override fun headers(): Headers = this@parseable.headers() - - override fun body(): InputStream = this@parseable.body() - - override fun close() = this@parseable.close() - } diff --git a/src/main/java/com/google/genai/interactions/core/http/PhantomReachableClosingAsyncStreamResponse.kt b/src/main/java/com/google/genai/interactions/core/http/PhantomReachableClosingAsyncStreamResponse.kt deleted file mode 100644 index 94030f15e6e..00000000000 --- a/src/main/java/com/google/genai/interactions/core/http/PhantomReachableClosingAsyncStreamResponse.kt +++ /dev/null @@ -1,72 +0,0 @@ -/* -* 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 -* -* http://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.interactions.core.http - -import com.google.genai.interactions.core.closeWhenPhantomReachable -import com.google.genai.interactions.core.http.AsyncStreamResponse.Handler -import java.util.Optional -import java.util.concurrent.CompletableFuture -import java.util.concurrent.Executor - -/** - * A delegating wrapper around an `AsyncStreamResponse` that closes it once it's only phantom - * reachable. - * - * This class ensures the `AsyncStreamResponse` is closed even if the user forgets to close it. - */ -internal class PhantomReachableClosingAsyncStreamResponse( - private val asyncStreamResponse: AsyncStreamResponse -) : AsyncStreamResponse { - - /** - * An object used for keeping `asyncStreamResponse` open while the object is still reachable. - */ - private val reachabilityTracker = Object() - - init { - closeWhenPhantomReachable(reachabilityTracker, asyncStreamResponse::close) - } - - override fun subscribe(handler: Handler): AsyncStreamResponse = apply { - asyncStreamResponse.subscribe(TrackedHandler(handler, reachabilityTracker)) - } - - override fun subscribe(handler: Handler, executor: Executor): AsyncStreamResponse = - apply { - asyncStreamResponse.subscribe(TrackedHandler(handler, reachabilityTracker), executor) - } - - override fun onCompleteFuture(): CompletableFuture = - asyncStreamResponse.onCompleteFuture() - - override fun close() = asyncStreamResponse.close() -} - -/** - * A wrapper around a `Handler` that also references a `reachabilityTracker` object. - * - * Referencing the `reachabilityTracker` object prevents it from getting reclaimed while the handler - * is still reachable. - */ -private class TrackedHandler( - private val handler: Handler, - private val reachabilityTracker: Any, -) : Handler { - override fun onNext(value: T) = handler.onNext(value) - - override fun onComplete(error: Optional) = handler.onComplete(error) -} diff --git a/src/main/java/com/google/genai/interactions/core/http/PhantomReachableClosingHttpClient.kt b/src/main/java/com/google/genai/interactions/core/http/PhantomReachableClosingHttpClient.kt deleted file mode 100644 index 201261b5b47..00000000000 --- a/src/main/java/com/google/genai/interactions/core/http/PhantomReachableClosingHttpClient.kt +++ /dev/null @@ -1,42 +0,0 @@ -/* -* 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 -* -* http://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.interactions.core.http - -import com.google.genai.interactions.core.RequestOptions -import com.google.genai.interactions.core.closeWhenPhantomReachable -import java.util.concurrent.CompletableFuture - -/** - * A delegating wrapper around an `HttpClient` that closes it once it's only phantom reachable. - * - * This class ensures the `HttpClient` is closed even if the user forgets to close it. - */ -internal class PhantomReachableClosingHttpClient(private val httpClient: HttpClient) : HttpClient { - init { - closeWhenPhantomReachable(this, httpClient) - } - - override fun execute(request: HttpRequest, requestOptions: RequestOptions): HttpResponse = - httpClient.execute(request, requestOptions) - - override fun executeAsync( - request: HttpRequest, - requestOptions: RequestOptions, - ): CompletableFuture = httpClient.executeAsync(request, requestOptions) - - override fun close() = httpClient.close() -} diff --git a/src/main/java/com/google/genai/interactions/core/http/PhantomReachableClosingStreamResponse.kt b/src/main/java/com/google/genai/interactions/core/http/PhantomReachableClosingStreamResponse.kt deleted file mode 100644 index 850b242335e..00000000000 --- a/src/main/java/com/google/genai/interactions/core/http/PhantomReachableClosingStreamResponse.kt +++ /dev/null @@ -1,37 +0,0 @@ -/* -* 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 -* -* http://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.interactions.core.http - -import com.google.genai.interactions.core.closeWhenPhantomReachable -import java.util.stream.Stream - -/** - * A delegating wrapper around a `StreamResponse` that closes it once it's only phantom reachable. - * - * This class ensures the `StreamResponse` is closed even if the user forgets to close it. - */ -internal class PhantomReachableClosingStreamResponse( - private val streamResponse: StreamResponse -) : StreamResponse { - init { - closeWhenPhantomReachable(this, streamResponse) - } - - override fun stream(): Stream = streamResponse.stream() - - override fun close() = streamResponse.close() -} diff --git a/src/main/java/com/google/genai/interactions/core/http/QueryParams.kt b/src/main/java/com/google/genai/interactions/core/http/QueryParams.kt deleted file mode 100644 index 11402d7cd85..00000000000 --- a/src/main/java/com/google/genai/interactions/core/http/QueryParams.kt +++ /dev/null @@ -1,145 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.core.http - -import com.google.genai.interactions.core.JsonArray -import com.google.genai.interactions.core.JsonBoolean -import com.google.genai.interactions.core.JsonMissing -import com.google.genai.interactions.core.JsonNull -import com.google.genai.interactions.core.JsonNumber -import com.google.genai.interactions.core.JsonObject -import com.google.genai.interactions.core.JsonString -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.core.toImmutable - -class QueryParams -private constructor( - private val map: Map>, - @get:JvmName("size") val size: Int, -) { - - fun isEmpty(): Boolean = map.isEmpty() - - fun keys(): Set = map.keys - - fun values(key: String): List = map[key].orEmpty() - - fun toBuilder(): Builder = Builder().putAll(map) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder internal constructor() { - - private val map: MutableMap> = mutableMapOf() - private var size: Int = 0 - - fun put(key: String, value: JsonValue): Builder = apply { - when (value) { - is JsonMissing, - is JsonNull -> {} - is JsonBoolean -> put(key, value.value.toString()) - is JsonNumber -> put(key, value.value.toString()) - is JsonString -> put(key, value.value) - is JsonArray -> - put( - key, - value.values - .asSequence() - .mapNotNull { - when (it) { - is JsonMissing, - is JsonNull -> null - is JsonBoolean -> it.value.toString() - is JsonNumber -> it.value.toString() - is JsonString -> it.value - is JsonArray, - is JsonObject -> - throw IllegalArgumentException( - "Cannot comma separate non-primitives in query params" - ) - } - } - .joinToString(","), - ) - is JsonObject -> - value.values.forEach { (nestedKey, value) -> put("$key[$nestedKey]", value) } - } - } - - fun put(key: String, value: String) = apply { - map.getOrPut(key) { mutableListOf() }.add(value) - size++ - } - - fun put(key: String, values: Iterable) = apply { values.forEach { put(key, it) } } - - fun putAll(queryParams: Map>) = apply { - queryParams.forEach(::put) - } - - fun putAll(queryParams: QueryParams) = apply { - queryParams.keys().forEach { put(it, queryParams.values(it)) } - } - - fun replace(key: String, value: String) = apply { - remove(key) - put(key, value) - } - - fun replace(key: String, values: Iterable) = apply { - remove(key) - put(key, values) - } - - fun replaceAll(queryParams: Map>) = apply { - queryParams.forEach(::replace) - } - - fun replaceAll(queryParams: QueryParams) = apply { - queryParams.keys().forEach { replace(it, queryParams.values(it)) } - } - - fun remove(key: String) = apply { size -= map.remove(key).orEmpty().size } - - fun removeAll(keys: Set) = apply { keys.forEach(::remove) } - - fun clear() = apply { - map.clear() - size = 0 - } - - fun build() = - QueryParams(map.mapValues { (_, values) -> values.toImmutable() }.toImmutable(), size) - } - - override fun hashCode(): Int = map.hashCode() - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is QueryParams && map == other.map - } - - override fun toString(): String = "QueryParams{map=$map}" -} diff --git a/src/main/java/com/google/genai/interactions/core/http/RetryingHttpClient.kt b/src/main/java/com/google/genai/interactions/core/http/RetryingHttpClient.kt deleted file mode 100644 index d74eb4f9431..00000000000 --- a/src/main/java/com/google/genai/interactions/core/http/RetryingHttpClient.kt +++ /dev/null @@ -1,261 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.core.http - -import com.google.genai.interactions.core.DefaultSleeper -import com.google.genai.interactions.core.RequestOptions -import com.google.genai.interactions.core.Sleeper -import com.google.genai.interactions.core.checkRequired -import com.google.genai.interactions.errors.GeminiNextGenApiIoException -import com.google.genai.interactions.errors.GeminiNextGenApiRetryableException -import java.io.IOException -import java.time.Clock -import java.time.Duration -import java.time.OffsetDateTime -import java.time.format.DateTimeFormatter -import java.time.format.DateTimeParseException -import java.time.temporal.ChronoUnit -import java.util.UUID -import java.util.concurrent.CompletableFuture -import java.util.concurrent.ThreadLocalRandom -import java.util.concurrent.TimeUnit -import java.util.function.Function -import kotlin.math.min -import kotlin.math.pow - -class RetryingHttpClient -private constructor( - private val httpClient: HttpClient, - private val sleeper: Sleeper, - private val clock: Clock, - private val maxRetries: Int, - private val idempotencyHeader: String?, -) : HttpClient { - - override fun execute(request: HttpRequest, requestOptions: RequestOptions): HttpResponse { - var modifiedRequest = maybeAddIdempotencyHeader(request) - - var retries = 0 - - while (true) { - if (!isRetryable(modifiedRequest)) { - return httpClient.execute(modifiedRequest, requestOptions) - } - - val response = - try { - val response = httpClient.execute(modifiedRequest, requestOptions) - if (++retries > maxRetries || !shouldRetry(response)) { - return response - } - - response - } catch (throwable: Throwable) { - if (++retries > maxRetries || !shouldRetry(throwable)) { - throw throwable - } - - null - } - - val backoffDuration = getRetryBackoffDuration(retries, response) - // All responses must be closed, so close the failed one before retrying. - response?.close() - sleeper.sleep(backoffDuration) - } - } - - override fun executeAsync( - request: HttpRequest, - requestOptions: RequestOptions, - ): CompletableFuture { - val modifiedRequest = maybeAddIdempotencyHeader(request) - - var retries = 0 - - fun executeWithRetries( - request: HttpRequest, - requestOptions: RequestOptions, - ): CompletableFuture { - - val responseFuture = httpClient.executeAsync(request, requestOptions) - if (!isRetryable(request)) { - return responseFuture - } - - return responseFuture - .handleAsync( - fun( - response: HttpResponse?, - throwable: Throwable?, - ): CompletableFuture { - if (response != null) { - if (++retries > maxRetries || !shouldRetry(response)) { - return CompletableFuture.completedFuture(response) - } - } else { - if (++retries > maxRetries || !shouldRetry(throwable!!)) { - val failedFuture = CompletableFuture() - failedFuture.completeExceptionally(throwable) - return failedFuture - } - } - - val backoffDuration = getRetryBackoffDuration(retries, response) - // All responses must be closed, so close the failed one before retrying. - response?.close() - return sleeper.sleepAsync(backoffDuration).thenCompose { - executeWithRetries(request, requestOptions) - } - } - ) { - // Run in the same thread. - it.run() - } - .thenCompose(Function.identity()) - } - - return executeWithRetries(modifiedRequest, requestOptions) - } - - override fun close() { - httpClient.close() - sleeper.close() - } - - private fun isRetryable(request: HttpRequest): Boolean = - // Some requests, such as when a request body is being streamed, cannot be retried because - // the body data aren't available on subsequent attempts. - request.body?.repeatable() ?: true - - private fun idempotencyKey(): String = "stainless-java-retry-${UUID.randomUUID()}" - - private fun maybeAddIdempotencyHeader(request: HttpRequest): HttpRequest { - if (idempotencyHeader == null || request.headers.names().contains(idempotencyHeader)) { - return request - } - - return request - .toBuilder() - // Set a header to uniquely identify the request when retried. - .putHeader(idempotencyHeader, idempotencyKey()) - .build() - } - - private fun shouldRetry(response: HttpResponse): Boolean { - // Note: this is not a standard header - val shouldRetryHeader = response.headers().values("X-Should-Retry").getOrNull(0) - val statusCode = response.statusCode() - - return when { - // If the server explicitly says whether to retry, obey - shouldRetryHeader == "true" -> true - shouldRetryHeader == "false" -> false - - // Retry on request timeouts - statusCode == 408 -> true - // Retry on lock timeouts - statusCode == 409 -> true - // Retry on rate limits - statusCode == 429 -> true - // Retry internal errors - statusCode >= 500 -> true - else -> false - } - } - - private fun shouldRetry(throwable: Throwable): Boolean = - // Only retry known retryable exceptions, other exceptions are not intended to be retried. - throwable is IOException || - throwable is GeminiNextGenApiIoException || - throwable is GeminiNextGenApiRetryableException - - private fun getRetryBackoffDuration(retries: Int, response: HttpResponse?): Duration { - // About the Retry-After header: - // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After - response - ?.headers() - ?.let { headers -> - headers - .values("Retry-After-Ms") - .getOrNull(0) - ?.toFloatOrNull() - ?.times(TimeUnit.MILLISECONDS.toNanos(1)) - ?: headers.values("Retry-After").getOrNull(0)?.let { retryAfter -> - retryAfter.toFloatOrNull()?.times(TimeUnit.SECONDS.toNanos(1)) - ?: try { - ChronoUnit.NANOS.between( - OffsetDateTime.now(clock), - OffsetDateTime.parse( - retryAfter, - DateTimeFormatter.RFC_1123_DATE_TIME, - ), - ) - } catch (e: DateTimeParseException) { - null - } - } - } - ?.let { retryAfterNanos -> - // If the API asks us to wait a certain amount of time, do what it says. - return Duration.ofNanos(retryAfterNanos.toLong()) - } - - // Apply exponential backoff, but not more than the max. - val backoffSeconds = min(0.5 * 2.0.pow(retries - 1), 8.0) - - // Apply some jitter - val jitter = 1.0 - 0.25 * ThreadLocalRandom.current().nextDouble() - - return Duration.ofNanos((TimeUnit.SECONDS.toNanos(1) * backoffSeconds * jitter).toLong()) - } - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder internal constructor() { - - private var httpClient: HttpClient? = null - private var sleeper: Sleeper? = null - private var clock: Clock = Clock.systemUTC() - private var maxRetries: Int = 2 - private var idempotencyHeader: String? = null - - fun httpClient(httpClient: HttpClient) = apply { this.httpClient = httpClient } - - fun sleeper(sleeper: Sleeper) = apply { this.sleeper = sleeper } - - fun clock(clock: Clock) = apply { this.clock = clock } - - fun maxRetries(maxRetries: Int) = apply { this.maxRetries = maxRetries } - - fun idempotencyHeader(header: String) = apply { this.idempotencyHeader = header } - - fun build(): HttpClient = - RetryingHttpClient( - checkRequired("httpClient", httpClient), - sleeper ?: DefaultSleeper(), - clock, - maxRetries, - idempotencyHeader, - ) - } -} diff --git a/src/main/java/com/google/genai/interactions/core/http/SseMessage.kt b/src/main/java/com/google/genai/interactions/core/http/SseMessage.kt deleted file mode 100644 index 532387727bc..00000000000 --- a/src/main/java/com/google/genai/interactions/core/http/SseMessage.kt +++ /dev/null @@ -1,90 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.core.http - -import com.fasterxml.jackson.databind.json.JsonMapper -import com.fasterxml.jackson.module.kotlin.jacksonTypeRef -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.util.Objects - -internal class SseMessage -private constructor( - val jsonMapper: JsonMapper, - val event: String?, - val data: String, - val id: String?, - val retry: Int?, -) { - - companion object { - @JvmStatic fun builder() = Builder() - } - - class Builder internal constructor() { - - private var jsonMapper: JsonMapper? = null - private var event: String? = null - private var data: String = "" - private var id: String? = null - private var retry: Int? = null - - fun jsonMapper(jsonMapper: JsonMapper) = apply { this.jsonMapper = jsonMapper } - - fun event(event: String?) = apply { this.event = event } - - fun data(data: String) = apply { this.data = data } - - fun id(id: String?) = apply { this.id = id } - - fun retry(retry: Int?) = apply { this.retry = retry } - - fun build(): SseMessage = SseMessage(jsonMapper!!, event, data, id, retry) - } - - inline fun json(): T = - try { - jsonMapper.readerFor(jacksonTypeRef()).readValue(jsonNode) - } catch (e: Exception) { - throw GeminiNextGenApiInvalidDataException("Error reading response", e) - } - - private val jsonNode by lazy { - try { - jsonMapper.readTree(data) - } catch (e: Exception) { - throw GeminiNextGenApiInvalidDataException("Error reading response", e) - } - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is SseMessage && - event == other.event && - data == other.data && - id == other.id && - retry == other.retry - } - - override fun hashCode(): Int = Objects.hash(event, data, id, retry) - - override fun toString(): String = "SseMessage{event=$event, data=$data, id=$id, retry=$retry}" -} diff --git a/src/main/java/com/google/genai/interactions/core/http/StreamResponse.kt b/src/main/java/com/google/genai/interactions/core/http/StreamResponse.kt deleted file mode 100644 index 289b51a1ed2..00000000000 --- a/src/main/java/com/google/genai/interactions/core/http/StreamResponse.kt +++ /dev/null @@ -1,35 +0,0 @@ -/* -* 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 -* -* http://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.interactions.core.http - -import java.util.stream.Stream - -interface StreamResponse : AutoCloseable { - - fun stream(): Stream - - /** Overridden from [AutoCloseable] to not have a checked exception in its signature. */ - override fun close() -} - -@JvmSynthetic -internal fun StreamResponse.map(transform: (T) -> R): StreamResponse = - object : StreamResponse { - override fun stream(): Stream = this@map.stream().map(transform) - - override fun close() = this@map.close() - } diff --git a/src/main/java/com/google/genai/interactions/errors/BadRequestException.kt b/src/main/java/com/google/genai/interactions/errors/BadRequestException.kt deleted file mode 100644 index ecd55787518..00000000000 --- a/src/main/java/com/google/genai/interactions/errors/BadRequestException.kt +++ /dev/null @@ -1,96 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.errors - -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.core.checkRequired -import com.google.genai.interactions.core.http.Headers -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -class BadRequestException -private constructor(private val headers: Headers, private val body: JsonValue, cause: Throwable?) : - GeminiNextGenApiServiceException("400: $body", cause) { - - override fun statusCode(): Int = 400 - - override fun headers(): Headers = headers - - override fun body(): JsonValue = body - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [BadRequestException]. - * - * The following fields are required: - * ```java - * .headers() - * .body() - * ``` - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [BadRequestException]. */ - class Builder internal constructor() { - - private var headers: Headers? = null - private var body: JsonValue? = null - private var cause: Throwable? = null - - @JvmSynthetic - internal fun from(badRequestException: BadRequestException) = apply { - headers = badRequestException.headers - body = badRequestException.body - cause = badRequestException.cause - } - - fun headers(headers: Headers) = apply { this.headers = headers } - - fun body(body: JsonValue) = apply { this.body = body } - - fun cause(cause: Throwable?) = apply { this.cause = cause } - - /** Alias for calling [Builder.cause] with `cause.orElse(null)`. */ - fun cause(cause: Optional) = cause(cause.getOrNull()) - - /** - * Returns an immutable instance of [BadRequestException]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .headers() - * .body() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): BadRequestException = - BadRequestException( - checkRequired("headers", headers), - checkRequired("body", body), - cause, - ) - } -} diff --git a/src/main/java/com/google/genai/interactions/errors/GeminiNextGenApiException.kt b/src/main/java/com/google/genai/interactions/errors/GeminiNextGenApiException.kt deleted file mode 100644 index d2ea0795fa3..00000000000 --- a/src/main/java/com/google/genai/interactions/errors/GeminiNextGenApiException.kt +++ /dev/null @@ -1,21 +0,0 @@ -/* -* 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 -* -* http://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.interactions.errors - -open class GeminiNextGenApiException -@JvmOverloads -constructor(message: String? = null, cause: Throwable? = null) : RuntimeException(message, cause) diff --git a/src/main/java/com/google/genai/interactions/errors/GeminiNextGenApiInvalidDataException.kt b/src/main/java/com/google/genai/interactions/errors/GeminiNextGenApiInvalidDataException.kt deleted file mode 100644 index 35738bc4f30..00000000000 --- a/src/main/java/com/google/genai/interactions/errors/GeminiNextGenApiInvalidDataException.kt +++ /dev/null @@ -1,22 +0,0 @@ -/* -* 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 -* -* http://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.interactions.errors - -class GeminiNextGenApiInvalidDataException -@JvmOverloads -constructor(message: String? = null, cause: Throwable? = null) : - GeminiNextGenApiException(message, cause) diff --git a/src/main/java/com/google/genai/interactions/errors/GeminiNextGenApiIoException.kt b/src/main/java/com/google/genai/interactions/errors/GeminiNextGenApiIoException.kt deleted file mode 100644 index 4b9e9c833cc..00000000000 --- a/src/main/java/com/google/genai/interactions/errors/GeminiNextGenApiIoException.kt +++ /dev/null @@ -1,22 +0,0 @@ -/* -* 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 -* -* http://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.interactions.errors - -class GeminiNextGenApiIoException -@JvmOverloads -constructor(message: String? = null, cause: Throwable? = null) : - GeminiNextGenApiException(message, cause) diff --git a/src/main/java/com/google/genai/interactions/errors/GeminiNextGenApiRetryableException.kt b/src/main/java/com/google/genai/interactions/errors/GeminiNextGenApiRetryableException.kt deleted file mode 100644 index 8b28090cfcf..00000000000 --- a/src/main/java/com/google/genai/interactions/errors/GeminiNextGenApiRetryableException.kt +++ /dev/null @@ -1,31 +0,0 @@ -/* -* 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 -* -* http://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.interactions.errors - -/** - * Exception that indicates a transient error that can be retried. - * - * When this exception is thrown during an HTTP request, the SDK will automatically retry the - * request up to the maximum number of retries. - * - * @param message A descriptive error message - * @param cause The underlying cause of this exception, if any - */ -class GeminiNextGenApiRetryableException -@JvmOverloads -constructor(message: String? = null, cause: Throwable? = null) : - GeminiNextGenApiException(message, cause) diff --git a/src/main/java/com/google/genai/interactions/errors/GeminiNextGenApiServiceException.kt b/src/main/java/com/google/genai/interactions/errors/GeminiNextGenApiServiceException.kt deleted file mode 100644 index dcbb3e85cfe..00000000000 --- a/src/main/java/com/google/genai/interactions/errors/GeminiNextGenApiServiceException.kt +++ /dev/null @@ -1,33 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.errors - -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.core.http.Headers - -abstract class GeminiNextGenApiServiceException -protected constructor(message: String, cause: Throwable? = null) : - GeminiNextGenApiException(message, cause) { - - abstract fun statusCode(): Int - - abstract fun headers(): Headers - - abstract fun body(): JsonValue -} diff --git a/src/main/java/com/google/genai/interactions/errors/InternalServerException.kt b/src/main/java/com/google/genai/interactions/errors/InternalServerException.kt deleted file mode 100644 index 40df20c3bdc..00000000000 --- a/src/main/java/com/google/genai/interactions/errors/InternalServerException.kt +++ /dev/null @@ -1,107 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.errors - -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.core.checkRequired -import com.google.genai.interactions.core.http.Headers -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -class InternalServerException -private constructor( - private val statusCode: Int, - private val headers: Headers, - private val body: JsonValue, - cause: Throwable?, -) : GeminiNextGenApiServiceException("$statusCode: $body", cause) { - - override fun statusCode(): Int = statusCode - - override fun headers(): Headers = headers - - override fun body(): JsonValue = body - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [InternalServerException]. - * - * The following fields are required: - * ```java - * .statusCode() - * .headers() - * .body() - * ``` - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [InternalServerException]. */ - class Builder internal constructor() { - - private var statusCode: Int? = null - private var headers: Headers? = null - private var body: JsonValue? = null - private var cause: Throwable? = null - - @JvmSynthetic - internal fun from(internalServerException: InternalServerException) = apply { - statusCode = internalServerException.statusCode - headers = internalServerException.headers - body = internalServerException.body - cause = internalServerException.cause - } - - fun statusCode(statusCode: Int) = apply { this.statusCode = statusCode } - - fun headers(headers: Headers) = apply { this.headers = headers } - - fun body(body: JsonValue) = apply { this.body = body } - - fun cause(cause: Throwable?) = apply { this.cause = cause } - - /** Alias for calling [Builder.cause] with `cause.orElse(null)`. */ - fun cause(cause: Optional) = cause(cause.getOrNull()) - - /** - * Returns an immutable instance of [InternalServerException]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .statusCode() - * .headers() - * .body() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): InternalServerException = - InternalServerException( - checkRequired("statusCode", statusCode), - checkRequired("headers", headers), - checkRequired("body", body), - cause, - ) - } -} diff --git a/src/main/java/com/google/genai/interactions/errors/NotFoundException.kt b/src/main/java/com/google/genai/interactions/errors/NotFoundException.kt deleted file mode 100644 index 8047d4857a9..00000000000 --- a/src/main/java/com/google/genai/interactions/errors/NotFoundException.kt +++ /dev/null @@ -1,92 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.errors - -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.core.checkRequired -import com.google.genai.interactions.core.http.Headers -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -class NotFoundException -private constructor(private val headers: Headers, private val body: JsonValue, cause: Throwable?) : - GeminiNextGenApiServiceException("404: $body", cause) { - - override fun statusCode(): Int = 404 - - override fun headers(): Headers = headers - - override fun body(): JsonValue = body - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [NotFoundException]. - * - * The following fields are required: - * ```java - * .headers() - * .body() - * ``` - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [NotFoundException]. */ - class Builder internal constructor() { - - private var headers: Headers? = null - private var body: JsonValue? = null - private var cause: Throwable? = null - - @JvmSynthetic - internal fun from(notFoundException: NotFoundException) = apply { - headers = notFoundException.headers - body = notFoundException.body - cause = notFoundException.cause - } - - fun headers(headers: Headers) = apply { this.headers = headers } - - fun body(body: JsonValue) = apply { this.body = body } - - fun cause(cause: Throwable?) = apply { this.cause = cause } - - /** Alias for calling [Builder.cause] with `cause.orElse(null)`. */ - fun cause(cause: Optional) = cause(cause.getOrNull()) - - /** - * Returns an immutable instance of [NotFoundException]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .headers() - * .body() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): NotFoundException = - NotFoundException(checkRequired("headers", headers), checkRequired("body", body), cause) - } -} diff --git a/src/main/java/com/google/genai/interactions/errors/PermissionDeniedException.kt b/src/main/java/com/google/genai/interactions/errors/PermissionDeniedException.kt deleted file mode 100644 index 67ef0d5e632..00000000000 --- a/src/main/java/com/google/genai/interactions/errors/PermissionDeniedException.kt +++ /dev/null @@ -1,96 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.errors - -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.core.checkRequired -import com.google.genai.interactions.core.http.Headers -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -class PermissionDeniedException -private constructor(private val headers: Headers, private val body: JsonValue, cause: Throwable?) : - GeminiNextGenApiServiceException("403: $body", cause) { - - override fun statusCode(): Int = 403 - - override fun headers(): Headers = headers - - override fun body(): JsonValue = body - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [PermissionDeniedException]. - * - * The following fields are required: - * ```java - * .headers() - * .body() - * ``` - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [PermissionDeniedException]. */ - class Builder internal constructor() { - - private var headers: Headers? = null - private var body: JsonValue? = null - private var cause: Throwable? = null - - @JvmSynthetic - internal fun from(permissionDeniedException: PermissionDeniedException) = apply { - headers = permissionDeniedException.headers - body = permissionDeniedException.body - cause = permissionDeniedException.cause - } - - fun headers(headers: Headers) = apply { this.headers = headers } - - fun body(body: JsonValue) = apply { this.body = body } - - fun cause(cause: Throwable?) = apply { this.cause = cause } - - /** Alias for calling [Builder.cause] with `cause.orElse(null)`. */ - fun cause(cause: Optional) = cause(cause.getOrNull()) - - /** - * Returns an immutable instance of [PermissionDeniedException]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .headers() - * .body() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): PermissionDeniedException = - PermissionDeniedException( - checkRequired("headers", headers), - checkRequired("body", body), - cause, - ) - } -} diff --git a/src/main/java/com/google/genai/interactions/errors/RateLimitException.kt b/src/main/java/com/google/genai/interactions/errors/RateLimitException.kt deleted file mode 100644 index 650aecd136e..00000000000 --- a/src/main/java/com/google/genai/interactions/errors/RateLimitException.kt +++ /dev/null @@ -1,96 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.errors - -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.core.checkRequired -import com.google.genai.interactions.core.http.Headers -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -class RateLimitException -private constructor(private val headers: Headers, private val body: JsonValue, cause: Throwable?) : - GeminiNextGenApiServiceException("429: $body", cause) { - - override fun statusCode(): Int = 429 - - override fun headers(): Headers = headers - - override fun body(): JsonValue = body - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [RateLimitException]. - * - * The following fields are required: - * ```java - * .headers() - * .body() - * ``` - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [RateLimitException]. */ - class Builder internal constructor() { - - private var headers: Headers? = null - private var body: JsonValue? = null - private var cause: Throwable? = null - - @JvmSynthetic - internal fun from(rateLimitException: RateLimitException) = apply { - headers = rateLimitException.headers - body = rateLimitException.body - cause = rateLimitException.cause - } - - fun headers(headers: Headers) = apply { this.headers = headers } - - fun body(body: JsonValue) = apply { this.body = body } - - fun cause(cause: Throwable?) = apply { this.cause = cause } - - /** Alias for calling [Builder.cause] with `cause.orElse(null)`. */ - fun cause(cause: Optional) = cause(cause.getOrNull()) - - /** - * Returns an immutable instance of [RateLimitException]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .headers() - * .body() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): RateLimitException = - RateLimitException( - checkRequired("headers", headers), - checkRequired("body", body), - cause, - ) - } -} diff --git a/src/main/java/com/google/genai/interactions/errors/SseException.kt b/src/main/java/com/google/genai/interactions/errors/SseException.kt deleted file mode 100644 index f4d8cdfa722..00000000000 --- a/src/main/java/com/google/genai/interactions/errors/SseException.kt +++ /dev/null @@ -1,107 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.errors - -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.core.checkRequired -import com.google.genai.interactions.core.http.Headers -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -class SseException -private constructor( - private val statusCode: Int, - private val headers: Headers, - private val body: JsonValue, - cause: Throwable?, -) : GeminiNextGenApiServiceException("$statusCode: $body", cause) { - - override fun statusCode(): Int = statusCode - - override fun headers(): Headers = headers - - override fun body(): JsonValue = body - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [SseException]. - * - * The following fields are required: - * ```java - * .statusCode() - * .headers() - * .body() - * ``` - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [SseException]. */ - class Builder internal constructor() { - - private var statusCode: Int? = null - private var headers: Headers? = null - private var body: JsonValue? = null - private var cause: Throwable? = null - - @JvmSynthetic - internal fun from(sseException: SseException) = apply { - statusCode = sseException.statusCode - headers = sseException.headers - body = sseException.body - cause = sseException.cause - } - - fun statusCode(statusCode: Int) = apply { this.statusCode = statusCode } - - fun headers(headers: Headers) = apply { this.headers = headers } - - fun body(body: JsonValue) = apply { this.body = body } - - fun cause(cause: Throwable?) = apply { this.cause = cause } - - /** Alias for calling [Builder.cause] with `cause.orElse(null)`. */ - fun cause(cause: Optional) = cause(cause.getOrNull()) - - /** - * Returns an immutable instance of [SseException]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .statusCode() - * .headers() - * .body() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): SseException = - SseException( - checkRequired("statusCode", statusCode), - checkRequired("headers", headers), - checkRequired("body", body), - cause, - ) - } -} diff --git a/src/main/java/com/google/genai/interactions/errors/UnauthorizedException.kt b/src/main/java/com/google/genai/interactions/errors/UnauthorizedException.kt deleted file mode 100644 index 4c16018e628..00000000000 --- a/src/main/java/com/google/genai/interactions/errors/UnauthorizedException.kt +++ /dev/null @@ -1,96 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.errors - -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.core.checkRequired -import com.google.genai.interactions.core.http.Headers -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -class UnauthorizedException -private constructor(private val headers: Headers, private val body: JsonValue, cause: Throwable?) : - GeminiNextGenApiServiceException("401: $body", cause) { - - override fun statusCode(): Int = 401 - - override fun headers(): Headers = headers - - override fun body(): JsonValue = body - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [UnauthorizedException]. - * - * The following fields are required: - * ```java - * .headers() - * .body() - * ``` - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [UnauthorizedException]. */ - class Builder internal constructor() { - - private var headers: Headers? = null - private var body: JsonValue? = null - private var cause: Throwable? = null - - @JvmSynthetic - internal fun from(unauthorizedException: UnauthorizedException) = apply { - headers = unauthorizedException.headers - body = unauthorizedException.body - cause = unauthorizedException.cause - } - - fun headers(headers: Headers) = apply { this.headers = headers } - - fun body(body: JsonValue) = apply { this.body = body } - - fun cause(cause: Throwable?) = apply { this.cause = cause } - - /** Alias for calling [Builder.cause] with `cause.orElse(null)`. */ - fun cause(cause: Optional) = cause(cause.getOrNull()) - - /** - * Returns an immutable instance of [UnauthorizedException]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .headers() - * .body() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): UnauthorizedException = - UnauthorizedException( - checkRequired("headers", headers), - checkRequired("body", body), - cause, - ) - } -} diff --git a/src/main/java/com/google/genai/interactions/errors/UnexpectedStatusCodeException.kt b/src/main/java/com/google/genai/interactions/errors/UnexpectedStatusCodeException.kt deleted file mode 100644 index 1ff6a718a9e..00000000000 --- a/src/main/java/com/google/genai/interactions/errors/UnexpectedStatusCodeException.kt +++ /dev/null @@ -1,108 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.errors - -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.core.checkRequired -import com.google.genai.interactions.core.http.Headers -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -class UnexpectedStatusCodeException -private constructor( - private val statusCode: Int, - private val headers: Headers, - private val body: JsonValue, - cause: Throwable?, -) : GeminiNextGenApiServiceException("$statusCode: $body", cause) { - - override fun statusCode(): Int = statusCode - - override fun headers(): Headers = headers - - override fun body(): JsonValue = body - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of - * [UnexpectedStatusCodeException]. - * - * The following fields are required: - * ```java - * .statusCode() - * .headers() - * .body() - * ``` - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [UnexpectedStatusCodeException]. */ - class Builder internal constructor() { - - private var statusCode: Int? = null - private var headers: Headers? = null - private var body: JsonValue? = null - private var cause: Throwable? = null - - @JvmSynthetic - internal fun from(unexpectedStatusCodeException: UnexpectedStatusCodeException) = apply { - statusCode = unexpectedStatusCodeException.statusCode - headers = unexpectedStatusCodeException.headers - body = unexpectedStatusCodeException.body - cause = unexpectedStatusCodeException.cause - } - - fun statusCode(statusCode: Int) = apply { this.statusCode = statusCode } - - fun headers(headers: Headers) = apply { this.headers = headers } - - fun body(body: JsonValue) = apply { this.body = body } - - fun cause(cause: Throwable?) = apply { this.cause = cause } - - /** Alias for calling [Builder.cause] with `cause.orElse(null)`. */ - fun cause(cause: Optional) = cause(cause.getOrNull()) - - /** - * Returns an immutable instance of [UnexpectedStatusCodeException]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .statusCode() - * .headers() - * .body() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): UnexpectedStatusCodeException = - UnexpectedStatusCodeException( - checkRequired("statusCode", statusCode), - checkRequired("headers", headers), - checkRequired("body", body), - cause, - ) - } -} diff --git a/src/main/java/com/google/genai/interactions/errors/UnprocessableEntityException.kt b/src/main/java/com/google/genai/interactions/errors/UnprocessableEntityException.kt deleted file mode 100644 index b6eab21304b..00000000000 --- a/src/main/java/com/google/genai/interactions/errors/UnprocessableEntityException.kt +++ /dev/null @@ -1,96 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.errors - -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.core.checkRequired -import com.google.genai.interactions.core.http.Headers -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -class UnprocessableEntityException -private constructor(private val headers: Headers, private val body: JsonValue, cause: Throwable?) : - GeminiNextGenApiServiceException("422: $body", cause) { - - override fun statusCode(): Int = 422 - - override fun headers(): Headers = headers - - override fun body(): JsonValue = body - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [UnprocessableEntityException]. - * - * The following fields are required: - * ```java - * .headers() - * .body() - * ``` - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [UnprocessableEntityException]. */ - class Builder internal constructor() { - - private var headers: Headers? = null - private var body: JsonValue? = null - private var cause: Throwable? = null - - @JvmSynthetic - internal fun from(unprocessableEntityException: UnprocessableEntityException) = apply { - headers = unprocessableEntityException.headers - body = unprocessableEntityException.body - cause = unprocessableEntityException.cause - } - - fun headers(headers: Headers) = apply { this.headers = headers } - - fun body(body: JsonValue) = apply { this.body = body } - - fun cause(cause: Throwable?) = apply { this.cause = cause } - - /** Alias for calling [Builder.cause] with `cause.orElse(null)`. */ - fun cause(cause: Optional) = cause(cause.getOrNull()) - - /** - * Returns an immutable instance of [UnprocessableEntityException]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .headers() - * .body() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): UnprocessableEntityException = - UnprocessableEntityException( - checkRequired("headers", headers), - checkRequired("body", body), - cause, - ) - } -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/AllowedTools.kt b/src/main/java/com/google/genai/interactions/models/interactions/AllowedTools.kt deleted file mode 100644 index 1f252179d5c..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/AllowedTools.kt +++ /dev/null @@ -1,228 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import com.google.genai.interactions.core.ExcludeMissing -import com.google.genai.interactions.core.JsonField -import com.google.genai.interactions.core.JsonMissing -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.core.checkKnown -import com.google.genai.interactions.core.toImmutable -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.util.Collections -import java.util.Objects -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -/** The configuration for allowed tools. */ -class AllowedTools -@JsonCreator(mode = JsonCreator.Mode.DISABLED) -private constructor( - private val mode: JsonField, - private val tools: JsonField>, - private val additionalProperties: MutableMap, -) { - - @JsonCreator - private constructor( - @JsonProperty("mode") @ExcludeMissing mode: JsonField = JsonMissing.of(), - @JsonProperty("tools") @ExcludeMissing tools: JsonField> = JsonMissing.of(), - ) : this(mode, tools, mutableMapOf()) - - /** - * The mode of the tool choice. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun mode(): Optional = mode.getOptional("mode") - - /** - * The names of the allowed tools. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun tools(): Optional> = tools.getOptional("tools") - - /** - * Returns the raw JSON value of [mode]. - * - * Unlike [mode], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("mode") @ExcludeMissing fun _mode(): JsonField = mode - - /** - * Returns the raw JSON value of [tools]. - * - * Unlike [tools], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("tools") @ExcludeMissing fun _tools(): JsonField> = tools - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [AllowedTools]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [AllowedTools]. */ - class Builder internal constructor() { - - private var mode: JsonField = JsonMissing.of() - private var tools: JsonField>? = null - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(allowedTools: AllowedTools) = apply { - mode = allowedTools.mode - tools = allowedTools.tools.map { it.toMutableList() } - additionalProperties = allowedTools.additionalProperties.toMutableMap() - } - - /** The mode of the tool choice. */ - fun mode(mode: ToolChoiceType) = mode(JsonField.of(mode)) - - /** - * Sets [Builder.mode] to an arbitrary JSON value. - * - * You should usually call [Builder.mode] with a well-typed [ToolChoiceType] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun mode(mode: JsonField) = apply { this.mode = mode } - - /** The names of the allowed tools. */ - fun tools(tools: List) = tools(JsonField.of(tools)) - - /** - * Sets [Builder.tools] to an arbitrary JSON value. - * - * You should usually call [Builder.tools] with a well-typed `List` value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun tools(tools: JsonField>) = apply { - this.tools = tools.map { it.toMutableList() } - } - - /** - * Adds a single [String] to [tools]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addTool(tool: String) = apply { - tools = - (tools ?: JsonField.of(mutableListOf())).also { checkKnown("tools", it).add(tool) } - } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [AllowedTools]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): AllowedTools = - AllowedTools( - mode, - (tools ?: JsonMissing.of()).map { it.toImmutable() }, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): AllowedTools = apply { - if (validated) { - return@apply - } - - mode().ifPresent { it.validate() } - tools() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - (mode.asKnown().getOrNull()?.validity() ?: 0) + (tools.asKnown().getOrNull()?.size ?: 0) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is AllowedTools && - mode == other.mode && - tools == other.tools && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { Objects.hash(mode, tools, additionalProperties) } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "AllowedTools{mode=$mode, tools=$tools, additionalProperties=$additionalProperties}" -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/Annotation.kt b/src/main/java/com/google/genai/interactions/models/interactions/Annotation.kt deleted file mode 100644 index 63870942e7d..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/Annotation.kt +++ /dev/null @@ -1,243 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.core.JsonGenerator -import com.fasterxml.jackson.core.ObjectCodec -import com.fasterxml.jackson.databind.JsonNode -import com.fasterxml.jackson.databind.SerializerProvider -import com.fasterxml.jackson.databind.annotation.JsonDeserialize -import com.fasterxml.jackson.databind.annotation.JsonSerialize -import com.fasterxml.jackson.module.kotlin.jacksonTypeRef -import com.google.genai.interactions.core.BaseDeserializer -import com.google.genai.interactions.core.BaseSerializer -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.core.getOrThrow -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.util.Objects -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -/** Citation information for model-generated content. */ -@JsonDeserialize(using = Annotation.Deserializer::class) -@JsonSerialize(using = Annotation.Serializer::class) -class Annotation -private constructor( - private val urlCitation: UrlCitation? = null, - private val fileCitation: FileCitation? = null, - private val placeCitation: PlaceCitation? = null, - private val _json: JsonValue? = null, -) { - - /** A URL citation annotation. */ - fun urlCitation(): Optional = Optional.ofNullable(urlCitation) - - /** A file citation annotation. */ - fun fileCitation(): Optional = Optional.ofNullable(fileCitation) - - /** A place citation annotation. */ - fun placeCitation(): Optional = Optional.ofNullable(placeCitation) - - fun isUrlCitation(): Boolean = urlCitation != null - - fun isFileCitation(): Boolean = fileCitation != null - - fun isPlaceCitation(): Boolean = placeCitation != null - - /** A URL citation annotation. */ - fun asUrlCitation(): UrlCitation = urlCitation.getOrThrow("urlCitation") - - /** A file citation annotation. */ - fun asFileCitation(): FileCitation = fileCitation.getOrThrow("fileCitation") - - /** A place citation annotation. */ - fun asPlaceCitation(): PlaceCitation = placeCitation.getOrThrow("placeCitation") - - fun _json(): Optional = Optional.ofNullable(_json) - - fun accept(visitor: Visitor): T = - when { - urlCitation != null -> visitor.visitUrlCitation(urlCitation) - fileCitation != null -> visitor.visitFileCitation(fileCitation) - placeCitation != null -> visitor.visitPlaceCitation(placeCitation) - else -> visitor.unknown(_json) - } - - private var validated: Boolean = false - - fun validate(): Annotation = apply { - if (validated) { - return@apply - } - - accept( - object : Visitor { - override fun visitUrlCitation(urlCitation: UrlCitation) { - urlCitation.validate() - } - - override fun visitFileCitation(fileCitation: FileCitation) { - fileCitation.validate() - } - - override fun visitPlaceCitation(placeCitation: PlaceCitation) { - placeCitation.validate() - } - } - ) - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - accept( - object : Visitor { - override fun visitUrlCitation(urlCitation: UrlCitation) = urlCitation.validity() - - override fun visitFileCitation(fileCitation: FileCitation) = fileCitation.validity() - - override fun visitPlaceCitation(placeCitation: PlaceCitation) = - placeCitation.validity() - - override fun unknown(json: JsonValue?) = 0 - } - ) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Annotation && - urlCitation == other.urlCitation && - fileCitation == other.fileCitation && - placeCitation == other.placeCitation - } - - override fun hashCode(): Int = Objects.hash(urlCitation, fileCitation, placeCitation) - - override fun toString(): String = - when { - urlCitation != null -> "Annotation{urlCitation=$urlCitation}" - fileCitation != null -> "Annotation{fileCitation=$fileCitation}" - placeCitation != null -> "Annotation{placeCitation=$placeCitation}" - _json != null -> "Annotation{_unknown=$_json}" - else -> throw IllegalStateException("Invalid Annotation") - } - - companion object { - - /** A URL citation annotation. */ - @JvmStatic - fun ofUrlCitation(urlCitation: UrlCitation) = Annotation(urlCitation = urlCitation) - - /** A file citation annotation. */ - @JvmStatic - fun ofFileCitation(fileCitation: FileCitation) = Annotation(fileCitation = fileCitation) - - /** A place citation annotation. */ - @JvmStatic - fun ofPlaceCitation(placeCitation: PlaceCitation) = - Annotation(placeCitation = placeCitation) - } - - /** An interface that defines how to map each variant of [Annotation] to a value of type [T]. */ - interface Visitor { - - /** A URL citation annotation. */ - fun visitUrlCitation(urlCitation: UrlCitation): T - - /** A file citation annotation. */ - fun visitFileCitation(fileCitation: FileCitation): T - - /** A place citation annotation. */ - fun visitPlaceCitation(placeCitation: PlaceCitation): T - - /** - * Maps an unknown variant of [Annotation] to a value of type [T]. - * - * An instance of [Annotation] can contain an unknown variant if it was deserialized from - * data that doesn't match any known variant. For example, if the SDK is on an older version - * than the API, then the API may respond with new variants that the SDK is unaware of. - * - * @throws GeminiNextGenApiInvalidDataException in the default implementation. - */ - fun unknown(json: JsonValue?): T { - throw GeminiNextGenApiInvalidDataException("Unknown Annotation: $json") - } - } - - internal class Deserializer : BaseDeserializer(Annotation::class) { - - override fun ObjectCodec.deserialize(node: JsonNode): Annotation { - val json = JsonValue.fromJsonNode(node) - val type = json.asObject().getOrNull()?.get("type")?.asString()?.getOrNull() - - when (type) { - "url_citation" -> { - return tryDeserialize(node, jacksonTypeRef())?.let { - Annotation(urlCitation = it, _json = json) - } ?: Annotation(_json = json) - } - "file_citation" -> { - return tryDeserialize(node, jacksonTypeRef())?.let { - Annotation(fileCitation = it, _json = json) - } ?: Annotation(_json = json) - } - "place_citation" -> { - return tryDeserialize(node, jacksonTypeRef())?.let { - Annotation(placeCitation = it, _json = json) - } ?: Annotation(_json = json) - } - } - - return Annotation(_json = json) - } - } - - internal class Serializer : BaseSerializer(Annotation::class) { - - override fun serialize( - value: Annotation, - generator: JsonGenerator, - provider: SerializerProvider, - ) { - when { - value.urlCitation != null -> generator.writeObject(value.urlCitation) - value.fileCitation != null -> generator.writeObject(value.fileCitation) - value.placeCitation != null -> generator.writeObject(value.placeCitation) - value._json != null -> generator.writeObject(value._json) - else -> throw IllegalStateException("Invalid Annotation") - } - } - } -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/ArgumentsDelta.kt b/src/main/java/com/google/genai/interactions/models/interactions/ArgumentsDelta.kt deleted file mode 100644 index 0f909bc207e..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/ArgumentsDelta.kt +++ /dev/null @@ -1,208 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import com.google.genai.interactions.core.ExcludeMissing -import com.google.genai.interactions.core.JsonField -import com.google.genai.interactions.core.JsonMissing -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.util.Collections -import java.util.Objects -import java.util.Optional - -class ArgumentsDelta -@JsonCreator(mode = JsonCreator.Mode.DISABLED) -private constructor( - private val type: JsonValue, - private val arguments: JsonField, - private val additionalProperties: MutableMap, -) { - - @JsonCreator - private constructor( - @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), - @JsonProperty("arguments") @ExcludeMissing arguments: JsonField = JsonMissing.of(), - ) : this(type, arguments, mutableMapOf()) - - /** - * Expected to always return the following: - * ```java - * JsonValue.from("arguments_delta") - * ``` - * - * However, this method can be useful for debugging and logging (e.g. if the server responded - * with an unexpected value). - */ - @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type - - /** - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun arguments(): Optional = arguments.getOptional("arguments") - - /** - * Returns the raw JSON value of [arguments]. - * - * Unlike [arguments], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("arguments") @ExcludeMissing fun _arguments(): JsonField = arguments - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [ArgumentsDelta]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [ArgumentsDelta]. */ - class Builder internal constructor() { - - private var type: JsonValue = JsonValue.from("arguments_delta") - private var arguments: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(argumentsDelta: ArgumentsDelta) = apply { - type = argumentsDelta.type - arguments = argumentsDelta.arguments - additionalProperties = argumentsDelta.additionalProperties.toMutableMap() - } - - /** - * Sets the field to an arbitrary JSON value. - * - * It is usually unnecessary to call this method because the field defaults to the - * following: - * ```java - * JsonValue.from("arguments_delta") - * ``` - * - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun type(type: JsonValue) = apply { this.type = type } - - fun arguments(arguments: String) = arguments(JsonField.of(arguments)) - - /** - * Sets [Builder.arguments] to an arbitrary JSON value. - * - * You should usually call [Builder.arguments] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun arguments(arguments: JsonField) = apply { this.arguments = arguments } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [ArgumentsDelta]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): ArgumentsDelta = - ArgumentsDelta(type, arguments, additionalProperties.toMutableMap()) - } - - private var validated: Boolean = false - - fun validate(): ArgumentsDelta = apply { - if (validated) { - return@apply - } - - _type().let { - if (it != JsonValue.from("arguments_delta")) { - throw GeminiNextGenApiInvalidDataException("'type' is invalid, received $it") - } - } - arguments() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - type.let { if (it == JsonValue.from("arguments_delta")) 1 else 0 } + - (if (arguments.asKnown().isPresent) 1 else 0) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is ArgumentsDelta && - type == other.type && - arguments == other.arguments && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { Objects.hash(type, arguments, additionalProperties) } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "ArgumentsDelta{type=$type, arguments=$arguments, additionalProperties=$additionalProperties}" -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/AudioContent.kt b/src/main/java/com/google/genai/interactions/models/interactions/AudioContent.kt deleted file mode 100644 index fc4b18d5be0..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/AudioContent.kt +++ /dev/null @@ -1,544 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import com.google.genai.interactions.core.Enum -import com.google.genai.interactions.core.ExcludeMissing -import com.google.genai.interactions.core.JsonField -import com.google.genai.interactions.core.JsonMissing -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.util.Collections -import java.util.Objects -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -/** An audio content block. */ -class AudioContent -@JsonCreator(mode = JsonCreator.Mode.DISABLED) -private constructor( - private val type: JsonValue, - private val channels: JsonField, - private val data: JsonField, - private val mimeType: JsonField, - private val sampleRate: JsonField, - private val uri: JsonField, - private val additionalProperties: MutableMap, -) { - - @JsonCreator - private constructor( - @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), - @JsonProperty("channels") @ExcludeMissing channels: JsonField = JsonMissing.of(), - @JsonProperty("data") @ExcludeMissing data: JsonField = JsonMissing.of(), - @JsonProperty("mime_type") @ExcludeMissing mimeType: JsonField = JsonMissing.of(), - @JsonProperty("sample_rate") @ExcludeMissing sampleRate: JsonField = JsonMissing.of(), - @JsonProperty("uri") @ExcludeMissing uri: JsonField = JsonMissing.of(), - ) : this(type, channels, data, mimeType, sampleRate, uri, mutableMapOf()) - - /** - * Expected to always return the following: - * ```java - * JsonValue.from("audio") - * ``` - * - * However, this method can be useful for debugging and logging (e.g. if the server responded - * with an unexpected value). - */ - @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type - - /** - * The number of audio channels. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun channels(): Optional = channels.getOptional("channels") - - /** - * The audio content. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun data(): Optional = data.getOptional("data") - - /** - * The mime type of the audio. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun mimeType(): Optional = mimeType.getOptional("mime_type") - - /** - * The sample rate of the audio. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun sampleRate(): Optional = sampleRate.getOptional("sample_rate") - - /** - * The URI of the audio. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun uri(): Optional = uri.getOptional("uri") - - /** - * Returns the raw JSON value of [channels]. - * - * Unlike [channels], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("channels") @ExcludeMissing fun _channels(): JsonField = channels - - /** - * Returns the raw JSON value of [data]. - * - * Unlike [data], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("data") @ExcludeMissing fun _data(): JsonField = data - - /** - * Returns the raw JSON value of [mimeType]. - * - * Unlike [mimeType], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("mime_type") @ExcludeMissing fun _mimeType(): JsonField = mimeType - - /** - * Returns the raw JSON value of [sampleRate]. - * - * Unlike [sampleRate], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("sample_rate") @ExcludeMissing fun _sampleRate(): JsonField = sampleRate - - /** - * Returns the raw JSON value of [uri]. - * - * Unlike [uri], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("uri") @ExcludeMissing fun _uri(): JsonField = uri - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [AudioContent]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [AudioContent]. */ - class Builder internal constructor() { - - private var type: JsonValue = JsonValue.from("audio") - private var channels: JsonField = JsonMissing.of() - private var data: JsonField = JsonMissing.of() - private var mimeType: JsonField = JsonMissing.of() - private var sampleRate: JsonField = JsonMissing.of() - private var uri: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(audioContent: AudioContent) = apply { - type = audioContent.type - channels = audioContent.channels - data = audioContent.data - mimeType = audioContent.mimeType - sampleRate = audioContent.sampleRate - uri = audioContent.uri - additionalProperties = audioContent.additionalProperties.toMutableMap() - } - - /** - * Sets the field to an arbitrary JSON value. - * - * It is usually unnecessary to call this method because the field defaults to the - * following: - * ```java - * JsonValue.from("audio") - * ``` - * - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun type(type: JsonValue) = apply { this.type = type } - - /** The number of audio channels. */ - fun channels(channels: Int) = channels(JsonField.of(channels)) - - /** - * Sets [Builder.channels] to an arbitrary JSON value. - * - * You should usually call [Builder.channels] with a well-typed [Int] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun channels(channels: JsonField) = apply { this.channels = channels } - - /** The audio content. */ - fun data(data: String) = data(JsonField.of(data)) - - /** - * Sets [Builder.data] to an arbitrary JSON value. - * - * You should usually call [Builder.data] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun data(data: JsonField) = apply { this.data = data } - - /** The mime type of the audio. */ - fun mimeType(mimeType: MimeType) = mimeType(JsonField.of(mimeType)) - - /** - * Sets [Builder.mimeType] to an arbitrary JSON value. - * - * You should usually call [Builder.mimeType] with a well-typed [MimeType] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun mimeType(mimeType: JsonField) = apply { this.mimeType = mimeType } - - /** The sample rate of the audio. */ - fun sampleRate(sampleRate: Int) = sampleRate(JsonField.of(sampleRate)) - - /** - * Sets [Builder.sampleRate] to an arbitrary JSON value. - * - * You should usually call [Builder.sampleRate] with a well-typed [Int] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun sampleRate(sampleRate: JsonField) = apply { this.sampleRate = sampleRate } - - /** The URI of the audio. */ - fun uri(uri: String) = uri(JsonField.of(uri)) - - /** - * Sets [Builder.uri] to an arbitrary JSON value. - * - * You should usually call [Builder.uri] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun uri(uri: JsonField) = apply { this.uri = uri } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [AudioContent]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): AudioContent = - AudioContent( - type, - channels, - data, - mimeType, - sampleRate, - uri, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): AudioContent = apply { - if (validated) { - return@apply - } - - _type().let { - if (it != JsonValue.from("audio")) { - throw GeminiNextGenApiInvalidDataException("'type' is invalid, received $it") - } - } - channels() - data() - mimeType().ifPresent { it.validate() } - sampleRate() - uri() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - type.let { if (it == JsonValue.from("audio")) 1 else 0 } + - (if (channels.asKnown().isPresent) 1 else 0) + - (if (data.asKnown().isPresent) 1 else 0) + - (mimeType.asKnown().getOrNull()?.validity() ?: 0) + - (if (sampleRate.asKnown().isPresent) 1 else 0) + - (if (uri.asKnown().isPresent) 1 else 0) - - /** The mime type of the audio. */ - class MimeType @JsonCreator private constructor(private val value: JsonField) : Enum { - - /** - * Returns this class instance's raw value. - * - * This is usually only useful if this instance was deserialized from data that doesn't - * match any known member, and you want to know that value. For example, if the SDK is on an - * older version than the API, then the API may respond with new members that the SDK is - * unaware of. - */ - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - companion object { - - @JvmField val AUDIO_WAV = of("audio/wav") - - @JvmField val AUDIO_MP3 = of("audio/mp3") - - @JvmField val AUDIO_AIFF = of("audio/aiff") - - @JvmField val AUDIO_AAC = of("audio/aac") - - @JvmField val AUDIO_OGG = of("audio/ogg") - - @JvmField val AUDIO_FLAC = of("audio/flac") - - @JvmField val AUDIO_MPEG = of("audio/mpeg") - - @JvmField val AUDIO_M4A = of("audio/m4a") - - @JvmField val AUDIO_L16 = of("audio/l16") - - @JvmField val AUDIO_OPUS = of("audio/opus") - - @JvmField val AUDIO_ALAW = of("audio/alaw") - - @JvmField val AUDIO_MULAW = of("audio/mulaw") - - @JvmStatic fun of(value: String) = MimeType(JsonField.of(value)) - } - - /** An enum containing [MimeType]'s known values. */ - enum class Known { - AUDIO_WAV, - AUDIO_MP3, - AUDIO_AIFF, - AUDIO_AAC, - AUDIO_OGG, - AUDIO_FLAC, - AUDIO_MPEG, - AUDIO_M4A, - AUDIO_L16, - AUDIO_OPUS, - AUDIO_ALAW, - AUDIO_MULAW, - } - - /** - * An enum containing [MimeType]'s known values, as well as an [_UNKNOWN] member. - * - * An instance of [MimeType] can contain an unknown value in a couple of cases: - * - It was deserialized from data that doesn't match any known member. For example, if the - * SDK is on an older version than the API, then the API may respond with new members that - * the SDK is unaware of. - * - It was constructed with an arbitrary value using the [of] method. - */ - enum class Value { - AUDIO_WAV, - AUDIO_MP3, - AUDIO_AIFF, - AUDIO_AAC, - AUDIO_OGG, - AUDIO_FLAC, - AUDIO_MPEG, - AUDIO_M4A, - AUDIO_L16, - AUDIO_OPUS, - AUDIO_ALAW, - AUDIO_MULAW, - /** An enum member indicating that [MimeType] was instantiated with an unknown value. */ - _UNKNOWN, - } - - /** - * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] - * if the class was instantiated with an unknown value. - * - * Use the [known] method instead if you're certain the value is always known or if you want - * to throw for the unknown case. - */ - fun value(): Value = - when (this) { - AUDIO_WAV -> Value.AUDIO_WAV - AUDIO_MP3 -> Value.AUDIO_MP3 - AUDIO_AIFF -> Value.AUDIO_AIFF - AUDIO_AAC -> Value.AUDIO_AAC - AUDIO_OGG -> Value.AUDIO_OGG - AUDIO_FLAC -> Value.AUDIO_FLAC - AUDIO_MPEG -> Value.AUDIO_MPEG - AUDIO_M4A -> Value.AUDIO_M4A - AUDIO_L16 -> Value.AUDIO_L16 - AUDIO_OPUS -> Value.AUDIO_OPUS - AUDIO_ALAW -> Value.AUDIO_ALAW - AUDIO_MULAW -> Value.AUDIO_MULAW - else -> Value._UNKNOWN - } - - /** - * Returns an enum member corresponding to this class instance's value. - * - * Use the [value] method instead if you're uncertain the value is always known and don't - * want to throw for the unknown case. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value is a not a - * known member. - */ - fun known(): Known = - when (this) { - AUDIO_WAV -> Known.AUDIO_WAV - AUDIO_MP3 -> Known.AUDIO_MP3 - AUDIO_AIFF -> Known.AUDIO_AIFF - AUDIO_AAC -> Known.AUDIO_AAC - AUDIO_OGG -> Known.AUDIO_OGG - AUDIO_FLAC -> Known.AUDIO_FLAC - AUDIO_MPEG -> Known.AUDIO_MPEG - AUDIO_M4A -> Known.AUDIO_M4A - AUDIO_L16 -> Known.AUDIO_L16 - AUDIO_OPUS -> Known.AUDIO_OPUS - AUDIO_ALAW -> Known.AUDIO_ALAW - AUDIO_MULAW -> Known.AUDIO_MULAW - else -> throw GeminiNextGenApiInvalidDataException("Unknown MimeType: $value") - } - - /** - * Returns this class instance's primitive wire representation. - * - * This differs from the [toString] method because that method is primarily for debugging - * and generally doesn't throw. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value does not have - * the expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - GeminiNextGenApiInvalidDataException("Value is not a String") - } - - private var validated: Boolean = false - - fun validate(): MimeType = apply { - if (validated) { - return@apply - } - - known() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is MimeType && value == other.value - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is AudioContent && - type == other.type && - channels == other.channels && - data == other.data && - mimeType == other.mimeType && - sampleRate == other.sampleRate && - uri == other.uri && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { - Objects.hash(type, channels, data, mimeType, sampleRate, uri, additionalProperties) - } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "AudioContent{type=$type, channels=$channels, data=$data, mimeType=$mimeType, sampleRate=$sampleRate, uri=$uri, additionalProperties=$additionalProperties}" -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/AudioResponseFormat.kt b/src/main/java/com/google/genai/interactions/models/interactions/AudioResponseFormat.kt deleted file mode 100644 index e9d320b33df..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/AudioResponseFormat.kt +++ /dev/null @@ -1,605 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import com.google.genai.interactions.core.Enum -import com.google.genai.interactions.core.ExcludeMissing -import com.google.genai.interactions.core.JsonField -import com.google.genai.interactions.core.JsonMissing -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.util.Collections -import java.util.Objects -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -/** Configuration for audio output format. */ -class AudioResponseFormat -@JsonCreator(mode = JsonCreator.Mode.DISABLED) -private constructor( - private val type: JsonValue, - private val bitRate: JsonField, - private val delivery: JsonField, - private val mimeType: JsonField, - private val sampleRate: JsonField, - private val additionalProperties: MutableMap, -) { - - @JsonCreator - private constructor( - @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), - @JsonProperty("bit_rate") @ExcludeMissing bitRate: JsonField = JsonMissing.of(), - @JsonProperty("delivery") @ExcludeMissing delivery: JsonField = JsonMissing.of(), - @JsonProperty("mime_type") @ExcludeMissing mimeType: JsonField = JsonMissing.of(), - @JsonProperty("sample_rate") @ExcludeMissing sampleRate: JsonField = JsonMissing.of(), - ) : this(type, bitRate, delivery, mimeType, sampleRate, mutableMapOf()) - - /** - * Expected to always return the following: - * ```java - * JsonValue.from("audio") - * ``` - * - * However, this method can be useful for debugging and logging (e.g. if the server responded - * with an unexpected value). - */ - @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type - - /** - * Bit rate in bits per second (bps). Only applicable for compressed formats (MP3, Opus). - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun bitRate(): Optional = bitRate.getOptional("bit_rate") - - /** - * The delivery mode for the audio output. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun delivery(): Optional = delivery.getOptional("delivery") - - /** - * The MIME type of the audio output. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun mimeType(): Optional = mimeType.getOptional("mime_type") - - /** - * Sample rate in Hz. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun sampleRate(): Optional = sampleRate.getOptional("sample_rate") - - /** - * Returns the raw JSON value of [bitRate]. - * - * Unlike [bitRate], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("bit_rate") @ExcludeMissing fun _bitRate(): JsonField = bitRate - - /** - * Returns the raw JSON value of [delivery]. - * - * Unlike [delivery], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("delivery") @ExcludeMissing fun _delivery(): JsonField = delivery - - /** - * Returns the raw JSON value of [mimeType]. - * - * Unlike [mimeType], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("mime_type") @ExcludeMissing fun _mimeType(): JsonField = mimeType - - /** - * Returns the raw JSON value of [sampleRate]. - * - * Unlike [sampleRate], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("sample_rate") @ExcludeMissing fun _sampleRate(): JsonField = sampleRate - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [AudioResponseFormat]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [AudioResponseFormat]. */ - class Builder internal constructor() { - - private var type: JsonValue = JsonValue.from("audio") - private var bitRate: JsonField = JsonMissing.of() - private var delivery: JsonField = JsonMissing.of() - private var mimeType: JsonField = JsonMissing.of() - private var sampleRate: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(audioResponseFormat: AudioResponseFormat) = apply { - type = audioResponseFormat.type - bitRate = audioResponseFormat.bitRate - delivery = audioResponseFormat.delivery - mimeType = audioResponseFormat.mimeType - sampleRate = audioResponseFormat.sampleRate - additionalProperties = audioResponseFormat.additionalProperties.toMutableMap() - } - - /** - * Sets the field to an arbitrary JSON value. - * - * It is usually unnecessary to call this method because the field defaults to the - * following: - * ```java - * JsonValue.from("audio") - * ``` - * - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun type(type: JsonValue) = apply { this.type = type } - - /** - * Bit rate in bits per second (bps). Only applicable for compressed formats (MP3, Opus). - */ - fun bitRate(bitRate: Int) = bitRate(JsonField.of(bitRate)) - - /** - * Sets [Builder.bitRate] to an arbitrary JSON value. - * - * You should usually call [Builder.bitRate] with a well-typed [Int] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun bitRate(bitRate: JsonField) = apply { this.bitRate = bitRate } - - /** The delivery mode for the audio output. */ - fun delivery(delivery: Delivery) = delivery(JsonField.of(delivery)) - - /** - * Sets [Builder.delivery] to an arbitrary JSON value. - * - * You should usually call [Builder.delivery] with a well-typed [Delivery] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun delivery(delivery: JsonField) = apply { this.delivery = delivery } - - /** The MIME type of the audio output. */ - fun mimeType(mimeType: MimeType) = mimeType(JsonField.of(mimeType)) - - /** - * Sets [Builder.mimeType] to an arbitrary JSON value. - * - * You should usually call [Builder.mimeType] with a well-typed [MimeType] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun mimeType(mimeType: JsonField) = apply { this.mimeType = mimeType } - - /** Sample rate in Hz. */ - fun sampleRate(sampleRate: Int) = sampleRate(JsonField.of(sampleRate)) - - /** - * Sets [Builder.sampleRate] to an arbitrary JSON value. - * - * You should usually call [Builder.sampleRate] with a well-typed [Int] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun sampleRate(sampleRate: JsonField) = apply { this.sampleRate = sampleRate } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [AudioResponseFormat]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): AudioResponseFormat = - AudioResponseFormat( - type, - bitRate, - delivery, - mimeType, - sampleRate, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): AudioResponseFormat = apply { - if (validated) { - return@apply - } - - _type().let { - if (it != JsonValue.from("audio")) { - throw GeminiNextGenApiInvalidDataException("'type' is invalid, received $it") - } - } - bitRate() - delivery().ifPresent { it.validate() } - mimeType().ifPresent { it.validate() } - sampleRate() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - type.let { if (it == JsonValue.from("audio")) 1 else 0 } + - (if (bitRate.asKnown().isPresent) 1 else 0) + - (delivery.asKnown().getOrNull()?.validity() ?: 0) + - (mimeType.asKnown().getOrNull()?.validity() ?: 0) + - (if (sampleRate.asKnown().isPresent) 1 else 0) - - /** The delivery mode for the audio output. */ - class Delivery @JsonCreator private constructor(private val value: JsonField) : Enum { - - /** - * Returns this class instance's raw value. - * - * This is usually only useful if this instance was deserialized from data that doesn't - * match any known member, and you want to know that value. For example, if the SDK is on an - * older version than the API, then the API may respond with new members that the SDK is - * unaware of. - */ - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - companion object { - - @JvmField val INLINE = of("inline") - - @JvmField val URI = of("uri") - - @JvmStatic fun of(value: String) = Delivery(JsonField.of(value)) - } - - /** An enum containing [Delivery]'s known values. */ - enum class Known { - INLINE, - URI, - } - - /** - * An enum containing [Delivery]'s known values, as well as an [_UNKNOWN] member. - * - * An instance of [Delivery] can contain an unknown value in a couple of cases: - * - It was deserialized from data that doesn't match any known member. For example, if the - * SDK is on an older version than the API, then the API may respond with new members that - * the SDK is unaware of. - * - It was constructed with an arbitrary value using the [of] method. - */ - enum class Value { - INLINE, - URI, - /** An enum member indicating that [Delivery] was instantiated with an unknown value. */ - _UNKNOWN, - } - - /** - * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] - * if the class was instantiated with an unknown value. - * - * Use the [known] method instead if you're certain the value is always known or if you want - * to throw for the unknown case. - */ - fun value(): Value = - when (this) { - INLINE -> Value.INLINE - URI -> Value.URI - else -> Value._UNKNOWN - } - - /** - * Returns an enum member corresponding to this class instance's value. - * - * Use the [value] method instead if you're uncertain the value is always known and don't - * want to throw for the unknown case. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value is a not a - * known member. - */ - fun known(): Known = - when (this) { - INLINE -> Known.INLINE - URI -> Known.URI - else -> throw GeminiNextGenApiInvalidDataException("Unknown Delivery: $value") - } - - /** - * Returns this class instance's primitive wire representation. - * - * This differs from the [toString] method because that method is primarily for debugging - * and generally doesn't throw. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value does not have - * the expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - GeminiNextGenApiInvalidDataException("Value is not a String") - } - - private var validated: Boolean = false - - fun validate(): Delivery = apply { - if (validated) { - return@apply - } - - known() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Delivery && value == other.value - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - /** The MIME type of the audio output. */ - class MimeType @JsonCreator private constructor(private val value: JsonField) : Enum { - - /** - * Returns this class instance's raw value. - * - * This is usually only useful if this instance was deserialized from data that doesn't - * match any known member, and you want to know that value. For example, if the SDK is on an - * older version than the API, then the API may respond with new members that the SDK is - * unaware of. - */ - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - companion object { - - @JvmField val AUDIO_MP3 = of("audio/mp3") - - @JvmField val AUDIO_OGG_OPUS = of("audio/ogg_opus") - - @JvmField val AUDIO_L16 = of("audio/l16") - - @JvmField val AUDIO_WAV = of("audio/wav") - - @JvmField val AUDIO_ALAW = of("audio/alaw") - - @JvmField val AUDIO_MULAW = of("audio/mulaw") - - @JvmStatic fun of(value: String) = MimeType(JsonField.of(value)) - } - - /** An enum containing [MimeType]'s known values. */ - enum class Known { - AUDIO_MP3, - AUDIO_OGG_OPUS, - AUDIO_L16, - AUDIO_WAV, - AUDIO_ALAW, - AUDIO_MULAW, - } - - /** - * An enum containing [MimeType]'s known values, as well as an [_UNKNOWN] member. - * - * An instance of [MimeType] can contain an unknown value in a couple of cases: - * - It was deserialized from data that doesn't match any known member. For example, if the - * SDK is on an older version than the API, then the API may respond with new members that - * the SDK is unaware of. - * - It was constructed with an arbitrary value using the [of] method. - */ - enum class Value { - AUDIO_MP3, - AUDIO_OGG_OPUS, - AUDIO_L16, - AUDIO_WAV, - AUDIO_ALAW, - AUDIO_MULAW, - /** An enum member indicating that [MimeType] was instantiated with an unknown value. */ - _UNKNOWN, - } - - /** - * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] - * if the class was instantiated with an unknown value. - * - * Use the [known] method instead if you're certain the value is always known or if you want - * to throw for the unknown case. - */ - fun value(): Value = - when (this) { - AUDIO_MP3 -> Value.AUDIO_MP3 - AUDIO_OGG_OPUS -> Value.AUDIO_OGG_OPUS - AUDIO_L16 -> Value.AUDIO_L16 - AUDIO_WAV -> Value.AUDIO_WAV - AUDIO_ALAW -> Value.AUDIO_ALAW - AUDIO_MULAW -> Value.AUDIO_MULAW - else -> Value._UNKNOWN - } - - /** - * Returns an enum member corresponding to this class instance's value. - * - * Use the [value] method instead if you're uncertain the value is always known and don't - * want to throw for the unknown case. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value is a not a - * known member. - */ - fun known(): Known = - when (this) { - AUDIO_MP3 -> Known.AUDIO_MP3 - AUDIO_OGG_OPUS -> Known.AUDIO_OGG_OPUS - AUDIO_L16 -> Known.AUDIO_L16 - AUDIO_WAV -> Known.AUDIO_WAV - AUDIO_ALAW -> Known.AUDIO_ALAW - AUDIO_MULAW -> Known.AUDIO_MULAW - else -> throw GeminiNextGenApiInvalidDataException("Unknown MimeType: $value") - } - - /** - * Returns this class instance's primitive wire representation. - * - * This differs from the [toString] method because that method is primarily for debugging - * and generally doesn't throw. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value does not have - * the expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - GeminiNextGenApiInvalidDataException("Value is not a String") - } - - private var validated: Boolean = false - - fun validate(): MimeType = apply { - if (validated) { - return@apply - } - - known() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is MimeType && value == other.value - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is AudioResponseFormat && - type == other.type && - bitRate == other.bitRate && - delivery == other.delivery && - mimeType == other.mimeType && - sampleRate == other.sampleRate && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { - Objects.hash(type, bitRate, delivery, mimeType, sampleRate, additionalProperties) - } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "AudioResponseFormat{type=$type, bitRate=$bitRate, delivery=$delivery, mimeType=$mimeType, sampleRate=$sampleRate, additionalProperties=$additionalProperties}" -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/CodeExecutionCallArguments.kt b/src/main/java/com/google/genai/interactions/models/interactions/CodeExecutionCallArguments.kt deleted file mode 100644 index 53effbb0ab1..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/CodeExecutionCallArguments.kt +++ /dev/null @@ -1,334 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import com.google.genai.interactions.core.Enum -import com.google.genai.interactions.core.ExcludeMissing -import com.google.genai.interactions.core.JsonField -import com.google.genai.interactions.core.JsonMissing -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.util.Collections -import java.util.Objects -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -/** The arguments to pass to the code execution. */ -class CodeExecutionCallArguments -@JsonCreator(mode = JsonCreator.Mode.DISABLED) -private constructor( - private val code: JsonField, - private val language: JsonField, - private val additionalProperties: MutableMap, -) { - - @JsonCreator - private constructor( - @JsonProperty("code") @ExcludeMissing code: JsonField = JsonMissing.of(), - @JsonProperty("language") @ExcludeMissing language: JsonField = JsonMissing.of(), - ) : this(code, language, mutableMapOf()) - - /** - * The code to be executed. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun code(): Optional = code.getOptional("code") - - /** - * Programming language of the `code`. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun language(): Optional = language.getOptional("language") - - /** - * Returns the raw JSON value of [code]. - * - * Unlike [code], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("code") @ExcludeMissing fun _code(): JsonField = code - - /** - * Returns the raw JSON value of [language]. - * - * Unlike [language], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("language") @ExcludeMissing fun _language(): JsonField = language - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [CodeExecutionCallArguments]. - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [CodeExecutionCallArguments]. */ - class Builder internal constructor() { - - private var code: JsonField = JsonMissing.of() - private var language: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(codeExecutionCallArguments: CodeExecutionCallArguments) = apply { - code = codeExecutionCallArguments.code - language = codeExecutionCallArguments.language - additionalProperties = codeExecutionCallArguments.additionalProperties.toMutableMap() - } - - /** The code to be executed. */ - fun code(code: String) = code(JsonField.of(code)) - - /** - * Sets [Builder.code] to an arbitrary JSON value. - * - * You should usually call [Builder.code] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun code(code: JsonField) = apply { this.code = code } - - /** Programming language of the `code`. */ - fun language(language: Language) = language(JsonField.of(language)) - - /** - * Sets [Builder.language] to an arbitrary JSON value. - * - * You should usually call [Builder.language] with a well-typed [Language] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun language(language: JsonField) = apply { this.language = language } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [CodeExecutionCallArguments]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): CodeExecutionCallArguments = - CodeExecutionCallArguments(code, language, additionalProperties.toMutableMap()) - } - - private var validated: Boolean = false - - fun validate(): CodeExecutionCallArguments = apply { - if (validated) { - return@apply - } - - code() - language().ifPresent { it.validate() } - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - (if (code.asKnown().isPresent) 1 else 0) + (language.asKnown().getOrNull()?.validity() ?: 0) - - /** Programming language of the `code`. */ - class Language @JsonCreator private constructor(private val value: JsonField) : Enum { - - /** - * Returns this class instance's raw value. - * - * This is usually only useful if this instance was deserialized from data that doesn't - * match any known member, and you want to know that value. For example, if the SDK is on an - * older version than the API, then the API may respond with new members that the SDK is - * unaware of. - */ - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - companion object { - - @JvmField val PYTHON = of("python") - - @JvmStatic fun of(value: String) = Language(JsonField.of(value)) - } - - /** An enum containing [Language]'s known values. */ - enum class Known { - PYTHON - } - - /** - * An enum containing [Language]'s known values, as well as an [_UNKNOWN] member. - * - * An instance of [Language] can contain an unknown value in a couple of cases: - * - It was deserialized from data that doesn't match any known member. For example, if the - * SDK is on an older version than the API, then the API may respond with new members that - * the SDK is unaware of. - * - It was constructed with an arbitrary value using the [of] method. - */ - enum class Value { - PYTHON, - /** An enum member indicating that [Language] was instantiated with an unknown value. */ - _UNKNOWN, - } - - /** - * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] - * if the class was instantiated with an unknown value. - * - * Use the [known] method instead if you're certain the value is always known or if you want - * to throw for the unknown case. - */ - fun value(): Value = - when (this) { - PYTHON -> Value.PYTHON - else -> Value._UNKNOWN - } - - /** - * Returns an enum member corresponding to this class instance's value. - * - * Use the [value] method instead if you're uncertain the value is always known and don't - * want to throw for the unknown case. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value is a not a - * known member. - */ - fun known(): Known = - when (this) { - PYTHON -> Known.PYTHON - else -> throw GeminiNextGenApiInvalidDataException("Unknown Language: $value") - } - - /** - * Returns this class instance's primitive wire representation. - * - * This differs from the [toString] method because that method is primarily for debugging - * and generally doesn't throw. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value does not have - * the expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - GeminiNextGenApiInvalidDataException("Value is not a String") - } - - private var validated: Boolean = false - - fun validate(): Language = apply { - if (validated) { - return@apply - } - - known() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Language && value == other.value - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is CodeExecutionCallArguments && - code == other.code && - language == other.language && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { Objects.hash(code, language, additionalProperties) } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "CodeExecutionCallArguments{code=$code, language=$language, additionalProperties=$additionalProperties}" -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/CodeExecutionCallStep.kt b/src/main/java/com/google/genai/interactions/models/interactions/CodeExecutionCallStep.kt deleted file mode 100644 index fde995f4ad3..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/CodeExecutionCallStep.kt +++ /dev/null @@ -1,613 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import com.google.genai.interactions.core.Enum -import com.google.genai.interactions.core.ExcludeMissing -import com.google.genai.interactions.core.JsonField -import com.google.genai.interactions.core.JsonMissing -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.core.checkRequired -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.util.Collections -import java.util.Objects -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -/** Code execution call step. */ -class CodeExecutionCallStep -@JsonCreator(mode = JsonCreator.Mode.DISABLED) -private constructor( - private val id: JsonField, - private val arguments: JsonField, - private val type: JsonValue, - private val signature: JsonField, - private val additionalProperties: MutableMap, -) { - - @JsonCreator - private constructor( - @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), - @JsonProperty("arguments") - @ExcludeMissing - arguments: JsonField = JsonMissing.of(), - @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), - @JsonProperty("signature") @ExcludeMissing signature: JsonField = JsonMissing.of(), - ) : this(id, arguments, type, signature, mutableMapOf()) - - /** - * Required. A unique ID for this specific tool call. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). - */ - fun id(): String = id.getRequired("id") - - /** - * Required. The arguments to pass to the code execution. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). - */ - fun arguments(): Arguments = arguments.getRequired("arguments") - - /** - * Expected to always return the following: - * ```java - * JsonValue.from("code_execution_call") - * ``` - * - * However, this method can be useful for debugging and logging (e.g. if the server responded - * with an unexpected value). - */ - @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type - - /** - * A signature hash for backend validation. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun signature(): Optional = signature.getOptional("signature") - - /** - * Returns the raw JSON value of [id]. - * - * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id - - /** - * Returns the raw JSON value of [arguments]. - * - * Unlike [arguments], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("arguments") @ExcludeMissing fun _arguments(): JsonField = arguments - - /** - * Returns the raw JSON value of [signature]. - * - * Unlike [signature], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("signature") @ExcludeMissing fun _signature(): JsonField = signature - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [CodeExecutionCallStep]. - * - * The following fields are required: - * ```java - * .id() - * .arguments() - * ``` - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [CodeExecutionCallStep]. */ - class Builder internal constructor() { - - private var id: JsonField? = null - private var arguments: JsonField? = null - private var type: JsonValue = JsonValue.from("code_execution_call") - private var signature: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(codeExecutionCallStep: CodeExecutionCallStep) = apply { - id = codeExecutionCallStep.id - arguments = codeExecutionCallStep.arguments - type = codeExecutionCallStep.type - signature = codeExecutionCallStep.signature - additionalProperties = codeExecutionCallStep.additionalProperties.toMutableMap() - } - - /** Required. A unique ID for this specific tool call. */ - fun id(id: String) = id(JsonField.of(id)) - - /** - * Sets [Builder.id] to an arbitrary JSON value. - * - * You should usually call [Builder.id] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun id(id: JsonField) = apply { this.id = id } - - /** Required. The arguments to pass to the code execution. */ - fun arguments(arguments: Arguments) = arguments(JsonField.of(arguments)) - - /** - * Sets [Builder.arguments] to an arbitrary JSON value. - * - * You should usually call [Builder.arguments] with a well-typed [Arguments] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun arguments(arguments: JsonField) = apply { this.arguments = arguments } - - /** - * Sets the field to an arbitrary JSON value. - * - * It is usually unnecessary to call this method because the field defaults to the - * following: - * ```java - * JsonValue.from("code_execution_call") - * ``` - * - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun type(type: JsonValue) = apply { this.type = type } - - /** A signature hash for backend validation. */ - fun signature(signature: String) = signature(JsonField.of(signature)) - - /** - * Sets [Builder.signature] to an arbitrary JSON value. - * - * You should usually call [Builder.signature] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun signature(signature: JsonField) = apply { this.signature = signature } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [CodeExecutionCallStep]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .id() - * .arguments() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): CodeExecutionCallStep = - CodeExecutionCallStep( - checkRequired("id", id), - checkRequired("arguments", arguments), - type, - signature, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): CodeExecutionCallStep = apply { - if (validated) { - return@apply - } - - id() - arguments().validate() - _type().let { - if (it != JsonValue.from("code_execution_call")) { - throw GeminiNextGenApiInvalidDataException("'type' is invalid, received $it") - } - } - signature() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - (if (id.asKnown().isPresent) 1 else 0) + - (arguments.asKnown().getOrNull()?.validity() ?: 0) + - type.let { if (it == JsonValue.from("code_execution_call")) 1 else 0 } + - (if (signature.asKnown().isPresent) 1 else 0) - - /** Required. The arguments to pass to the code execution. */ - class Arguments - @JsonCreator(mode = JsonCreator.Mode.DISABLED) - private constructor( - private val code: JsonField, - private val language: JsonField, - private val additionalProperties: MutableMap, - ) { - - @JsonCreator - private constructor( - @JsonProperty("code") @ExcludeMissing code: JsonField = JsonMissing.of(), - @JsonProperty("language") - @ExcludeMissing - language: JsonField = JsonMissing.of(), - ) : this(code, language, mutableMapOf()) - - /** - * The code to be executed. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type - * (e.g. if the server responded with an unexpected value). - */ - fun code(): Optional = code.getOptional("code") - - /** - * Programming language of the `code`. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type - * (e.g. if the server responded with an unexpected value). - */ - fun language(): Optional = language.getOptional("language") - - /** - * Returns the raw JSON value of [code]. - * - * Unlike [code], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("code") @ExcludeMissing fun _code(): JsonField = code - - /** - * Returns the raw JSON value of [language]. - * - * Unlike [language], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("language") @ExcludeMissing fun _language(): JsonField = language - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [Arguments]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Arguments]. */ - class Builder internal constructor() { - - private var code: JsonField = JsonMissing.of() - private var language: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(arguments: Arguments) = apply { - code = arguments.code - language = arguments.language - additionalProperties = arguments.additionalProperties.toMutableMap() - } - - /** The code to be executed. */ - fun code(code: String) = code(JsonField.of(code)) - - /** - * Sets [Builder.code] to an arbitrary JSON value. - * - * You should usually call [Builder.code] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun code(code: JsonField) = apply { this.code = code } - - /** Programming language of the `code`. */ - fun language(language: Language) = language(JsonField.of(language)) - - /** - * Sets [Builder.language] to an arbitrary JSON value. - * - * You should usually call [Builder.language] with a well-typed [Language] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun language(language: JsonField) = apply { this.language = language } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [Arguments]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): Arguments = Arguments(code, language, additionalProperties.toMutableMap()) - } - - private var validated: Boolean = false - - fun validate(): Arguments = apply { - if (validated) { - return@apply - } - - code() - language().ifPresent { it.validate() } - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - (if (code.asKnown().isPresent) 1 else 0) + - (language.asKnown().getOrNull()?.validity() ?: 0) - - /** Programming language of the `code`. */ - class Language @JsonCreator private constructor(private val value: JsonField) : - Enum { - - /** - * Returns this class instance's raw value. - * - * This is usually only useful if this instance was deserialized from data that doesn't - * match any known member, and you want to know that value. For example, if the SDK is - * on an older version than the API, then the API may respond with new members that the - * SDK is unaware of. - */ - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - companion object { - - @JvmField val PYTHON = of("python") - - @JvmStatic fun of(value: String) = Language(JsonField.of(value)) - } - - /** An enum containing [Language]'s known values. */ - enum class Known { - PYTHON - } - - /** - * An enum containing [Language]'s known values, as well as an [_UNKNOWN] member. - * - * An instance of [Language] can contain an unknown value in a couple of cases: - * - It was deserialized from data that doesn't match any known member. For example, if - * the SDK is on an older version than the API, then the API may respond with new - * members that the SDK is unaware of. - * - It was constructed with an arbitrary value using the [of] method. - */ - enum class Value { - PYTHON, - /** - * An enum member indicating that [Language] was instantiated with an unknown value. - */ - _UNKNOWN, - } - - /** - * Returns an enum member corresponding to this class instance's value, or - * [Value._UNKNOWN] if the class was instantiated with an unknown value. - * - * Use the [known] method instead if you're certain the value is always known or if you - * want to throw for the unknown case. - */ - fun value(): Value = - when (this) { - PYTHON -> Value.PYTHON - else -> Value._UNKNOWN - } - - /** - * Returns an enum member corresponding to this class instance's value. - * - * Use the [value] method instead if you're uncertain the value is always known and - * don't want to throw for the unknown case. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value is a not - * a known member. - */ - fun known(): Known = - when (this) { - PYTHON -> Known.PYTHON - else -> throw GeminiNextGenApiInvalidDataException("Unknown Language: $value") - } - - /** - * Returns this class instance's primitive wire representation. - * - * This differs from the [toString] method because that method is primarily for - * debugging and generally doesn't throw. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value does not - * have the expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - GeminiNextGenApiInvalidDataException("Value is not a String") - } - - private var validated: Boolean = false - - fun validate(): Language = apply { - if (validated) { - return@apply - } - - known() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Language && value == other.value - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Arguments && - code == other.code && - language == other.language && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { Objects.hash(code, language, additionalProperties) } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Arguments{code=$code, language=$language, additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is CodeExecutionCallStep && - id == other.id && - arguments == other.arguments && - type == other.type && - signature == other.signature && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { - Objects.hash(id, arguments, type, signature, additionalProperties) - } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "CodeExecutionCallStep{id=$id, arguments=$arguments, type=$type, signature=$signature, additionalProperties=$additionalProperties}" -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/CodeExecutionResultStep.kt b/src/main/java/com/google/genai/interactions/models/interactions/CodeExecutionResultStep.kt deleted file mode 100644 index b900f8a7dbc..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/CodeExecutionResultStep.kt +++ /dev/null @@ -1,337 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import com.google.genai.interactions.core.ExcludeMissing -import com.google.genai.interactions.core.JsonField -import com.google.genai.interactions.core.JsonMissing -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.core.checkRequired -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.util.Collections -import java.util.Objects -import java.util.Optional - -/** Code execution result step. */ -class CodeExecutionResultStep -@JsonCreator(mode = JsonCreator.Mode.DISABLED) -private constructor( - private val callId: JsonField, - private val result: JsonField, - private val type: JsonValue, - private val isError: JsonField, - private val signature: JsonField, - private val additionalProperties: MutableMap, -) { - - @JsonCreator - private constructor( - @JsonProperty("call_id") @ExcludeMissing callId: JsonField = JsonMissing.of(), - @JsonProperty("result") @ExcludeMissing result: JsonField = JsonMissing.of(), - @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), - @JsonProperty("is_error") @ExcludeMissing isError: JsonField = JsonMissing.of(), - @JsonProperty("signature") @ExcludeMissing signature: JsonField = JsonMissing.of(), - ) : this(callId, result, type, isError, signature, mutableMapOf()) - - /** - * Required. ID to match the ID from the function call block. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). - */ - fun callId(): String = callId.getRequired("call_id") - - /** - * Required. The output of the code execution. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). - */ - fun result(): String = result.getRequired("result") - - /** - * Expected to always return the following: - * ```java - * JsonValue.from("code_execution_result") - * ``` - * - * However, this method can be useful for debugging and logging (e.g. if the server responded - * with an unexpected value). - */ - @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type - - /** - * Whether the code execution resulted in an error. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun isError(): Optional = isError.getOptional("is_error") - - /** - * A signature hash for backend validation. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun signature(): Optional = signature.getOptional("signature") - - /** - * Returns the raw JSON value of [callId]. - * - * Unlike [callId], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("call_id") @ExcludeMissing fun _callId(): JsonField = callId - - /** - * Returns the raw JSON value of [result]. - * - * Unlike [result], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("result") @ExcludeMissing fun _result(): JsonField = result - - /** - * Returns the raw JSON value of [isError]. - * - * Unlike [isError], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("is_error") @ExcludeMissing fun _isError(): JsonField = isError - - /** - * Returns the raw JSON value of [signature]. - * - * Unlike [signature], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("signature") @ExcludeMissing fun _signature(): JsonField = signature - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [CodeExecutionResultStep]. - * - * The following fields are required: - * ```java - * .callId() - * .result() - * ``` - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [CodeExecutionResultStep]. */ - class Builder internal constructor() { - - private var callId: JsonField? = null - private var result: JsonField? = null - private var type: JsonValue = JsonValue.from("code_execution_result") - private var isError: JsonField = JsonMissing.of() - private var signature: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(codeExecutionResultStep: CodeExecutionResultStep) = apply { - callId = codeExecutionResultStep.callId - result = codeExecutionResultStep.result - type = codeExecutionResultStep.type - isError = codeExecutionResultStep.isError - signature = codeExecutionResultStep.signature - additionalProperties = codeExecutionResultStep.additionalProperties.toMutableMap() - } - - /** Required. ID to match the ID from the function call block. */ - fun callId(callId: String) = callId(JsonField.of(callId)) - - /** - * Sets [Builder.callId] to an arbitrary JSON value. - * - * You should usually call [Builder.callId] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun callId(callId: JsonField) = apply { this.callId = callId } - - /** Required. The output of the code execution. */ - fun result(result: String) = result(JsonField.of(result)) - - /** - * Sets [Builder.result] to an arbitrary JSON value. - * - * You should usually call [Builder.result] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun result(result: JsonField) = apply { this.result = result } - - /** - * Sets the field to an arbitrary JSON value. - * - * It is usually unnecessary to call this method because the field defaults to the - * following: - * ```java - * JsonValue.from("code_execution_result") - * ``` - * - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun type(type: JsonValue) = apply { this.type = type } - - /** Whether the code execution resulted in an error. */ - fun isError(isError: Boolean) = isError(JsonField.of(isError)) - - /** - * Sets [Builder.isError] to an arbitrary JSON value. - * - * You should usually call [Builder.isError] with a well-typed [Boolean] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun isError(isError: JsonField) = apply { this.isError = isError } - - /** A signature hash for backend validation. */ - fun signature(signature: String) = signature(JsonField.of(signature)) - - /** - * Sets [Builder.signature] to an arbitrary JSON value. - * - * You should usually call [Builder.signature] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun signature(signature: JsonField) = apply { this.signature = signature } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [CodeExecutionResultStep]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .callId() - * .result() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): CodeExecutionResultStep = - CodeExecutionResultStep( - checkRequired("callId", callId), - checkRequired("result", result), - type, - isError, - signature, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): CodeExecutionResultStep = apply { - if (validated) { - return@apply - } - - callId() - result() - _type().let { - if (it != JsonValue.from("code_execution_result")) { - throw GeminiNextGenApiInvalidDataException("'type' is invalid, received $it") - } - } - isError() - signature() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - (if (callId.asKnown().isPresent) 1 else 0) + - (if (result.asKnown().isPresent) 1 else 0) + - type.let { if (it == JsonValue.from("code_execution_result")) 1 else 0 } + - (if (isError.asKnown().isPresent) 1 else 0) + - (if (signature.asKnown().isPresent) 1 else 0) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is CodeExecutionResultStep && - callId == other.callId && - result == other.result && - type == other.type && - isError == other.isError && - signature == other.signature && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { - Objects.hash(callId, result, type, isError, signature, additionalProperties) - } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "CodeExecutionResultStep{callId=$callId, result=$result, type=$type, isError=$isError, signature=$signature, additionalProperties=$additionalProperties}" -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/Content.kt b/src/main/java/com/google/genai/interactions/models/interactions/Content.kt deleted file mode 100644 index e59b2ed98bf..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/Content.kt +++ /dev/null @@ -1,298 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.core.JsonGenerator -import com.fasterxml.jackson.core.ObjectCodec -import com.fasterxml.jackson.databind.JsonNode -import com.fasterxml.jackson.databind.SerializerProvider -import com.fasterxml.jackson.databind.annotation.JsonDeserialize -import com.fasterxml.jackson.databind.annotation.JsonSerialize -import com.fasterxml.jackson.module.kotlin.jacksonTypeRef -import com.google.genai.interactions.core.BaseDeserializer -import com.google.genai.interactions.core.BaseSerializer -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.core.getOrThrow -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.util.Objects -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -/** The content of the response. */ -@JsonDeserialize(using = Content.Deserializer::class) -@JsonSerialize(using = Content.Serializer::class) -class Content -private constructor( - private val text: TextContent? = null, - private val image: ImageContent? = null, - private val audio: AudioContent? = null, - private val document: DocumentContent? = null, - private val video: VideoContent? = null, - private val _json: JsonValue? = null, -) { - - /** A text content block. */ - fun text(): Optional = Optional.ofNullable(text) - - /** An image content block. */ - fun image(): Optional = Optional.ofNullable(image) - - /** An audio content block. */ - fun audio(): Optional = Optional.ofNullable(audio) - - /** A document content block. */ - fun document(): Optional = Optional.ofNullable(document) - - /** A video content block. */ - fun video(): Optional = Optional.ofNullable(video) - - fun isText(): Boolean = text != null - - fun isImage(): Boolean = image != null - - fun isAudio(): Boolean = audio != null - - fun isDocument(): Boolean = document != null - - fun isVideo(): Boolean = video != null - - /** A text content block. */ - fun asText(): TextContent = text.getOrThrow("text") - - /** An image content block. */ - fun asImage(): ImageContent = image.getOrThrow("image") - - /** An audio content block. */ - fun asAudio(): AudioContent = audio.getOrThrow("audio") - - /** A document content block. */ - fun asDocument(): DocumentContent = document.getOrThrow("document") - - /** A video content block. */ - fun asVideo(): VideoContent = video.getOrThrow("video") - - fun _json(): Optional = Optional.ofNullable(_json) - - fun accept(visitor: Visitor): T = - when { - text != null -> visitor.visitText(text) - image != null -> visitor.visitImage(image) - audio != null -> visitor.visitAudio(audio) - document != null -> visitor.visitDocument(document) - video != null -> visitor.visitVideo(video) - else -> visitor.unknown(_json) - } - - private var validated: Boolean = false - - fun validate(): Content = apply { - if (validated) { - return@apply - } - - accept( - object : Visitor { - override fun visitText(text: TextContent) { - text.validate() - } - - override fun visitImage(image: ImageContent) { - image.validate() - } - - override fun visitAudio(audio: AudioContent) { - audio.validate() - } - - override fun visitDocument(document: DocumentContent) { - document.validate() - } - - override fun visitVideo(video: VideoContent) { - video.validate() - } - } - ) - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - accept( - object : Visitor { - override fun visitText(text: TextContent) = text.validity() - - override fun visitImage(image: ImageContent) = image.validity() - - override fun visitAudio(audio: AudioContent) = audio.validity() - - override fun visitDocument(document: DocumentContent) = document.validity() - - override fun visitVideo(video: VideoContent) = video.validity() - - override fun unknown(json: JsonValue?) = 0 - } - ) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Content && - text == other.text && - image == other.image && - audio == other.audio && - document == other.document && - video == other.video - } - - override fun hashCode(): Int = Objects.hash(text, image, audio, document, video) - - override fun toString(): String = - when { - text != null -> "Content{text=$text}" - image != null -> "Content{image=$image}" - audio != null -> "Content{audio=$audio}" - document != null -> "Content{document=$document}" - video != null -> "Content{video=$video}" - _json != null -> "Content{_unknown=$_json}" - else -> throw IllegalStateException("Invalid Content") - } - - companion object { - - /** A text content block. */ - @JvmStatic fun ofText(text: TextContent) = Content(text = text) - - /** An image content block. */ - @JvmStatic fun ofImage(image: ImageContent) = Content(image = image) - - /** An audio content block. */ - @JvmStatic fun ofAudio(audio: AudioContent) = Content(audio = audio) - - /** A document content block. */ - @JvmStatic fun ofDocument(document: DocumentContent) = Content(document = document) - - /** A video content block. */ - @JvmStatic fun ofVideo(video: VideoContent) = Content(video = video) - } - - /** An interface that defines how to map each variant of [Content] to a value of type [T]. */ - interface Visitor { - - /** A text content block. */ - fun visitText(text: TextContent): T - - /** An image content block. */ - fun visitImage(image: ImageContent): T - - /** An audio content block. */ - fun visitAudio(audio: AudioContent): T - - /** A document content block. */ - fun visitDocument(document: DocumentContent): T - - /** A video content block. */ - fun visitVideo(video: VideoContent): T - - /** - * Maps an unknown variant of [Content] to a value of type [T]. - * - * An instance of [Content] can contain an unknown variant if it was deserialized from data - * that doesn't match any known variant. For example, if the SDK is on an older version than - * the API, then the API may respond with new variants that the SDK is unaware of. - * - * @throws GeminiNextGenApiInvalidDataException in the default implementation. - */ - fun unknown(json: JsonValue?): T { - throw GeminiNextGenApiInvalidDataException("Unknown Content: $json") - } - } - - internal class Deserializer : BaseDeserializer(Content::class) { - - override fun ObjectCodec.deserialize(node: JsonNode): Content { - val json = JsonValue.fromJsonNode(node) - val type = json.asObject().getOrNull()?.get("type")?.asString()?.getOrNull() - - when (type) { - "text" -> { - return tryDeserialize(node, jacksonTypeRef())?.let { - Content(text = it, _json = json) - } ?: Content(_json = json) - } - "image" -> { - return tryDeserialize(node, jacksonTypeRef())?.let { - Content(image = it, _json = json) - } ?: Content(_json = json) - } - "audio" -> { - return tryDeserialize(node, jacksonTypeRef())?.let { - Content(audio = it, _json = json) - } ?: Content(_json = json) - } - "document" -> { - return tryDeserialize(node, jacksonTypeRef())?.let { - Content(document = it, _json = json) - } ?: Content(_json = json) - } - "video" -> { - return tryDeserialize(node, jacksonTypeRef())?.let { - Content(video = it, _json = json) - } ?: Content(_json = json) - } - } - - return Content(_json = json) - } - } - - internal class Serializer : BaseSerializer(Content::class) { - - override fun serialize( - value: Content, - generator: JsonGenerator, - provider: SerializerProvider, - ) { - when { - value.text != null -> generator.writeObject(value.text) - value.image != null -> generator.writeObject(value.image) - value.audio != null -> generator.writeObject(value.audio) - value.document != null -> generator.writeObject(value.document) - value.video != null -> generator.writeObject(value.video) - value._json != null -> generator.writeObject(value._json) - else -> throw IllegalStateException("Invalid Content") - } - } - } -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/CreateAgentInteractionParams.kt b/src/main/java/com/google/genai/interactions/models/interactions/CreateAgentInteractionParams.kt deleted file mode 100644 index 4bfa0f9fa19..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/CreateAgentInteractionParams.kt +++ /dev/null @@ -1,3055 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import com.fasterxml.jackson.core.JsonGenerator -import com.fasterxml.jackson.core.ObjectCodec -import com.fasterxml.jackson.databind.JsonNode -import com.fasterxml.jackson.databind.SerializerProvider -import com.fasterxml.jackson.databind.annotation.JsonDeserialize -import com.fasterxml.jackson.databind.annotation.JsonSerialize -import com.fasterxml.jackson.module.kotlin.jacksonTypeRef -import com.google.genai.interactions.core.BaseDeserializer -import com.google.genai.interactions.core.BaseSerializer -import com.google.genai.interactions.core.Enum -import com.google.genai.interactions.core.ExcludeMissing -import com.google.genai.interactions.core.JsonField -import com.google.genai.interactions.core.JsonMissing -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.core.allMaxBy -import com.google.genai.interactions.core.checkKnown -import com.google.genai.interactions.core.checkRequired -import com.google.genai.interactions.core.getOrThrow -import com.google.genai.interactions.core.toImmutable -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.time.OffsetDateTime -import java.util.Collections -import java.util.Objects -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -/** Parameters for creating agent interactions */ -class CreateAgentInteractionParams -@JsonCreator(mode = JsonCreator.Mode.DISABLED) -private constructor( - private val agent: JsonField, - private val input: JsonField, - private val id: JsonField, - private val agentConfig: JsonField, - private val background: JsonField, - private val created: JsonField, - private val previousInteractionId: JsonField, - private val responseFormat: JsonField, - private val responseMimeType: JsonField, - private val responseModalities: JsonField>, - private val role: JsonField, - private val serviceTier: JsonField, - private val status: JsonField, - private val store: JsonField, - private val stream: JsonField, - private val systemInstruction: JsonField, - private val tools: JsonField>, - private val updated: JsonField, - private val usage: JsonField, - private val webhookConfig: JsonField, - private val additionalProperties: MutableMap, -) { - - @JsonCreator - private constructor( - @JsonProperty("agent") @ExcludeMissing agent: JsonField = JsonMissing.of(), - @JsonProperty("input") @ExcludeMissing input: JsonField = JsonMissing.of(), - @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), - @JsonProperty("agent_config") - @ExcludeMissing - agentConfig: JsonField = JsonMissing.of(), - @JsonProperty("background") - @ExcludeMissing - background: JsonField = JsonMissing.of(), - @JsonProperty("created") - @ExcludeMissing - created: JsonField = JsonMissing.of(), - @JsonProperty("previous_interaction_id") - @ExcludeMissing - previousInteractionId: JsonField = JsonMissing.of(), - @JsonProperty("response_format") - @ExcludeMissing - responseFormat: JsonField = JsonMissing.of(), - @JsonProperty("response_mime_type") - @ExcludeMissing - responseMimeType: JsonField = JsonMissing.of(), - @JsonProperty("response_modalities") - @ExcludeMissing - responseModalities: JsonField> = JsonMissing.of(), - @JsonProperty("role") @ExcludeMissing role: JsonField = JsonMissing.of(), - @JsonProperty("service_tier") - @ExcludeMissing - serviceTier: JsonField = JsonMissing.of(), - @JsonProperty("status") @ExcludeMissing status: JsonField = JsonMissing.of(), - @JsonProperty("store") @ExcludeMissing store: JsonField = JsonMissing.of(), - @JsonProperty("stream") @ExcludeMissing stream: JsonField = JsonMissing.of(), - @JsonProperty("system_instruction") - @ExcludeMissing - systemInstruction: JsonField = JsonMissing.of(), - @JsonProperty("tools") @ExcludeMissing tools: JsonField> = JsonMissing.of(), - @JsonProperty("updated") - @ExcludeMissing - updated: JsonField = JsonMissing.of(), - @JsonProperty("usage") @ExcludeMissing usage: JsonField = JsonMissing.of(), - @JsonProperty("webhook_config") - @ExcludeMissing - webhookConfig: JsonField = JsonMissing.of(), - ) : this( - agent, - input, - id, - agentConfig, - background, - created, - previousInteractionId, - responseFormat, - responseMimeType, - responseModalities, - role, - serviceTier, - status, - store, - stream, - systemInstruction, - tools, - updated, - usage, - webhookConfig, - mutableMapOf(), - ) - - /** - * The name of the `Agent` used for generating the interaction. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). - */ - fun agent(): Agent = agent.getRequired("agent") - - /** - * The input for the interaction. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). - */ - fun input(): Input = input.getRequired("input") - - /** - * Required. Output only. A unique identifier for the interaction completion. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun id(): Optional = id.getOptional("id") - - /** - * Configuration parameters for the agent interaction. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun agentConfig(): Optional = agentConfig.getOptional("agent_config") - - /** - * Input only. Whether to run the model interaction in the background. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun background(): Optional = background.getOptional("background") - - /** - * Required. Output only. The time at which the response was created in ISO 8601 format - * (YYYY-MM-DDThh:mm:ssZ). - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun created(): Optional = created.getOptional("created") - - /** - * The ID of the previous interaction, if any. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun previousInteractionId(): Optional = - previousInteractionId.getOptional("previous_interaction_id") - - /** - * Enforces that the generated response is a JSON object that complies with the JSON schema - * specified in this field. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun responseFormat(): Optional = responseFormat.getOptional("response_format") - - /** - * The mime type of the response. This is required if response_format is set. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun responseMimeType(): Optional = responseMimeType.getOptional("response_mime_type") - - /** - * The requested modalities of the response (TEXT, IMAGE, AUDIO). - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun responseModalities(): Optional> = - responseModalities.getOptional("response_modalities") - - /** - * Output only. The role of the interaction. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - @Deprecated("deprecated") fun role(): Optional = role.getOptional("role") - - /** - * The service tier for the interaction. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun serviceTier(): Optional = serviceTier.getOptional("service_tier") - - /** - * Required. Output only. The status of the interaction. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun status(): Optional = status.getOptional("status") - - /** - * Input only. Whether to store the response and request for later retrieval. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun store(): Optional = store.getOptional("store") - - /** - * Input only. Whether the interaction will be streamed. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun stream(): Optional = stream.getOptional("stream") - - /** - * System instruction for the interaction. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun systemInstruction(): Optional = systemInstruction.getOptional("system_instruction") - - /** - * A list of tool declarations the model may call during interaction. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun tools(): Optional> = tools.getOptional("tools") - - /** - * Required. Output only. The time at which the response was last updated in ISO 8601 format - * (YYYY-MM-DDThh:mm:ssZ). - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun updated(): Optional = updated.getOptional("updated") - - /** - * Output only. Statistics on the interaction request's token usage. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun usage(): Optional = usage.getOptional("usage") - - /** - * Optional. Webhook configuration for receiving notifications when the interaction completes. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun webhookConfig(): Optional = webhookConfig.getOptional("webhook_config") - - /** - * Returns the raw JSON value of [agent]. - * - * Unlike [agent], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("agent") @ExcludeMissing fun _agent(): JsonField = agent - - /** - * Returns the raw JSON value of [input]. - * - * Unlike [input], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("input") @ExcludeMissing fun _input(): JsonField = input - - /** - * Returns the raw JSON value of [id]. - * - * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id - - /** - * Returns the raw JSON value of [agentConfig]. - * - * Unlike [agentConfig], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("agent_config") - @ExcludeMissing - fun _agentConfig(): JsonField = agentConfig - - /** - * Returns the raw JSON value of [background]. - * - * Unlike [background], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("background") @ExcludeMissing fun _background(): JsonField = background - - /** - * Returns the raw JSON value of [created]. - * - * Unlike [created], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("created") @ExcludeMissing fun _created(): JsonField = created - - /** - * Returns the raw JSON value of [previousInteractionId]. - * - * Unlike [previousInteractionId], this method doesn't throw if the JSON field has an unexpected - * type. - */ - @JsonProperty("previous_interaction_id") - @ExcludeMissing - fun _previousInteractionId(): JsonField = previousInteractionId - - /** - * Returns the raw JSON value of [responseFormat]. - * - * Unlike [responseFormat], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("response_format") - @ExcludeMissing - fun _responseFormat(): JsonField = responseFormat - - /** - * Returns the raw JSON value of [responseMimeType]. - * - * Unlike [responseMimeType], this method doesn't throw if the JSON field has an unexpected - * type. - */ - @JsonProperty("response_mime_type") - @ExcludeMissing - fun _responseMimeType(): JsonField = responseMimeType - - /** - * Returns the raw JSON value of [responseModalities]. - * - * Unlike [responseModalities], this method doesn't throw if the JSON field has an unexpected - * type. - */ - @JsonProperty("response_modalities") - @ExcludeMissing - fun _responseModalities(): JsonField> = responseModalities - - /** - * Returns the raw JSON value of [role]. - * - * Unlike [role], this method doesn't throw if the JSON field has an unexpected type. - */ - @Deprecated("deprecated") - @JsonProperty("role") - @ExcludeMissing - fun _role(): JsonField = role - - /** - * Returns the raw JSON value of [serviceTier]. - * - * Unlike [serviceTier], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("service_tier") - @ExcludeMissing - fun _serviceTier(): JsonField = serviceTier - - /** - * Returns the raw JSON value of [status]. - * - * Unlike [status], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("status") @ExcludeMissing fun _status(): JsonField = status - - /** - * Returns the raw JSON value of [store]. - * - * Unlike [store], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("store") @ExcludeMissing fun _store(): JsonField = store - - /** - * Returns the raw JSON value of [stream]. - * - * Unlike [stream], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("stream") @ExcludeMissing fun _stream(): JsonField = stream - - /** - * Returns the raw JSON value of [systemInstruction]. - * - * Unlike [systemInstruction], this method doesn't throw if the JSON field has an unexpected - * type. - */ - @JsonProperty("system_instruction") - @ExcludeMissing - fun _systemInstruction(): JsonField = systemInstruction - - /** - * Returns the raw JSON value of [tools]. - * - * Unlike [tools], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("tools") @ExcludeMissing fun _tools(): JsonField> = tools - - /** - * Returns the raw JSON value of [updated]. - * - * Unlike [updated], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("updated") @ExcludeMissing fun _updated(): JsonField = updated - - /** - * Returns the raw JSON value of [usage]. - * - * Unlike [usage], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("usage") @ExcludeMissing fun _usage(): JsonField = usage - - /** - * Returns the raw JSON value of [webhookConfig]. - * - * Unlike [webhookConfig], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("webhook_config") - @ExcludeMissing - fun _webhookConfig(): JsonField = webhookConfig - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [CreateAgentInteractionParams]. - * - * The following fields are required: - * ```java - * .agent() - * .input() - * ``` - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [CreateAgentInteractionParams]. */ - class Builder internal constructor() { - - private var agent: JsonField? = null - private var input: JsonField? = null - private var id: JsonField = JsonMissing.of() - private var agentConfig: JsonField = JsonMissing.of() - private var background: JsonField = JsonMissing.of() - private var created: JsonField = JsonMissing.of() - private var previousInteractionId: JsonField = JsonMissing.of() - private var responseFormat: JsonField = JsonMissing.of() - private var responseMimeType: JsonField = JsonMissing.of() - private var responseModalities: JsonField>? = null - private var role: JsonField = JsonMissing.of() - private var serviceTier: JsonField = JsonMissing.of() - private var status: JsonField = JsonMissing.of() - private var store: JsonField = JsonMissing.of() - private var stream: JsonField = JsonMissing.of() - private var systemInstruction: JsonField = JsonMissing.of() - private var tools: JsonField>? = null - private var updated: JsonField = JsonMissing.of() - private var usage: JsonField = JsonMissing.of() - private var webhookConfig: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(createAgentInteractionParams: CreateAgentInteractionParams) = apply { - agent = createAgentInteractionParams.agent - input = createAgentInteractionParams.input - id = createAgentInteractionParams.id - agentConfig = createAgentInteractionParams.agentConfig - background = createAgentInteractionParams.background - created = createAgentInteractionParams.created - previousInteractionId = createAgentInteractionParams.previousInteractionId - responseFormat = createAgentInteractionParams.responseFormat - responseMimeType = createAgentInteractionParams.responseMimeType - responseModalities = - createAgentInteractionParams.responseModalities.map { it.toMutableList() } - role = createAgentInteractionParams.role - serviceTier = createAgentInteractionParams.serviceTier - status = createAgentInteractionParams.status - store = createAgentInteractionParams.store - stream = createAgentInteractionParams.stream - systemInstruction = createAgentInteractionParams.systemInstruction - tools = createAgentInteractionParams.tools.map { it.toMutableList() } - updated = createAgentInteractionParams.updated - usage = createAgentInteractionParams.usage - webhookConfig = createAgentInteractionParams.webhookConfig - additionalProperties = createAgentInteractionParams.additionalProperties.toMutableMap() - } - - /** The name of the `Agent` used for generating the interaction. */ - fun agent(agent: Agent) = agent(JsonField.of(agent)) - - /** - * Sets [Builder.agent] to an arbitrary JSON value. - * - * You should usually call [Builder.agent] with a well-typed [Agent] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun agent(agent: JsonField) = apply { this.agent = agent } - - /** - * Sets [agent] to an arbitrary [String]. - * - * You should usually call [agent] with a well-typed [Agent] constant instead. This method - * is primarily for setting the field to an undocumented or not yet supported value. - */ - fun agent(value: String) = agent(Agent.of(value)) - - /** The input for the interaction. */ - fun input(input: Input) = input(JsonField.of(input)) - - /** - * Sets [Builder.input] to an arbitrary JSON value. - * - * You should usually call [Builder.input] with a well-typed [Input] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun input(input: JsonField) = apply { this.input = input } - - /** Alias for calling [input] with `Input.ofString(string)`. */ - fun input(string: String) = input(Input.ofString(string)) - - /** Alias for calling [input] with `Input.ofStepList(stepList)`. */ - fun inputOfStepList(stepList: List) = input(Input.ofStepList(stepList)) - - /** Alias for calling [input] with `Input.ofContentList(contentList)`. */ - fun inputOfContentList(contentList: List) = input(Input.ofContentList(contentList)) - - /** Alias for calling [input] with `Input.ofTextContent(textContent)`. */ - fun input(textContent: TextContent) = input(Input.ofTextContent(textContent)) - - /** Alias for calling [input] with `Input.ofImageContent(imageContent)`. */ - fun input(imageContent: ImageContent) = input(Input.ofImageContent(imageContent)) - - /** Alias for calling [input] with `Input.ofAudioContent(audioContent)`. */ - fun input(audioContent: AudioContent) = input(Input.ofAudioContent(audioContent)) - - /** Alias for calling [input] with `Input.ofDocumentContent(documentContent)`. */ - fun input(documentContent: DocumentContent) = - input(Input.ofDocumentContent(documentContent)) - - /** Alias for calling [input] with `Input.ofVideoContent(videoContent)`. */ - fun input(videoContent: VideoContent) = input(Input.ofVideoContent(videoContent)) - - /** Required. Output only. A unique identifier for the interaction completion. */ - fun id(id: String) = id(JsonField.of(id)) - - /** - * Sets [Builder.id] to an arbitrary JSON value. - * - * You should usually call [Builder.id] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun id(id: JsonField) = apply { this.id = id } - - /** Configuration parameters for the agent interaction. */ - fun agentConfig(agentConfig: AgentConfig) = agentConfig(JsonField.of(agentConfig)) - - /** - * Sets [Builder.agentConfig] to an arbitrary JSON value. - * - * You should usually call [Builder.agentConfig] with a well-typed [AgentConfig] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun agentConfig(agentConfig: JsonField) = apply { - this.agentConfig = agentConfig - } - - /** Alias for calling [agentConfig] with `AgentConfig.ofDynamic(dynamic)`. */ - fun agentConfig(dynamic: DynamicAgentConfig) = agentConfig(AgentConfig.ofDynamic(dynamic)) - - /** Alias for calling [agentConfig] with `AgentConfig.ofDeepResearch(deepResearch)`. */ - fun agentConfig(deepResearch: DeepResearchAgentConfig) = - agentConfig(AgentConfig.ofDeepResearch(deepResearch)) - - /** Input only. Whether to run the model interaction in the background. */ - fun background(background: Boolean) = background(JsonField.of(background)) - - /** - * Sets [Builder.background] to an arbitrary JSON value. - * - * You should usually call [Builder.background] with a well-typed [Boolean] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun background(background: JsonField) = apply { this.background = background } - - /** - * Required. Output only. The time at which the response was created in ISO 8601 format - * (YYYY-MM-DDThh:mm:ssZ). - */ - fun created(created: OffsetDateTime) = created(JsonField.of(created)) - - /** - * Sets [Builder.created] to an arbitrary JSON value. - * - * You should usually call [Builder.created] with a well-typed [OffsetDateTime] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun created(created: JsonField) = apply { this.created = created } - - /** The ID of the previous interaction, if any. */ - fun previousInteractionId(previousInteractionId: String) = - previousInteractionId(JsonField.of(previousInteractionId)) - - /** - * Sets [Builder.previousInteractionId] to an arbitrary JSON value. - * - * You should usually call [Builder.previousInteractionId] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun previousInteractionId(previousInteractionId: JsonField) = apply { - this.previousInteractionId = previousInteractionId - } - - /** - * Enforces that the generated response is a JSON object that complies with the JSON schema - * specified in this field. - */ - fun responseFormat(responseFormat: ResponseFormat) = - responseFormat(JsonField.of(responseFormat)) - - /** - * Sets [Builder.responseFormat] to an arbitrary JSON value. - * - * You should usually call [Builder.responseFormat] with a well-typed [ResponseFormat] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun responseFormat(responseFormat: JsonField) = apply { - this.responseFormat = responseFormat - } - - /** Alias for calling [responseFormat] with `ResponseFormat.ofList(list)`. */ - fun responseFormatOfList(list: List) = - responseFormat(ResponseFormat.ofList(list)) - - /** Alias for calling [responseFormat] with `ResponseFormat.ofAudio(audio)`. */ - fun responseFormat(audio: AudioResponseFormat) = - responseFormat(ResponseFormat.ofAudio(audio)) - - /** Alias for calling [responseFormat] with `ResponseFormat.ofText(text)`. */ - fun responseFormat(text: TextResponseFormat) = responseFormat(ResponseFormat.ofText(text)) - - /** Alias for calling [responseFormat] with `ResponseFormat.ofImage(image)`. */ - fun responseFormat(image: ImageResponseFormat) = - responseFormat(ResponseFormat.ofImage(image)) - - /** Alias for calling [responseFormat] with `ResponseFormat.ofJsonValue(jsonValue)`. */ - fun responseFormat(jsonValue: JsonValue) = - responseFormat(ResponseFormat.ofJsonValue(jsonValue)) - - /** The mime type of the response. This is required if response_format is set. */ - fun responseMimeType(responseMimeType: String) = - responseMimeType(JsonField.of(responseMimeType)) - - /** - * Sets [Builder.responseMimeType] to an arbitrary JSON value. - * - * You should usually call [Builder.responseMimeType] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun responseMimeType(responseMimeType: JsonField) = apply { - this.responseMimeType = responseMimeType - } - - /** The requested modalities of the response (TEXT, IMAGE, AUDIO). */ - fun responseModalities(responseModalities: List) = - responseModalities(JsonField.of(responseModalities)) - - /** - * Sets [Builder.responseModalities] to an arbitrary JSON value. - * - * You should usually call [Builder.responseModalities] with a well-typed - * `List` value instead. This method is primarily for setting the field to - * an undocumented or not yet supported value. - */ - fun responseModalities(responseModalities: JsonField>) = apply { - this.responseModalities = responseModalities.map { it.toMutableList() } - } - - /** - * Adds a single [ResponseModality] to [responseModalities]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addResponseModality(responseModality: ResponseModality) = apply { - responseModalities = - (responseModalities ?: JsonField.of(mutableListOf())).also { - checkKnown("responseModalities", it).add(responseModality) - } - } - - /** Output only. The role of the interaction. */ - @Deprecated("deprecated") fun role(role: String) = role(JsonField.of(role)) - - /** - * Sets [Builder.role] to an arbitrary JSON value. - * - * You should usually call [Builder.role] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - @Deprecated("deprecated") fun role(role: JsonField) = apply { this.role = role } - - /** The service tier for the interaction. */ - fun serviceTier(serviceTier: ServiceTier) = serviceTier(JsonField.of(serviceTier)) - - /** - * Sets [Builder.serviceTier] to an arbitrary JSON value. - * - * You should usually call [Builder.serviceTier] with a well-typed [ServiceTier] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun serviceTier(serviceTier: JsonField) = apply { - this.serviceTier = serviceTier - } - - /** Required. Output only. The status of the interaction. */ - fun status(status: Status) = status(JsonField.of(status)) - - /** - * Sets [Builder.status] to an arbitrary JSON value. - * - * You should usually call [Builder.status] with a well-typed [Status] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun status(status: JsonField) = apply { this.status = status } - - /** Input only. Whether to store the response and request for later retrieval. */ - fun store(store: Boolean) = store(JsonField.of(store)) - - /** - * Sets [Builder.store] to an arbitrary JSON value. - * - * You should usually call [Builder.store] with a well-typed [Boolean] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun store(store: JsonField) = apply { this.store = store } - - /** Input only. Whether the interaction will be streamed. */ - fun stream(stream: Boolean) = stream(JsonField.of(stream)) - - /** - * Sets [Builder.stream] to an arbitrary JSON value. - * - * You should usually call [Builder.stream] with a well-typed [Boolean] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun stream(stream: JsonField) = apply { this.stream = stream } - - /** System instruction for the interaction. */ - fun systemInstruction(systemInstruction: String) = - systemInstruction(JsonField.of(systemInstruction)) - - /** - * Sets [Builder.systemInstruction] to an arbitrary JSON value. - * - * You should usually call [Builder.systemInstruction] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun systemInstruction(systemInstruction: JsonField) = apply { - this.systemInstruction = systemInstruction - } - - /** A list of tool declarations the model may call during interaction. */ - fun tools(tools: List) = tools(JsonField.of(tools)) - - /** - * Sets [Builder.tools] to an arbitrary JSON value. - * - * You should usually call [Builder.tools] with a well-typed `List` value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun tools(tools: JsonField>) = apply { - this.tools = tools.map { it.toMutableList() } - } - - /** - * Adds a single [Tool] to [tools]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addTool(tool: Tool) = apply { - tools = - (tools ?: JsonField.of(mutableListOf())).also { checkKnown("tools", it).add(tool) } - } - - /** Alias for calling [addTool] with `Tool.ofFunction(function)`. */ - fun addTool(function: Function) = addTool(Tool.ofFunction(function)) - - /** Alias for calling [addTool] with `Tool.ofCodeExecution()`. */ - fun addToolCodeExecution() = addTool(Tool.ofCodeExecution()) - - /** Alias for calling [addTool] with `Tool.ofUrlContext()`. */ - fun addToolUrlContext() = addTool(Tool.ofUrlContext()) - - /** Alias for calling [addTool] with `Tool.ofComputerUse(computerUse)`. */ - fun addTool(computerUse: Tool.ComputerUse) = addTool(Tool.ofComputerUse(computerUse)) - - /** Alias for calling [addTool] with `Tool.ofMcpServer(mcpServer)`. */ - fun addTool(mcpServer: Tool.McpServer) = addTool(Tool.ofMcpServer(mcpServer)) - - /** Alias for calling [addTool] with `Tool.ofGoogleSearch(googleSearch)`. */ - fun addTool(googleSearch: Tool.GoogleSearch) = addTool(Tool.ofGoogleSearch(googleSearch)) - - /** Alias for calling [addTool] with `Tool.ofFileSearch(fileSearch)`. */ - fun addTool(fileSearch: Tool.FileSearch) = addTool(Tool.ofFileSearch(fileSearch)) - - /** Alias for calling [addTool] with `Tool.ofGoogleMaps(googleMaps)`. */ - fun addTool(googleMaps: Tool.GoogleMaps) = addTool(Tool.ofGoogleMaps(googleMaps)) - - /** Alias for calling [addTool] with `Tool.ofRetrieval(retrieval)`. */ - fun addTool(retrieval: Tool.Retrieval) = addTool(Tool.ofRetrieval(retrieval)) - - /** - * Required. Output only. The time at which the response was last updated in ISO 8601 format - * (YYYY-MM-DDThh:mm:ssZ). - */ - fun updated(updated: OffsetDateTime) = updated(JsonField.of(updated)) - - /** - * Sets [Builder.updated] to an arbitrary JSON value. - * - * You should usually call [Builder.updated] with a well-typed [OffsetDateTime] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun updated(updated: JsonField) = apply { this.updated = updated } - - /** Output only. Statistics on the interaction request's token usage. */ - fun usage(usage: Usage) = usage(JsonField.of(usage)) - - /** - * Sets [Builder.usage] to an arbitrary JSON value. - * - * You should usually call [Builder.usage] with a well-typed [Usage] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun usage(usage: JsonField) = apply { this.usage = usage } - - /** - * Optional. Webhook configuration for receiving notifications when the interaction - * completes. - */ - fun webhookConfig(webhookConfig: WebhookConfig) = webhookConfig(JsonField.of(webhookConfig)) - - /** - * Sets [Builder.webhookConfig] to an arbitrary JSON value. - * - * You should usually call [Builder.webhookConfig] with a well-typed [WebhookConfig] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun webhookConfig(webhookConfig: JsonField) = apply { - this.webhookConfig = webhookConfig - } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [CreateAgentInteractionParams]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .agent() - * .input() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): CreateAgentInteractionParams = - CreateAgentInteractionParams( - checkRequired("agent", agent), - checkRequired("input", input), - id, - agentConfig, - background, - created, - previousInteractionId, - responseFormat, - responseMimeType, - (responseModalities ?: JsonMissing.of()).map { it.toImmutable() }, - role, - serviceTier, - status, - store, - stream, - systemInstruction, - (tools ?: JsonMissing.of()).map { it.toImmutable() }, - updated, - usage, - webhookConfig, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): CreateAgentInteractionParams = apply { - if (validated) { - return@apply - } - - agent() - input().validate() - id() - agentConfig().ifPresent { it.validate() } - background() - created() - previousInteractionId() - responseFormat().ifPresent { it.validate() } - responseMimeType() - responseModalities().ifPresent { it.forEach { it.validate() } } - role() - serviceTier().ifPresent { it.validate() } - status().ifPresent { it.validate() } - store() - stream() - systemInstruction() - tools().ifPresent { it.forEach { it.validate() } } - updated() - usage().ifPresent { it.validate() } - webhookConfig().ifPresent { it.validate() } - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - (if (agent.asKnown().isPresent) 1 else 0) + - (input.asKnown().getOrNull()?.validity() ?: 0) + - (if (id.asKnown().isPresent) 1 else 0) + - (agentConfig.asKnown().getOrNull()?.validity() ?: 0) + - (if (background.asKnown().isPresent) 1 else 0) + - (if (created.asKnown().isPresent) 1 else 0) + - (if (previousInteractionId.asKnown().isPresent) 1 else 0) + - (responseFormat.asKnown().getOrNull()?.validity() ?: 0) + - (if (responseMimeType.asKnown().isPresent) 1 else 0) + - (responseModalities.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + - (if (role.asKnown().isPresent) 1 else 0) + - (serviceTier.asKnown().getOrNull()?.validity() ?: 0) + - (status.asKnown().getOrNull()?.validity() ?: 0) + - (if (store.asKnown().isPresent) 1 else 0) + - (if (stream.asKnown().isPresent) 1 else 0) + - (if (systemInstruction.asKnown().isPresent) 1 else 0) + - (tools.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + - (if (updated.asKnown().isPresent) 1 else 0) + - (usage.asKnown().getOrNull()?.validity() ?: 0) + - (webhookConfig.asKnown().getOrNull()?.validity() ?: 0) - - /** The name of the `Agent` used for generating the interaction. */ - class Agent @JsonCreator private constructor(private val value: JsonField) : Enum { - - /** - * Returns this class instance's raw value. - * - * This is usually only useful if this instance was deserialized from data that doesn't - * match any known member, and you want to know that value. For example, if the SDK is on an - * older version than the API, then the API may respond with new members that the SDK is - * unaware of. - */ - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - companion object { - - /** Gemini Deep Research Agent */ - @JvmField - val DEEP_RESEARCH_PRO_PREVIEW_12_2025 = of("deep-research-pro-preview-12-2025") - - /** Gemini Deep Research Agent */ - @JvmField val DEEP_RESEARCH_PREVIEW_04_2026 = of("deep-research-preview-04-2026") - - /** Gemini Deep Research Max Agent */ - @JvmField - val DEEP_RESEARCH_MAX_PREVIEW_04_2026 = of("deep-research-max-preview-04-2026") - - @JvmStatic fun of(value: String) = Agent(JsonField.of(value)) - } - - /** An enum containing [Agent]'s known values. */ - enum class Known { - /** Gemini Deep Research Agent */ - DEEP_RESEARCH_PRO_PREVIEW_12_2025, - /** Gemini Deep Research Agent */ - DEEP_RESEARCH_PREVIEW_04_2026, - /** Gemini Deep Research Max Agent */ - DEEP_RESEARCH_MAX_PREVIEW_04_2026, - } - - /** - * An enum containing [Agent]'s known values, as well as an [_UNKNOWN] member. - * - * An instance of [Agent] can contain an unknown value in a couple of cases: - * - It was deserialized from data that doesn't match any known member. For example, if the - * SDK is on an older version than the API, then the API may respond with new members that - * the SDK is unaware of. - * - It was constructed with an arbitrary value using the [of] method. - */ - enum class Value { - /** Gemini Deep Research Agent */ - DEEP_RESEARCH_PRO_PREVIEW_12_2025, - /** Gemini Deep Research Agent */ - DEEP_RESEARCH_PREVIEW_04_2026, - /** Gemini Deep Research Max Agent */ - DEEP_RESEARCH_MAX_PREVIEW_04_2026, - /** An enum member indicating that [Agent] was instantiated with an unknown value. */ - _UNKNOWN, - } - - /** - * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] - * if the class was instantiated with an unknown value. - * - * Use the [known] method instead if you're certain the value is always known or if you want - * to throw for the unknown case. - */ - fun value(): Value = - when (this) { - DEEP_RESEARCH_PRO_PREVIEW_12_2025 -> Value.DEEP_RESEARCH_PRO_PREVIEW_12_2025 - DEEP_RESEARCH_PREVIEW_04_2026 -> Value.DEEP_RESEARCH_PREVIEW_04_2026 - DEEP_RESEARCH_MAX_PREVIEW_04_2026 -> Value.DEEP_RESEARCH_MAX_PREVIEW_04_2026 - else -> Value._UNKNOWN - } - - /** - * Returns an enum member corresponding to this class instance's value. - * - * Use the [value] method instead if you're uncertain the value is always known and don't - * want to throw for the unknown case. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value is a not a - * known member. - */ - fun known(): Known = - when (this) { - DEEP_RESEARCH_PRO_PREVIEW_12_2025 -> Known.DEEP_RESEARCH_PRO_PREVIEW_12_2025 - DEEP_RESEARCH_PREVIEW_04_2026 -> Known.DEEP_RESEARCH_PREVIEW_04_2026 - DEEP_RESEARCH_MAX_PREVIEW_04_2026 -> Known.DEEP_RESEARCH_MAX_PREVIEW_04_2026 - else -> throw GeminiNextGenApiInvalidDataException("Unknown Agent: $value") - } - - /** - * Returns this class instance's primitive wire representation. - * - * This differs from the [toString] method because that method is primarily for debugging - * and generally doesn't throw. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value does not have - * the expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - GeminiNextGenApiInvalidDataException("Value is not a String") - } - - private var validated: Boolean = false - - fun validate(): Agent = apply { - if (validated) { - return@apply - } - - known() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Agent && value == other.value - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - /** The input for the interaction. */ - @JsonDeserialize(using = Input.Deserializer::class) - @JsonSerialize(using = Input.Serializer::class) - class Input - private constructor( - private val string: String? = null, - private val stepList: List? = null, - private val contentList: List? = null, - private val textContent: TextContent? = null, - private val imageContent: ImageContent? = null, - private val audioContent: AudioContent? = null, - private val documentContent: DocumentContent? = null, - private val videoContent: VideoContent? = null, - private val _json: JsonValue? = null, - ) { - - fun string(): Optional = Optional.ofNullable(string) - - fun stepList(): Optional> = Optional.ofNullable(stepList) - - fun contentList(): Optional> = Optional.ofNullable(contentList) - - /** A text content block. */ - fun textContent(): Optional = Optional.ofNullable(textContent) - - /** An image content block. */ - fun imageContent(): Optional = Optional.ofNullable(imageContent) - - /** An audio content block. */ - fun audioContent(): Optional = Optional.ofNullable(audioContent) - - /** A document content block. */ - fun documentContent(): Optional = Optional.ofNullable(documentContent) - - /** A video content block. */ - fun videoContent(): Optional = Optional.ofNullable(videoContent) - - fun isString(): Boolean = string != null - - fun isStepList(): Boolean = stepList != null - - fun isContentList(): Boolean = contentList != null - - fun isTextContent(): Boolean = textContent != null - - fun isImageContent(): Boolean = imageContent != null - - fun isAudioContent(): Boolean = audioContent != null - - fun isDocumentContent(): Boolean = documentContent != null - - fun isVideoContent(): Boolean = videoContent != null - - fun asString(): String = string.getOrThrow("string") - - fun asStepList(): List = stepList.getOrThrow("stepList") - - fun asContentList(): List = contentList.getOrThrow("contentList") - - /** A text content block. */ - fun asTextContent(): TextContent = textContent.getOrThrow("textContent") - - /** An image content block. */ - fun asImageContent(): ImageContent = imageContent.getOrThrow("imageContent") - - /** An audio content block. */ - fun asAudioContent(): AudioContent = audioContent.getOrThrow("audioContent") - - /** A document content block. */ - fun asDocumentContent(): DocumentContent = documentContent.getOrThrow("documentContent") - - /** A video content block. */ - fun asVideoContent(): VideoContent = videoContent.getOrThrow("videoContent") - - fun _json(): Optional = Optional.ofNullable(_json) - - fun accept(visitor: Visitor): T = - when { - string != null -> visitor.visitString(string) - stepList != null -> visitor.visitStepList(stepList) - contentList != null -> visitor.visitContentList(contentList) - textContent != null -> visitor.visitTextContent(textContent) - imageContent != null -> visitor.visitImageContent(imageContent) - audioContent != null -> visitor.visitAudioContent(audioContent) - documentContent != null -> visitor.visitDocumentContent(documentContent) - videoContent != null -> visitor.visitVideoContent(videoContent) - else -> visitor.unknown(_json) - } - - private var validated: Boolean = false - - fun validate(): Input = apply { - if (validated) { - return@apply - } - - accept( - object : Visitor { - override fun visitString(string: String) {} - - override fun visitStepList(stepList: List) { - stepList.forEach { it.validate() } - } - - override fun visitContentList(contentList: List) { - contentList.forEach { it.validate() } - } - - override fun visitTextContent(textContent: TextContent) { - textContent.validate() - } - - override fun visitImageContent(imageContent: ImageContent) { - imageContent.validate() - } - - override fun visitAudioContent(audioContent: AudioContent) { - audioContent.validate() - } - - override fun visitDocumentContent(documentContent: DocumentContent) { - documentContent.validate() - } - - override fun visitVideoContent(videoContent: VideoContent) { - videoContent.validate() - } - } - ) - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - accept( - object : Visitor { - override fun visitString(string: String) = 1 - - override fun visitStepList(stepList: List) = - stepList.sumOf { it.validity().toInt() } - - override fun visitContentList(contentList: List) = - contentList.sumOf { it.validity().toInt() } - - override fun visitTextContent(textContent: TextContent) = textContent.validity() - - override fun visitImageContent(imageContent: ImageContent) = - imageContent.validity() - - override fun visitAudioContent(audioContent: AudioContent) = - audioContent.validity() - - override fun visitDocumentContent(documentContent: DocumentContent) = - documentContent.validity() - - override fun visitVideoContent(videoContent: VideoContent) = - videoContent.validity() - - override fun unknown(json: JsonValue?) = 0 - } - ) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Input && - string == other.string && - stepList == other.stepList && - contentList == other.contentList && - textContent == other.textContent && - imageContent == other.imageContent && - audioContent == other.audioContent && - documentContent == other.documentContent && - videoContent == other.videoContent - } - - override fun hashCode(): Int = - Objects.hash( - string, - stepList, - contentList, - textContent, - imageContent, - audioContent, - documentContent, - videoContent, - ) - - override fun toString(): String = - when { - string != null -> "Input{string=$string}" - stepList != null -> "Input{stepList=$stepList}" - contentList != null -> "Input{contentList=$contentList}" - textContent != null -> "Input{textContent=$textContent}" - imageContent != null -> "Input{imageContent=$imageContent}" - audioContent != null -> "Input{audioContent=$audioContent}" - documentContent != null -> "Input{documentContent=$documentContent}" - videoContent != null -> "Input{videoContent=$videoContent}" - _json != null -> "Input{_unknown=$_json}" - else -> throw IllegalStateException("Invalid Input") - } - - companion object { - - @JvmStatic fun ofString(string: String) = Input(string = string) - - @JvmStatic - fun ofStepList(stepList: List) = Input(stepList = stepList.toImmutable()) - - @JvmStatic - fun ofContentList(contentList: List) = - Input(contentList = contentList.toImmutable()) - - /** A text content block. */ - @JvmStatic - fun ofTextContent(textContent: TextContent) = Input(textContent = textContent) - - /** An image content block. */ - @JvmStatic - fun ofImageContent(imageContent: ImageContent) = Input(imageContent = imageContent) - - /** An audio content block. */ - @JvmStatic - fun ofAudioContent(audioContent: AudioContent) = Input(audioContent = audioContent) - - /** A document content block. */ - @JvmStatic - fun ofDocumentContent(documentContent: DocumentContent) = - Input(documentContent = documentContent) - - /** A video content block. */ - @JvmStatic - fun ofVideoContent(videoContent: VideoContent) = Input(videoContent = videoContent) - } - - /** An interface that defines how to map each variant of [Input] to a value of type [T]. */ - interface Visitor { - - fun visitString(string: String): T - - fun visitStepList(stepList: List): T - - fun visitContentList(contentList: List): T - - /** A text content block. */ - fun visitTextContent(textContent: TextContent): T - - /** An image content block. */ - fun visitImageContent(imageContent: ImageContent): T - - /** An audio content block. */ - fun visitAudioContent(audioContent: AudioContent): T - - /** A document content block. */ - fun visitDocumentContent(documentContent: DocumentContent): T - - /** A video content block. */ - fun visitVideoContent(videoContent: VideoContent): T - - /** - * Maps an unknown variant of [Input] to a value of type [T]. - * - * An instance of [Input] can contain an unknown variant if it was deserialized from - * data that doesn't match any known variant. For example, if the SDK is on an older - * version than the API, then the API may respond with new variants that the SDK is - * unaware of. - * - * @throws GeminiNextGenApiInvalidDataException in the default implementation. - */ - fun unknown(json: JsonValue?): T { - throw GeminiNextGenApiInvalidDataException("Unknown Input: $json") - } - } - - internal class Deserializer : BaseDeserializer(Input::class) { - - override fun ObjectCodec.deserialize(node: JsonNode): Input { - val json = JsonValue.fromJsonNode(node) - - val bestMatches = - sequenceOf( - tryDeserialize(node, jacksonTypeRef())?.let { - Input(textContent = it, _json = json) - }, - tryDeserialize(node, jacksonTypeRef())?.let { - Input(imageContent = it, _json = json) - }, - tryDeserialize(node, jacksonTypeRef())?.let { - Input(audioContent = it, _json = json) - }, - tryDeserialize(node, jacksonTypeRef())?.let { - Input(documentContent = it, _json = json) - }, - tryDeserialize(node, jacksonTypeRef())?.let { - Input(videoContent = it, _json = json) - }, - tryDeserialize(node, jacksonTypeRef())?.let { - Input(string = it, _json = json) - }, - tryDeserialize(node, jacksonTypeRef>())?.let { - Input(stepList = it, _json = json) - }, - tryDeserialize(node, jacksonTypeRef>())?.let { - Input(contentList = it, _json = json) - }, - ) - .filterNotNull() - .allMaxBy { it.validity() } - .toList() - return when (bestMatches.size) { - // This can happen if what we're deserializing is completely incompatible with - // all the possible variants (e.g. deserializing from boolean). - 0 -> Input(_json = json) - 1 -> bestMatches.single() - // If there's more than one match with the highest validity, then use the first - // completely valid match, or simply the first match if none are completely - // valid. - else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() - } - } - } - - internal class Serializer : BaseSerializer(Input::class) { - - override fun serialize( - value: Input, - generator: JsonGenerator, - provider: SerializerProvider, - ) { - when { - value.string != null -> generator.writeObject(value.string) - value.stepList != null -> generator.writeObject(value.stepList) - value.contentList != null -> generator.writeObject(value.contentList) - value.textContent != null -> generator.writeObject(value.textContent) - value.imageContent != null -> generator.writeObject(value.imageContent) - value.audioContent != null -> generator.writeObject(value.audioContent) - value.documentContent != null -> generator.writeObject(value.documentContent) - value.videoContent != null -> generator.writeObject(value.videoContent) - value._json != null -> generator.writeObject(value._json) - else -> throw IllegalStateException("Invalid Input") - } - } - } - } - - /** Configuration parameters for the agent interaction. */ - @JsonDeserialize(using = AgentConfig.Deserializer::class) - @JsonSerialize(using = AgentConfig.Serializer::class) - class AgentConfig - private constructor( - private val dynamic: DynamicAgentConfig? = null, - private val deepResearch: DeepResearchAgentConfig? = null, - private val _json: JsonValue? = null, - ) { - - /** Configuration for dynamic agents. */ - fun dynamic(): Optional = Optional.ofNullable(dynamic) - - /** Configuration for the Deep Research agent. */ - fun deepResearch(): Optional = Optional.ofNullable(deepResearch) - - fun isDynamic(): Boolean = dynamic != null - - fun isDeepResearch(): Boolean = deepResearch != null - - /** Configuration for dynamic agents. */ - fun asDynamic(): DynamicAgentConfig = dynamic.getOrThrow("dynamic") - - /** Configuration for the Deep Research agent. */ - fun asDeepResearch(): DeepResearchAgentConfig = deepResearch.getOrThrow("deepResearch") - - fun _json(): Optional = Optional.ofNullable(_json) - - fun accept(visitor: Visitor): T = - when { - dynamic != null -> visitor.visitDynamic(dynamic) - deepResearch != null -> visitor.visitDeepResearch(deepResearch) - else -> visitor.unknown(_json) - } - - private var validated: Boolean = false - - fun validate(): AgentConfig = apply { - if (validated) { - return@apply - } - - accept( - object : Visitor { - override fun visitDynamic(dynamic: DynamicAgentConfig) { - dynamic.validate() - } - - override fun visitDeepResearch(deepResearch: DeepResearchAgentConfig) { - deepResearch.validate() - } - } - ) - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - accept( - object : Visitor { - override fun visitDynamic(dynamic: DynamicAgentConfig) = dynamic.validity() - - override fun visitDeepResearch(deepResearch: DeepResearchAgentConfig) = - deepResearch.validity() - - override fun unknown(json: JsonValue?) = 0 - } - ) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is AgentConfig && - dynamic == other.dynamic && - deepResearch == other.deepResearch - } - - override fun hashCode(): Int = Objects.hash(dynamic, deepResearch) - - override fun toString(): String = - when { - dynamic != null -> "AgentConfig{dynamic=$dynamic}" - deepResearch != null -> "AgentConfig{deepResearch=$deepResearch}" - _json != null -> "AgentConfig{_unknown=$_json}" - else -> throw IllegalStateException("Invalid AgentConfig") - } - - companion object { - - /** Configuration for dynamic agents. */ - @JvmStatic fun ofDynamic(dynamic: DynamicAgentConfig) = AgentConfig(dynamic = dynamic) - - /** Configuration for the Deep Research agent. */ - @JvmStatic - fun ofDeepResearch(deepResearch: DeepResearchAgentConfig) = - AgentConfig(deepResearch = deepResearch) - } - - /** - * An interface that defines how to map each variant of [AgentConfig] to a value of type - * [T]. - */ - interface Visitor { - - /** Configuration for dynamic agents. */ - fun visitDynamic(dynamic: DynamicAgentConfig): T - - /** Configuration for the Deep Research agent. */ - fun visitDeepResearch(deepResearch: DeepResearchAgentConfig): T - - /** - * Maps an unknown variant of [AgentConfig] to a value of type [T]. - * - * An instance of [AgentConfig] can contain an unknown variant if it was deserialized - * from data that doesn't match any known variant. For example, if the SDK is on an - * older version than the API, then the API may respond with new variants that the SDK - * is unaware of. - * - * @throws GeminiNextGenApiInvalidDataException in the default implementation. - */ - fun unknown(json: JsonValue?): T { - throw GeminiNextGenApiInvalidDataException("Unknown AgentConfig: $json") - } - } - - internal class Deserializer : BaseDeserializer(AgentConfig::class) { - - override fun ObjectCodec.deserialize(node: JsonNode): AgentConfig { - val json = JsonValue.fromJsonNode(node) - val type = json.asObject().getOrNull()?.get("type")?.asString()?.getOrNull() - - when (type) { - "dynamic" -> { - return tryDeserialize(node, jacksonTypeRef())?.let { - AgentConfig(dynamic = it, _json = json) - } ?: AgentConfig(_json = json) - } - "deep-research" -> { - return tryDeserialize(node, jacksonTypeRef()) - ?.let { AgentConfig(deepResearch = it, _json = json) } - ?: AgentConfig(_json = json) - } - } - - return AgentConfig(_json = json) - } - } - - internal class Serializer : BaseSerializer(AgentConfig::class) { - - override fun serialize( - value: AgentConfig, - generator: JsonGenerator, - provider: SerializerProvider, - ) { - when { - value.dynamic != null -> generator.writeObject(value.dynamic) - value.deepResearch != null -> generator.writeObject(value.deepResearch) - value._json != null -> generator.writeObject(value._json) - else -> throw IllegalStateException("Invalid AgentConfig") - } - } - } - } - - /** - * Enforces that the generated response is a JSON object that complies with the JSON schema - * specified in this field. - */ - @JsonDeserialize(using = ResponseFormat.Deserializer::class) - @JsonSerialize(using = ResponseFormat.Serializer::class) - class ResponseFormat - private constructor( - private val list: List? = null, - private val audio: AudioResponseFormat? = null, - private val text: TextResponseFormat? = null, - private val image: ImageResponseFormat? = null, - private val jsonValue: JsonValue? = null, - private val _json: JsonValue? = null, - ) { - - fun list(): Optional> = Optional.ofNullable(list) - - /** Configuration for audio output format. */ - fun audio(): Optional = Optional.ofNullable(audio) - - /** Configuration for text output format. */ - fun text(): Optional = Optional.ofNullable(text) - - /** Configuration for image output format. */ - fun image(): Optional = Optional.ofNullable(image) - - fun jsonValue(): Optional = Optional.ofNullable(jsonValue) - - fun isList(): Boolean = list != null - - fun isAudio(): Boolean = audio != null - - fun isText(): Boolean = text != null - - fun isImage(): Boolean = image != null - - fun isJsonValue(): Boolean = jsonValue != null - - fun asList(): List = list.getOrThrow("list") - - /** Configuration for audio output format. */ - fun asAudio(): AudioResponseFormat = audio.getOrThrow("audio") - - /** Configuration for text output format. */ - fun asText(): TextResponseFormat = text.getOrThrow("text") - - /** Configuration for image output format. */ - fun asImage(): ImageResponseFormat = image.getOrThrow("image") - - fun asJsonValue(): JsonValue = jsonValue.getOrThrow("jsonValue") - - fun _json(): Optional = Optional.ofNullable(_json) - - fun accept(visitor: Visitor): T = - when { - list != null -> visitor.visitList(list) - audio != null -> visitor.visitAudio(audio) - text != null -> visitor.visitText(text) - image != null -> visitor.visitImage(image) - jsonValue != null -> visitor.visitJsonValue(jsonValue) - else -> visitor.unknown(_json) - } - - private var validated: Boolean = false - - fun validate(): ResponseFormat = apply { - if (validated) { - return@apply - } - - accept( - object : Visitor { - override fun visitList(list: List) { - list.forEach { it.validate() } - } - - override fun visitAudio(audio: AudioResponseFormat) { - audio.validate() - } - - override fun visitText(text: TextResponseFormat) { - text.validate() - } - - override fun visitImage(image: ImageResponseFormat) { - image.validate() - } - - override fun visitJsonValue(jsonValue: JsonValue) {} - } - ) - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - accept( - object : Visitor { - override fun visitList(list: List) = - list.sumOf { it.validity().toInt() } - - override fun visitAudio(audio: AudioResponseFormat) = audio.validity() - - override fun visitText(text: TextResponseFormat) = text.validity() - - override fun visitImage(image: ImageResponseFormat) = image.validity() - - override fun visitJsonValue(jsonValue: JsonValue) = 1 - - override fun unknown(json: JsonValue?) = 0 - } - ) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is ResponseFormat && - list == other.list && - audio == other.audio && - text == other.text && - image == other.image && - jsonValue == other.jsonValue - } - - override fun hashCode(): Int = Objects.hash(list, audio, text, image, jsonValue) - - override fun toString(): String = - when { - list != null -> "ResponseFormat{list=$list}" - audio != null -> "ResponseFormat{audio=$audio}" - text != null -> "ResponseFormat{text=$text}" - image != null -> "ResponseFormat{image=$image}" - jsonValue != null -> "ResponseFormat{jsonValue=$jsonValue}" - _json != null -> "ResponseFormat{_unknown=$_json}" - else -> throw IllegalStateException("Invalid ResponseFormat") - } - - companion object { - - @JvmStatic - fun ofList(list: List) = ResponseFormat(list = list.toImmutable()) - - /** Configuration for audio output format. */ - @JvmStatic fun ofAudio(audio: AudioResponseFormat) = ResponseFormat(audio = audio) - - /** Configuration for text output format. */ - @JvmStatic fun ofText(text: TextResponseFormat) = ResponseFormat(text = text) - - /** Configuration for image output format. */ - @JvmStatic fun ofImage(image: ImageResponseFormat) = ResponseFormat(image = image) - - @JvmStatic fun ofJsonValue(jsonValue: JsonValue) = ResponseFormat(jsonValue = jsonValue) - } - - /** - * An interface that defines how to map each variant of [ResponseFormat] to a value of type - * [T]. - */ - interface Visitor { - - fun visitList(list: List): T - - /** Configuration for audio output format. */ - fun visitAudio(audio: AudioResponseFormat): T - - /** Configuration for text output format. */ - fun visitText(text: TextResponseFormat): T - - /** Configuration for image output format. */ - fun visitImage(image: ImageResponseFormat): T - - fun visitJsonValue(jsonValue: JsonValue): T - - /** - * Maps an unknown variant of [ResponseFormat] to a value of type [T]. - * - * An instance of [ResponseFormat] can contain an unknown variant if it was deserialized - * from data that doesn't match any known variant. For example, if the SDK is on an - * older version than the API, then the API may respond with new variants that the SDK - * is unaware of. - * - * @throws GeminiNextGenApiInvalidDataException in the default implementation. - */ - fun unknown(json: JsonValue?): T { - throw GeminiNextGenApiInvalidDataException("Unknown ResponseFormat: $json") - } - } - - internal class Deserializer : BaseDeserializer(ResponseFormat::class) { - - override fun ObjectCodec.deserialize(node: JsonNode): ResponseFormat { - val json = JsonValue.fromJsonNode(node) - - val bestMatches = - sequenceOf( - tryDeserialize(node, jacksonTypeRef())?.let { - ResponseFormat(audio = it, _json = json) - }, - tryDeserialize(node, jacksonTypeRef())?.let { - ResponseFormat(text = it, _json = json) - }, - tryDeserialize(node, jacksonTypeRef())?.let { - ResponseFormat(image = it, _json = json) - }, - tryDeserialize(node, jacksonTypeRef>())?.let { - ResponseFormat(list = it, _json = json) - }, - tryDeserialize(node, jacksonTypeRef())?.let { - ResponseFormat(jsonValue = it, _json = json) - }, - ) - .filterNotNull() - .allMaxBy { it.validity() } - .toList() - return when (bestMatches.size) { - // This can happen if what we're deserializing is completely incompatible with - // all the possible variants. - 0 -> ResponseFormat(_json = json) - 1 -> bestMatches.single() - // If there's more than one match with the highest validity, then use the first - // completely valid match, or simply the first match if none are completely - // valid. - else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() - } - } - } - - internal class Serializer : BaseSerializer(ResponseFormat::class) { - - override fun serialize( - value: ResponseFormat, - generator: JsonGenerator, - provider: SerializerProvider, - ) { - when { - value.list != null -> generator.writeObject(value.list) - value.audio != null -> generator.writeObject(value.audio) - value.text != null -> generator.writeObject(value.text) - value.image != null -> generator.writeObject(value.image) - value.jsonValue != null -> generator.writeObject(value.jsonValue) - value._json != null -> generator.writeObject(value._json) - else -> throw IllegalStateException("Invalid ResponseFormat") - } - } - } - - /** Configuration for audio output format. */ - @JsonDeserialize(using = InnerResponseFormat.Deserializer::class) - @JsonSerialize(using = InnerResponseFormat.Serializer::class) - class InnerResponseFormat - private constructor( - private val audio: AudioResponseFormat? = null, - private val text: TextResponseFormat? = null, - private val image: ImageResponseFormat? = null, - private val jsonValue: JsonValue? = null, - private val _json: JsonValue? = null, - ) { - - /** Configuration for audio output format. */ - fun audio(): Optional = Optional.ofNullable(audio) - - /** Configuration for text output format. */ - fun text(): Optional = Optional.ofNullable(text) - - /** Configuration for image output format. */ - fun image(): Optional = Optional.ofNullable(image) - - fun jsonValue(): Optional = Optional.ofNullable(jsonValue) - - fun isAudio(): Boolean = audio != null - - fun isText(): Boolean = text != null - - fun isImage(): Boolean = image != null - - fun isJsonValue(): Boolean = jsonValue != null - - /** Configuration for audio output format. */ - fun asAudio(): AudioResponseFormat = audio.getOrThrow("audio") - - /** Configuration for text output format. */ - fun asText(): TextResponseFormat = text.getOrThrow("text") - - /** Configuration for image output format. */ - fun asImage(): ImageResponseFormat = image.getOrThrow("image") - - fun asJsonValue(): JsonValue = jsonValue.getOrThrow("jsonValue") - - fun _json(): Optional = Optional.ofNullable(_json) - - fun accept(visitor: Visitor): T = - when { - audio != null -> visitor.visitAudio(audio) - text != null -> visitor.visitText(text) - image != null -> visitor.visitImage(image) - jsonValue != null -> visitor.visitJsonValue(jsonValue) - else -> visitor.unknown(_json) - } - - private var validated: Boolean = false - - fun validate(): InnerResponseFormat = apply { - if (validated) { - return@apply - } - - accept( - object : Visitor { - override fun visitAudio(audio: AudioResponseFormat) { - audio.validate() - } - - override fun visitText(text: TextResponseFormat) { - text.validate() - } - - override fun visitImage(image: ImageResponseFormat) { - image.validate() - } - - override fun visitJsonValue(jsonValue: JsonValue) {} - } - ) - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - accept( - object : Visitor { - override fun visitAudio(audio: AudioResponseFormat) = audio.validity() - - override fun visitText(text: TextResponseFormat) = text.validity() - - override fun visitImage(image: ImageResponseFormat) = image.validity() - - override fun visitJsonValue(jsonValue: JsonValue) = 1 - - override fun unknown(json: JsonValue?) = 0 - } - ) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is InnerResponseFormat && - audio == other.audio && - text == other.text && - image == other.image && - jsonValue == other.jsonValue - } - - override fun hashCode(): Int = Objects.hash(audio, text, image, jsonValue) - - override fun toString(): String = - when { - audio != null -> "InnerResponseFormat{audio=$audio}" - text != null -> "InnerResponseFormat{text=$text}" - image != null -> "InnerResponseFormat{image=$image}" - jsonValue != null -> "InnerResponseFormat{jsonValue=$jsonValue}" - _json != null -> "InnerResponseFormat{_unknown=$_json}" - else -> throw IllegalStateException("Invalid InnerResponseFormat") - } - - companion object { - - /** Configuration for audio output format. */ - @JvmStatic - fun ofAudio(audio: AudioResponseFormat) = InnerResponseFormat(audio = audio) - - /** Configuration for text output format. */ - @JvmStatic fun ofText(text: TextResponseFormat) = InnerResponseFormat(text = text) - - /** Configuration for image output format. */ - @JvmStatic - fun ofImage(image: ImageResponseFormat) = InnerResponseFormat(image = image) - - @JvmStatic - fun ofJsonValue(jsonValue: JsonValue) = InnerResponseFormat(jsonValue = jsonValue) - } - - /** - * An interface that defines how to map each variant of [InnerResponseFormat] to a value - * of type [T]. - */ - interface Visitor { - - /** Configuration for audio output format. */ - fun visitAudio(audio: AudioResponseFormat): T - - /** Configuration for text output format. */ - fun visitText(text: TextResponseFormat): T - - /** Configuration for image output format. */ - fun visitImage(image: ImageResponseFormat): T - - fun visitJsonValue(jsonValue: JsonValue): T - - /** - * Maps an unknown variant of [InnerResponseFormat] to a value of type [T]. - * - * An instance of [InnerResponseFormat] can contain an unknown variant if it was - * deserialized from data that doesn't match any known variant. For example, if the - * SDK is on an older version than the API, then the API may respond with new - * variants that the SDK is unaware of. - * - * @throws GeminiNextGenApiInvalidDataException in the default implementation. - */ - fun unknown(json: JsonValue?): T { - throw GeminiNextGenApiInvalidDataException("Unknown InnerResponseFormat: $json") - } - } - - internal class Deserializer : - BaseDeserializer(InnerResponseFormat::class) { - - override fun ObjectCodec.deserialize(node: JsonNode): InnerResponseFormat { - val json = JsonValue.fromJsonNode(node) - - val bestMatches = - sequenceOf( - tryDeserialize(node, jacksonTypeRef())?.let { - InnerResponseFormat(audio = it, _json = json) - }, - tryDeserialize(node, jacksonTypeRef())?.let { - InnerResponseFormat(text = it, _json = json) - }, - tryDeserialize(node, jacksonTypeRef())?.let { - InnerResponseFormat(image = it, _json = json) - }, - tryDeserialize(node, jacksonTypeRef())?.let { - InnerResponseFormat(jsonValue = it, _json = json) - }, - ) - .filterNotNull() - .allMaxBy { it.validity() } - .toList() - return when (bestMatches.size) { - // This can happen if what we're deserializing is completely incompatible - // with all the possible variants. - 0 -> InnerResponseFormat(_json = json) - 1 -> bestMatches.single() - // If there's more than one match with the highest validity, then use the - // first completely valid match, or simply the first match if none are - // completely valid. - else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() - } - } - } - - internal class Serializer : - BaseSerializer(InnerResponseFormat::class) { - - override fun serialize( - value: InnerResponseFormat, - generator: JsonGenerator, - provider: SerializerProvider, - ) { - when { - value.audio != null -> generator.writeObject(value.audio) - value.text != null -> generator.writeObject(value.text) - value.image != null -> generator.writeObject(value.image) - value.jsonValue != null -> generator.writeObject(value.jsonValue) - value._json != null -> generator.writeObject(value._json) - else -> throw IllegalStateException("Invalid InnerResponseFormat") - } - } - } - } - } - - class ResponseModality @JsonCreator private constructor(private val value: JsonField) : - Enum { - - /** - * Returns this class instance's raw value. - * - * This is usually only useful if this instance was deserialized from data that doesn't - * match any known member, and you want to know that value. For example, if the SDK is on an - * older version than the API, then the API may respond with new members that the SDK is - * unaware of. - */ - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - companion object { - - @JvmField val TEXT = of("text") - - @JvmField val IMAGE = of("image") - - @JvmField val AUDIO = of("audio") - - @JvmField val VIDEO = of("video") - - @JvmField val DOCUMENT = of("document") - - @JvmStatic fun of(value: String) = ResponseModality(JsonField.of(value)) - } - - /** An enum containing [ResponseModality]'s known values. */ - enum class Known { - TEXT, - IMAGE, - AUDIO, - VIDEO, - DOCUMENT, - } - - /** - * An enum containing [ResponseModality]'s known values, as well as an [_UNKNOWN] member. - * - * An instance of [ResponseModality] can contain an unknown value in a couple of cases: - * - It was deserialized from data that doesn't match any known member. For example, if the - * SDK is on an older version than the API, then the API may respond with new members that - * the SDK is unaware of. - * - It was constructed with an arbitrary value using the [of] method. - */ - enum class Value { - TEXT, - IMAGE, - AUDIO, - VIDEO, - DOCUMENT, - /** - * An enum member indicating that [ResponseModality] was instantiated with an unknown - * value. - */ - _UNKNOWN, - } - - /** - * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] - * if the class was instantiated with an unknown value. - * - * Use the [known] method instead if you're certain the value is always known or if you want - * to throw for the unknown case. - */ - fun value(): Value = - when (this) { - TEXT -> Value.TEXT - IMAGE -> Value.IMAGE - AUDIO -> Value.AUDIO - VIDEO -> Value.VIDEO - DOCUMENT -> Value.DOCUMENT - else -> Value._UNKNOWN - } - - /** - * Returns an enum member corresponding to this class instance's value. - * - * Use the [value] method instead if you're uncertain the value is always known and don't - * want to throw for the unknown case. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value is a not a - * known member. - */ - fun known(): Known = - when (this) { - TEXT -> Known.TEXT - IMAGE -> Known.IMAGE - AUDIO -> Known.AUDIO - VIDEO -> Known.VIDEO - DOCUMENT -> Known.DOCUMENT - else -> - throw GeminiNextGenApiInvalidDataException("Unknown ResponseModality: $value") - } - - /** - * Returns this class instance's primitive wire representation. - * - * This differs from the [toString] method because that method is primarily for debugging - * and generally doesn't throw. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value does not have - * the expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - GeminiNextGenApiInvalidDataException("Value is not a String") - } - - private var validated: Boolean = false - - fun validate(): ResponseModality = apply { - if (validated) { - return@apply - } - - known() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is ResponseModality && value == other.value - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - /** The service tier for the interaction. */ - class ServiceTier @JsonCreator private constructor(private val value: JsonField) : - Enum { - - /** - * Returns this class instance's raw value. - * - * This is usually only useful if this instance was deserialized from data that doesn't - * match any known member, and you want to know that value. For example, if the SDK is on an - * older version than the API, then the API may respond with new members that the SDK is - * unaware of. - */ - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - companion object { - - @JvmField val FLEX = of("flex") - - @JvmField val STANDARD = of("standard") - - @JvmField val PRIORITY = of("priority") - - @JvmStatic fun of(value: String) = ServiceTier(JsonField.of(value)) - } - - /** An enum containing [ServiceTier]'s known values. */ - enum class Known { - FLEX, - STANDARD, - PRIORITY, - } - - /** - * An enum containing [ServiceTier]'s known values, as well as an [_UNKNOWN] member. - * - * An instance of [ServiceTier] can contain an unknown value in a couple of cases: - * - It was deserialized from data that doesn't match any known member. For example, if the - * SDK is on an older version than the API, then the API may respond with new members that - * the SDK is unaware of. - * - It was constructed with an arbitrary value using the [of] method. - */ - enum class Value { - FLEX, - STANDARD, - PRIORITY, - /** - * An enum member indicating that [ServiceTier] was instantiated with an unknown value. - */ - _UNKNOWN, - } - - /** - * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] - * if the class was instantiated with an unknown value. - * - * Use the [known] method instead if you're certain the value is always known or if you want - * to throw for the unknown case. - */ - fun value(): Value = - when (this) { - FLEX -> Value.FLEX - STANDARD -> Value.STANDARD - PRIORITY -> Value.PRIORITY - else -> Value._UNKNOWN - } - - /** - * Returns an enum member corresponding to this class instance's value. - * - * Use the [value] method instead if you're uncertain the value is always known and don't - * want to throw for the unknown case. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value is a not a - * known member. - */ - fun known(): Known = - when (this) { - FLEX -> Known.FLEX - STANDARD -> Known.STANDARD - PRIORITY -> Known.PRIORITY - else -> throw GeminiNextGenApiInvalidDataException("Unknown ServiceTier: $value") - } - - /** - * Returns this class instance's primitive wire representation. - * - * This differs from the [toString] method because that method is primarily for debugging - * and generally doesn't throw. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value does not have - * the expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - GeminiNextGenApiInvalidDataException("Value is not a String") - } - - private var validated: Boolean = false - - fun validate(): ServiceTier = apply { - if (validated) { - return@apply - } - - known() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is ServiceTier && value == other.value - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - /** Required. Output only. The status of the interaction. */ - class Status @JsonCreator private constructor(private val value: JsonField) : Enum { - - /** - * Returns this class instance's raw value. - * - * This is usually only useful if this instance was deserialized from data that doesn't - * match any known member, and you want to know that value. For example, if the SDK is on an - * older version than the API, then the API may respond with new members that the SDK is - * unaware of. - */ - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - companion object { - - @JvmField val IN_PROGRESS = of("in_progress") - - @JvmField val REQUIRES_ACTION = of("requires_action") - - @JvmField val COMPLETED = of("completed") - - @JvmField val FAILED = of("failed") - - @JvmField val CANCELLED = of("cancelled") - - @JvmField val INCOMPLETE = of("incomplete") - - @JvmStatic fun of(value: String) = Status(JsonField.of(value)) - } - - /** An enum containing [Status]'s known values. */ - enum class Known { - IN_PROGRESS, - REQUIRES_ACTION, - COMPLETED, - FAILED, - CANCELLED, - INCOMPLETE, - } - - /** - * An enum containing [Status]'s known values, as well as an [_UNKNOWN] member. - * - * An instance of [Status] can contain an unknown value in a couple of cases: - * - It was deserialized from data that doesn't match any known member. For example, if the - * SDK is on an older version than the API, then the API may respond with new members that - * the SDK is unaware of. - * - It was constructed with an arbitrary value using the [of] method. - */ - enum class Value { - IN_PROGRESS, - REQUIRES_ACTION, - COMPLETED, - FAILED, - CANCELLED, - INCOMPLETE, - /** An enum member indicating that [Status] was instantiated with an unknown value. */ - _UNKNOWN, - } - - /** - * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] - * if the class was instantiated with an unknown value. - * - * Use the [known] method instead if you're certain the value is always known or if you want - * to throw for the unknown case. - */ - fun value(): Value = - when (this) { - IN_PROGRESS -> Value.IN_PROGRESS - REQUIRES_ACTION -> Value.REQUIRES_ACTION - COMPLETED -> Value.COMPLETED - FAILED -> Value.FAILED - CANCELLED -> Value.CANCELLED - INCOMPLETE -> Value.INCOMPLETE - else -> Value._UNKNOWN - } - - /** - * Returns an enum member corresponding to this class instance's value. - * - * Use the [value] method instead if you're uncertain the value is always known and don't - * want to throw for the unknown case. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value is a not a - * known member. - */ - fun known(): Known = - when (this) { - IN_PROGRESS -> Known.IN_PROGRESS - REQUIRES_ACTION -> Known.REQUIRES_ACTION - COMPLETED -> Known.COMPLETED - FAILED -> Known.FAILED - CANCELLED -> Known.CANCELLED - INCOMPLETE -> Known.INCOMPLETE - else -> throw GeminiNextGenApiInvalidDataException("Unknown Status: $value") - } - - /** - * Returns this class instance's primitive wire representation. - * - * This differs from the [toString] method because that method is primarily for debugging - * and generally doesn't throw. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value does not have - * the expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - GeminiNextGenApiInvalidDataException("Value is not a String") - } - - private var validated: Boolean = false - - fun validate(): Status = apply { - if (validated) { - return@apply - } - - known() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Status && value == other.value - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - /** Message for configuring webhook events for a request. */ - class WebhookConfig - @JsonCreator(mode = JsonCreator.Mode.DISABLED) - private constructor( - private val uris: JsonField>, - private val userMetadata: JsonField, - private val additionalProperties: MutableMap, - ) { - - @JsonCreator - private constructor( - @JsonProperty("uris") @ExcludeMissing uris: JsonField> = JsonMissing.of(), - @JsonProperty("user_metadata") - @ExcludeMissing - userMetadata: JsonField = JsonMissing.of(), - ) : this(uris, userMetadata, mutableMapOf()) - - /** - * Optional. If set, these webhook URIs will be used for webhook events instead of the - * registered webhooks. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type - * (e.g. if the server responded with an unexpected value). - */ - fun uris(): Optional> = uris.getOptional("uris") - - /** - * Optional. The user metadata that will be returned on each event emission to the webhooks. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type - * (e.g. if the server responded with an unexpected value). - */ - fun userMetadata(): Optional = userMetadata.getOptional("user_metadata") - - /** - * Returns the raw JSON value of [uris]. - * - * Unlike [uris], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("uris") @ExcludeMissing fun _uris(): JsonField> = uris - - /** - * Returns the raw JSON value of [userMetadata]. - * - * Unlike [userMetadata], this method doesn't throw if the JSON field has an unexpected - * type. - */ - @JsonProperty("user_metadata") - @ExcludeMissing - fun _userMetadata(): JsonField = userMetadata - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [WebhookConfig]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [WebhookConfig]. */ - class Builder internal constructor() { - - private var uris: JsonField>? = null - private var userMetadata: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(webhookConfig: WebhookConfig) = apply { - uris = webhookConfig.uris.map { it.toMutableList() } - userMetadata = webhookConfig.userMetadata - additionalProperties = webhookConfig.additionalProperties.toMutableMap() - } - - /** - * Optional. If set, these webhook URIs will be used for webhook events instead of the - * registered webhooks. - */ - fun uris(uris: List) = uris(JsonField.of(uris)) - - /** - * Sets [Builder.uris] to an arbitrary JSON value. - * - * You should usually call [Builder.uris] with a well-typed `List` value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun uris(uris: JsonField>) = apply { - this.uris = uris.map { it.toMutableList() } - } - - /** - * Adds a single [String] to [Builder.uris]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addUris(uris: String) = apply { - this.uris = - (this.uris ?: JsonField.of(mutableListOf())).also { - checkKnown("uris", it).add(uris) - } - } - - /** - * Optional. The user metadata that will be returned on each event emission to the - * webhooks. - */ - fun userMetadata(userMetadata: UserMetadata) = userMetadata(JsonField.of(userMetadata)) - - /** - * Sets [Builder.userMetadata] to an arbitrary JSON value. - * - * You should usually call [Builder.userMetadata] with a well-typed [UserMetadata] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun userMetadata(userMetadata: JsonField) = apply { - this.userMetadata = userMetadata - } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [WebhookConfig]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): WebhookConfig = - WebhookConfig( - (uris ?: JsonMissing.of()).map { it.toImmutable() }, - userMetadata, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): WebhookConfig = apply { - if (validated) { - return@apply - } - - uris() - userMetadata().ifPresent { it.validate() } - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - (uris.asKnown().getOrNull()?.size ?: 0) + - (userMetadata.asKnown().getOrNull()?.validity() ?: 0) - - /** - * Optional. The user metadata that will be returned on each event emission to the webhooks. - */ - class UserMetadata - @JsonCreator - private constructor( - @com.fasterxml.jackson.annotation.JsonValue - private val additionalProperties: Map - ) { - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [UserMetadata]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [UserMetadata]. */ - class Builder internal constructor() { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(userMetadata: UserMetadata) = apply { - additionalProperties = userMetadata.additionalProperties.toMutableMap() - } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = - apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { - additionalProperties.remove(key) - } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [UserMetadata]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): UserMetadata = UserMetadata(additionalProperties.toImmutable()) - } - - private var validated: Boolean = false - - fun validate(): UserMetadata = apply { - if (validated) { - return@apply - } - - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is UserMetadata && additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - - override fun hashCode(): Int = hashCode - - override fun toString() = "UserMetadata{additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is WebhookConfig && - uris == other.uris && - userMetadata == other.userMetadata && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { Objects.hash(uris, userMetadata, additionalProperties) } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "WebhookConfig{uris=$uris, userMetadata=$userMetadata, additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is CreateAgentInteractionParams && - agent == other.agent && - input == other.input && - id == other.id && - agentConfig == other.agentConfig && - background == other.background && - created == other.created && - previousInteractionId == other.previousInteractionId && - responseFormat == other.responseFormat && - responseMimeType == other.responseMimeType && - responseModalities == other.responseModalities && - role == other.role && - serviceTier == other.serviceTier && - status == other.status && - store == other.store && - stream == other.stream && - systemInstruction == other.systemInstruction && - tools == other.tools && - updated == other.updated && - usage == other.usage && - webhookConfig == other.webhookConfig && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { - Objects.hash( - agent, - input, - id, - agentConfig, - background, - created, - previousInteractionId, - responseFormat, - responseMimeType, - responseModalities, - role, - serviceTier, - status, - store, - stream, - systemInstruction, - tools, - updated, - usage, - webhookConfig, - additionalProperties, - ) - } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "CreateAgentInteractionParams{agent=$agent, input=$input, id=$id, agentConfig=$agentConfig, background=$background, created=$created, previousInteractionId=$previousInteractionId, responseFormat=$responseFormat, responseMimeType=$responseMimeType, responseModalities=$responseModalities, role=$role, serviceTier=$serviceTier, status=$status, store=$store, stream=$stream, systemInstruction=$systemInstruction, tools=$tools, updated=$updated, usage=$usage, webhookConfig=$webhookConfig, additionalProperties=$additionalProperties}" -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/CreateModelInteractionParams.kt b/src/main/java/com/google/genai/interactions/models/interactions/CreateModelInteractionParams.kt deleted file mode 100644 index 8c4b85da299..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/CreateModelInteractionParams.kt +++ /dev/null @@ -1,2729 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import com.fasterxml.jackson.core.JsonGenerator -import com.fasterxml.jackson.core.ObjectCodec -import com.fasterxml.jackson.databind.JsonNode -import com.fasterxml.jackson.databind.SerializerProvider -import com.fasterxml.jackson.databind.annotation.JsonDeserialize -import com.fasterxml.jackson.databind.annotation.JsonSerialize -import com.fasterxml.jackson.module.kotlin.jacksonTypeRef -import com.google.genai.interactions.core.BaseDeserializer -import com.google.genai.interactions.core.BaseSerializer -import com.google.genai.interactions.core.Enum -import com.google.genai.interactions.core.ExcludeMissing -import com.google.genai.interactions.core.JsonField -import com.google.genai.interactions.core.JsonMissing -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.core.allMaxBy -import com.google.genai.interactions.core.checkKnown -import com.google.genai.interactions.core.checkRequired -import com.google.genai.interactions.core.getOrThrow -import com.google.genai.interactions.core.toImmutable -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.time.OffsetDateTime -import java.util.Collections -import java.util.Objects -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -/** Parameters for creating model interactions */ -class CreateModelInteractionParams -@JsonCreator(mode = JsonCreator.Mode.DISABLED) -private constructor( - private val input: JsonField, - private val model: JsonField, - private val id: JsonField, - private val background: JsonField, - private val created: JsonField, - private val generationConfig: JsonField, - private val previousInteractionId: JsonField, - private val responseFormat: JsonField, - private val responseMimeType: JsonField, - private val responseModalities: JsonField>, - private val role: JsonField, - private val serviceTier: JsonField, - private val status: JsonField, - private val store: JsonField, - private val stream: JsonField, - private val systemInstruction: JsonField, - private val tools: JsonField>, - private val updated: JsonField, - private val usage: JsonField, - private val webhookConfig: JsonField, - private val additionalProperties: MutableMap, -) { - - @JsonCreator - private constructor( - @JsonProperty("input") @ExcludeMissing input: JsonField = JsonMissing.of(), - @JsonProperty("model") @ExcludeMissing model: JsonField = JsonMissing.of(), - @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), - @JsonProperty("background") - @ExcludeMissing - background: JsonField = JsonMissing.of(), - @JsonProperty("created") - @ExcludeMissing - created: JsonField = JsonMissing.of(), - @JsonProperty("generation_config") - @ExcludeMissing - generationConfig: JsonField = JsonMissing.of(), - @JsonProperty("previous_interaction_id") - @ExcludeMissing - previousInteractionId: JsonField = JsonMissing.of(), - @JsonProperty("response_format") - @ExcludeMissing - responseFormat: JsonField = JsonMissing.of(), - @JsonProperty("response_mime_type") - @ExcludeMissing - responseMimeType: JsonField = JsonMissing.of(), - @JsonProperty("response_modalities") - @ExcludeMissing - responseModalities: JsonField> = JsonMissing.of(), - @JsonProperty("role") @ExcludeMissing role: JsonField = JsonMissing.of(), - @JsonProperty("service_tier") - @ExcludeMissing - serviceTier: JsonField = JsonMissing.of(), - @JsonProperty("status") @ExcludeMissing status: JsonField = JsonMissing.of(), - @JsonProperty("store") @ExcludeMissing store: JsonField = JsonMissing.of(), - @JsonProperty("stream") @ExcludeMissing stream: JsonField = JsonMissing.of(), - @JsonProperty("system_instruction") - @ExcludeMissing - systemInstruction: JsonField = JsonMissing.of(), - @JsonProperty("tools") @ExcludeMissing tools: JsonField> = JsonMissing.of(), - @JsonProperty("updated") - @ExcludeMissing - updated: JsonField = JsonMissing.of(), - @JsonProperty("usage") @ExcludeMissing usage: JsonField = JsonMissing.of(), - @JsonProperty("webhook_config") - @ExcludeMissing - webhookConfig: JsonField = JsonMissing.of(), - ) : this( - input, - model, - id, - background, - created, - generationConfig, - previousInteractionId, - responseFormat, - responseMimeType, - responseModalities, - role, - serviceTier, - status, - store, - stream, - systemInstruction, - tools, - updated, - usage, - webhookConfig, - mutableMapOf(), - ) - - /** - * The input for the interaction. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). - */ - fun input(): Input = input.getRequired("input") - - /** - * The model that will complete your prompt.\n\nSee - * [models](https://ai.google.dev/gemini-api/docs/models) for additional details. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). - */ - fun model(): Model = model.getRequired("model") - - /** - * Required. Output only. A unique identifier for the interaction completion. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun id(): Optional = id.getOptional("id") - - /** - * Input only. Whether to run the model interaction in the background. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun background(): Optional = background.getOptional("background") - - /** - * Required. Output only. The time at which the response was created in ISO 8601 format - * (YYYY-MM-DDThh:mm:ssZ). - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun created(): Optional = created.getOptional("created") - - /** - * Input only. Configuration parameters for the model interaction. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun generationConfig(): Optional = - generationConfig.getOptional("generation_config") - - /** - * The ID of the previous interaction, if any. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun previousInteractionId(): Optional = - previousInteractionId.getOptional("previous_interaction_id") - - /** - * Enforces that the generated response is a JSON object that complies with the JSON schema - * specified in this field. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun responseFormat(): Optional = responseFormat.getOptional("response_format") - - /** - * The mime type of the response. This is required if response_format is set. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun responseMimeType(): Optional = responseMimeType.getOptional("response_mime_type") - - /** - * The requested modalities of the response (TEXT, IMAGE, AUDIO). - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun responseModalities(): Optional> = - responseModalities.getOptional("response_modalities") - - /** - * Output only. The role of the interaction. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - @Deprecated("deprecated") fun role(): Optional = role.getOptional("role") - - /** - * The service tier for the interaction. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun serviceTier(): Optional = serviceTier.getOptional("service_tier") - - /** - * Required. Output only. The status of the interaction. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun status(): Optional = status.getOptional("status") - - /** - * Input only. Whether to store the response and request for later retrieval. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun store(): Optional = store.getOptional("store") - - /** - * Input only. Whether the interaction will be streamed. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun stream(): Optional = stream.getOptional("stream") - - /** - * System instruction for the interaction. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun systemInstruction(): Optional = systemInstruction.getOptional("system_instruction") - - /** - * A list of tool declarations the model may call during interaction. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun tools(): Optional> = tools.getOptional("tools") - - /** - * Required. Output only. The time at which the response was last updated in ISO 8601 format - * (YYYY-MM-DDThh:mm:ssZ). - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun updated(): Optional = updated.getOptional("updated") - - /** - * Output only. Statistics on the interaction request's token usage. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun usage(): Optional = usage.getOptional("usage") - - /** - * Optional. Webhook configuration for receiving notifications when the interaction completes. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun webhookConfig(): Optional = webhookConfig.getOptional("webhook_config") - - /** - * Returns the raw JSON value of [input]. - * - * Unlike [input], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("input") @ExcludeMissing fun _input(): JsonField = input - - /** - * Returns the raw JSON value of [model]. - * - * Unlike [model], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("model") @ExcludeMissing fun _model(): JsonField = model - - /** - * Returns the raw JSON value of [id]. - * - * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id - - /** - * Returns the raw JSON value of [background]. - * - * Unlike [background], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("background") @ExcludeMissing fun _background(): JsonField = background - - /** - * Returns the raw JSON value of [created]. - * - * Unlike [created], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("created") @ExcludeMissing fun _created(): JsonField = created - - /** - * Returns the raw JSON value of [generationConfig]. - * - * Unlike [generationConfig], this method doesn't throw if the JSON field has an unexpected - * type. - */ - @JsonProperty("generation_config") - @ExcludeMissing - fun _generationConfig(): JsonField = generationConfig - - /** - * Returns the raw JSON value of [previousInteractionId]. - * - * Unlike [previousInteractionId], this method doesn't throw if the JSON field has an unexpected - * type. - */ - @JsonProperty("previous_interaction_id") - @ExcludeMissing - fun _previousInteractionId(): JsonField = previousInteractionId - - /** - * Returns the raw JSON value of [responseFormat]. - * - * Unlike [responseFormat], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("response_format") - @ExcludeMissing - fun _responseFormat(): JsonField = responseFormat - - /** - * Returns the raw JSON value of [responseMimeType]. - * - * Unlike [responseMimeType], this method doesn't throw if the JSON field has an unexpected - * type. - */ - @JsonProperty("response_mime_type") - @ExcludeMissing - fun _responseMimeType(): JsonField = responseMimeType - - /** - * Returns the raw JSON value of [responseModalities]. - * - * Unlike [responseModalities], this method doesn't throw if the JSON field has an unexpected - * type. - */ - @JsonProperty("response_modalities") - @ExcludeMissing - fun _responseModalities(): JsonField> = responseModalities - - /** - * Returns the raw JSON value of [role]. - * - * Unlike [role], this method doesn't throw if the JSON field has an unexpected type. - */ - @Deprecated("deprecated") - @JsonProperty("role") - @ExcludeMissing - fun _role(): JsonField = role - - /** - * Returns the raw JSON value of [serviceTier]. - * - * Unlike [serviceTier], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("service_tier") - @ExcludeMissing - fun _serviceTier(): JsonField = serviceTier - - /** - * Returns the raw JSON value of [status]. - * - * Unlike [status], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("status") @ExcludeMissing fun _status(): JsonField = status - - /** - * Returns the raw JSON value of [store]. - * - * Unlike [store], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("store") @ExcludeMissing fun _store(): JsonField = store - - /** - * Returns the raw JSON value of [stream]. - * - * Unlike [stream], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("stream") @ExcludeMissing fun _stream(): JsonField = stream - - /** - * Returns the raw JSON value of [systemInstruction]. - * - * Unlike [systemInstruction], this method doesn't throw if the JSON field has an unexpected - * type. - */ - @JsonProperty("system_instruction") - @ExcludeMissing - fun _systemInstruction(): JsonField = systemInstruction - - /** - * Returns the raw JSON value of [tools]. - * - * Unlike [tools], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("tools") @ExcludeMissing fun _tools(): JsonField> = tools - - /** - * Returns the raw JSON value of [updated]. - * - * Unlike [updated], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("updated") @ExcludeMissing fun _updated(): JsonField = updated - - /** - * Returns the raw JSON value of [usage]. - * - * Unlike [usage], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("usage") @ExcludeMissing fun _usage(): JsonField = usage - - /** - * Returns the raw JSON value of [webhookConfig]. - * - * Unlike [webhookConfig], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("webhook_config") - @ExcludeMissing - fun _webhookConfig(): JsonField = webhookConfig - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [CreateModelInteractionParams]. - * - * The following fields are required: - * ```java - * .input() - * .model() - * ``` - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [CreateModelInteractionParams]. */ - class Builder internal constructor() { - - private var input: JsonField? = null - private var model: JsonField? = null - private var id: JsonField = JsonMissing.of() - private var background: JsonField = JsonMissing.of() - private var created: JsonField = JsonMissing.of() - private var generationConfig: JsonField = JsonMissing.of() - private var previousInteractionId: JsonField = JsonMissing.of() - private var responseFormat: JsonField = JsonMissing.of() - private var responseMimeType: JsonField = JsonMissing.of() - private var responseModalities: JsonField>? = null - private var role: JsonField = JsonMissing.of() - private var serviceTier: JsonField = JsonMissing.of() - private var status: JsonField = JsonMissing.of() - private var store: JsonField = JsonMissing.of() - private var stream: JsonField = JsonMissing.of() - private var systemInstruction: JsonField = JsonMissing.of() - private var tools: JsonField>? = null - private var updated: JsonField = JsonMissing.of() - private var usage: JsonField = JsonMissing.of() - private var webhookConfig: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(createModelInteractionParams: CreateModelInteractionParams) = apply { - input = createModelInteractionParams.input - model = createModelInteractionParams.model - id = createModelInteractionParams.id - background = createModelInteractionParams.background - created = createModelInteractionParams.created - generationConfig = createModelInteractionParams.generationConfig - previousInteractionId = createModelInteractionParams.previousInteractionId - responseFormat = createModelInteractionParams.responseFormat - responseMimeType = createModelInteractionParams.responseMimeType - responseModalities = - createModelInteractionParams.responseModalities.map { it.toMutableList() } - role = createModelInteractionParams.role - serviceTier = createModelInteractionParams.serviceTier - status = createModelInteractionParams.status - store = createModelInteractionParams.store - stream = createModelInteractionParams.stream - systemInstruction = createModelInteractionParams.systemInstruction - tools = createModelInteractionParams.tools.map { it.toMutableList() } - updated = createModelInteractionParams.updated - usage = createModelInteractionParams.usage - webhookConfig = createModelInteractionParams.webhookConfig - additionalProperties = createModelInteractionParams.additionalProperties.toMutableMap() - } - - /** The input for the interaction. */ - fun input(input: Input) = input(JsonField.of(input)) - - /** - * Sets [Builder.input] to an arbitrary JSON value. - * - * You should usually call [Builder.input] with a well-typed [Input] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun input(input: JsonField) = apply { this.input = input } - - /** Alias for calling [input] with `Input.ofString(string)`. */ - fun input(string: String) = input(Input.ofString(string)) - - /** Alias for calling [input] with `Input.ofStepList(stepList)`. */ - fun inputOfStepList(stepList: List) = input(Input.ofStepList(stepList)) - - /** Alias for calling [input] with `Input.ofContentList(contentList)`. */ - fun inputOfContentList(contentList: List) = input(Input.ofContentList(contentList)) - - /** Alias for calling [input] with `Input.ofTextContent(textContent)`. */ - fun input(textContent: TextContent) = input(Input.ofTextContent(textContent)) - - /** Alias for calling [input] with `Input.ofImageContent(imageContent)`. */ - fun input(imageContent: ImageContent) = input(Input.ofImageContent(imageContent)) - - /** Alias for calling [input] with `Input.ofAudioContent(audioContent)`. */ - fun input(audioContent: AudioContent) = input(Input.ofAudioContent(audioContent)) - - /** Alias for calling [input] with `Input.ofDocumentContent(documentContent)`. */ - fun input(documentContent: DocumentContent) = - input(Input.ofDocumentContent(documentContent)) - - /** Alias for calling [input] with `Input.ofVideoContent(videoContent)`. */ - fun input(videoContent: VideoContent) = input(Input.ofVideoContent(videoContent)) - - /** - * The model that will complete your prompt.\n\nSee - * [models](https://ai.google.dev/gemini-api/docs/models) for additional details. - */ - fun model(model: Model) = model(JsonField.of(model)) - - /** - * Sets [Builder.model] to an arbitrary JSON value. - * - * You should usually call [Builder.model] with a well-typed [Model] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun model(model: JsonField) = apply { this.model = model } - - /** - * Sets [model] to an arbitrary [String]. - * - * You should usually call [model] with a well-typed [Model] constant instead. This method - * is primarily for setting the field to an undocumented or not yet supported value. - */ - fun model(value: String) = model(Model.of(value)) - - /** Required. Output only. A unique identifier for the interaction completion. */ - fun id(id: String) = id(JsonField.of(id)) - - /** - * Sets [Builder.id] to an arbitrary JSON value. - * - * You should usually call [Builder.id] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun id(id: JsonField) = apply { this.id = id } - - /** Input only. Whether to run the model interaction in the background. */ - fun background(background: Boolean) = background(JsonField.of(background)) - - /** - * Sets [Builder.background] to an arbitrary JSON value. - * - * You should usually call [Builder.background] with a well-typed [Boolean] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun background(background: JsonField) = apply { this.background = background } - - /** - * Required. Output only. The time at which the response was created in ISO 8601 format - * (YYYY-MM-DDThh:mm:ssZ). - */ - fun created(created: OffsetDateTime) = created(JsonField.of(created)) - - /** - * Sets [Builder.created] to an arbitrary JSON value. - * - * You should usually call [Builder.created] with a well-typed [OffsetDateTime] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun created(created: JsonField) = apply { this.created = created } - - /** Input only. Configuration parameters for the model interaction. */ - fun generationConfig(generationConfig: GenerationConfig) = - generationConfig(JsonField.of(generationConfig)) - - /** - * Sets [Builder.generationConfig] to an arbitrary JSON value. - * - * You should usually call [Builder.generationConfig] with a well-typed [GenerationConfig] - * value instead. This method is primarily for setting the field to an undocumented or not - * yet supported value. - */ - fun generationConfig(generationConfig: JsonField) = apply { - this.generationConfig = generationConfig - } - - /** The ID of the previous interaction, if any. */ - fun previousInteractionId(previousInteractionId: String) = - previousInteractionId(JsonField.of(previousInteractionId)) - - /** - * Sets [Builder.previousInteractionId] to an arbitrary JSON value. - * - * You should usually call [Builder.previousInteractionId] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun previousInteractionId(previousInteractionId: JsonField) = apply { - this.previousInteractionId = previousInteractionId - } - - /** - * Enforces that the generated response is a JSON object that complies with the JSON schema - * specified in this field. - */ - fun responseFormat(responseFormat: ResponseFormat) = - responseFormat(JsonField.of(responseFormat)) - - /** - * Sets [Builder.responseFormat] to an arbitrary JSON value. - * - * You should usually call [Builder.responseFormat] with a well-typed [ResponseFormat] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun responseFormat(responseFormat: JsonField) = apply { - this.responseFormat = responseFormat - } - - /** Alias for calling [responseFormat] with `ResponseFormat.ofList(list)`. */ - fun responseFormatOfList(list: List) = - responseFormat(ResponseFormat.ofList(list)) - - /** Alias for calling [responseFormat] with `ResponseFormat.ofAudio(audio)`. */ - fun responseFormat(audio: AudioResponseFormat) = - responseFormat(ResponseFormat.ofAudio(audio)) - - /** Alias for calling [responseFormat] with `ResponseFormat.ofText(text)`. */ - fun responseFormat(text: TextResponseFormat) = responseFormat(ResponseFormat.ofText(text)) - - /** Alias for calling [responseFormat] with `ResponseFormat.ofImage(image)`. */ - fun responseFormat(image: ImageResponseFormat) = - responseFormat(ResponseFormat.ofImage(image)) - - /** Alias for calling [responseFormat] with `ResponseFormat.ofJsonValue(jsonValue)`. */ - fun responseFormat(jsonValue: JsonValue) = - responseFormat(ResponseFormat.ofJsonValue(jsonValue)) - - /** The mime type of the response. This is required if response_format is set. */ - fun responseMimeType(responseMimeType: String) = - responseMimeType(JsonField.of(responseMimeType)) - - /** - * Sets [Builder.responseMimeType] to an arbitrary JSON value. - * - * You should usually call [Builder.responseMimeType] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun responseMimeType(responseMimeType: JsonField) = apply { - this.responseMimeType = responseMimeType - } - - /** The requested modalities of the response (TEXT, IMAGE, AUDIO). */ - fun responseModalities(responseModalities: List) = - responseModalities(JsonField.of(responseModalities)) - - /** - * Sets [Builder.responseModalities] to an arbitrary JSON value. - * - * You should usually call [Builder.responseModalities] with a well-typed - * `List` value instead. This method is primarily for setting the field to - * an undocumented or not yet supported value. - */ - fun responseModalities(responseModalities: JsonField>) = apply { - this.responseModalities = responseModalities.map { it.toMutableList() } - } - - /** - * Adds a single [ResponseModality] to [responseModalities]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addResponseModality(responseModality: ResponseModality) = apply { - responseModalities = - (responseModalities ?: JsonField.of(mutableListOf())).also { - checkKnown("responseModalities", it).add(responseModality) - } - } - - /** Output only. The role of the interaction. */ - @Deprecated("deprecated") fun role(role: String) = role(JsonField.of(role)) - - /** - * Sets [Builder.role] to an arbitrary JSON value. - * - * You should usually call [Builder.role] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - @Deprecated("deprecated") fun role(role: JsonField) = apply { this.role = role } - - /** The service tier for the interaction. */ - fun serviceTier(serviceTier: ServiceTier) = serviceTier(JsonField.of(serviceTier)) - - /** - * Sets [Builder.serviceTier] to an arbitrary JSON value. - * - * You should usually call [Builder.serviceTier] with a well-typed [ServiceTier] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun serviceTier(serviceTier: JsonField) = apply { - this.serviceTier = serviceTier - } - - /** Required. Output only. The status of the interaction. */ - fun status(status: Status) = status(JsonField.of(status)) - - /** - * Sets [Builder.status] to an arbitrary JSON value. - * - * You should usually call [Builder.status] with a well-typed [Status] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun status(status: JsonField) = apply { this.status = status } - - /** Input only. Whether to store the response and request for later retrieval. */ - fun store(store: Boolean) = store(JsonField.of(store)) - - /** - * Sets [Builder.store] to an arbitrary JSON value. - * - * You should usually call [Builder.store] with a well-typed [Boolean] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun store(store: JsonField) = apply { this.store = store } - - /** Input only. Whether the interaction will be streamed. */ - fun stream(stream: Boolean) = stream(JsonField.of(stream)) - - /** - * Sets [Builder.stream] to an arbitrary JSON value. - * - * You should usually call [Builder.stream] with a well-typed [Boolean] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun stream(stream: JsonField) = apply { this.stream = stream } - - /** System instruction for the interaction. */ - fun systemInstruction(systemInstruction: String) = - systemInstruction(JsonField.of(systemInstruction)) - - /** - * Sets [Builder.systemInstruction] to an arbitrary JSON value. - * - * You should usually call [Builder.systemInstruction] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun systemInstruction(systemInstruction: JsonField) = apply { - this.systemInstruction = systemInstruction - } - - /** A list of tool declarations the model may call during interaction. */ - fun tools(tools: List) = tools(JsonField.of(tools)) - - /** - * Sets [Builder.tools] to an arbitrary JSON value. - * - * You should usually call [Builder.tools] with a well-typed `List` value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun tools(tools: JsonField>) = apply { - this.tools = tools.map { it.toMutableList() } - } - - /** - * Adds a single [Tool] to [tools]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addTool(tool: Tool) = apply { - tools = - (tools ?: JsonField.of(mutableListOf())).also { checkKnown("tools", it).add(tool) } - } - - /** Alias for calling [addTool] with `Tool.ofFunction(function)`. */ - fun addTool(function: Function) = addTool(Tool.ofFunction(function)) - - /** Alias for calling [addTool] with `Tool.ofCodeExecution()`. */ - fun addToolCodeExecution() = addTool(Tool.ofCodeExecution()) - - /** Alias for calling [addTool] with `Tool.ofUrlContext()`. */ - fun addToolUrlContext() = addTool(Tool.ofUrlContext()) - - /** Alias for calling [addTool] with `Tool.ofComputerUse(computerUse)`. */ - fun addTool(computerUse: Tool.ComputerUse) = addTool(Tool.ofComputerUse(computerUse)) - - /** Alias for calling [addTool] with `Tool.ofMcpServer(mcpServer)`. */ - fun addTool(mcpServer: Tool.McpServer) = addTool(Tool.ofMcpServer(mcpServer)) - - /** Alias for calling [addTool] with `Tool.ofGoogleSearch(googleSearch)`. */ - fun addTool(googleSearch: Tool.GoogleSearch) = addTool(Tool.ofGoogleSearch(googleSearch)) - - /** Alias for calling [addTool] with `Tool.ofFileSearch(fileSearch)`. */ - fun addTool(fileSearch: Tool.FileSearch) = addTool(Tool.ofFileSearch(fileSearch)) - - /** Alias for calling [addTool] with `Tool.ofGoogleMaps(googleMaps)`. */ - fun addTool(googleMaps: Tool.GoogleMaps) = addTool(Tool.ofGoogleMaps(googleMaps)) - - /** Alias for calling [addTool] with `Tool.ofRetrieval(retrieval)`. */ - fun addTool(retrieval: Tool.Retrieval) = addTool(Tool.ofRetrieval(retrieval)) - - /** - * Required. Output only. The time at which the response was last updated in ISO 8601 format - * (YYYY-MM-DDThh:mm:ssZ). - */ - fun updated(updated: OffsetDateTime) = updated(JsonField.of(updated)) - - /** - * Sets [Builder.updated] to an arbitrary JSON value. - * - * You should usually call [Builder.updated] with a well-typed [OffsetDateTime] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun updated(updated: JsonField) = apply { this.updated = updated } - - /** Output only. Statistics on the interaction request's token usage. */ - fun usage(usage: Usage) = usage(JsonField.of(usage)) - - /** - * Sets [Builder.usage] to an arbitrary JSON value. - * - * You should usually call [Builder.usage] with a well-typed [Usage] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun usage(usage: JsonField) = apply { this.usage = usage } - - /** - * Optional. Webhook configuration for receiving notifications when the interaction - * completes. - */ - fun webhookConfig(webhookConfig: WebhookConfig) = webhookConfig(JsonField.of(webhookConfig)) - - /** - * Sets [Builder.webhookConfig] to an arbitrary JSON value. - * - * You should usually call [Builder.webhookConfig] with a well-typed [WebhookConfig] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun webhookConfig(webhookConfig: JsonField) = apply { - this.webhookConfig = webhookConfig - } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [CreateModelInteractionParams]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .input() - * .model() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): CreateModelInteractionParams = - CreateModelInteractionParams( - checkRequired("input", input), - checkRequired("model", model), - id, - background, - created, - generationConfig, - previousInteractionId, - responseFormat, - responseMimeType, - (responseModalities ?: JsonMissing.of()).map { it.toImmutable() }, - role, - serviceTier, - status, - store, - stream, - systemInstruction, - (tools ?: JsonMissing.of()).map { it.toImmutable() }, - updated, - usage, - webhookConfig, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): CreateModelInteractionParams = apply { - if (validated) { - return@apply - } - - input().validate() - model() - id() - background() - created() - generationConfig().ifPresent { it.validate() } - previousInteractionId() - responseFormat().ifPresent { it.validate() } - responseMimeType() - responseModalities().ifPresent { it.forEach { it.validate() } } - role() - serviceTier().ifPresent { it.validate() } - status().ifPresent { it.validate() } - store() - stream() - systemInstruction() - tools().ifPresent { it.forEach { it.validate() } } - updated() - usage().ifPresent { it.validate() } - webhookConfig().ifPresent { it.validate() } - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - (input.asKnown().getOrNull()?.validity() ?: 0) + - (if (model.asKnown().isPresent) 1 else 0) + - (if (id.asKnown().isPresent) 1 else 0) + - (if (background.asKnown().isPresent) 1 else 0) + - (if (created.asKnown().isPresent) 1 else 0) + - (generationConfig.asKnown().getOrNull()?.validity() ?: 0) + - (if (previousInteractionId.asKnown().isPresent) 1 else 0) + - (responseFormat.asKnown().getOrNull()?.validity() ?: 0) + - (if (responseMimeType.asKnown().isPresent) 1 else 0) + - (responseModalities.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + - (if (role.asKnown().isPresent) 1 else 0) + - (serviceTier.asKnown().getOrNull()?.validity() ?: 0) + - (status.asKnown().getOrNull()?.validity() ?: 0) + - (if (store.asKnown().isPresent) 1 else 0) + - (if (stream.asKnown().isPresent) 1 else 0) + - (if (systemInstruction.asKnown().isPresent) 1 else 0) + - (tools.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + - (if (updated.asKnown().isPresent) 1 else 0) + - (usage.asKnown().getOrNull()?.validity() ?: 0) + - (webhookConfig.asKnown().getOrNull()?.validity() ?: 0) - - /** The input for the interaction. */ - @JsonDeserialize(using = Input.Deserializer::class) - @JsonSerialize(using = Input.Serializer::class) - class Input - private constructor( - private val string: String? = null, - private val stepList: List? = null, - private val contentList: List? = null, - private val textContent: TextContent? = null, - private val imageContent: ImageContent? = null, - private val audioContent: AudioContent? = null, - private val documentContent: DocumentContent? = null, - private val videoContent: VideoContent? = null, - private val _json: JsonValue? = null, - ) { - - fun string(): Optional = Optional.ofNullable(string) - - fun stepList(): Optional> = Optional.ofNullable(stepList) - - fun contentList(): Optional> = Optional.ofNullable(contentList) - - /** A text content block. */ - fun textContent(): Optional = Optional.ofNullable(textContent) - - /** An image content block. */ - fun imageContent(): Optional = Optional.ofNullable(imageContent) - - /** An audio content block. */ - fun audioContent(): Optional = Optional.ofNullable(audioContent) - - /** A document content block. */ - fun documentContent(): Optional = Optional.ofNullable(documentContent) - - /** A video content block. */ - fun videoContent(): Optional = Optional.ofNullable(videoContent) - - fun isString(): Boolean = string != null - - fun isStepList(): Boolean = stepList != null - - fun isContentList(): Boolean = contentList != null - - fun isTextContent(): Boolean = textContent != null - - fun isImageContent(): Boolean = imageContent != null - - fun isAudioContent(): Boolean = audioContent != null - - fun isDocumentContent(): Boolean = documentContent != null - - fun isVideoContent(): Boolean = videoContent != null - - fun asString(): String = string.getOrThrow("string") - - fun asStepList(): List = stepList.getOrThrow("stepList") - - fun asContentList(): List = contentList.getOrThrow("contentList") - - /** A text content block. */ - fun asTextContent(): TextContent = textContent.getOrThrow("textContent") - - /** An image content block. */ - fun asImageContent(): ImageContent = imageContent.getOrThrow("imageContent") - - /** An audio content block. */ - fun asAudioContent(): AudioContent = audioContent.getOrThrow("audioContent") - - /** A document content block. */ - fun asDocumentContent(): DocumentContent = documentContent.getOrThrow("documentContent") - - /** A video content block. */ - fun asVideoContent(): VideoContent = videoContent.getOrThrow("videoContent") - - fun _json(): Optional = Optional.ofNullable(_json) - - fun accept(visitor: Visitor): T = - when { - string != null -> visitor.visitString(string) - stepList != null -> visitor.visitStepList(stepList) - contentList != null -> visitor.visitContentList(contentList) - textContent != null -> visitor.visitTextContent(textContent) - imageContent != null -> visitor.visitImageContent(imageContent) - audioContent != null -> visitor.visitAudioContent(audioContent) - documentContent != null -> visitor.visitDocumentContent(documentContent) - videoContent != null -> visitor.visitVideoContent(videoContent) - else -> visitor.unknown(_json) - } - - private var validated: Boolean = false - - fun validate(): Input = apply { - if (validated) { - return@apply - } - - accept( - object : Visitor { - override fun visitString(string: String) {} - - override fun visitStepList(stepList: List) { - stepList.forEach { it.validate() } - } - - override fun visitContentList(contentList: List) { - contentList.forEach { it.validate() } - } - - override fun visitTextContent(textContent: TextContent) { - textContent.validate() - } - - override fun visitImageContent(imageContent: ImageContent) { - imageContent.validate() - } - - override fun visitAudioContent(audioContent: AudioContent) { - audioContent.validate() - } - - override fun visitDocumentContent(documentContent: DocumentContent) { - documentContent.validate() - } - - override fun visitVideoContent(videoContent: VideoContent) { - videoContent.validate() - } - } - ) - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - accept( - object : Visitor { - override fun visitString(string: String) = 1 - - override fun visitStepList(stepList: List) = - stepList.sumOf { it.validity().toInt() } - - override fun visitContentList(contentList: List) = - contentList.sumOf { it.validity().toInt() } - - override fun visitTextContent(textContent: TextContent) = textContent.validity() - - override fun visitImageContent(imageContent: ImageContent) = - imageContent.validity() - - override fun visitAudioContent(audioContent: AudioContent) = - audioContent.validity() - - override fun visitDocumentContent(documentContent: DocumentContent) = - documentContent.validity() - - override fun visitVideoContent(videoContent: VideoContent) = - videoContent.validity() - - override fun unknown(json: JsonValue?) = 0 - } - ) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Input && - string == other.string && - stepList == other.stepList && - contentList == other.contentList && - textContent == other.textContent && - imageContent == other.imageContent && - audioContent == other.audioContent && - documentContent == other.documentContent && - videoContent == other.videoContent - } - - override fun hashCode(): Int = - Objects.hash( - string, - stepList, - contentList, - textContent, - imageContent, - audioContent, - documentContent, - videoContent, - ) - - override fun toString(): String = - when { - string != null -> "Input{string=$string}" - stepList != null -> "Input{stepList=$stepList}" - contentList != null -> "Input{contentList=$contentList}" - textContent != null -> "Input{textContent=$textContent}" - imageContent != null -> "Input{imageContent=$imageContent}" - audioContent != null -> "Input{audioContent=$audioContent}" - documentContent != null -> "Input{documentContent=$documentContent}" - videoContent != null -> "Input{videoContent=$videoContent}" - _json != null -> "Input{_unknown=$_json}" - else -> throw IllegalStateException("Invalid Input") - } - - companion object { - - @JvmStatic fun ofString(string: String) = Input(string = string) - - @JvmStatic - fun ofStepList(stepList: List) = Input(stepList = stepList.toImmutable()) - - @JvmStatic - fun ofContentList(contentList: List) = - Input(contentList = contentList.toImmutable()) - - /** A text content block. */ - @JvmStatic - fun ofTextContent(textContent: TextContent) = Input(textContent = textContent) - - /** An image content block. */ - @JvmStatic - fun ofImageContent(imageContent: ImageContent) = Input(imageContent = imageContent) - - /** An audio content block. */ - @JvmStatic - fun ofAudioContent(audioContent: AudioContent) = Input(audioContent = audioContent) - - /** A document content block. */ - @JvmStatic - fun ofDocumentContent(documentContent: DocumentContent) = - Input(documentContent = documentContent) - - /** A video content block. */ - @JvmStatic - fun ofVideoContent(videoContent: VideoContent) = Input(videoContent = videoContent) - } - - /** An interface that defines how to map each variant of [Input] to a value of type [T]. */ - interface Visitor { - - fun visitString(string: String): T - - fun visitStepList(stepList: List): T - - fun visitContentList(contentList: List): T - - /** A text content block. */ - fun visitTextContent(textContent: TextContent): T - - /** An image content block. */ - fun visitImageContent(imageContent: ImageContent): T - - /** An audio content block. */ - fun visitAudioContent(audioContent: AudioContent): T - - /** A document content block. */ - fun visitDocumentContent(documentContent: DocumentContent): T - - /** A video content block. */ - fun visitVideoContent(videoContent: VideoContent): T - - /** - * Maps an unknown variant of [Input] to a value of type [T]. - * - * An instance of [Input] can contain an unknown variant if it was deserialized from - * data that doesn't match any known variant. For example, if the SDK is on an older - * version than the API, then the API may respond with new variants that the SDK is - * unaware of. - * - * @throws GeminiNextGenApiInvalidDataException in the default implementation. - */ - fun unknown(json: JsonValue?): T { - throw GeminiNextGenApiInvalidDataException("Unknown Input: $json") - } - } - - internal class Deserializer : BaseDeserializer(Input::class) { - - override fun ObjectCodec.deserialize(node: JsonNode): Input { - val json = JsonValue.fromJsonNode(node) - - val bestMatches = - sequenceOf( - tryDeserialize(node, jacksonTypeRef())?.let { - Input(textContent = it, _json = json) - }, - tryDeserialize(node, jacksonTypeRef())?.let { - Input(imageContent = it, _json = json) - }, - tryDeserialize(node, jacksonTypeRef())?.let { - Input(audioContent = it, _json = json) - }, - tryDeserialize(node, jacksonTypeRef())?.let { - Input(documentContent = it, _json = json) - }, - tryDeserialize(node, jacksonTypeRef())?.let { - Input(videoContent = it, _json = json) - }, - tryDeserialize(node, jacksonTypeRef())?.let { - Input(string = it, _json = json) - }, - tryDeserialize(node, jacksonTypeRef>())?.let { - Input(stepList = it, _json = json) - }, - tryDeserialize(node, jacksonTypeRef>())?.let { - Input(contentList = it, _json = json) - }, - ) - .filterNotNull() - .allMaxBy { it.validity() } - .toList() - return when (bestMatches.size) { - // This can happen if what we're deserializing is completely incompatible with - // all the possible variants (e.g. deserializing from boolean). - 0 -> Input(_json = json) - 1 -> bestMatches.single() - // If there's more than one match with the highest validity, then use the first - // completely valid match, or simply the first match if none are completely - // valid. - else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() - } - } - } - - internal class Serializer : BaseSerializer(Input::class) { - - override fun serialize( - value: Input, - generator: JsonGenerator, - provider: SerializerProvider, - ) { - when { - value.string != null -> generator.writeObject(value.string) - value.stepList != null -> generator.writeObject(value.stepList) - value.contentList != null -> generator.writeObject(value.contentList) - value.textContent != null -> generator.writeObject(value.textContent) - value.imageContent != null -> generator.writeObject(value.imageContent) - value.audioContent != null -> generator.writeObject(value.audioContent) - value.documentContent != null -> generator.writeObject(value.documentContent) - value.videoContent != null -> generator.writeObject(value.videoContent) - value._json != null -> generator.writeObject(value._json) - else -> throw IllegalStateException("Invalid Input") - } - } - } - } - - /** - * Enforces that the generated response is a JSON object that complies with the JSON schema - * specified in this field. - */ - @JsonDeserialize(using = ResponseFormat.Deserializer::class) - @JsonSerialize(using = ResponseFormat.Serializer::class) - class ResponseFormat - private constructor( - private val list: List? = null, - private val audio: AudioResponseFormat? = null, - private val text: TextResponseFormat? = null, - private val image: ImageResponseFormat? = null, - private val jsonValue: JsonValue? = null, - private val _json: JsonValue? = null, - ) { - - fun list(): Optional> = Optional.ofNullable(list) - - /** Configuration for audio output format. */ - fun audio(): Optional = Optional.ofNullable(audio) - - /** Configuration for text output format. */ - fun text(): Optional = Optional.ofNullable(text) - - /** Configuration for image output format. */ - fun image(): Optional = Optional.ofNullable(image) - - fun jsonValue(): Optional = Optional.ofNullable(jsonValue) - - fun isList(): Boolean = list != null - - fun isAudio(): Boolean = audio != null - - fun isText(): Boolean = text != null - - fun isImage(): Boolean = image != null - - fun isJsonValue(): Boolean = jsonValue != null - - fun asList(): List = list.getOrThrow("list") - - /** Configuration for audio output format. */ - fun asAudio(): AudioResponseFormat = audio.getOrThrow("audio") - - /** Configuration for text output format. */ - fun asText(): TextResponseFormat = text.getOrThrow("text") - - /** Configuration for image output format. */ - fun asImage(): ImageResponseFormat = image.getOrThrow("image") - - fun asJsonValue(): JsonValue = jsonValue.getOrThrow("jsonValue") - - fun _json(): Optional = Optional.ofNullable(_json) - - fun accept(visitor: Visitor): T = - when { - list != null -> visitor.visitList(list) - audio != null -> visitor.visitAudio(audio) - text != null -> visitor.visitText(text) - image != null -> visitor.visitImage(image) - jsonValue != null -> visitor.visitJsonValue(jsonValue) - else -> visitor.unknown(_json) - } - - private var validated: Boolean = false - - fun validate(): ResponseFormat = apply { - if (validated) { - return@apply - } - - accept( - object : Visitor { - override fun visitList(list: List) { - list.forEach { it.validate() } - } - - override fun visitAudio(audio: AudioResponseFormat) { - audio.validate() - } - - override fun visitText(text: TextResponseFormat) { - text.validate() - } - - override fun visitImage(image: ImageResponseFormat) { - image.validate() - } - - override fun visitJsonValue(jsonValue: JsonValue) {} - } - ) - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - accept( - object : Visitor { - override fun visitList(list: List) = - list.sumOf { it.validity().toInt() } - - override fun visitAudio(audio: AudioResponseFormat) = audio.validity() - - override fun visitText(text: TextResponseFormat) = text.validity() - - override fun visitImage(image: ImageResponseFormat) = image.validity() - - override fun visitJsonValue(jsonValue: JsonValue) = 1 - - override fun unknown(json: JsonValue?) = 0 - } - ) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is ResponseFormat && - list == other.list && - audio == other.audio && - text == other.text && - image == other.image && - jsonValue == other.jsonValue - } - - override fun hashCode(): Int = Objects.hash(list, audio, text, image, jsonValue) - - override fun toString(): String = - when { - list != null -> "ResponseFormat{list=$list}" - audio != null -> "ResponseFormat{audio=$audio}" - text != null -> "ResponseFormat{text=$text}" - image != null -> "ResponseFormat{image=$image}" - jsonValue != null -> "ResponseFormat{jsonValue=$jsonValue}" - _json != null -> "ResponseFormat{_unknown=$_json}" - else -> throw IllegalStateException("Invalid ResponseFormat") - } - - companion object { - - @JvmStatic - fun ofList(list: List) = ResponseFormat(list = list.toImmutable()) - - /** Configuration for audio output format. */ - @JvmStatic fun ofAudio(audio: AudioResponseFormat) = ResponseFormat(audio = audio) - - /** Configuration for text output format. */ - @JvmStatic fun ofText(text: TextResponseFormat) = ResponseFormat(text = text) - - /** Configuration for image output format. */ - @JvmStatic fun ofImage(image: ImageResponseFormat) = ResponseFormat(image = image) - - @JvmStatic fun ofJsonValue(jsonValue: JsonValue) = ResponseFormat(jsonValue = jsonValue) - } - - /** - * An interface that defines how to map each variant of [ResponseFormat] to a value of type - * [T]. - */ - interface Visitor { - - fun visitList(list: List): T - - /** Configuration for audio output format. */ - fun visitAudio(audio: AudioResponseFormat): T - - /** Configuration for text output format. */ - fun visitText(text: TextResponseFormat): T - - /** Configuration for image output format. */ - fun visitImage(image: ImageResponseFormat): T - - fun visitJsonValue(jsonValue: JsonValue): T - - /** - * Maps an unknown variant of [ResponseFormat] to a value of type [T]. - * - * An instance of [ResponseFormat] can contain an unknown variant if it was deserialized - * from data that doesn't match any known variant. For example, if the SDK is on an - * older version than the API, then the API may respond with new variants that the SDK - * is unaware of. - * - * @throws GeminiNextGenApiInvalidDataException in the default implementation. - */ - fun unknown(json: JsonValue?): T { - throw GeminiNextGenApiInvalidDataException("Unknown ResponseFormat: $json") - } - } - - internal class Deserializer : BaseDeserializer(ResponseFormat::class) { - - override fun ObjectCodec.deserialize(node: JsonNode): ResponseFormat { - val json = JsonValue.fromJsonNode(node) - - val bestMatches = - sequenceOf( - tryDeserialize(node, jacksonTypeRef())?.let { - ResponseFormat(audio = it, _json = json) - }, - tryDeserialize(node, jacksonTypeRef())?.let { - ResponseFormat(text = it, _json = json) - }, - tryDeserialize(node, jacksonTypeRef())?.let { - ResponseFormat(image = it, _json = json) - }, - tryDeserialize(node, jacksonTypeRef>())?.let { - ResponseFormat(list = it, _json = json) - }, - tryDeserialize(node, jacksonTypeRef())?.let { - ResponseFormat(jsonValue = it, _json = json) - }, - ) - .filterNotNull() - .allMaxBy { it.validity() } - .toList() - return when (bestMatches.size) { - // This can happen if what we're deserializing is completely incompatible with - // all the possible variants. - 0 -> ResponseFormat(_json = json) - 1 -> bestMatches.single() - // If there's more than one match with the highest validity, then use the first - // completely valid match, or simply the first match if none are completely - // valid. - else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() - } - } - } - - internal class Serializer : BaseSerializer(ResponseFormat::class) { - - override fun serialize( - value: ResponseFormat, - generator: JsonGenerator, - provider: SerializerProvider, - ) { - when { - value.list != null -> generator.writeObject(value.list) - value.audio != null -> generator.writeObject(value.audio) - value.text != null -> generator.writeObject(value.text) - value.image != null -> generator.writeObject(value.image) - value.jsonValue != null -> generator.writeObject(value.jsonValue) - value._json != null -> generator.writeObject(value._json) - else -> throw IllegalStateException("Invalid ResponseFormat") - } - } - } - - /** Configuration for audio output format. */ - @JsonDeserialize(using = InnerResponseFormat.Deserializer::class) - @JsonSerialize(using = InnerResponseFormat.Serializer::class) - class InnerResponseFormat - private constructor( - private val audio: AudioResponseFormat? = null, - private val text: TextResponseFormat? = null, - private val image: ImageResponseFormat? = null, - private val jsonValue: JsonValue? = null, - private val _json: JsonValue? = null, - ) { - - /** Configuration for audio output format. */ - fun audio(): Optional = Optional.ofNullable(audio) - - /** Configuration for text output format. */ - fun text(): Optional = Optional.ofNullable(text) - - /** Configuration for image output format. */ - fun image(): Optional = Optional.ofNullable(image) - - fun jsonValue(): Optional = Optional.ofNullable(jsonValue) - - fun isAudio(): Boolean = audio != null - - fun isText(): Boolean = text != null - - fun isImage(): Boolean = image != null - - fun isJsonValue(): Boolean = jsonValue != null - - /** Configuration for audio output format. */ - fun asAudio(): AudioResponseFormat = audio.getOrThrow("audio") - - /** Configuration for text output format. */ - fun asText(): TextResponseFormat = text.getOrThrow("text") - - /** Configuration for image output format. */ - fun asImage(): ImageResponseFormat = image.getOrThrow("image") - - fun asJsonValue(): JsonValue = jsonValue.getOrThrow("jsonValue") - - fun _json(): Optional = Optional.ofNullable(_json) - - fun accept(visitor: Visitor): T = - when { - audio != null -> visitor.visitAudio(audio) - text != null -> visitor.visitText(text) - image != null -> visitor.visitImage(image) - jsonValue != null -> visitor.visitJsonValue(jsonValue) - else -> visitor.unknown(_json) - } - - private var validated: Boolean = false - - fun validate(): InnerResponseFormat = apply { - if (validated) { - return@apply - } - - accept( - object : Visitor { - override fun visitAudio(audio: AudioResponseFormat) { - audio.validate() - } - - override fun visitText(text: TextResponseFormat) { - text.validate() - } - - override fun visitImage(image: ImageResponseFormat) { - image.validate() - } - - override fun visitJsonValue(jsonValue: JsonValue) {} - } - ) - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - accept( - object : Visitor { - override fun visitAudio(audio: AudioResponseFormat) = audio.validity() - - override fun visitText(text: TextResponseFormat) = text.validity() - - override fun visitImage(image: ImageResponseFormat) = image.validity() - - override fun visitJsonValue(jsonValue: JsonValue) = 1 - - override fun unknown(json: JsonValue?) = 0 - } - ) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is InnerResponseFormat && - audio == other.audio && - text == other.text && - image == other.image && - jsonValue == other.jsonValue - } - - override fun hashCode(): Int = Objects.hash(audio, text, image, jsonValue) - - override fun toString(): String = - when { - audio != null -> "InnerResponseFormat{audio=$audio}" - text != null -> "InnerResponseFormat{text=$text}" - image != null -> "InnerResponseFormat{image=$image}" - jsonValue != null -> "InnerResponseFormat{jsonValue=$jsonValue}" - _json != null -> "InnerResponseFormat{_unknown=$_json}" - else -> throw IllegalStateException("Invalid InnerResponseFormat") - } - - companion object { - - /** Configuration for audio output format. */ - @JvmStatic - fun ofAudio(audio: AudioResponseFormat) = InnerResponseFormat(audio = audio) - - /** Configuration for text output format. */ - @JvmStatic fun ofText(text: TextResponseFormat) = InnerResponseFormat(text = text) - - /** Configuration for image output format. */ - @JvmStatic - fun ofImage(image: ImageResponseFormat) = InnerResponseFormat(image = image) - - @JvmStatic - fun ofJsonValue(jsonValue: JsonValue) = InnerResponseFormat(jsonValue = jsonValue) - } - - /** - * An interface that defines how to map each variant of [InnerResponseFormat] to a value - * of type [T]. - */ - interface Visitor { - - /** Configuration for audio output format. */ - fun visitAudio(audio: AudioResponseFormat): T - - /** Configuration for text output format. */ - fun visitText(text: TextResponseFormat): T - - /** Configuration for image output format. */ - fun visitImage(image: ImageResponseFormat): T - - fun visitJsonValue(jsonValue: JsonValue): T - - /** - * Maps an unknown variant of [InnerResponseFormat] to a value of type [T]. - * - * An instance of [InnerResponseFormat] can contain an unknown variant if it was - * deserialized from data that doesn't match any known variant. For example, if the - * SDK is on an older version than the API, then the API may respond with new - * variants that the SDK is unaware of. - * - * @throws GeminiNextGenApiInvalidDataException in the default implementation. - */ - fun unknown(json: JsonValue?): T { - throw GeminiNextGenApiInvalidDataException("Unknown InnerResponseFormat: $json") - } - } - - internal class Deserializer : - BaseDeserializer(InnerResponseFormat::class) { - - override fun ObjectCodec.deserialize(node: JsonNode): InnerResponseFormat { - val json = JsonValue.fromJsonNode(node) - - val bestMatches = - sequenceOf( - tryDeserialize(node, jacksonTypeRef())?.let { - InnerResponseFormat(audio = it, _json = json) - }, - tryDeserialize(node, jacksonTypeRef())?.let { - InnerResponseFormat(text = it, _json = json) - }, - tryDeserialize(node, jacksonTypeRef())?.let { - InnerResponseFormat(image = it, _json = json) - }, - tryDeserialize(node, jacksonTypeRef())?.let { - InnerResponseFormat(jsonValue = it, _json = json) - }, - ) - .filterNotNull() - .allMaxBy { it.validity() } - .toList() - return when (bestMatches.size) { - // This can happen if what we're deserializing is completely incompatible - // with all the possible variants. - 0 -> InnerResponseFormat(_json = json) - 1 -> bestMatches.single() - // If there's more than one match with the highest validity, then use the - // first completely valid match, or simply the first match if none are - // completely valid. - else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() - } - } - } - - internal class Serializer : - BaseSerializer(InnerResponseFormat::class) { - - override fun serialize( - value: InnerResponseFormat, - generator: JsonGenerator, - provider: SerializerProvider, - ) { - when { - value.audio != null -> generator.writeObject(value.audio) - value.text != null -> generator.writeObject(value.text) - value.image != null -> generator.writeObject(value.image) - value.jsonValue != null -> generator.writeObject(value.jsonValue) - value._json != null -> generator.writeObject(value._json) - else -> throw IllegalStateException("Invalid InnerResponseFormat") - } - } - } - } - } - - class ResponseModality @JsonCreator private constructor(private val value: JsonField) : - Enum { - - /** - * Returns this class instance's raw value. - * - * This is usually only useful if this instance was deserialized from data that doesn't - * match any known member, and you want to know that value. For example, if the SDK is on an - * older version than the API, then the API may respond with new members that the SDK is - * unaware of. - */ - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - companion object { - - @JvmField val TEXT = of("text") - - @JvmField val IMAGE = of("image") - - @JvmField val AUDIO = of("audio") - - @JvmField val VIDEO = of("video") - - @JvmField val DOCUMENT = of("document") - - @JvmStatic fun of(value: String) = ResponseModality(JsonField.of(value)) - } - - /** An enum containing [ResponseModality]'s known values. */ - enum class Known { - TEXT, - IMAGE, - AUDIO, - VIDEO, - DOCUMENT, - } - - /** - * An enum containing [ResponseModality]'s known values, as well as an [_UNKNOWN] member. - * - * An instance of [ResponseModality] can contain an unknown value in a couple of cases: - * - It was deserialized from data that doesn't match any known member. For example, if the - * SDK is on an older version than the API, then the API may respond with new members that - * the SDK is unaware of. - * - It was constructed with an arbitrary value using the [of] method. - */ - enum class Value { - TEXT, - IMAGE, - AUDIO, - VIDEO, - DOCUMENT, - /** - * An enum member indicating that [ResponseModality] was instantiated with an unknown - * value. - */ - _UNKNOWN, - } - - /** - * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] - * if the class was instantiated with an unknown value. - * - * Use the [known] method instead if you're certain the value is always known or if you want - * to throw for the unknown case. - */ - fun value(): Value = - when (this) { - TEXT -> Value.TEXT - IMAGE -> Value.IMAGE - AUDIO -> Value.AUDIO - VIDEO -> Value.VIDEO - DOCUMENT -> Value.DOCUMENT - else -> Value._UNKNOWN - } - - /** - * Returns an enum member corresponding to this class instance's value. - * - * Use the [value] method instead if you're uncertain the value is always known and don't - * want to throw for the unknown case. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value is a not a - * known member. - */ - fun known(): Known = - when (this) { - TEXT -> Known.TEXT - IMAGE -> Known.IMAGE - AUDIO -> Known.AUDIO - VIDEO -> Known.VIDEO - DOCUMENT -> Known.DOCUMENT - else -> - throw GeminiNextGenApiInvalidDataException("Unknown ResponseModality: $value") - } - - /** - * Returns this class instance's primitive wire representation. - * - * This differs from the [toString] method because that method is primarily for debugging - * and generally doesn't throw. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value does not have - * the expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - GeminiNextGenApiInvalidDataException("Value is not a String") - } - - private var validated: Boolean = false - - fun validate(): ResponseModality = apply { - if (validated) { - return@apply - } - - known() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is ResponseModality && value == other.value - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - /** The service tier for the interaction. */ - class ServiceTier @JsonCreator private constructor(private val value: JsonField) : - Enum { - - /** - * Returns this class instance's raw value. - * - * This is usually only useful if this instance was deserialized from data that doesn't - * match any known member, and you want to know that value. For example, if the SDK is on an - * older version than the API, then the API may respond with new members that the SDK is - * unaware of. - */ - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - companion object { - - @JvmField val FLEX = of("flex") - - @JvmField val STANDARD = of("standard") - - @JvmField val PRIORITY = of("priority") - - @JvmStatic fun of(value: String) = ServiceTier(JsonField.of(value)) - } - - /** An enum containing [ServiceTier]'s known values. */ - enum class Known { - FLEX, - STANDARD, - PRIORITY, - } - - /** - * An enum containing [ServiceTier]'s known values, as well as an [_UNKNOWN] member. - * - * An instance of [ServiceTier] can contain an unknown value in a couple of cases: - * - It was deserialized from data that doesn't match any known member. For example, if the - * SDK is on an older version than the API, then the API may respond with new members that - * the SDK is unaware of. - * - It was constructed with an arbitrary value using the [of] method. - */ - enum class Value { - FLEX, - STANDARD, - PRIORITY, - /** - * An enum member indicating that [ServiceTier] was instantiated with an unknown value. - */ - _UNKNOWN, - } - - /** - * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] - * if the class was instantiated with an unknown value. - * - * Use the [known] method instead if you're certain the value is always known or if you want - * to throw for the unknown case. - */ - fun value(): Value = - when (this) { - FLEX -> Value.FLEX - STANDARD -> Value.STANDARD - PRIORITY -> Value.PRIORITY - else -> Value._UNKNOWN - } - - /** - * Returns an enum member corresponding to this class instance's value. - * - * Use the [value] method instead if you're uncertain the value is always known and don't - * want to throw for the unknown case. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value is a not a - * known member. - */ - fun known(): Known = - when (this) { - FLEX -> Known.FLEX - STANDARD -> Known.STANDARD - PRIORITY -> Known.PRIORITY - else -> throw GeminiNextGenApiInvalidDataException("Unknown ServiceTier: $value") - } - - /** - * Returns this class instance's primitive wire representation. - * - * This differs from the [toString] method because that method is primarily for debugging - * and generally doesn't throw. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value does not have - * the expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - GeminiNextGenApiInvalidDataException("Value is not a String") - } - - private var validated: Boolean = false - - fun validate(): ServiceTier = apply { - if (validated) { - return@apply - } - - known() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is ServiceTier && value == other.value - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - /** Required. Output only. The status of the interaction. */ - class Status @JsonCreator private constructor(private val value: JsonField) : Enum { - - /** - * Returns this class instance's raw value. - * - * This is usually only useful if this instance was deserialized from data that doesn't - * match any known member, and you want to know that value. For example, if the SDK is on an - * older version than the API, then the API may respond with new members that the SDK is - * unaware of. - */ - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - companion object { - - @JvmField val IN_PROGRESS = of("in_progress") - - @JvmField val REQUIRES_ACTION = of("requires_action") - - @JvmField val COMPLETED = of("completed") - - @JvmField val FAILED = of("failed") - - @JvmField val CANCELLED = of("cancelled") - - @JvmField val INCOMPLETE = of("incomplete") - - @JvmStatic fun of(value: String) = Status(JsonField.of(value)) - } - - /** An enum containing [Status]'s known values. */ - enum class Known { - IN_PROGRESS, - REQUIRES_ACTION, - COMPLETED, - FAILED, - CANCELLED, - INCOMPLETE, - } - - /** - * An enum containing [Status]'s known values, as well as an [_UNKNOWN] member. - * - * An instance of [Status] can contain an unknown value in a couple of cases: - * - It was deserialized from data that doesn't match any known member. For example, if the - * SDK is on an older version than the API, then the API may respond with new members that - * the SDK is unaware of. - * - It was constructed with an arbitrary value using the [of] method. - */ - enum class Value { - IN_PROGRESS, - REQUIRES_ACTION, - COMPLETED, - FAILED, - CANCELLED, - INCOMPLETE, - /** An enum member indicating that [Status] was instantiated with an unknown value. */ - _UNKNOWN, - } - - /** - * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] - * if the class was instantiated with an unknown value. - * - * Use the [known] method instead if you're certain the value is always known or if you want - * to throw for the unknown case. - */ - fun value(): Value = - when (this) { - IN_PROGRESS -> Value.IN_PROGRESS - REQUIRES_ACTION -> Value.REQUIRES_ACTION - COMPLETED -> Value.COMPLETED - FAILED -> Value.FAILED - CANCELLED -> Value.CANCELLED - INCOMPLETE -> Value.INCOMPLETE - else -> Value._UNKNOWN - } - - /** - * Returns an enum member corresponding to this class instance's value. - * - * Use the [value] method instead if you're uncertain the value is always known and don't - * want to throw for the unknown case. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value is a not a - * known member. - */ - fun known(): Known = - when (this) { - IN_PROGRESS -> Known.IN_PROGRESS - REQUIRES_ACTION -> Known.REQUIRES_ACTION - COMPLETED -> Known.COMPLETED - FAILED -> Known.FAILED - CANCELLED -> Known.CANCELLED - INCOMPLETE -> Known.INCOMPLETE - else -> throw GeminiNextGenApiInvalidDataException("Unknown Status: $value") - } - - /** - * Returns this class instance's primitive wire representation. - * - * This differs from the [toString] method because that method is primarily for debugging - * and generally doesn't throw. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value does not have - * the expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - GeminiNextGenApiInvalidDataException("Value is not a String") - } - - private var validated: Boolean = false - - fun validate(): Status = apply { - if (validated) { - return@apply - } - - known() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Status && value == other.value - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - /** Message for configuring webhook events for a request. */ - class WebhookConfig - @JsonCreator(mode = JsonCreator.Mode.DISABLED) - private constructor( - private val uris: JsonField>, - private val userMetadata: JsonField, - private val additionalProperties: MutableMap, - ) { - - @JsonCreator - private constructor( - @JsonProperty("uris") @ExcludeMissing uris: JsonField> = JsonMissing.of(), - @JsonProperty("user_metadata") - @ExcludeMissing - userMetadata: JsonField = JsonMissing.of(), - ) : this(uris, userMetadata, mutableMapOf()) - - /** - * Optional. If set, these webhook URIs will be used for webhook events instead of the - * registered webhooks. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type - * (e.g. if the server responded with an unexpected value). - */ - fun uris(): Optional> = uris.getOptional("uris") - - /** - * Optional. The user metadata that will be returned on each event emission to the webhooks. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type - * (e.g. if the server responded with an unexpected value). - */ - fun userMetadata(): Optional = userMetadata.getOptional("user_metadata") - - /** - * Returns the raw JSON value of [uris]. - * - * Unlike [uris], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("uris") @ExcludeMissing fun _uris(): JsonField> = uris - - /** - * Returns the raw JSON value of [userMetadata]. - * - * Unlike [userMetadata], this method doesn't throw if the JSON field has an unexpected - * type. - */ - @JsonProperty("user_metadata") - @ExcludeMissing - fun _userMetadata(): JsonField = userMetadata - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [WebhookConfig]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [WebhookConfig]. */ - class Builder internal constructor() { - - private var uris: JsonField>? = null - private var userMetadata: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(webhookConfig: WebhookConfig) = apply { - uris = webhookConfig.uris.map { it.toMutableList() } - userMetadata = webhookConfig.userMetadata - additionalProperties = webhookConfig.additionalProperties.toMutableMap() - } - - /** - * Optional. If set, these webhook URIs will be used for webhook events instead of the - * registered webhooks. - */ - fun uris(uris: List) = uris(JsonField.of(uris)) - - /** - * Sets [Builder.uris] to an arbitrary JSON value. - * - * You should usually call [Builder.uris] with a well-typed `List` value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun uris(uris: JsonField>) = apply { - this.uris = uris.map { it.toMutableList() } - } - - /** - * Adds a single [String] to [Builder.uris]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addUris(uris: String) = apply { - this.uris = - (this.uris ?: JsonField.of(mutableListOf())).also { - checkKnown("uris", it).add(uris) - } - } - - /** - * Optional. The user metadata that will be returned on each event emission to the - * webhooks. - */ - fun userMetadata(userMetadata: UserMetadata) = userMetadata(JsonField.of(userMetadata)) - - /** - * Sets [Builder.userMetadata] to an arbitrary JSON value. - * - * You should usually call [Builder.userMetadata] with a well-typed [UserMetadata] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun userMetadata(userMetadata: JsonField) = apply { - this.userMetadata = userMetadata - } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [WebhookConfig]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): WebhookConfig = - WebhookConfig( - (uris ?: JsonMissing.of()).map { it.toImmutable() }, - userMetadata, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): WebhookConfig = apply { - if (validated) { - return@apply - } - - uris() - userMetadata().ifPresent { it.validate() } - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - (uris.asKnown().getOrNull()?.size ?: 0) + - (userMetadata.asKnown().getOrNull()?.validity() ?: 0) - - /** - * Optional. The user metadata that will be returned on each event emission to the webhooks. - */ - class UserMetadata - @JsonCreator - private constructor( - @com.fasterxml.jackson.annotation.JsonValue - private val additionalProperties: Map - ) { - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [UserMetadata]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [UserMetadata]. */ - class Builder internal constructor() { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(userMetadata: UserMetadata) = apply { - additionalProperties = userMetadata.additionalProperties.toMutableMap() - } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = - apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { - additionalProperties.remove(key) - } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [UserMetadata]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): UserMetadata = UserMetadata(additionalProperties.toImmutable()) - } - - private var validated: Boolean = false - - fun validate(): UserMetadata = apply { - if (validated) { - return@apply - } - - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is UserMetadata && additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - - override fun hashCode(): Int = hashCode - - override fun toString() = "UserMetadata{additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is WebhookConfig && - uris == other.uris && - userMetadata == other.userMetadata && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { Objects.hash(uris, userMetadata, additionalProperties) } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "WebhookConfig{uris=$uris, userMetadata=$userMetadata, additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is CreateModelInteractionParams && - input == other.input && - model == other.model && - id == other.id && - background == other.background && - created == other.created && - generationConfig == other.generationConfig && - previousInteractionId == other.previousInteractionId && - responseFormat == other.responseFormat && - responseMimeType == other.responseMimeType && - responseModalities == other.responseModalities && - role == other.role && - serviceTier == other.serviceTier && - status == other.status && - store == other.store && - stream == other.stream && - systemInstruction == other.systemInstruction && - tools == other.tools && - updated == other.updated && - usage == other.usage && - webhookConfig == other.webhookConfig && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { - Objects.hash( - input, - model, - id, - background, - created, - generationConfig, - previousInteractionId, - responseFormat, - responseMimeType, - responseModalities, - role, - serviceTier, - status, - store, - stream, - systemInstruction, - tools, - updated, - usage, - webhookConfig, - additionalProperties, - ) - } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "CreateModelInteractionParams{input=$input, model=$model, id=$id, background=$background, created=$created, generationConfig=$generationConfig, previousInteractionId=$previousInteractionId, responseFormat=$responseFormat, responseMimeType=$responseMimeType, responseModalities=$responseModalities, role=$role, serviceTier=$serviceTier, status=$status, store=$store, stream=$stream, systemInstruction=$systemInstruction, tools=$tools, updated=$updated, usage=$usage, webhookConfig=$webhookConfig, additionalProperties=$additionalProperties}" -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/DeepResearchAgentConfig.kt b/src/main/java/com/google/genai/interactions/models/interactions/DeepResearchAgentConfig.kt deleted file mode 100644 index 7ba2d68d7da..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/DeepResearchAgentConfig.kt +++ /dev/null @@ -1,591 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import com.google.genai.interactions.core.Enum -import com.google.genai.interactions.core.ExcludeMissing -import com.google.genai.interactions.core.JsonField -import com.google.genai.interactions.core.JsonMissing -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.util.Collections -import java.util.Objects -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -/** Configuration for the Deep Research agent. */ -class DeepResearchAgentConfig -@JsonCreator(mode = JsonCreator.Mode.DISABLED) -private constructor( - private val type: JsonValue, - private val collaborativePlanning: JsonField, - private val thinkingSummaries: JsonField, - private val visualization: JsonField, - private val additionalProperties: MutableMap, -) { - - @JsonCreator - private constructor( - @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), - @JsonProperty("collaborative_planning") - @ExcludeMissing - collaborativePlanning: JsonField = JsonMissing.of(), - @JsonProperty("thinking_summaries") - @ExcludeMissing - thinkingSummaries: JsonField = JsonMissing.of(), - @JsonProperty("visualization") - @ExcludeMissing - visualization: JsonField = JsonMissing.of(), - ) : this(type, collaborativePlanning, thinkingSummaries, visualization, mutableMapOf()) - - /** - * Expected to always return the following: - * ```java - * JsonValue.from("deep-research") - * ``` - * - * However, this method can be useful for debugging and logging (e.g. if the server responded - * with an unexpected value). - */ - @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type - - /** - * Enables human-in-the-loop planning for the Deep Research agent. If set to true, the Deep - * Research agent will provide a research plan in its response. The agent will then proceed only - * if the user confirms the plan in the next turn. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun collaborativePlanning(): Optional = - collaborativePlanning.getOptional("collaborative_planning") - - /** - * Whether to include thought summaries in the response. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun thinkingSummaries(): Optional = - thinkingSummaries.getOptional("thinking_summaries") - - /** - * Whether to include visualizations in the response. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun visualization(): Optional = visualization.getOptional("visualization") - - /** - * Returns the raw JSON value of [collaborativePlanning]. - * - * Unlike [collaborativePlanning], this method doesn't throw if the JSON field has an unexpected - * type. - */ - @JsonProperty("collaborative_planning") - @ExcludeMissing - fun _collaborativePlanning(): JsonField = collaborativePlanning - - /** - * Returns the raw JSON value of [thinkingSummaries]. - * - * Unlike [thinkingSummaries], this method doesn't throw if the JSON field has an unexpected - * type. - */ - @JsonProperty("thinking_summaries") - @ExcludeMissing - fun _thinkingSummaries(): JsonField = thinkingSummaries - - /** - * Returns the raw JSON value of [visualization]. - * - * Unlike [visualization], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("visualization") - @ExcludeMissing - fun _visualization(): JsonField = visualization - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [DeepResearchAgentConfig]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [DeepResearchAgentConfig]. */ - class Builder internal constructor() { - - private var type: JsonValue = JsonValue.from("deep-research") - private var collaborativePlanning: JsonField = JsonMissing.of() - private var thinkingSummaries: JsonField = JsonMissing.of() - private var visualization: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(deepResearchAgentConfig: DeepResearchAgentConfig) = apply { - type = deepResearchAgentConfig.type - collaborativePlanning = deepResearchAgentConfig.collaborativePlanning - thinkingSummaries = deepResearchAgentConfig.thinkingSummaries - visualization = deepResearchAgentConfig.visualization - additionalProperties = deepResearchAgentConfig.additionalProperties.toMutableMap() - } - - /** - * Sets the field to an arbitrary JSON value. - * - * It is usually unnecessary to call this method because the field defaults to the - * following: - * ```java - * JsonValue.from("deep-research") - * ``` - * - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun type(type: JsonValue) = apply { this.type = type } - - /** - * Enables human-in-the-loop planning for the Deep Research agent. If set to true, the Deep - * Research agent will provide a research plan in its response. The agent will then proceed - * only if the user confirms the plan in the next turn. - */ - fun collaborativePlanning(collaborativePlanning: Boolean) = - collaborativePlanning(JsonField.of(collaborativePlanning)) - - /** - * Sets [Builder.collaborativePlanning] to an arbitrary JSON value. - * - * You should usually call [Builder.collaborativePlanning] with a well-typed [Boolean] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun collaborativePlanning(collaborativePlanning: JsonField) = apply { - this.collaborativePlanning = collaborativePlanning - } - - /** Whether to include thought summaries in the response. */ - fun thinkingSummaries(thinkingSummaries: ThinkingSummaries) = - thinkingSummaries(JsonField.of(thinkingSummaries)) - - /** - * Sets [Builder.thinkingSummaries] to an arbitrary JSON value. - * - * You should usually call [Builder.thinkingSummaries] with a well-typed [ThinkingSummaries] - * value instead. This method is primarily for setting the field to an undocumented or not - * yet supported value. - */ - fun thinkingSummaries(thinkingSummaries: JsonField) = apply { - this.thinkingSummaries = thinkingSummaries - } - - /** Whether to include visualizations in the response. */ - fun visualization(visualization: Visualization) = visualization(JsonField.of(visualization)) - - /** - * Sets [Builder.visualization] to an arbitrary JSON value. - * - * You should usually call [Builder.visualization] with a well-typed [Visualization] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun visualization(visualization: JsonField) = apply { - this.visualization = visualization - } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [DeepResearchAgentConfig]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): DeepResearchAgentConfig = - DeepResearchAgentConfig( - type, - collaborativePlanning, - thinkingSummaries, - visualization, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): DeepResearchAgentConfig = apply { - if (validated) { - return@apply - } - - _type().let { - if (it != JsonValue.from("deep-research")) { - throw GeminiNextGenApiInvalidDataException("'type' is invalid, received $it") - } - } - collaborativePlanning() - thinkingSummaries().ifPresent { it.validate() } - visualization().ifPresent { it.validate() } - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - type.let { if (it == JsonValue.from("deep-research")) 1 else 0 } + - (if (collaborativePlanning.asKnown().isPresent) 1 else 0) + - (thinkingSummaries.asKnown().getOrNull()?.validity() ?: 0) + - (visualization.asKnown().getOrNull()?.validity() ?: 0) - - /** Whether to include thought summaries in the response. */ - class ThinkingSummaries @JsonCreator private constructor(private val value: JsonField) : - Enum { - - /** - * Returns this class instance's raw value. - * - * This is usually only useful if this instance was deserialized from data that doesn't - * match any known member, and you want to know that value. For example, if the SDK is on an - * older version than the API, then the API may respond with new members that the SDK is - * unaware of. - */ - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - companion object { - - @JvmField val AUTO = of("auto") - - @JvmField val NONE = of("none") - - @JvmStatic fun of(value: String) = ThinkingSummaries(JsonField.of(value)) - } - - /** An enum containing [ThinkingSummaries]'s known values. */ - enum class Known { - AUTO, - NONE, - } - - /** - * An enum containing [ThinkingSummaries]'s known values, as well as an [_UNKNOWN] member. - * - * An instance of [ThinkingSummaries] can contain an unknown value in a couple of cases: - * - It was deserialized from data that doesn't match any known member. For example, if the - * SDK is on an older version than the API, then the API may respond with new members that - * the SDK is unaware of. - * - It was constructed with an arbitrary value using the [of] method. - */ - enum class Value { - AUTO, - NONE, - /** - * An enum member indicating that [ThinkingSummaries] was instantiated with an unknown - * value. - */ - _UNKNOWN, - } - - /** - * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] - * if the class was instantiated with an unknown value. - * - * Use the [known] method instead if you're certain the value is always known or if you want - * to throw for the unknown case. - */ - fun value(): Value = - when (this) { - AUTO -> Value.AUTO - NONE -> Value.NONE - else -> Value._UNKNOWN - } - - /** - * Returns an enum member corresponding to this class instance's value. - * - * Use the [value] method instead if you're uncertain the value is always known and don't - * want to throw for the unknown case. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value is a not a - * known member. - */ - fun known(): Known = - when (this) { - AUTO -> Known.AUTO - NONE -> Known.NONE - else -> - throw GeminiNextGenApiInvalidDataException("Unknown ThinkingSummaries: $value") - } - - /** - * Returns this class instance's primitive wire representation. - * - * This differs from the [toString] method because that method is primarily for debugging - * and generally doesn't throw. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value does not have - * the expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - GeminiNextGenApiInvalidDataException("Value is not a String") - } - - private var validated: Boolean = false - - fun validate(): ThinkingSummaries = apply { - if (validated) { - return@apply - } - - known() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is ThinkingSummaries && value == other.value - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - /** Whether to include visualizations in the response. */ - class Visualization @JsonCreator private constructor(private val value: JsonField) : - Enum { - - /** - * Returns this class instance's raw value. - * - * This is usually only useful if this instance was deserialized from data that doesn't - * match any known member, and you want to know that value. For example, if the SDK is on an - * older version than the API, then the API may respond with new members that the SDK is - * unaware of. - */ - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - companion object { - - @JvmField val OFF = of("off") - - @JvmField val AUTO = of("auto") - - @JvmStatic fun of(value: String) = Visualization(JsonField.of(value)) - } - - /** An enum containing [Visualization]'s known values. */ - enum class Known { - OFF, - AUTO, - } - - /** - * An enum containing [Visualization]'s known values, as well as an [_UNKNOWN] member. - * - * An instance of [Visualization] can contain an unknown value in a couple of cases: - * - It was deserialized from data that doesn't match any known member. For example, if the - * SDK is on an older version than the API, then the API may respond with new members that - * the SDK is unaware of. - * - It was constructed with an arbitrary value using the [of] method. - */ - enum class Value { - OFF, - AUTO, - /** - * An enum member indicating that [Visualization] was instantiated with an unknown - * value. - */ - _UNKNOWN, - } - - /** - * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] - * if the class was instantiated with an unknown value. - * - * Use the [known] method instead if you're certain the value is always known or if you want - * to throw for the unknown case. - */ - fun value(): Value = - when (this) { - OFF -> Value.OFF - AUTO -> Value.AUTO - else -> Value._UNKNOWN - } - - /** - * Returns an enum member corresponding to this class instance's value. - * - * Use the [value] method instead if you're uncertain the value is always known and don't - * want to throw for the unknown case. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value is a not a - * known member. - */ - fun known(): Known = - when (this) { - OFF -> Known.OFF - AUTO -> Known.AUTO - else -> throw GeminiNextGenApiInvalidDataException("Unknown Visualization: $value") - } - - /** - * Returns this class instance's primitive wire representation. - * - * This differs from the [toString] method because that method is primarily for debugging - * and generally doesn't throw. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value does not have - * the expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - GeminiNextGenApiInvalidDataException("Value is not a String") - } - - private var validated: Boolean = false - - fun validate(): Visualization = apply { - if (validated) { - return@apply - } - - known() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Visualization && value == other.value - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is DeepResearchAgentConfig && - type == other.type && - collaborativePlanning == other.collaborativePlanning && - thinkingSummaries == other.thinkingSummaries && - visualization == other.visualization && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { - Objects.hash( - type, - collaborativePlanning, - thinkingSummaries, - visualization, - additionalProperties, - ) - } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "DeepResearchAgentConfig{type=$type, collaborativePlanning=$collaborativePlanning, thinkingSummaries=$thinkingSummaries, visualization=$visualization, additionalProperties=$additionalProperties}" -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/DocumentContent.kt b/src/main/java/com/google/genai/interactions/models/interactions/DocumentContent.kt deleted file mode 100644 index d968b36ccc9..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/DocumentContent.kt +++ /dev/null @@ -1,404 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import com.google.genai.interactions.core.Enum -import com.google.genai.interactions.core.ExcludeMissing -import com.google.genai.interactions.core.JsonField -import com.google.genai.interactions.core.JsonMissing -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.util.Collections -import java.util.Objects -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -/** A document content block. */ -class DocumentContent -@JsonCreator(mode = JsonCreator.Mode.DISABLED) -private constructor( - private val type: JsonValue, - private val data: JsonField, - private val mimeType: JsonField, - private val uri: JsonField, - private val additionalProperties: MutableMap, -) { - - @JsonCreator - private constructor( - @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), - @JsonProperty("data") @ExcludeMissing data: JsonField = JsonMissing.of(), - @JsonProperty("mime_type") @ExcludeMissing mimeType: JsonField = JsonMissing.of(), - @JsonProperty("uri") @ExcludeMissing uri: JsonField = JsonMissing.of(), - ) : this(type, data, mimeType, uri, mutableMapOf()) - - /** - * Expected to always return the following: - * ```java - * JsonValue.from("document") - * ``` - * - * However, this method can be useful for debugging and logging (e.g. if the server responded - * with an unexpected value). - */ - @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type - - /** - * The document content. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun data(): Optional = data.getOptional("data") - - /** - * The mime type of the document. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun mimeType(): Optional = mimeType.getOptional("mime_type") - - /** - * The URI of the document. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun uri(): Optional = uri.getOptional("uri") - - /** - * Returns the raw JSON value of [data]. - * - * Unlike [data], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("data") @ExcludeMissing fun _data(): JsonField = data - - /** - * Returns the raw JSON value of [mimeType]. - * - * Unlike [mimeType], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("mime_type") @ExcludeMissing fun _mimeType(): JsonField = mimeType - - /** - * Returns the raw JSON value of [uri]. - * - * Unlike [uri], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("uri") @ExcludeMissing fun _uri(): JsonField = uri - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [DocumentContent]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [DocumentContent]. */ - class Builder internal constructor() { - - private var type: JsonValue = JsonValue.from("document") - private var data: JsonField = JsonMissing.of() - private var mimeType: JsonField = JsonMissing.of() - private var uri: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(documentContent: DocumentContent) = apply { - type = documentContent.type - data = documentContent.data - mimeType = documentContent.mimeType - uri = documentContent.uri - additionalProperties = documentContent.additionalProperties.toMutableMap() - } - - /** - * Sets the field to an arbitrary JSON value. - * - * It is usually unnecessary to call this method because the field defaults to the - * following: - * ```java - * JsonValue.from("document") - * ``` - * - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun type(type: JsonValue) = apply { this.type = type } - - /** The document content. */ - fun data(data: String) = data(JsonField.of(data)) - - /** - * Sets [Builder.data] to an arbitrary JSON value. - * - * You should usually call [Builder.data] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun data(data: JsonField) = apply { this.data = data } - - /** The mime type of the document. */ - fun mimeType(mimeType: MimeType) = mimeType(JsonField.of(mimeType)) - - /** - * Sets [Builder.mimeType] to an arbitrary JSON value. - * - * You should usually call [Builder.mimeType] with a well-typed [MimeType] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun mimeType(mimeType: JsonField) = apply { this.mimeType = mimeType } - - /** The URI of the document. */ - fun uri(uri: String) = uri(JsonField.of(uri)) - - /** - * Sets [Builder.uri] to an arbitrary JSON value. - * - * You should usually call [Builder.uri] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun uri(uri: JsonField) = apply { this.uri = uri } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [DocumentContent]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): DocumentContent = - DocumentContent(type, data, mimeType, uri, additionalProperties.toMutableMap()) - } - - private var validated: Boolean = false - - fun validate(): DocumentContent = apply { - if (validated) { - return@apply - } - - _type().let { - if (it != JsonValue.from("document")) { - throw GeminiNextGenApiInvalidDataException("'type' is invalid, received $it") - } - } - data() - mimeType().ifPresent { it.validate() } - uri() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - type.let { if (it == JsonValue.from("document")) 1 else 0 } + - (if (data.asKnown().isPresent) 1 else 0) + - (mimeType.asKnown().getOrNull()?.validity() ?: 0) + - (if (uri.asKnown().isPresent) 1 else 0) - - /** The mime type of the document. */ - class MimeType @JsonCreator private constructor(private val value: JsonField) : Enum { - - /** - * Returns this class instance's raw value. - * - * This is usually only useful if this instance was deserialized from data that doesn't - * match any known member, and you want to know that value. For example, if the SDK is on an - * older version than the API, then the API may respond with new members that the SDK is - * unaware of. - */ - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - companion object { - - @JvmField val APPLICATION_PDF = of("application/pdf") - - @JvmStatic fun of(value: String) = MimeType(JsonField.of(value)) - } - - /** An enum containing [MimeType]'s known values. */ - enum class Known { - APPLICATION_PDF - } - - /** - * An enum containing [MimeType]'s known values, as well as an [_UNKNOWN] member. - * - * An instance of [MimeType] can contain an unknown value in a couple of cases: - * - It was deserialized from data that doesn't match any known member. For example, if the - * SDK is on an older version than the API, then the API may respond with new members that - * the SDK is unaware of. - * - It was constructed with an arbitrary value using the [of] method. - */ - enum class Value { - APPLICATION_PDF, - /** An enum member indicating that [MimeType] was instantiated with an unknown value. */ - _UNKNOWN, - } - - /** - * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] - * if the class was instantiated with an unknown value. - * - * Use the [known] method instead if you're certain the value is always known or if you want - * to throw for the unknown case. - */ - fun value(): Value = - when (this) { - APPLICATION_PDF -> Value.APPLICATION_PDF - else -> Value._UNKNOWN - } - - /** - * Returns an enum member corresponding to this class instance's value. - * - * Use the [value] method instead if you're uncertain the value is always known and don't - * want to throw for the unknown case. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value is a not a - * known member. - */ - fun known(): Known = - when (this) { - APPLICATION_PDF -> Known.APPLICATION_PDF - else -> throw GeminiNextGenApiInvalidDataException("Unknown MimeType: $value") - } - - /** - * Returns this class instance's primitive wire representation. - * - * This differs from the [toString] method because that method is primarily for debugging - * and generally doesn't throw. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value does not have - * the expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - GeminiNextGenApiInvalidDataException("Value is not a String") - } - - private var validated: Boolean = false - - fun validate(): MimeType = apply { - if (validated) { - return@apply - } - - known() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is MimeType && value == other.value - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is DocumentContent && - type == other.type && - data == other.data && - mimeType == other.mimeType && - uri == other.uri && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { - Objects.hash(type, data, mimeType, uri, additionalProperties) - } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "DocumentContent{type=$type, data=$data, mimeType=$mimeType, uri=$uri, additionalProperties=$additionalProperties}" -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/DynamicAgentConfig.kt b/src/main/java/com/google/genai/interactions/models/interactions/DynamicAgentConfig.kt deleted file mode 100644 index 3df27a60d27..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/DynamicAgentConfig.kt +++ /dev/null @@ -1,175 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import com.google.genai.interactions.core.ExcludeMissing -import com.google.genai.interactions.core.JsonMissing -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.util.Collections -import java.util.Objects - -/** Configuration for dynamic agents. */ -class DynamicAgentConfig -@JsonCreator(mode = JsonCreator.Mode.DISABLED) -private constructor( - private val type: JsonValue, - private val additionalProperties: MutableMap, -) { - - @JsonCreator - private constructor( - @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of() - ) : this(type, mutableMapOf()) - - /** - * Expected to always return the following: - * ```java - * JsonValue.from("dynamic") - * ``` - * - * However, this method can be useful for debugging and logging (e.g. if the server responded - * with an unexpected value). - */ - @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [DynamicAgentConfig]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [DynamicAgentConfig]. */ - class Builder internal constructor() { - - private var type: JsonValue = JsonValue.from("dynamic") - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(dynamicAgentConfig: DynamicAgentConfig) = apply { - type = dynamicAgentConfig.type - additionalProperties = dynamicAgentConfig.additionalProperties.toMutableMap() - } - - /** - * Sets the field to an arbitrary JSON value. - * - * It is usually unnecessary to call this method because the field defaults to the - * following: - * ```java - * JsonValue.from("dynamic") - * ``` - * - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun type(type: JsonValue) = apply { this.type = type } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [DynamicAgentConfig]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): DynamicAgentConfig = - DynamicAgentConfig(type, additionalProperties.toMutableMap()) - } - - private var validated: Boolean = false - - fun validate(): DynamicAgentConfig = apply { - if (validated) { - return@apply - } - - _type().let { - if (it != JsonValue.from("dynamic")) { - throw GeminiNextGenApiInvalidDataException("'type' is invalid, received $it") - } - } - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = type.let { if (it == JsonValue.from("dynamic")) 1 else 0 } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is DynamicAgentConfig && - type == other.type && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { Objects.hash(type, additionalProperties) } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "DynamicAgentConfig{type=$type, additionalProperties=$additionalProperties}" -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/ErrorEvent.kt b/src/main/java/com/google/genai/interactions/models/interactions/ErrorEvent.kt deleted file mode 100644 index 8b1e68371b6..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/ErrorEvent.kt +++ /dev/null @@ -1,423 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import com.google.genai.interactions.core.ExcludeMissing -import com.google.genai.interactions.core.JsonField -import com.google.genai.interactions.core.JsonMissing -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.util.Collections -import java.util.Objects -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -class ErrorEvent -@JsonCreator(mode = JsonCreator.Mode.DISABLED) -private constructor( - private val eventType: JsonValue, - private val error: JsonField, - private val eventId: JsonField, - private val additionalProperties: MutableMap, -) { - - @JsonCreator - private constructor( - @JsonProperty("event_type") @ExcludeMissing eventType: JsonValue = JsonMissing.of(), - @JsonProperty("error") @ExcludeMissing error: JsonField = JsonMissing.of(), - @JsonProperty("event_id") @ExcludeMissing eventId: JsonField = JsonMissing.of(), - ) : this(eventType, error, eventId, mutableMapOf()) - - /** - * Expected to always return the following: - * ```java - * JsonValue.from("error") - * ``` - * - * However, this method can be useful for debugging and logging (e.g. if the server responded - * with an unexpected value). - */ - @JsonProperty("event_type") @ExcludeMissing fun _eventType(): JsonValue = eventType - - /** - * Error message from an interaction. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun error(): Optional = error.getOptional("error") - - /** - * The event_id token to be used to resume the interaction stream, from this event. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun eventId(): Optional = eventId.getOptional("event_id") - - /** - * Returns the raw JSON value of [error]. - * - * Unlike [error], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("error") @ExcludeMissing fun _error(): JsonField = error - - /** - * Returns the raw JSON value of [eventId]. - * - * Unlike [eventId], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("event_id") @ExcludeMissing fun _eventId(): JsonField = eventId - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [ErrorEvent]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [ErrorEvent]. */ - class Builder internal constructor() { - - private var eventType: JsonValue = JsonValue.from("error") - private var error: JsonField = JsonMissing.of() - private var eventId: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(errorEvent: ErrorEvent) = apply { - eventType = errorEvent.eventType - error = errorEvent.error - eventId = errorEvent.eventId - additionalProperties = errorEvent.additionalProperties.toMutableMap() - } - - /** - * Sets the field to an arbitrary JSON value. - * - * It is usually unnecessary to call this method because the field defaults to the - * following: - * ```java - * JsonValue.from("error") - * ``` - * - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun eventType(eventType: JsonValue) = apply { this.eventType = eventType } - - /** Error message from an interaction. */ - fun error(error: Error) = error(JsonField.of(error)) - - /** - * Sets [Builder.error] to an arbitrary JSON value. - * - * You should usually call [Builder.error] with a well-typed [Error] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun error(error: JsonField) = apply { this.error = error } - - /** The event_id token to be used to resume the interaction stream, from this event. */ - fun eventId(eventId: String) = eventId(JsonField.of(eventId)) - - /** - * Sets [Builder.eventId] to an arbitrary JSON value. - * - * You should usually call [Builder.eventId] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun eventId(eventId: JsonField) = apply { this.eventId = eventId } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [ErrorEvent]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): ErrorEvent = - ErrorEvent(eventType, error, eventId, additionalProperties.toMutableMap()) - } - - private var validated: Boolean = false - - fun validate(): ErrorEvent = apply { - if (validated) { - return@apply - } - - _eventType().let { - if (it != JsonValue.from("error")) { - throw GeminiNextGenApiInvalidDataException("'eventType' is invalid, received $it") - } - } - error().ifPresent { it.validate() } - eventId() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - eventType.let { if (it == JsonValue.from("error")) 1 else 0 } + - (error.asKnown().getOrNull()?.validity() ?: 0) + - (if (eventId.asKnown().isPresent) 1 else 0) - - /** Error message from an interaction. */ - class Error - @JsonCreator(mode = JsonCreator.Mode.DISABLED) - private constructor( - private val code: JsonField, - private val message: JsonField, - private val additionalProperties: MutableMap, - ) { - - @JsonCreator - private constructor( - @JsonProperty("code") @ExcludeMissing code: JsonField = JsonMissing.of(), - @JsonProperty("message") @ExcludeMissing message: JsonField = JsonMissing.of(), - ) : this(code, message, mutableMapOf()) - - /** - * A URI that identifies the error type. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type - * (e.g. if the server responded with an unexpected value). - */ - fun code(): Optional = code.getOptional("code") - - /** - * A human-readable error message. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type - * (e.g. if the server responded with an unexpected value). - */ - fun message(): Optional = message.getOptional("message") - - /** - * Returns the raw JSON value of [code]. - * - * Unlike [code], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("code") @ExcludeMissing fun _code(): JsonField = code - - /** - * Returns the raw JSON value of [message]. - * - * Unlike [message], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("message") @ExcludeMissing fun _message(): JsonField = message - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [Error]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Error]. */ - class Builder internal constructor() { - - private var code: JsonField = JsonMissing.of() - private var message: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(error: Error) = apply { - code = error.code - message = error.message - additionalProperties = error.additionalProperties.toMutableMap() - } - - /** A URI that identifies the error type. */ - fun code(code: String) = code(JsonField.of(code)) - - /** - * Sets [Builder.code] to an arbitrary JSON value. - * - * You should usually call [Builder.code] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun code(code: JsonField) = apply { this.code = code } - - /** A human-readable error message. */ - fun message(message: String) = message(JsonField.of(message)) - - /** - * Sets [Builder.message] to an arbitrary JSON value. - * - * You should usually call [Builder.message] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun message(message: JsonField) = apply { this.message = message } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [Error]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): Error = Error(code, message, additionalProperties.toMutableMap()) - } - - private var validated: Boolean = false - - fun validate(): Error = apply { - if (validated) { - return@apply - } - - code() - message() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - (if (code.asKnown().isPresent) 1 else 0) + (if (message.asKnown().isPresent) 1 else 0) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Error && - code == other.code && - message == other.message && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { Objects.hash(code, message, additionalProperties) } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Error{code=$code, message=$message, additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is ErrorEvent && - eventType == other.eventType && - error == other.error && - eventId == other.eventId && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { - Objects.hash(eventType, error, eventId, additionalProperties) - } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "ErrorEvent{eventType=$eventType, error=$error, eventId=$eventId, additionalProperties=$additionalProperties}" -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/FileCitation.kt b/src/main/java/com/google/genai/interactions/models/interactions/FileCitation.kt deleted file mode 100644 index af93126baf3..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/FileCitation.kt +++ /dev/null @@ -1,598 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import com.google.genai.interactions.core.ExcludeMissing -import com.google.genai.interactions.core.JsonField -import com.google.genai.interactions.core.JsonMissing -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.core.toImmutable -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.util.Collections -import java.util.Objects -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -/** A file citation annotation. */ -class FileCitation -@JsonCreator(mode = JsonCreator.Mode.DISABLED) -private constructor( - private val type: JsonValue, - private val customMetadata: JsonField, - private val documentUri: JsonField, - private val endIndex: JsonField, - private val fileName: JsonField, - private val mediaId: JsonField, - private val pageNumber: JsonField, - private val source: JsonField, - private val startIndex: JsonField, - private val additionalProperties: MutableMap, -) { - - @JsonCreator - private constructor( - @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), - @JsonProperty("custom_metadata") - @ExcludeMissing - customMetadata: JsonField = JsonMissing.of(), - @JsonProperty("document_uri") - @ExcludeMissing - documentUri: JsonField = JsonMissing.of(), - @JsonProperty("end_index") @ExcludeMissing endIndex: JsonField = JsonMissing.of(), - @JsonProperty("file_name") @ExcludeMissing fileName: JsonField = JsonMissing.of(), - @JsonProperty("media_id") @ExcludeMissing mediaId: JsonField = JsonMissing.of(), - @JsonProperty("page_number") @ExcludeMissing pageNumber: JsonField = JsonMissing.of(), - @JsonProperty("source") @ExcludeMissing source: JsonField = JsonMissing.of(), - @JsonProperty("start_index") @ExcludeMissing startIndex: JsonField = JsonMissing.of(), - ) : this( - type, - customMetadata, - documentUri, - endIndex, - fileName, - mediaId, - pageNumber, - source, - startIndex, - mutableMapOf(), - ) - - /** - * Expected to always return the following: - * ```java - * JsonValue.from("file_citation") - * ``` - * - * However, this method can be useful for debugging and logging (e.g. if the server responded - * with an unexpected value). - */ - @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type - - /** - * User provided metadata about the retrieved context. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun customMetadata(): Optional = customMetadata.getOptional("custom_metadata") - - /** - * The URI of the file. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun documentUri(): Optional = documentUri.getOptional("document_uri") - - /** - * End of the attributed segment, exclusive. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun endIndex(): Optional = endIndex.getOptional("end_index") - - /** - * The name of the file. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun fileName(): Optional = fileName.getOptional("file_name") - - /** - * Media ID in-case of image citations, if applicable. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun mediaId(): Optional = mediaId.getOptional("media_id") - - /** - * Page number of the cited document, if applicable. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun pageNumber(): Optional = pageNumber.getOptional("page_number") - - /** - * Source attributed for a portion of the text. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun source(): Optional = source.getOptional("source") - - /** - * Start of segment of the response that is attributed to this source. - * - * Index indicates the start of the segment, measured in bytes. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun startIndex(): Optional = startIndex.getOptional("start_index") - - /** - * Returns the raw JSON value of [customMetadata]. - * - * Unlike [customMetadata], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("custom_metadata") - @ExcludeMissing - fun _customMetadata(): JsonField = customMetadata - - /** - * Returns the raw JSON value of [documentUri]. - * - * Unlike [documentUri], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("document_uri") - @ExcludeMissing - fun _documentUri(): JsonField = documentUri - - /** - * Returns the raw JSON value of [endIndex]. - * - * Unlike [endIndex], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("end_index") @ExcludeMissing fun _endIndex(): JsonField = endIndex - - /** - * Returns the raw JSON value of [fileName]. - * - * Unlike [fileName], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("file_name") @ExcludeMissing fun _fileName(): JsonField = fileName - - /** - * Returns the raw JSON value of [mediaId]. - * - * Unlike [mediaId], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("media_id") @ExcludeMissing fun _mediaId(): JsonField = mediaId - - /** - * Returns the raw JSON value of [pageNumber]. - * - * Unlike [pageNumber], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("page_number") @ExcludeMissing fun _pageNumber(): JsonField = pageNumber - - /** - * Returns the raw JSON value of [source]. - * - * Unlike [source], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("source") @ExcludeMissing fun _source(): JsonField = source - - /** - * Returns the raw JSON value of [startIndex]. - * - * Unlike [startIndex], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("start_index") @ExcludeMissing fun _startIndex(): JsonField = startIndex - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [FileCitation]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [FileCitation]. */ - class Builder internal constructor() { - - private var type: JsonValue = JsonValue.from("file_citation") - private var customMetadata: JsonField = JsonMissing.of() - private var documentUri: JsonField = JsonMissing.of() - private var endIndex: JsonField = JsonMissing.of() - private var fileName: JsonField = JsonMissing.of() - private var mediaId: JsonField = JsonMissing.of() - private var pageNumber: JsonField = JsonMissing.of() - private var source: JsonField = JsonMissing.of() - private var startIndex: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(fileCitation: FileCitation) = apply { - type = fileCitation.type - customMetadata = fileCitation.customMetadata - documentUri = fileCitation.documentUri - endIndex = fileCitation.endIndex - fileName = fileCitation.fileName - mediaId = fileCitation.mediaId - pageNumber = fileCitation.pageNumber - source = fileCitation.source - startIndex = fileCitation.startIndex - additionalProperties = fileCitation.additionalProperties.toMutableMap() - } - - /** - * Sets the field to an arbitrary JSON value. - * - * It is usually unnecessary to call this method because the field defaults to the - * following: - * ```java - * JsonValue.from("file_citation") - * ``` - * - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun type(type: JsonValue) = apply { this.type = type } - - /** User provided metadata about the retrieved context. */ - fun customMetadata(customMetadata: CustomMetadata) = - customMetadata(JsonField.of(customMetadata)) - - /** - * Sets [Builder.customMetadata] to an arbitrary JSON value. - * - * You should usually call [Builder.customMetadata] with a well-typed [CustomMetadata] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun customMetadata(customMetadata: JsonField) = apply { - this.customMetadata = customMetadata - } - - /** The URI of the file. */ - fun documentUri(documentUri: String) = documentUri(JsonField.of(documentUri)) - - /** - * Sets [Builder.documentUri] to an arbitrary JSON value. - * - * You should usually call [Builder.documentUri] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun documentUri(documentUri: JsonField) = apply { this.documentUri = documentUri } - - /** End of the attributed segment, exclusive. */ - fun endIndex(endIndex: Int) = endIndex(JsonField.of(endIndex)) - - /** - * Sets [Builder.endIndex] to an arbitrary JSON value. - * - * You should usually call [Builder.endIndex] with a well-typed [Int] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun endIndex(endIndex: JsonField) = apply { this.endIndex = endIndex } - - /** The name of the file. */ - fun fileName(fileName: String) = fileName(JsonField.of(fileName)) - - /** - * Sets [Builder.fileName] to an arbitrary JSON value. - * - * You should usually call [Builder.fileName] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun fileName(fileName: JsonField) = apply { this.fileName = fileName } - - /** Media ID in-case of image citations, if applicable. */ - fun mediaId(mediaId: String) = mediaId(JsonField.of(mediaId)) - - /** - * Sets [Builder.mediaId] to an arbitrary JSON value. - * - * You should usually call [Builder.mediaId] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun mediaId(mediaId: JsonField) = apply { this.mediaId = mediaId } - - /** Page number of the cited document, if applicable. */ - fun pageNumber(pageNumber: Int) = pageNumber(JsonField.of(pageNumber)) - - /** - * Sets [Builder.pageNumber] to an arbitrary JSON value. - * - * You should usually call [Builder.pageNumber] with a well-typed [Int] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun pageNumber(pageNumber: JsonField) = apply { this.pageNumber = pageNumber } - - /** Source attributed for a portion of the text. */ - fun source(source: String) = source(JsonField.of(source)) - - /** - * Sets [Builder.source] to an arbitrary JSON value. - * - * You should usually call [Builder.source] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun source(source: JsonField) = apply { this.source = source } - - /** - * Start of segment of the response that is attributed to this source. - * - * Index indicates the start of the segment, measured in bytes. - */ - fun startIndex(startIndex: Int) = startIndex(JsonField.of(startIndex)) - - /** - * Sets [Builder.startIndex] to an arbitrary JSON value. - * - * You should usually call [Builder.startIndex] with a well-typed [Int] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun startIndex(startIndex: JsonField) = apply { this.startIndex = startIndex } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [FileCitation]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): FileCitation = - FileCitation( - type, - customMetadata, - documentUri, - endIndex, - fileName, - mediaId, - pageNumber, - source, - startIndex, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): FileCitation = apply { - if (validated) { - return@apply - } - - _type().let { - if (it != JsonValue.from("file_citation")) { - throw GeminiNextGenApiInvalidDataException("'type' is invalid, received $it") - } - } - customMetadata().ifPresent { it.validate() } - documentUri() - endIndex() - fileName() - mediaId() - pageNumber() - source() - startIndex() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - type.let { if (it == JsonValue.from("file_citation")) 1 else 0 } + - (customMetadata.asKnown().getOrNull()?.validity() ?: 0) + - (if (documentUri.asKnown().isPresent) 1 else 0) + - (if (endIndex.asKnown().isPresent) 1 else 0) + - (if (fileName.asKnown().isPresent) 1 else 0) + - (if (mediaId.asKnown().isPresent) 1 else 0) + - (if (pageNumber.asKnown().isPresent) 1 else 0) + - (if (source.asKnown().isPresent) 1 else 0) + - (if (startIndex.asKnown().isPresent) 1 else 0) - - /** User provided metadata about the retrieved context. */ - class CustomMetadata - @JsonCreator - private constructor( - @com.fasterxml.jackson.annotation.JsonValue - private val additionalProperties: Map - ) { - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [CustomMetadata]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [CustomMetadata]. */ - class Builder internal constructor() { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(customMetadata: CustomMetadata) = apply { - additionalProperties = customMetadata.additionalProperties.toMutableMap() - } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [CustomMetadata]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): CustomMetadata = CustomMetadata(additionalProperties.toImmutable()) - } - - private var validated: Boolean = false - - fun validate(): CustomMetadata = apply { - if (validated) { - return@apply - } - - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is CustomMetadata && additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - - override fun hashCode(): Int = hashCode - - override fun toString() = "CustomMetadata{additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is FileCitation && - type == other.type && - customMetadata == other.customMetadata && - documentUri == other.documentUri && - endIndex == other.endIndex && - fileName == other.fileName && - mediaId == other.mediaId && - pageNumber == other.pageNumber && - source == other.source && - startIndex == other.startIndex && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { - Objects.hash( - type, - customMetadata, - documentUri, - endIndex, - fileName, - mediaId, - pageNumber, - source, - startIndex, - additionalProperties, - ) - } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "FileCitation{type=$type, customMetadata=$customMetadata, documentUri=$documentUri, endIndex=$endIndex, fileName=$fileName, mediaId=$mediaId, pageNumber=$pageNumber, source=$source, startIndex=$startIndex, additionalProperties=$additionalProperties}" -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/FileSearchCallStep.kt b/src/main/java/com/google/genai/interactions/models/interactions/FileSearchCallStep.kt deleted file mode 100644 index 796a32ceedc..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/FileSearchCallStep.kt +++ /dev/null @@ -1,265 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import com.google.genai.interactions.core.ExcludeMissing -import com.google.genai.interactions.core.JsonField -import com.google.genai.interactions.core.JsonMissing -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.core.checkRequired -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.util.Collections -import java.util.Objects -import java.util.Optional - -/** File Search call step. */ -class FileSearchCallStep -@JsonCreator(mode = JsonCreator.Mode.DISABLED) -private constructor( - private val id: JsonField, - private val type: JsonValue, - private val signature: JsonField, - private val additionalProperties: MutableMap, -) { - - @JsonCreator - private constructor( - @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), - @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), - @JsonProperty("signature") @ExcludeMissing signature: JsonField = JsonMissing.of(), - ) : this(id, type, signature, mutableMapOf()) - - /** - * Required. A unique ID for this specific tool call. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). - */ - fun id(): String = id.getRequired("id") - - /** - * Expected to always return the following: - * ```java - * JsonValue.from("file_search_call") - * ``` - * - * However, this method can be useful for debugging and logging (e.g. if the server responded - * with an unexpected value). - */ - @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type - - /** - * A signature hash for backend validation. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun signature(): Optional = signature.getOptional("signature") - - /** - * Returns the raw JSON value of [id]. - * - * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id - - /** - * Returns the raw JSON value of [signature]. - * - * Unlike [signature], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("signature") @ExcludeMissing fun _signature(): JsonField = signature - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [FileSearchCallStep]. - * - * The following fields are required: - * ```java - * .id() - * ``` - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [FileSearchCallStep]. */ - class Builder internal constructor() { - - private var id: JsonField? = null - private var type: JsonValue = JsonValue.from("file_search_call") - private var signature: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(fileSearchCallStep: FileSearchCallStep) = apply { - id = fileSearchCallStep.id - type = fileSearchCallStep.type - signature = fileSearchCallStep.signature - additionalProperties = fileSearchCallStep.additionalProperties.toMutableMap() - } - - /** Required. A unique ID for this specific tool call. */ - fun id(id: String) = id(JsonField.of(id)) - - /** - * Sets [Builder.id] to an arbitrary JSON value. - * - * You should usually call [Builder.id] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun id(id: JsonField) = apply { this.id = id } - - /** - * Sets the field to an arbitrary JSON value. - * - * It is usually unnecessary to call this method because the field defaults to the - * following: - * ```java - * JsonValue.from("file_search_call") - * ``` - * - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun type(type: JsonValue) = apply { this.type = type } - - /** A signature hash for backend validation. */ - fun signature(signature: String) = signature(JsonField.of(signature)) - - /** - * Sets [Builder.signature] to an arbitrary JSON value. - * - * You should usually call [Builder.signature] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun signature(signature: JsonField) = apply { this.signature = signature } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [FileSearchCallStep]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .id() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): FileSearchCallStep = - FileSearchCallStep( - checkRequired("id", id), - type, - signature, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): FileSearchCallStep = apply { - if (validated) { - return@apply - } - - id() - _type().let { - if (it != JsonValue.from("file_search_call")) { - throw GeminiNextGenApiInvalidDataException("'type' is invalid, received $it") - } - } - signature() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - (if (id.asKnown().isPresent) 1 else 0) + - type.let { if (it == JsonValue.from("file_search_call")) 1 else 0 } + - (if (signature.asKnown().isPresent) 1 else 0) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is FileSearchCallStep && - id == other.id && - type == other.type && - signature == other.signature && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { Objects.hash(id, type, signature, additionalProperties) } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "FileSearchCallStep{id=$id, type=$type, signature=$signature, additionalProperties=$additionalProperties}" -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/FileSearchResultStep.kt b/src/main/java/com/google/genai/interactions/models/interactions/FileSearchResultStep.kt deleted file mode 100644 index fbfb2faa072..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/FileSearchResultStep.kt +++ /dev/null @@ -1,267 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import com.google.genai.interactions.core.ExcludeMissing -import com.google.genai.interactions.core.JsonField -import com.google.genai.interactions.core.JsonMissing -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.core.checkRequired -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.util.Collections -import java.util.Objects -import java.util.Optional - -/** File Search result step. */ -class FileSearchResultStep -@JsonCreator(mode = JsonCreator.Mode.DISABLED) -private constructor( - private val callId: JsonField, - private val type: JsonValue, - private val signature: JsonField, - private val additionalProperties: MutableMap, -) { - - @JsonCreator - private constructor( - @JsonProperty("call_id") @ExcludeMissing callId: JsonField = JsonMissing.of(), - @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), - @JsonProperty("signature") @ExcludeMissing signature: JsonField = JsonMissing.of(), - ) : this(callId, type, signature, mutableMapOf()) - - /** - * Required. ID to match the ID from the function call block. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). - */ - fun callId(): String = callId.getRequired("call_id") - - /** - * Expected to always return the following: - * ```java - * JsonValue.from("file_search_result") - * ``` - * - * However, this method can be useful for debugging and logging (e.g. if the server responded - * with an unexpected value). - */ - @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type - - /** - * A signature hash for backend validation. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun signature(): Optional = signature.getOptional("signature") - - /** - * Returns the raw JSON value of [callId]. - * - * Unlike [callId], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("call_id") @ExcludeMissing fun _callId(): JsonField = callId - - /** - * Returns the raw JSON value of [signature]. - * - * Unlike [signature], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("signature") @ExcludeMissing fun _signature(): JsonField = signature - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [FileSearchResultStep]. - * - * The following fields are required: - * ```java - * .callId() - * ``` - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [FileSearchResultStep]. */ - class Builder internal constructor() { - - private var callId: JsonField? = null - private var type: JsonValue = JsonValue.from("file_search_result") - private var signature: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(fileSearchResultStep: FileSearchResultStep) = apply { - callId = fileSearchResultStep.callId - type = fileSearchResultStep.type - signature = fileSearchResultStep.signature - additionalProperties = fileSearchResultStep.additionalProperties.toMutableMap() - } - - /** Required. ID to match the ID from the function call block. */ - fun callId(callId: String) = callId(JsonField.of(callId)) - - /** - * Sets [Builder.callId] to an arbitrary JSON value. - * - * You should usually call [Builder.callId] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun callId(callId: JsonField) = apply { this.callId = callId } - - /** - * Sets the field to an arbitrary JSON value. - * - * It is usually unnecessary to call this method because the field defaults to the - * following: - * ```java - * JsonValue.from("file_search_result") - * ``` - * - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun type(type: JsonValue) = apply { this.type = type } - - /** A signature hash for backend validation. */ - fun signature(signature: String) = signature(JsonField.of(signature)) - - /** - * Sets [Builder.signature] to an arbitrary JSON value. - * - * You should usually call [Builder.signature] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun signature(signature: JsonField) = apply { this.signature = signature } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [FileSearchResultStep]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .callId() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): FileSearchResultStep = - FileSearchResultStep( - checkRequired("callId", callId), - type, - signature, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): FileSearchResultStep = apply { - if (validated) { - return@apply - } - - callId() - _type().let { - if (it != JsonValue.from("file_search_result")) { - throw GeminiNextGenApiInvalidDataException("'type' is invalid, received $it") - } - } - signature() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - (if (callId.asKnown().isPresent) 1 else 0) + - type.let { if (it == JsonValue.from("file_search_result")) 1 else 0 } + - (if (signature.asKnown().isPresent) 1 else 0) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is FileSearchResultStep && - callId == other.callId && - type == other.type && - signature == other.signature && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { - Objects.hash(callId, type, signature, additionalProperties) - } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "FileSearchResultStep{callId=$callId, type=$type, signature=$signature, additionalProperties=$additionalProperties}" -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/Function.kt b/src/main/java/com/google/genai/interactions/models/interactions/Function.kt deleted file mode 100644 index b9b247144ba..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/Function.kt +++ /dev/null @@ -1,267 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import com.google.genai.interactions.core.ExcludeMissing -import com.google.genai.interactions.core.JsonField -import com.google.genai.interactions.core.JsonMissing -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.util.Collections -import java.util.Objects -import java.util.Optional - -/** A tool that can be used by the model. */ -class Function -@JsonCreator(mode = JsonCreator.Mode.DISABLED) -private constructor( - private val type: JsonValue, - private val description: JsonField, - private val name: JsonField, - private val parameters: JsonValue, - private val additionalProperties: MutableMap, -) { - - @JsonCreator - private constructor( - @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), - @JsonProperty("description") - @ExcludeMissing - description: JsonField = JsonMissing.of(), - @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), - @JsonProperty("parameters") @ExcludeMissing parameters: JsonValue = JsonMissing.of(), - ) : this(type, description, name, parameters, mutableMapOf()) - - /** - * Expected to always return the following: - * ```java - * JsonValue.from("function") - * ``` - * - * However, this method can be useful for debugging and logging (e.g. if the server responded - * with an unexpected value). - */ - @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type - - /** - * A description of the function. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun description(): Optional = description.getOptional("description") - - /** - * The name of the function. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun name(): Optional = name.getOptional("name") - - /** - * The JSON Schema for the function's parameters. - * - * This arbitrary value can be deserialized into a custom type using the `convert` method: - * ```java - * MyClass myObject = function.parameters().convert(MyClass.class); - * ``` - */ - @JsonProperty("parameters") @ExcludeMissing fun _parameters(): JsonValue = parameters - - /** - * Returns the raw JSON value of [description]. - * - * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("description") @ExcludeMissing fun _description(): JsonField = description - - /** - * Returns the raw JSON value of [name]. - * - * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [Function]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Function]. */ - class Builder internal constructor() { - - private var type: JsonValue = JsonValue.from("function") - private var description: JsonField = JsonMissing.of() - private var name: JsonField = JsonMissing.of() - private var parameters: JsonValue = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(function: Function) = apply { - type = function.type - description = function.description - name = function.name - parameters = function.parameters - additionalProperties = function.additionalProperties.toMutableMap() - } - - /** - * Sets the field to an arbitrary JSON value. - * - * It is usually unnecessary to call this method because the field defaults to the - * following: - * ```java - * JsonValue.from("function") - * ``` - * - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun type(type: JsonValue) = apply { this.type = type } - - /** A description of the function. */ - fun description(description: String) = description(JsonField.of(description)) - - /** - * Sets [Builder.description] to an arbitrary JSON value. - * - * You should usually call [Builder.description] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun description(description: JsonField) = apply { this.description = description } - - /** The name of the function. */ - fun name(name: String) = name(JsonField.of(name)) - - /** - * Sets [Builder.name] to an arbitrary JSON value. - * - * You should usually call [Builder.name] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun name(name: JsonField) = apply { this.name = name } - - /** The JSON Schema for the function's parameters. */ - fun parameters(parameters: JsonValue) = apply { this.parameters = parameters } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [Function]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): Function = - Function(type, description, name, parameters, additionalProperties.toMutableMap()) - } - - private var validated: Boolean = false - - fun validate(): Function = apply { - if (validated) { - return@apply - } - - _type().let { - if (it != JsonValue.from("function")) { - throw GeminiNextGenApiInvalidDataException("'type' is invalid, received $it") - } - } - description() - name() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - type.let { if (it == JsonValue.from("function")) 1 else 0 } + - (if (description.asKnown().isPresent) 1 else 0) + - (if (name.asKnown().isPresent) 1 else 0) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Function && - type == other.type && - description == other.description && - name == other.name && - parameters == other.parameters && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { - Objects.hash(type, description, name, parameters, additionalProperties) - } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Function{type=$type, description=$description, name=$name, parameters=$parameters, additionalProperties=$additionalProperties}" -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/FunctionCallStep.kt b/src/main/java/com/google/genai/interactions/models/interactions/FunctionCallStep.kt deleted file mode 100644 index 017e53b9d1c..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/FunctionCallStep.kt +++ /dev/null @@ -1,444 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import com.google.genai.interactions.core.ExcludeMissing -import com.google.genai.interactions.core.JsonField -import com.google.genai.interactions.core.JsonMissing -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.core.checkRequired -import com.google.genai.interactions.core.toImmutable -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.util.Collections -import java.util.Objects -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -/** A function tool call step. */ -class FunctionCallStep -@JsonCreator(mode = JsonCreator.Mode.DISABLED) -private constructor( - private val id: JsonField, - private val arguments: JsonField, - private val name: JsonField, - private val type: JsonValue, - private val signature: JsonField, - private val additionalProperties: MutableMap, -) { - - @JsonCreator - private constructor( - @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), - @JsonProperty("arguments") - @ExcludeMissing - arguments: JsonField = JsonMissing.of(), - @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), - @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), - @JsonProperty("signature") @ExcludeMissing signature: JsonField = JsonMissing.of(), - ) : this(id, arguments, name, type, signature, mutableMapOf()) - - /** - * Required. A unique ID for this specific tool call. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). - */ - fun id(): String = id.getRequired("id") - - /** - * Required. The arguments to pass to the function. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). - */ - fun arguments(): Arguments = arguments.getRequired("arguments") - - /** - * Required. The name of the tool to call. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). - */ - fun name(): String = name.getRequired("name") - - /** - * Expected to always return the following: - * ```java - * JsonValue.from("function_call") - * ``` - * - * However, this method can be useful for debugging and logging (e.g. if the server responded - * with an unexpected value). - */ - @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type - - /** - * A signature hash for backend validation. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun signature(): Optional = signature.getOptional("signature") - - /** - * Returns the raw JSON value of [id]. - * - * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id - - /** - * Returns the raw JSON value of [arguments]. - * - * Unlike [arguments], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("arguments") @ExcludeMissing fun _arguments(): JsonField = arguments - - /** - * Returns the raw JSON value of [name]. - * - * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name - - /** - * Returns the raw JSON value of [signature]. - * - * Unlike [signature], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("signature") @ExcludeMissing fun _signature(): JsonField = signature - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [FunctionCallStep]. - * - * The following fields are required: - * ```java - * .id() - * .arguments() - * .name() - * ``` - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [FunctionCallStep]. */ - class Builder internal constructor() { - - private var id: JsonField? = null - private var arguments: JsonField? = null - private var name: JsonField? = null - private var type: JsonValue = JsonValue.from("function_call") - private var signature: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(functionCallStep: FunctionCallStep) = apply { - id = functionCallStep.id - arguments = functionCallStep.arguments - name = functionCallStep.name - type = functionCallStep.type - signature = functionCallStep.signature - additionalProperties = functionCallStep.additionalProperties.toMutableMap() - } - - /** Required. A unique ID for this specific tool call. */ - fun id(id: String) = id(JsonField.of(id)) - - /** - * Sets [Builder.id] to an arbitrary JSON value. - * - * You should usually call [Builder.id] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun id(id: JsonField) = apply { this.id = id } - - /** Required. The arguments to pass to the function. */ - fun arguments(arguments: Arguments) = arguments(JsonField.of(arguments)) - - /** - * Sets [Builder.arguments] to an arbitrary JSON value. - * - * You should usually call [Builder.arguments] with a well-typed [Arguments] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun arguments(arguments: JsonField) = apply { this.arguments = arguments } - - /** Required. The name of the tool to call. */ - fun name(name: String) = name(JsonField.of(name)) - - /** - * Sets [Builder.name] to an arbitrary JSON value. - * - * You should usually call [Builder.name] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun name(name: JsonField) = apply { this.name = name } - - /** - * Sets the field to an arbitrary JSON value. - * - * It is usually unnecessary to call this method because the field defaults to the - * following: - * ```java - * JsonValue.from("function_call") - * ``` - * - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun type(type: JsonValue) = apply { this.type = type } - - /** A signature hash for backend validation. */ - fun signature(signature: String) = signature(JsonField.of(signature)) - - /** - * Sets [Builder.signature] to an arbitrary JSON value. - * - * You should usually call [Builder.signature] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun signature(signature: JsonField) = apply { this.signature = signature } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [FunctionCallStep]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .id() - * .arguments() - * .name() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): FunctionCallStep = - FunctionCallStep( - checkRequired("id", id), - checkRequired("arguments", arguments), - checkRequired("name", name), - type, - signature, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): FunctionCallStep = apply { - if (validated) { - return@apply - } - - id() - arguments().validate() - name() - _type().let { - if (it != JsonValue.from("function_call")) { - throw GeminiNextGenApiInvalidDataException("'type' is invalid, received $it") - } - } - signature() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - (if (id.asKnown().isPresent) 1 else 0) + - (arguments.asKnown().getOrNull()?.validity() ?: 0) + - (if (name.asKnown().isPresent) 1 else 0) + - type.let { if (it == JsonValue.from("function_call")) 1 else 0 } + - (if (signature.asKnown().isPresent) 1 else 0) - - /** Required. The arguments to pass to the function. */ - class Arguments - @JsonCreator - private constructor( - @com.fasterxml.jackson.annotation.JsonValue - private val additionalProperties: Map - ) { - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [Arguments]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Arguments]. */ - class Builder internal constructor() { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(arguments: Arguments) = apply { - additionalProperties = arguments.additionalProperties.toMutableMap() - } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [Arguments]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): Arguments = Arguments(additionalProperties.toImmutable()) - } - - private var validated: Boolean = false - - fun validate(): Arguments = apply { - if (validated) { - return@apply - } - - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Arguments && additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - - override fun hashCode(): Int = hashCode - - override fun toString() = "Arguments{additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is FunctionCallStep && - id == other.id && - arguments == other.arguments && - name == other.name && - type == other.type && - signature == other.signature && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { - Objects.hash(id, arguments, name, type, signature, additionalProperties) - } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "FunctionCallStep{id=$id, arguments=$arguments, name=$name, type=$type, signature=$signature, additionalProperties=$additionalProperties}" -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/FunctionResultDelta.kt b/src/main/java/com/google/genai/interactions/models/interactions/FunctionResultDelta.kt deleted file mode 100644 index 275bdef0738..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/FunctionResultDelta.kt +++ /dev/null @@ -1,742 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import com.fasterxml.jackson.core.JsonGenerator -import com.fasterxml.jackson.core.ObjectCodec -import com.fasterxml.jackson.databind.JsonNode -import com.fasterxml.jackson.databind.SerializerProvider -import com.fasterxml.jackson.databind.annotation.JsonDeserialize -import com.fasterxml.jackson.databind.annotation.JsonSerialize -import com.fasterxml.jackson.module.kotlin.jacksonTypeRef -import com.google.genai.interactions.core.BaseDeserializer -import com.google.genai.interactions.core.BaseSerializer -import com.google.genai.interactions.core.ExcludeMissing -import com.google.genai.interactions.core.JsonField -import com.google.genai.interactions.core.JsonMissing -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.core.allMaxBy -import com.google.genai.interactions.core.checkRequired -import com.google.genai.interactions.core.getOrThrow -import com.google.genai.interactions.core.toImmutable -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.util.Collections -import java.util.Objects -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -class FunctionResultDelta -@JsonCreator(mode = JsonCreator.Mode.DISABLED) -private constructor( - private val callId: JsonField, - private val result: JsonField, - private val type: JsonValue, - private val isError: JsonField, - private val name: JsonField, - private val additionalProperties: MutableMap, -) { - - @JsonCreator - private constructor( - @JsonProperty("call_id") @ExcludeMissing callId: JsonField = JsonMissing.of(), - @JsonProperty("result") @ExcludeMissing result: JsonField = JsonMissing.of(), - @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), - @JsonProperty("is_error") @ExcludeMissing isError: JsonField = JsonMissing.of(), - @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), - ) : this(callId, result, type, isError, name, mutableMapOf()) - - /** - * Required. ID to match the ID from the function call block. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). - */ - fun callId(): String = callId.getRequired("call_id") - - /** - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). - */ - fun result(): Result = result.getRequired("result") - - /** - * Expected to always return the following: - * ```java - * JsonValue.from("function_result") - * ``` - * - * However, this method can be useful for debugging and logging (e.g. if the server responded - * with an unexpected value). - */ - @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type - - /** - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun isError(): Optional = isError.getOptional("is_error") - - /** - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun name(): Optional = name.getOptional("name") - - /** - * Returns the raw JSON value of [callId]. - * - * Unlike [callId], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("call_id") @ExcludeMissing fun _callId(): JsonField = callId - - /** - * Returns the raw JSON value of [result]. - * - * Unlike [result], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("result") @ExcludeMissing fun _result(): JsonField = result - - /** - * Returns the raw JSON value of [isError]. - * - * Unlike [isError], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("is_error") @ExcludeMissing fun _isError(): JsonField = isError - - /** - * Returns the raw JSON value of [name]. - * - * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [FunctionResultDelta]. - * - * The following fields are required: - * ```java - * .callId() - * .result() - * ``` - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [FunctionResultDelta]. */ - class Builder internal constructor() { - - private var callId: JsonField? = null - private var result: JsonField? = null - private var type: JsonValue = JsonValue.from("function_result") - private var isError: JsonField = JsonMissing.of() - private var name: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(functionResultDelta: FunctionResultDelta) = apply { - callId = functionResultDelta.callId - result = functionResultDelta.result - type = functionResultDelta.type - isError = functionResultDelta.isError - name = functionResultDelta.name - additionalProperties = functionResultDelta.additionalProperties.toMutableMap() - } - - /** Required. ID to match the ID from the function call block. */ - fun callId(callId: String) = callId(JsonField.of(callId)) - - /** - * Sets [Builder.callId] to an arbitrary JSON value. - * - * You should usually call [Builder.callId] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun callId(callId: JsonField) = apply { this.callId = callId } - - fun result(result: Result) = result(JsonField.of(result)) - - /** - * Sets [Builder.result] to an arbitrary JSON value. - * - * You should usually call [Builder.result] with a well-typed [Result] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun result(result: JsonField) = apply { this.result = result } - - /** Alias for calling [result] with `Result.ofJsonValue(jsonValue)`. */ - fun result(jsonValue: JsonValue) = result(Result.ofJsonValue(jsonValue)) - - /** - * Alias for calling [result] with - * `Result.ofFunctionResultSubcontentList(functionResultSubcontentList)`. - */ - fun resultOfFunctionResultSubcontentList( - functionResultSubcontentList: List - ) = result(Result.ofFunctionResultSubcontentList(functionResultSubcontentList)) - - /** Alias for calling [result] with `Result.ofString(string)`. */ - fun result(string: String) = result(Result.ofString(string)) - - /** - * Sets the field to an arbitrary JSON value. - * - * It is usually unnecessary to call this method because the field defaults to the - * following: - * ```java - * JsonValue.from("function_result") - * ``` - * - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun type(type: JsonValue) = apply { this.type = type } - - fun isError(isError: Boolean) = isError(JsonField.of(isError)) - - /** - * Sets [Builder.isError] to an arbitrary JSON value. - * - * You should usually call [Builder.isError] with a well-typed [Boolean] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun isError(isError: JsonField) = apply { this.isError = isError } - - fun name(name: String) = name(JsonField.of(name)) - - /** - * Sets [Builder.name] to an arbitrary JSON value. - * - * You should usually call [Builder.name] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun name(name: JsonField) = apply { this.name = name } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [FunctionResultDelta]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .callId() - * .result() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): FunctionResultDelta = - FunctionResultDelta( - checkRequired("callId", callId), - checkRequired("result", result), - type, - isError, - name, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): FunctionResultDelta = apply { - if (validated) { - return@apply - } - - callId() - result().validate() - _type().let { - if (it != JsonValue.from("function_result")) { - throw GeminiNextGenApiInvalidDataException("'type' is invalid, received $it") - } - } - isError() - name() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - (if (callId.asKnown().isPresent) 1 else 0) + - (result.asKnown().getOrNull()?.validity() ?: 0) + - type.let { if (it == JsonValue.from("function_result")) 1 else 0 } + - (if (isError.asKnown().isPresent) 1 else 0) + - (if (name.asKnown().isPresent) 1 else 0) - - @JsonDeserialize(using = Result.Deserializer::class) - @JsonSerialize(using = Result.Serializer::class) - class Result - private constructor( - private val jsonValue: JsonValue? = null, - private val functionResultSubcontentList: List? = null, - private val string: String? = null, - private val _json: JsonValue? = null, - ) { - - fun jsonValue(): Optional = Optional.ofNullable(jsonValue) - - fun functionResultSubcontentList(): Optional> = - Optional.ofNullable(functionResultSubcontentList) - - fun string(): Optional = Optional.ofNullable(string) - - fun isJsonValue(): Boolean = jsonValue != null - - fun isFunctionResultSubcontentList(): Boolean = functionResultSubcontentList != null - - fun isString(): Boolean = string != null - - fun asJsonValue(): JsonValue = jsonValue.getOrThrow("jsonValue") - - fun asFunctionResultSubcontentList(): List = - functionResultSubcontentList.getOrThrow("functionResultSubcontentList") - - fun asString(): String = string.getOrThrow("string") - - fun _json(): Optional = Optional.ofNullable(_json) - - fun accept(visitor: Visitor): T = - when { - jsonValue != null -> visitor.visitJsonValue(jsonValue) - functionResultSubcontentList != null -> - visitor.visitFunctionResultSubcontentList(functionResultSubcontentList) - string != null -> visitor.visitString(string) - else -> visitor.unknown(_json) - } - - private var validated: Boolean = false - - fun validate(): Result = apply { - if (validated) { - return@apply - } - - accept( - object : Visitor { - override fun visitJsonValue(jsonValue: JsonValue) {} - - override fun visitFunctionResultSubcontentList( - functionResultSubcontentList: List - ) { - functionResultSubcontentList.forEach { it.validate() } - } - - override fun visitString(string: String) {} - } - ) - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - accept( - object : Visitor { - override fun visitJsonValue(jsonValue: JsonValue) = 1 - - override fun visitFunctionResultSubcontentList( - functionResultSubcontentList: List - ) = functionResultSubcontentList.sumOf { it.validity().toInt() } - - override fun visitString(string: String) = 1 - - override fun unknown(json: JsonValue?) = 0 - } - ) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Result && - jsonValue == other.jsonValue && - functionResultSubcontentList == other.functionResultSubcontentList && - string == other.string - } - - override fun hashCode(): Int = Objects.hash(jsonValue, functionResultSubcontentList, string) - - override fun toString(): String = - when { - jsonValue != null -> "Result{jsonValue=$jsonValue}" - functionResultSubcontentList != null -> - "Result{functionResultSubcontentList=$functionResultSubcontentList}" - string != null -> "Result{string=$string}" - _json != null -> "Result{_unknown=$_json}" - else -> throw IllegalStateException("Invalid Result") - } - - companion object { - - @JvmStatic fun ofJsonValue(jsonValue: JsonValue) = Result(jsonValue = jsonValue) - - @JvmStatic - fun ofFunctionResultSubcontentList( - functionResultSubcontentList: List - ) = Result(functionResultSubcontentList = functionResultSubcontentList.toImmutable()) - - @JvmStatic fun ofString(string: String) = Result(string = string) - } - - /** An interface that defines how to map each variant of [Result] to a value of type [T]. */ - interface Visitor { - - fun visitJsonValue(jsonValue: JsonValue): T - - fun visitFunctionResultSubcontentList( - functionResultSubcontentList: List - ): T - - fun visitString(string: String): T - - /** - * Maps an unknown variant of [Result] to a value of type [T]. - * - * An instance of [Result] can contain an unknown variant if it was deserialized from - * data that doesn't match any known variant. For example, if the SDK is on an older - * version than the API, then the API may respond with new variants that the SDK is - * unaware of. - * - * @throws GeminiNextGenApiInvalidDataException in the default implementation. - */ - fun unknown(json: JsonValue?): T { - throw GeminiNextGenApiInvalidDataException("Unknown Result: $json") - } - } - - internal class Deserializer : BaseDeserializer(Result::class) { - - override fun ObjectCodec.deserialize(node: JsonNode): Result { - val json = JsonValue.fromJsonNode(node) - - val bestMatches = - sequenceOf( - tryDeserialize(node, jacksonTypeRef())?.let { - Result(string = it, _json = json) - }, - tryDeserialize(node, jacksonTypeRef>()) - ?.let { Result(functionResultSubcontentList = it, _json = json) }, - tryDeserialize(node, jacksonTypeRef())?.let { - Result(jsonValue = it, _json = json) - }, - ) - .filterNotNull() - .allMaxBy { it.validity() } - .toList() - return when (bestMatches.size) { - // This can happen if what we're deserializing is completely incompatible with - // all the possible variants. - 0 -> Result(_json = json) - 1 -> bestMatches.single() - // If there's more than one match with the highest validity, then use the first - // completely valid match, or simply the first match if none are completely - // valid. - else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() - } - } - } - - internal class Serializer : BaseSerializer(Result::class) { - - override fun serialize( - value: Result, - generator: JsonGenerator, - provider: SerializerProvider, - ) { - when { - value.jsonValue != null -> generator.writeObject(value.jsonValue) - value.functionResultSubcontentList != null -> - generator.writeObject(value.functionResultSubcontentList) - value.string != null -> generator.writeObject(value.string) - value._json != null -> generator.writeObject(value._json) - else -> throw IllegalStateException("Invalid Result") - } - } - } - - /** A text content block. */ - @JsonDeserialize(using = FunctionResultSubcontent.Deserializer::class) - @JsonSerialize(using = FunctionResultSubcontent.Serializer::class) - class FunctionResultSubcontent - private constructor( - private val text: TextContent? = null, - private val image: ImageContent? = null, - private val _json: JsonValue? = null, - ) { - - /** A text content block. */ - fun text(): Optional = Optional.ofNullable(text) - - /** An image content block. */ - fun image(): Optional = Optional.ofNullable(image) - - fun isText(): Boolean = text != null - - fun isImage(): Boolean = image != null - - /** A text content block. */ - fun asText(): TextContent = text.getOrThrow("text") - - /** An image content block. */ - fun asImage(): ImageContent = image.getOrThrow("image") - - fun _json(): Optional = Optional.ofNullable(_json) - - fun accept(visitor: Visitor): T = - when { - text != null -> visitor.visitText(text) - image != null -> visitor.visitImage(image) - else -> visitor.unknown(_json) - } - - private var validated: Boolean = false - - fun validate(): FunctionResultSubcontent = apply { - if (validated) { - return@apply - } - - accept( - object : Visitor { - override fun visitText(text: TextContent) { - text.validate() - } - - override fun visitImage(image: ImageContent) { - image.validate() - } - } - ) - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - accept( - object : Visitor { - override fun visitText(text: TextContent) = text.validity() - - override fun visitImage(image: ImageContent) = image.validity() - - override fun unknown(json: JsonValue?) = 0 - } - ) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is FunctionResultSubcontent && - text == other.text && - image == other.image - } - - override fun hashCode(): Int = Objects.hash(text, image) - - override fun toString(): String = - when { - text != null -> "FunctionResultSubcontent{text=$text}" - image != null -> "FunctionResultSubcontent{image=$image}" - _json != null -> "FunctionResultSubcontent{_unknown=$_json}" - else -> throw IllegalStateException("Invalid FunctionResultSubcontent") - } - - companion object { - - /** A text content block. */ - @JvmStatic fun ofText(text: TextContent) = FunctionResultSubcontent(text = text) - - /** An image content block. */ - @JvmStatic - fun ofImage(image: ImageContent) = FunctionResultSubcontent(image = image) - } - - /** - * An interface that defines how to map each variant of [FunctionResultSubcontent] to a - * value of type [T]. - */ - interface Visitor { - - /** A text content block. */ - fun visitText(text: TextContent): T - - /** An image content block. */ - fun visitImage(image: ImageContent): T - - /** - * Maps an unknown variant of [FunctionResultSubcontent] to a value of type [T]. - * - * An instance of [FunctionResultSubcontent] can contain an unknown variant if it - * was deserialized from data that doesn't match any known variant. For example, if - * the SDK is on an older version than the API, then the API may respond with new - * variants that the SDK is unaware of. - * - * @throws GeminiNextGenApiInvalidDataException in the default implementation. - */ - fun unknown(json: JsonValue?): T { - throw GeminiNextGenApiInvalidDataException( - "Unknown FunctionResultSubcontent: $json" - ) - } - } - - internal class Deserializer : - BaseDeserializer(FunctionResultSubcontent::class) { - - override fun ObjectCodec.deserialize(node: JsonNode): FunctionResultSubcontent { - val json = JsonValue.fromJsonNode(node) - val type = json.asObject().getOrNull()?.get("type")?.asString()?.getOrNull() - - when (type) { - "text" -> { - return tryDeserialize(node, jacksonTypeRef())?.let { - FunctionResultSubcontent(text = it, _json = json) - } ?: FunctionResultSubcontent(_json = json) - } - "image" -> { - return tryDeserialize(node, jacksonTypeRef())?.let { - FunctionResultSubcontent(image = it, _json = json) - } ?: FunctionResultSubcontent(_json = json) - } - } - - return FunctionResultSubcontent(_json = json) - } - } - - internal class Serializer : - BaseSerializer(FunctionResultSubcontent::class) { - - override fun serialize( - value: FunctionResultSubcontent, - generator: JsonGenerator, - provider: SerializerProvider, - ) { - when { - value.text != null -> generator.writeObject(value.text) - value.image != null -> generator.writeObject(value.image) - value._json != null -> generator.writeObject(value._json) - else -> throw IllegalStateException("Invalid FunctionResultSubcontent") - } - } - } - } - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is FunctionResultDelta && - callId == other.callId && - result == other.result && - type == other.type && - isError == other.isError && - name == other.name && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { - Objects.hash(callId, result, type, isError, name, additionalProperties) - } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "FunctionResultDelta{callId=$callId, result=$result, type=$type, isError=$isError, name=$name, additionalProperties=$additionalProperties}" -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/FunctionResultStep.kt b/src/main/java/com/google/genai/interactions/models/interactions/FunctionResultStep.kt deleted file mode 100644 index 493092aec42..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/FunctionResultStep.kt +++ /dev/null @@ -1,788 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import com.fasterxml.jackson.core.JsonGenerator -import com.fasterxml.jackson.core.ObjectCodec -import com.fasterxml.jackson.databind.JsonNode -import com.fasterxml.jackson.databind.SerializerProvider -import com.fasterxml.jackson.databind.annotation.JsonDeserialize -import com.fasterxml.jackson.databind.annotation.JsonSerialize -import com.fasterxml.jackson.module.kotlin.jacksonTypeRef -import com.google.genai.interactions.core.BaseDeserializer -import com.google.genai.interactions.core.BaseSerializer -import com.google.genai.interactions.core.ExcludeMissing -import com.google.genai.interactions.core.JsonField -import com.google.genai.interactions.core.JsonMissing -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.core.allMaxBy -import com.google.genai.interactions.core.checkRequired -import com.google.genai.interactions.core.getOrThrow -import com.google.genai.interactions.core.toImmutable -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.util.Collections -import java.util.Objects -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -/** Result of a function tool call. */ -class FunctionResultStep -@JsonCreator(mode = JsonCreator.Mode.DISABLED) -private constructor( - private val callId: JsonField, - private val result: JsonField, - private val type: JsonValue, - private val isError: JsonField, - private val name: JsonField, - private val signature: JsonField, - private val additionalProperties: MutableMap, -) { - - @JsonCreator - private constructor( - @JsonProperty("call_id") @ExcludeMissing callId: JsonField = JsonMissing.of(), - @JsonProperty("result") @ExcludeMissing result: JsonField = JsonMissing.of(), - @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), - @JsonProperty("is_error") @ExcludeMissing isError: JsonField = JsonMissing.of(), - @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), - @JsonProperty("signature") @ExcludeMissing signature: JsonField = JsonMissing.of(), - ) : this(callId, result, type, isError, name, signature, mutableMapOf()) - - /** - * Required. ID to match the ID from the function call block. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). - */ - fun callId(): String = callId.getRequired("call_id") - - /** - * The result of the tool call. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). - */ - fun result(): Result = result.getRequired("result") - - /** - * Expected to always return the following: - * ```java - * JsonValue.from("function_result") - * ``` - * - * However, this method can be useful for debugging and logging (e.g. if the server responded - * with an unexpected value). - */ - @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type - - /** - * Whether the tool call resulted in an error. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun isError(): Optional = isError.getOptional("is_error") - - /** - * The name of the tool that was called. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun name(): Optional = name.getOptional("name") - - /** - * A signature hash for backend validation. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun signature(): Optional = signature.getOptional("signature") - - /** - * Returns the raw JSON value of [callId]. - * - * Unlike [callId], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("call_id") @ExcludeMissing fun _callId(): JsonField = callId - - /** - * Returns the raw JSON value of [result]. - * - * Unlike [result], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("result") @ExcludeMissing fun _result(): JsonField = result - - /** - * Returns the raw JSON value of [isError]. - * - * Unlike [isError], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("is_error") @ExcludeMissing fun _isError(): JsonField = isError - - /** - * Returns the raw JSON value of [name]. - * - * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name - - /** - * Returns the raw JSON value of [signature]. - * - * Unlike [signature], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("signature") @ExcludeMissing fun _signature(): JsonField = signature - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [FunctionResultStep]. - * - * The following fields are required: - * ```java - * .callId() - * .result() - * ``` - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [FunctionResultStep]. */ - class Builder internal constructor() { - - private var callId: JsonField? = null - private var result: JsonField? = null - private var type: JsonValue = JsonValue.from("function_result") - private var isError: JsonField = JsonMissing.of() - private var name: JsonField = JsonMissing.of() - private var signature: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(functionResultStep: FunctionResultStep) = apply { - callId = functionResultStep.callId - result = functionResultStep.result - type = functionResultStep.type - isError = functionResultStep.isError - name = functionResultStep.name - signature = functionResultStep.signature - additionalProperties = functionResultStep.additionalProperties.toMutableMap() - } - - /** Required. ID to match the ID from the function call block. */ - fun callId(callId: String) = callId(JsonField.of(callId)) - - /** - * Sets [Builder.callId] to an arbitrary JSON value. - * - * You should usually call [Builder.callId] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun callId(callId: JsonField) = apply { this.callId = callId } - - /** The result of the tool call. */ - fun result(result: Result) = result(JsonField.of(result)) - - /** - * Sets [Builder.result] to an arbitrary JSON value. - * - * You should usually call [Builder.result] with a well-typed [Result] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun result(result: JsonField) = apply { this.result = result } - - /** Alias for calling [result] with `Result.ofJsonValue(jsonValue)`. */ - fun result(jsonValue: JsonValue) = result(Result.ofJsonValue(jsonValue)) - - /** - * Alias for calling [result] with - * `Result.ofFunctionResultSubcontentList(functionResultSubcontentList)`. - */ - fun resultOfFunctionResultSubcontentList( - functionResultSubcontentList: List - ) = result(Result.ofFunctionResultSubcontentList(functionResultSubcontentList)) - - /** Alias for calling [result] with `Result.ofString(string)`. */ - fun result(string: String) = result(Result.ofString(string)) - - /** - * Sets the field to an arbitrary JSON value. - * - * It is usually unnecessary to call this method because the field defaults to the - * following: - * ```java - * JsonValue.from("function_result") - * ``` - * - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun type(type: JsonValue) = apply { this.type = type } - - /** Whether the tool call resulted in an error. */ - fun isError(isError: Boolean) = isError(JsonField.of(isError)) - - /** - * Sets [Builder.isError] to an arbitrary JSON value. - * - * You should usually call [Builder.isError] with a well-typed [Boolean] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun isError(isError: JsonField) = apply { this.isError = isError } - - /** The name of the tool that was called. */ - fun name(name: String) = name(JsonField.of(name)) - - /** - * Sets [Builder.name] to an arbitrary JSON value. - * - * You should usually call [Builder.name] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun name(name: JsonField) = apply { this.name = name } - - /** A signature hash for backend validation. */ - fun signature(signature: String) = signature(JsonField.of(signature)) - - /** - * Sets [Builder.signature] to an arbitrary JSON value. - * - * You should usually call [Builder.signature] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun signature(signature: JsonField) = apply { this.signature = signature } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [FunctionResultStep]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .callId() - * .result() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): FunctionResultStep = - FunctionResultStep( - checkRequired("callId", callId), - checkRequired("result", result), - type, - isError, - name, - signature, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): FunctionResultStep = apply { - if (validated) { - return@apply - } - - callId() - result().validate() - _type().let { - if (it != JsonValue.from("function_result")) { - throw GeminiNextGenApiInvalidDataException("'type' is invalid, received $it") - } - } - isError() - name() - signature() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - (if (callId.asKnown().isPresent) 1 else 0) + - (result.asKnown().getOrNull()?.validity() ?: 0) + - type.let { if (it == JsonValue.from("function_result")) 1 else 0 } + - (if (isError.asKnown().isPresent) 1 else 0) + - (if (name.asKnown().isPresent) 1 else 0) + - (if (signature.asKnown().isPresent) 1 else 0) - - /** The result of the tool call. */ - @JsonDeserialize(using = Result.Deserializer::class) - @JsonSerialize(using = Result.Serializer::class) - class Result - private constructor( - private val jsonValue: JsonValue? = null, - private val functionResultSubcontentList: List? = null, - private val string: String? = null, - private val _json: JsonValue? = null, - ) { - - fun jsonValue(): Optional = Optional.ofNullable(jsonValue) - - fun functionResultSubcontentList(): Optional> = - Optional.ofNullable(functionResultSubcontentList) - - fun string(): Optional = Optional.ofNullable(string) - - fun isJsonValue(): Boolean = jsonValue != null - - fun isFunctionResultSubcontentList(): Boolean = functionResultSubcontentList != null - - fun isString(): Boolean = string != null - - fun asJsonValue(): JsonValue = jsonValue.getOrThrow("jsonValue") - - fun asFunctionResultSubcontentList(): List = - functionResultSubcontentList.getOrThrow("functionResultSubcontentList") - - fun asString(): String = string.getOrThrow("string") - - fun _json(): Optional = Optional.ofNullable(_json) - - fun accept(visitor: Visitor): T = - when { - jsonValue != null -> visitor.visitJsonValue(jsonValue) - functionResultSubcontentList != null -> - visitor.visitFunctionResultSubcontentList(functionResultSubcontentList) - string != null -> visitor.visitString(string) - else -> visitor.unknown(_json) - } - - private var validated: Boolean = false - - fun validate(): Result = apply { - if (validated) { - return@apply - } - - accept( - object : Visitor { - override fun visitJsonValue(jsonValue: JsonValue) {} - - override fun visitFunctionResultSubcontentList( - functionResultSubcontentList: List - ) { - functionResultSubcontentList.forEach { it.validate() } - } - - override fun visitString(string: String) {} - } - ) - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - accept( - object : Visitor { - override fun visitJsonValue(jsonValue: JsonValue) = 1 - - override fun visitFunctionResultSubcontentList( - functionResultSubcontentList: List - ) = functionResultSubcontentList.sumOf { it.validity().toInt() } - - override fun visitString(string: String) = 1 - - override fun unknown(json: JsonValue?) = 0 - } - ) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Result && - jsonValue == other.jsonValue && - functionResultSubcontentList == other.functionResultSubcontentList && - string == other.string - } - - override fun hashCode(): Int = Objects.hash(jsonValue, functionResultSubcontentList, string) - - override fun toString(): String = - when { - jsonValue != null -> "Result{jsonValue=$jsonValue}" - functionResultSubcontentList != null -> - "Result{functionResultSubcontentList=$functionResultSubcontentList}" - string != null -> "Result{string=$string}" - _json != null -> "Result{_unknown=$_json}" - else -> throw IllegalStateException("Invalid Result") - } - - companion object { - - @JvmStatic fun ofJsonValue(jsonValue: JsonValue) = Result(jsonValue = jsonValue) - - @JvmStatic - fun ofFunctionResultSubcontentList( - functionResultSubcontentList: List - ) = Result(functionResultSubcontentList = functionResultSubcontentList.toImmutable()) - - @JvmStatic fun ofString(string: String) = Result(string = string) - } - - /** An interface that defines how to map each variant of [Result] to a value of type [T]. */ - interface Visitor { - - fun visitJsonValue(jsonValue: JsonValue): T - - fun visitFunctionResultSubcontentList( - functionResultSubcontentList: List - ): T - - fun visitString(string: String): T - - /** - * Maps an unknown variant of [Result] to a value of type [T]. - * - * An instance of [Result] can contain an unknown variant if it was deserialized from - * data that doesn't match any known variant. For example, if the SDK is on an older - * version than the API, then the API may respond with new variants that the SDK is - * unaware of. - * - * @throws GeminiNextGenApiInvalidDataException in the default implementation. - */ - fun unknown(json: JsonValue?): T { - throw GeminiNextGenApiInvalidDataException("Unknown Result: $json") - } - } - - internal class Deserializer : BaseDeserializer(Result::class) { - - override fun ObjectCodec.deserialize(node: JsonNode): Result { - val json = JsonValue.fromJsonNode(node) - - val bestMatches = - sequenceOf( - tryDeserialize(node, jacksonTypeRef())?.let { - Result(string = it, _json = json) - }, - tryDeserialize(node, jacksonTypeRef>()) - ?.let { Result(functionResultSubcontentList = it, _json = json) }, - tryDeserialize(node, jacksonTypeRef())?.let { - Result(jsonValue = it, _json = json) - }, - ) - .filterNotNull() - .allMaxBy { it.validity() } - .toList() - return when (bestMatches.size) { - // This can happen if what we're deserializing is completely incompatible with - // all the possible variants. - 0 -> Result(_json = json) - 1 -> bestMatches.single() - // If there's more than one match with the highest validity, then use the first - // completely valid match, or simply the first match if none are completely - // valid. - else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() - } - } - } - - internal class Serializer : BaseSerializer(Result::class) { - - override fun serialize( - value: Result, - generator: JsonGenerator, - provider: SerializerProvider, - ) { - when { - value.jsonValue != null -> generator.writeObject(value.jsonValue) - value.functionResultSubcontentList != null -> - generator.writeObject(value.functionResultSubcontentList) - value.string != null -> generator.writeObject(value.string) - value._json != null -> generator.writeObject(value._json) - else -> throw IllegalStateException("Invalid Result") - } - } - } - - /** A text content block. */ - @JsonDeserialize(using = FunctionResultSubcontent.Deserializer::class) - @JsonSerialize(using = FunctionResultSubcontent.Serializer::class) - class FunctionResultSubcontent - private constructor( - private val text: TextContent? = null, - private val image: ImageContent? = null, - private val _json: JsonValue? = null, - ) { - - /** A text content block. */ - fun text(): Optional = Optional.ofNullable(text) - - /** An image content block. */ - fun image(): Optional = Optional.ofNullable(image) - - fun isText(): Boolean = text != null - - fun isImage(): Boolean = image != null - - /** A text content block. */ - fun asText(): TextContent = text.getOrThrow("text") - - /** An image content block. */ - fun asImage(): ImageContent = image.getOrThrow("image") - - fun _json(): Optional = Optional.ofNullable(_json) - - fun accept(visitor: Visitor): T = - when { - text != null -> visitor.visitText(text) - image != null -> visitor.visitImage(image) - else -> visitor.unknown(_json) - } - - private var validated: Boolean = false - - fun validate(): FunctionResultSubcontent = apply { - if (validated) { - return@apply - } - - accept( - object : Visitor { - override fun visitText(text: TextContent) { - text.validate() - } - - override fun visitImage(image: ImageContent) { - image.validate() - } - } - ) - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - accept( - object : Visitor { - override fun visitText(text: TextContent) = text.validity() - - override fun visitImage(image: ImageContent) = image.validity() - - override fun unknown(json: JsonValue?) = 0 - } - ) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is FunctionResultSubcontent && - text == other.text && - image == other.image - } - - override fun hashCode(): Int = Objects.hash(text, image) - - override fun toString(): String = - when { - text != null -> "FunctionResultSubcontent{text=$text}" - image != null -> "FunctionResultSubcontent{image=$image}" - _json != null -> "FunctionResultSubcontent{_unknown=$_json}" - else -> throw IllegalStateException("Invalid FunctionResultSubcontent") - } - - companion object { - - /** A text content block. */ - @JvmStatic fun ofText(text: TextContent) = FunctionResultSubcontent(text = text) - - /** An image content block. */ - @JvmStatic - fun ofImage(image: ImageContent) = FunctionResultSubcontent(image = image) - } - - /** - * An interface that defines how to map each variant of [FunctionResultSubcontent] to a - * value of type [T]. - */ - interface Visitor { - - /** A text content block. */ - fun visitText(text: TextContent): T - - /** An image content block. */ - fun visitImage(image: ImageContent): T - - /** - * Maps an unknown variant of [FunctionResultSubcontent] to a value of type [T]. - * - * An instance of [FunctionResultSubcontent] can contain an unknown variant if it - * was deserialized from data that doesn't match any known variant. For example, if - * the SDK is on an older version than the API, then the API may respond with new - * variants that the SDK is unaware of. - * - * @throws GeminiNextGenApiInvalidDataException in the default implementation. - */ - fun unknown(json: JsonValue?): T { - throw GeminiNextGenApiInvalidDataException( - "Unknown FunctionResultSubcontent: $json" - ) - } - } - - internal class Deserializer : - BaseDeserializer(FunctionResultSubcontent::class) { - - override fun ObjectCodec.deserialize(node: JsonNode): FunctionResultSubcontent { - val json = JsonValue.fromJsonNode(node) - val type = json.asObject().getOrNull()?.get("type")?.asString()?.getOrNull() - - when (type) { - "text" -> { - return tryDeserialize(node, jacksonTypeRef())?.let { - FunctionResultSubcontent(text = it, _json = json) - } ?: FunctionResultSubcontent(_json = json) - } - "image" -> { - return tryDeserialize(node, jacksonTypeRef())?.let { - FunctionResultSubcontent(image = it, _json = json) - } ?: FunctionResultSubcontent(_json = json) - } - } - - return FunctionResultSubcontent(_json = json) - } - } - - internal class Serializer : - BaseSerializer(FunctionResultSubcontent::class) { - - override fun serialize( - value: FunctionResultSubcontent, - generator: JsonGenerator, - provider: SerializerProvider, - ) { - when { - value.text != null -> generator.writeObject(value.text) - value.image != null -> generator.writeObject(value.image) - value._json != null -> generator.writeObject(value._json) - else -> throw IllegalStateException("Invalid FunctionResultSubcontent") - } - } - } - } - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is FunctionResultStep && - callId == other.callId && - result == other.result && - type == other.type && - isError == other.isError && - name == other.name && - signature == other.signature && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { - Objects.hash(callId, result, type, isError, name, signature, additionalProperties) - } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "FunctionResultStep{callId=$callId, result=$result, type=$type, isError=$isError, name=$name, signature=$signature, additionalProperties=$additionalProperties}" -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/GenerationConfig.kt b/src/main/java/com/google/genai/interactions/models/interactions/GenerationConfig.kt deleted file mode 100644 index dd29cf4c0cd..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/GenerationConfig.kt +++ /dev/null @@ -1,920 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import com.fasterxml.jackson.core.JsonGenerator -import com.fasterxml.jackson.core.ObjectCodec -import com.fasterxml.jackson.databind.JsonNode -import com.fasterxml.jackson.databind.SerializerProvider -import com.fasterxml.jackson.databind.annotation.JsonDeserialize -import com.fasterxml.jackson.databind.annotation.JsonSerialize -import com.fasterxml.jackson.module.kotlin.jacksonTypeRef -import com.google.genai.interactions.core.BaseDeserializer -import com.google.genai.interactions.core.BaseSerializer -import com.google.genai.interactions.core.Enum -import com.google.genai.interactions.core.ExcludeMissing -import com.google.genai.interactions.core.JsonField -import com.google.genai.interactions.core.JsonMissing -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.core.allMaxBy -import com.google.genai.interactions.core.checkKnown -import com.google.genai.interactions.core.getOrThrow -import com.google.genai.interactions.core.toImmutable -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.util.Collections -import java.util.Objects -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -/** Configuration parameters for model interactions. */ -class GenerationConfig -@JsonCreator(mode = JsonCreator.Mode.DISABLED) -private constructor( - private val imageConfig: JsonField, - private val maxOutputTokens: JsonField, - private val seed: JsonField, - private val speechConfig: JsonField>, - private val stopSequences: JsonField>, - private val temperature: JsonField, - private val thinkingLevel: JsonField, - private val thinkingSummaries: JsonField, - private val toolChoice: JsonField, - private val topP: JsonField, - private val additionalProperties: MutableMap, -) { - - @JsonCreator - private constructor( - @JsonProperty("image_config") - @ExcludeMissing - imageConfig: JsonField = JsonMissing.of(), - @JsonProperty("max_output_tokens") - @ExcludeMissing - maxOutputTokens: JsonField = JsonMissing.of(), - @JsonProperty("seed") @ExcludeMissing seed: JsonField = JsonMissing.of(), - @JsonProperty("speech_config") - @ExcludeMissing - speechConfig: JsonField> = JsonMissing.of(), - @JsonProperty("stop_sequences") - @ExcludeMissing - stopSequences: JsonField> = JsonMissing.of(), - @JsonProperty("temperature") - @ExcludeMissing - temperature: JsonField = JsonMissing.of(), - @JsonProperty("thinking_level") - @ExcludeMissing - thinkingLevel: JsonField = JsonMissing.of(), - @JsonProperty("thinking_summaries") - @ExcludeMissing - thinkingSummaries: JsonField = JsonMissing.of(), - @JsonProperty("tool_choice") - @ExcludeMissing - toolChoice: JsonField = JsonMissing.of(), - @JsonProperty("top_p") @ExcludeMissing topP: JsonField = JsonMissing.of(), - ) : this( - imageConfig, - maxOutputTokens, - seed, - speechConfig, - stopSequences, - temperature, - thinkingLevel, - thinkingSummaries, - toolChoice, - topP, - mutableMapOf(), - ) - - /** - * Configuration for image interaction. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun imageConfig(): Optional = imageConfig.getOptional("image_config") - - /** - * The maximum number of tokens to include in the response. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun maxOutputTokens(): Optional = maxOutputTokens.getOptional("max_output_tokens") - - /** - * Seed used in decoding for reproducibility. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun seed(): Optional = seed.getOptional("seed") - - /** - * Configuration for speech interaction. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun speechConfig(): Optional> = speechConfig.getOptional("speech_config") - - /** - * A list of character sequences that will stop output interaction. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun stopSequences(): Optional> = stopSequences.getOptional("stop_sequences") - - /** - * Controls the randomness of the output. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun temperature(): Optional = temperature.getOptional("temperature") - - /** - * The level of thought tokens that the model should generate. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun thinkingLevel(): Optional = thinkingLevel.getOptional("thinking_level") - - /** - * Whether to include thought summaries in the response. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun thinkingSummaries(): Optional = - thinkingSummaries.getOptional("thinking_summaries") - - /** - * The tool choice configuration. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun toolChoice(): Optional = toolChoice.getOptional("tool_choice") - - /** - * The maximum cumulative probability of tokens to consider when sampling. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun topP(): Optional = topP.getOptional("top_p") - - /** - * Returns the raw JSON value of [imageConfig]. - * - * Unlike [imageConfig], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("image_config") - @ExcludeMissing - fun _imageConfig(): JsonField = imageConfig - - /** - * Returns the raw JSON value of [maxOutputTokens]. - * - * Unlike [maxOutputTokens], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("max_output_tokens") - @ExcludeMissing - fun _maxOutputTokens(): JsonField = maxOutputTokens - - /** - * Returns the raw JSON value of [seed]. - * - * Unlike [seed], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("seed") @ExcludeMissing fun _seed(): JsonField = seed - - /** - * Returns the raw JSON value of [speechConfig]. - * - * Unlike [speechConfig], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("speech_config") - @ExcludeMissing - fun _speechConfig(): JsonField> = speechConfig - - /** - * Returns the raw JSON value of [stopSequences]. - * - * Unlike [stopSequences], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("stop_sequences") - @ExcludeMissing - fun _stopSequences(): JsonField> = stopSequences - - /** - * Returns the raw JSON value of [temperature]. - * - * Unlike [temperature], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("temperature") @ExcludeMissing fun _temperature(): JsonField = temperature - - /** - * Returns the raw JSON value of [thinkingLevel]. - * - * Unlike [thinkingLevel], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("thinking_level") - @ExcludeMissing - fun _thinkingLevel(): JsonField = thinkingLevel - - /** - * Returns the raw JSON value of [thinkingSummaries]. - * - * Unlike [thinkingSummaries], this method doesn't throw if the JSON field has an unexpected - * type. - */ - @JsonProperty("thinking_summaries") - @ExcludeMissing - fun _thinkingSummaries(): JsonField = thinkingSummaries - - /** - * Returns the raw JSON value of [toolChoice]. - * - * Unlike [toolChoice], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("tool_choice") - @ExcludeMissing - fun _toolChoice(): JsonField = toolChoice - - /** - * Returns the raw JSON value of [topP]. - * - * Unlike [topP], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("top_p") @ExcludeMissing fun _topP(): JsonField = topP - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [GenerationConfig]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [GenerationConfig]. */ - class Builder internal constructor() { - - private var imageConfig: JsonField = JsonMissing.of() - private var maxOutputTokens: JsonField = JsonMissing.of() - private var seed: JsonField = JsonMissing.of() - private var speechConfig: JsonField>? = null - private var stopSequences: JsonField>? = null - private var temperature: JsonField = JsonMissing.of() - private var thinkingLevel: JsonField = JsonMissing.of() - private var thinkingSummaries: JsonField = JsonMissing.of() - private var toolChoice: JsonField = JsonMissing.of() - private var topP: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(generationConfig: GenerationConfig) = apply { - imageConfig = generationConfig.imageConfig - maxOutputTokens = generationConfig.maxOutputTokens - seed = generationConfig.seed - speechConfig = generationConfig.speechConfig.map { it.toMutableList() } - stopSequences = generationConfig.stopSequences.map { it.toMutableList() } - temperature = generationConfig.temperature - thinkingLevel = generationConfig.thinkingLevel - thinkingSummaries = generationConfig.thinkingSummaries - toolChoice = generationConfig.toolChoice - topP = generationConfig.topP - additionalProperties = generationConfig.additionalProperties.toMutableMap() - } - - /** Configuration for image interaction. */ - fun imageConfig(imageConfig: ImageConfig) = imageConfig(JsonField.of(imageConfig)) - - /** - * Sets [Builder.imageConfig] to an arbitrary JSON value. - * - * You should usually call [Builder.imageConfig] with a well-typed [ImageConfig] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun imageConfig(imageConfig: JsonField) = apply { - this.imageConfig = imageConfig - } - - /** The maximum number of tokens to include in the response. */ - fun maxOutputTokens(maxOutputTokens: Int) = maxOutputTokens(JsonField.of(maxOutputTokens)) - - /** - * Sets [Builder.maxOutputTokens] to an arbitrary JSON value. - * - * You should usually call [Builder.maxOutputTokens] with a well-typed [Int] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun maxOutputTokens(maxOutputTokens: JsonField) = apply { - this.maxOutputTokens = maxOutputTokens - } - - /** Seed used in decoding for reproducibility. */ - fun seed(seed: Int) = seed(JsonField.of(seed)) - - /** - * Sets [Builder.seed] to an arbitrary JSON value. - * - * You should usually call [Builder.seed] with a well-typed [Int] value instead. This method - * is primarily for setting the field to an undocumented or not yet supported value. - */ - fun seed(seed: JsonField) = apply { this.seed = seed } - - /** Configuration for speech interaction. */ - fun speechConfig(speechConfig: List) = - speechConfig(JsonField.of(speechConfig)) - - /** - * Sets [Builder.speechConfig] to an arbitrary JSON value. - * - * You should usually call [Builder.speechConfig] with a well-typed `List` - * value instead. This method is primarily for setting the field to an undocumented or not - * yet supported value. - */ - fun speechConfig(speechConfig: JsonField>) = apply { - this.speechConfig = speechConfig.map { it.toMutableList() } - } - - /** - * Adds a single [SpeechConfig] to [Builder.speechConfig]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addSpeechConfig(speechConfig: SpeechConfig) = apply { - this.speechConfig = - (this.speechConfig ?: JsonField.of(mutableListOf())).also { - checkKnown("speechConfig", it).add(speechConfig) - } - } - - /** A list of character sequences that will stop output interaction. */ - fun stopSequences(stopSequences: List) = stopSequences(JsonField.of(stopSequences)) - - /** - * Sets [Builder.stopSequences] to an arbitrary JSON value. - * - * You should usually call [Builder.stopSequences] with a well-typed `List` value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun stopSequences(stopSequences: JsonField>) = apply { - this.stopSequences = stopSequences.map { it.toMutableList() } - } - - /** - * Adds a single [String] to [stopSequences]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addStopSequence(stopSequence: String) = apply { - stopSequences = - (stopSequences ?: JsonField.of(mutableListOf())).also { - checkKnown("stopSequences", it).add(stopSequence) - } - } - - /** Controls the randomness of the output. */ - fun temperature(temperature: Float) = temperature(JsonField.of(temperature)) - - /** - * Sets [Builder.temperature] to an arbitrary JSON value. - * - * You should usually call [Builder.temperature] with a well-typed [Float] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun temperature(temperature: JsonField) = apply { this.temperature = temperature } - - /** The level of thought tokens that the model should generate. */ - fun thinkingLevel(thinkingLevel: ThinkingLevel) = thinkingLevel(JsonField.of(thinkingLevel)) - - /** - * Sets [Builder.thinkingLevel] to an arbitrary JSON value. - * - * You should usually call [Builder.thinkingLevel] with a well-typed [ThinkingLevel] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun thinkingLevel(thinkingLevel: JsonField) = apply { - this.thinkingLevel = thinkingLevel - } - - /** Whether to include thought summaries in the response. */ - fun thinkingSummaries(thinkingSummaries: ThinkingSummaries) = - thinkingSummaries(JsonField.of(thinkingSummaries)) - - /** - * Sets [Builder.thinkingSummaries] to an arbitrary JSON value. - * - * You should usually call [Builder.thinkingSummaries] with a well-typed [ThinkingSummaries] - * value instead. This method is primarily for setting the field to an undocumented or not - * yet supported value. - */ - fun thinkingSummaries(thinkingSummaries: JsonField) = apply { - this.thinkingSummaries = thinkingSummaries - } - - /** The tool choice configuration. */ - fun toolChoice(toolChoice: ToolChoice) = toolChoice(JsonField.of(toolChoice)) - - /** - * Sets [Builder.toolChoice] to an arbitrary JSON value. - * - * You should usually call [Builder.toolChoice] with a well-typed [ToolChoice] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun toolChoice(toolChoice: JsonField) = apply { this.toolChoice = toolChoice } - - /** Alias for calling [toolChoice] with `ToolChoice.ofType(type)`. */ - fun toolChoice(type: ToolChoiceType) = toolChoice(ToolChoice.ofType(type)) - - /** Alias for calling [toolChoice] with `ToolChoice.ofConfig(config)`. */ - fun toolChoice(config: ToolChoiceConfig) = toolChoice(ToolChoice.ofConfig(config)) - - /** The maximum cumulative probability of tokens to consider when sampling. */ - fun topP(topP: Float) = topP(JsonField.of(topP)) - - /** - * Sets [Builder.topP] to an arbitrary JSON value. - * - * You should usually call [Builder.topP] with a well-typed [Float] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun topP(topP: JsonField) = apply { this.topP = topP } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [GenerationConfig]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): GenerationConfig = - GenerationConfig( - imageConfig, - maxOutputTokens, - seed, - (speechConfig ?: JsonMissing.of()).map { it.toImmutable() }, - (stopSequences ?: JsonMissing.of()).map { it.toImmutable() }, - temperature, - thinkingLevel, - thinkingSummaries, - toolChoice, - topP, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): GenerationConfig = apply { - if (validated) { - return@apply - } - - imageConfig().ifPresent { it.validate() } - maxOutputTokens() - seed() - speechConfig().ifPresent { it.forEach { it.validate() } } - stopSequences() - temperature() - thinkingLevel().ifPresent { it.validate() } - thinkingSummaries().ifPresent { it.validate() } - toolChoice().ifPresent { it.validate() } - topP() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - (imageConfig.asKnown().getOrNull()?.validity() ?: 0) + - (if (maxOutputTokens.asKnown().isPresent) 1 else 0) + - (if (seed.asKnown().isPresent) 1 else 0) + - (speechConfig.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + - (stopSequences.asKnown().getOrNull()?.size ?: 0) + - (if (temperature.asKnown().isPresent) 1 else 0) + - (thinkingLevel.asKnown().getOrNull()?.validity() ?: 0) + - (thinkingSummaries.asKnown().getOrNull()?.validity() ?: 0) + - (toolChoice.asKnown().getOrNull()?.validity() ?: 0) + - (if (topP.asKnown().isPresent) 1 else 0) - - /** Whether to include thought summaries in the response. */ - class ThinkingSummaries @JsonCreator private constructor(private val value: JsonField) : - Enum { - - /** - * Returns this class instance's raw value. - * - * This is usually only useful if this instance was deserialized from data that doesn't - * match any known member, and you want to know that value. For example, if the SDK is on an - * older version than the API, then the API may respond with new members that the SDK is - * unaware of. - */ - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - companion object { - - @JvmField val AUTO = of("auto") - - @JvmField val NONE = of("none") - - @JvmStatic fun of(value: String) = ThinkingSummaries(JsonField.of(value)) - } - - /** An enum containing [ThinkingSummaries]'s known values. */ - enum class Known { - AUTO, - NONE, - } - - /** - * An enum containing [ThinkingSummaries]'s known values, as well as an [_UNKNOWN] member. - * - * An instance of [ThinkingSummaries] can contain an unknown value in a couple of cases: - * - It was deserialized from data that doesn't match any known member. For example, if the - * SDK is on an older version than the API, then the API may respond with new members that - * the SDK is unaware of. - * - It was constructed with an arbitrary value using the [of] method. - */ - enum class Value { - AUTO, - NONE, - /** - * An enum member indicating that [ThinkingSummaries] was instantiated with an unknown - * value. - */ - _UNKNOWN, - } - - /** - * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] - * if the class was instantiated with an unknown value. - * - * Use the [known] method instead if you're certain the value is always known or if you want - * to throw for the unknown case. - */ - fun value(): Value = - when (this) { - AUTO -> Value.AUTO - NONE -> Value.NONE - else -> Value._UNKNOWN - } - - /** - * Returns an enum member corresponding to this class instance's value. - * - * Use the [value] method instead if you're uncertain the value is always known and don't - * want to throw for the unknown case. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value is a not a - * known member. - */ - fun known(): Known = - when (this) { - AUTO -> Known.AUTO - NONE -> Known.NONE - else -> - throw GeminiNextGenApiInvalidDataException("Unknown ThinkingSummaries: $value") - } - - /** - * Returns this class instance's primitive wire representation. - * - * This differs from the [toString] method because that method is primarily for debugging - * and generally doesn't throw. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value does not have - * the expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - GeminiNextGenApiInvalidDataException("Value is not a String") - } - - private var validated: Boolean = false - - fun validate(): ThinkingSummaries = apply { - if (validated) { - return@apply - } - - known() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is ThinkingSummaries && value == other.value - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - /** The tool choice configuration. */ - @JsonDeserialize(using = ToolChoice.Deserializer::class) - @JsonSerialize(using = ToolChoice.Serializer::class) - class ToolChoice - private constructor( - private val type: ToolChoiceType? = null, - private val config: ToolChoiceConfig? = null, - private val _json: JsonValue? = null, - ) { - - fun type(): Optional = Optional.ofNullable(type) - - /** The tool choice configuration containing allowed tools. */ - fun config(): Optional = Optional.ofNullable(config) - - fun isType(): Boolean = type != null - - fun isConfig(): Boolean = config != null - - fun asType(): ToolChoiceType = type.getOrThrow("type") - - /** The tool choice configuration containing allowed tools. */ - fun asConfig(): ToolChoiceConfig = config.getOrThrow("config") - - fun _json(): Optional = Optional.ofNullable(_json) - - fun accept(visitor: Visitor): T = - when { - type != null -> visitor.visitType(type) - config != null -> visitor.visitConfig(config) - else -> visitor.unknown(_json) - } - - private var validated: Boolean = false - - fun validate(): ToolChoice = apply { - if (validated) { - return@apply - } - - accept( - object : Visitor { - override fun visitType(type: ToolChoiceType) { - type.validate() - } - - override fun visitConfig(config: ToolChoiceConfig) { - config.validate() - } - } - ) - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - accept( - object : Visitor { - override fun visitType(type: ToolChoiceType) = type.validity() - - override fun visitConfig(config: ToolChoiceConfig) = config.validity() - - override fun unknown(json: JsonValue?) = 0 - } - ) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is ToolChoice && type == other.type && config == other.config - } - - override fun hashCode(): Int = Objects.hash(type, config) - - override fun toString(): String = - when { - type != null -> "ToolChoice{type=$type}" - config != null -> "ToolChoice{config=$config}" - _json != null -> "ToolChoice{_unknown=$_json}" - else -> throw IllegalStateException("Invalid ToolChoice") - } - - companion object { - - @JvmStatic fun ofType(type: ToolChoiceType) = ToolChoice(type = type) - - /** The tool choice configuration containing allowed tools. */ - @JvmStatic fun ofConfig(config: ToolChoiceConfig) = ToolChoice(config = config) - } - - /** - * An interface that defines how to map each variant of [ToolChoice] to a value of type [T]. - */ - interface Visitor { - - fun visitType(type: ToolChoiceType): T - - /** The tool choice configuration containing allowed tools. */ - fun visitConfig(config: ToolChoiceConfig): T - - /** - * Maps an unknown variant of [ToolChoice] to a value of type [T]. - * - * An instance of [ToolChoice] can contain an unknown variant if it was deserialized - * from data that doesn't match any known variant. For example, if the SDK is on an - * older version than the API, then the API may respond with new variants that the SDK - * is unaware of. - * - * @throws GeminiNextGenApiInvalidDataException in the default implementation. - */ - fun unknown(json: JsonValue?): T { - throw GeminiNextGenApiInvalidDataException("Unknown ToolChoice: $json") - } - } - - internal class Deserializer : BaseDeserializer(ToolChoice::class) { - - override fun ObjectCodec.deserialize(node: JsonNode): ToolChoice { - val json = JsonValue.fromJsonNode(node) - - val bestMatches = - sequenceOf( - tryDeserialize(node, jacksonTypeRef())?.let { - ToolChoice(type = it, _json = json) - }, - tryDeserialize(node, jacksonTypeRef())?.let { - ToolChoice(config = it, _json = json) - }, - ) - .filterNotNull() - .allMaxBy { it.validity() } - .toList() - return when (bestMatches.size) { - // This can happen if what we're deserializing is completely incompatible with - // all the possible variants (e.g. deserializing from boolean). - 0 -> ToolChoice(_json = json) - 1 -> bestMatches.single() - // If there's more than one match with the highest validity, then use the first - // completely valid match, or simply the first match if none are completely - // valid. - else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() - } - } - } - - internal class Serializer : BaseSerializer(ToolChoice::class) { - - override fun serialize( - value: ToolChoice, - generator: JsonGenerator, - provider: SerializerProvider, - ) { - when { - value.type != null -> generator.writeObject(value.type) - value.config != null -> generator.writeObject(value.config) - value._json != null -> generator.writeObject(value._json) - else -> throw IllegalStateException("Invalid ToolChoice") - } - } - } - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is GenerationConfig && - imageConfig == other.imageConfig && - maxOutputTokens == other.maxOutputTokens && - seed == other.seed && - speechConfig == other.speechConfig && - stopSequences == other.stopSequences && - temperature == other.temperature && - thinkingLevel == other.thinkingLevel && - thinkingSummaries == other.thinkingSummaries && - toolChoice == other.toolChoice && - topP == other.topP && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { - Objects.hash( - imageConfig, - maxOutputTokens, - seed, - speechConfig, - stopSequences, - temperature, - thinkingLevel, - thinkingSummaries, - toolChoice, - topP, - additionalProperties, - ) - } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "GenerationConfig{imageConfig=$imageConfig, maxOutputTokens=$maxOutputTokens, seed=$seed, speechConfig=$speechConfig, stopSequences=$stopSequences, temperature=$temperature, thinkingLevel=$thinkingLevel, thinkingSummaries=$thinkingSummaries, toolChoice=$toolChoice, topP=$topP, additionalProperties=$additionalProperties}" -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/GoogleMapsCallArguments.kt b/src/main/java/com/google/genai/interactions/models/interactions/GoogleMapsCallArguments.kt deleted file mode 100644 index 1f1b2ccd747..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/GoogleMapsCallArguments.kt +++ /dev/null @@ -1,194 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import com.google.genai.interactions.core.ExcludeMissing -import com.google.genai.interactions.core.JsonField -import com.google.genai.interactions.core.JsonMissing -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.core.checkKnown -import com.google.genai.interactions.core.toImmutable -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.util.Collections -import java.util.Objects -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -/** The arguments to pass to the Google Maps tool. */ -class GoogleMapsCallArguments -@JsonCreator(mode = JsonCreator.Mode.DISABLED) -private constructor( - private val queries: JsonField>, - private val additionalProperties: MutableMap, -) { - - @JsonCreator - private constructor( - @JsonProperty("queries") @ExcludeMissing queries: JsonField> = JsonMissing.of() - ) : this(queries, mutableMapOf()) - - /** - * The queries to be executed. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun queries(): Optional> = queries.getOptional("queries") - - /** - * Returns the raw JSON value of [queries]. - * - * Unlike [queries], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("queries") @ExcludeMissing fun _queries(): JsonField> = queries - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [GoogleMapsCallArguments]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [GoogleMapsCallArguments]. */ - class Builder internal constructor() { - - private var queries: JsonField>? = null - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(googleMapsCallArguments: GoogleMapsCallArguments) = apply { - queries = googleMapsCallArguments.queries.map { it.toMutableList() } - additionalProperties = googleMapsCallArguments.additionalProperties.toMutableMap() - } - - /** The queries to be executed. */ - fun queries(queries: List) = queries(JsonField.of(queries)) - - /** - * Sets [Builder.queries] to an arbitrary JSON value. - * - * You should usually call [Builder.queries] with a well-typed `List` value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun queries(queries: JsonField>) = apply { - this.queries = queries.map { it.toMutableList() } - } - - /** - * Adds a single [String] to [queries]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addQuery(query: String) = apply { - queries = - (queries ?: JsonField.of(mutableListOf())).also { - checkKnown("queries", it).add(query) - } - } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [GoogleMapsCallArguments]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): GoogleMapsCallArguments = - GoogleMapsCallArguments( - (queries ?: JsonMissing.of()).map { it.toImmutable() }, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): GoogleMapsCallArguments = apply { - if (validated) { - return@apply - } - - queries() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic internal fun validity(): Int = (queries.asKnown().getOrNull()?.size ?: 0) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is GoogleMapsCallArguments && - queries == other.queries && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { Objects.hash(queries, additionalProperties) } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "GoogleMapsCallArguments{queries=$queries, additionalProperties=$additionalProperties}" -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/GoogleMapsCallStep.kt b/src/main/java/com/google/genai/interactions/models/interactions/GoogleMapsCallStep.kt deleted file mode 100644 index fb4b021bb98..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/GoogleMapsCallStep.kt +++ /dev/null @@ -1,469 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import com.google.genai.interactions.core.ExcludeMissing -import com.google.genai.interactions.core.JsonField -import com.google.genai.interactions.core.JsonMissing -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.core.checkKnown -import com.google.genai.interactions.core.checkRequired -import com.google.genai.interactions.core.toImmutable -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.util.Collections -import java.util.Objects -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -/** Google Maps call step. */ -class GoogleMapsCallStep -@JsonCreator(mode = JsonCreator.Mode.DISABLED) -private constructor( - private val id: JsonField, - private val type: JsonValue, - private val arguments: JsonField, - private val signature: JsonField, - private val additionalProperties: MutableMap, -) { - - @JsonCreator - private constructor( - @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), - @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), - @JsonProperty("arguments") - @ExcludeMissing - arguments: JsonField = JsonMissing.of(), - @JsonProperty("signature") @ExcludeMissing signature: JsonField = JsonMissing.of(), - ) : this(id, type, arguments, signature, mutableMapOf()) - - /** - * Required. A unique ID for this specific tool call. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). - */ - fun id(): String = id.getRequired("id") - - /** - * Expected to always return the following: - * ```java - * JsonValue.from("google_maps_call") - * ``` - * - * However, this method can be useful for debugging and logging (e.g. if the server responded - * with an unexpected value). - */ - @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type - - /** - * The arguments to pass to the Google Maps tool. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun arguments(): Optional = arguments.getOptional("arguments") - - /** - * A signature hash for backend validation. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun signature(): Optional = signature.getOptional("signature") - - /** - * Returns the raw JSON value of [id]. - * - * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id - - /** - * Returns the raw JSON value of [arguments]. - * - * Unlike [arguments], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("arguments") @ExcludeMissing fun _arguments(): JsonField = arguments - - /** - * Returns the raw JSON value of [signature]. - * - * Unlike [signature], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("signature") @ExcludeMissing fun _signature(): JsonField = signature - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [GoogleMapsCallStep]. - * - * The following fields are required: - * ```java - * .id() - * ``` - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [GoogleMapsCallStep]. */ - class Builder internal constructor() { - - private var id: JsonField? = null - private var type: JsonValue = JsonValue.from("google_maps_call") - private var arguments: JsonField = JsonMissing.of() - private var signature: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(googleMapsCallStep: GoogleMapsCallStep) = apply { - id = googleMapsCallStep.id - type = googleMapsCallStep.type - arguments = googleMapsCallStep.arguments - signature = googleMapsCallStep.signature - additionalProperties = googleMapsCallStep.additionalProperties.toMutableMap() - } - - /** Required. A unique ID for this specific tool call. */ - fun id(id: String) = id(JsonField.of(id)) - - /** - * Sets [Builder.id] to an arbitrary JSON value. - * - * You should usually call [Builder.id] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun id(id: JsonField) = apply { this.id = id } - - /** - * Sets the field to an arbitrary JSON value. - * - * It is usually unnecessary to call this method because the field defaults to the - * following: - * ```java - * JsonValue.from("google_maps_call") - * ``` - * - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun type(type: JsonValue) = apply { this.type = type } - - /** The arguments to pass to the Google Maps tool. */ - fun arguments(arguments: Arguments) = arguments(JsonField.of(arguments)) - - /** - * Sets [Builder.arguments] to an arbitrary JSON value. - * - * You should usually call [Builder.arguments] with a well-typed [Arguments] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun arguments(arguments: JsonField) = apply { this.arguments = arguments } - - /** A signature hash for backend validation. */ - fun signature(signature: String) = signature(JsonField.of(signature)) - - /** - * Sets [Builder.signature] to an arbitrary JSON value. - * - * You should usually call [Builder.signature] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun signature(signature: JsonField) = apply { this.signature = signature } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [GoogleMapsCallStep]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .id() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): GoogleMapsCallStep = - GoogleMapsCallStep( - checkRequired("id", id), - type, - arguments, - signature, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): GoogleMapsCallStep = apply { - if (validated) { - return@apply - } - - id() - _type().let { - if (it != JsonValue.from("google_maps_call")) { - throw GeminiNextGenApiInvalidDataException("'type' is invalid, received $it") - } - } - arguments().ifPresent { it.validate() } - signature() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - (if (id.asKnown().isPresent) 1 else 0) + - type.let { if (it == JsonValue.from("google_maps_call")) 1 else 0 } + - (arguments.asKnown().getOrNull()?.validity() ?: 0) + - (if (signature.asKnown().isPresent) 1 else 0) - - /** The arguments to pass to the Google Maps tool. */ - class Arguments - @JsonCreator(mode = JsonCreator.Mode.DISABLED) - private constructor( - private val queries: JsonField>, - private val additionalProperties: MutableMap, - ) { - - @JsonCreator - private constructor( - @JsonProperty("queries") - @ExcludeMissing - queries: JsonField> = JsonMissing.of() - ) : this(queries, mutableMapOf()) - - /** - * The queries to be executed. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type - * (e.g. if the server responded with an unexpected value). - */ - fun queries(): Optional> = queries.getOptional("queries") - - /** - * Returns the raw JSON value of [queries]. - * - * Unlike [queries], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("queries") @ExcludeMissing fun _queries(): JsonField> = queries - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [Arguments]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Arguments]. */ - class Builder internal constructor() { - - private var queries: JsonField>? = null - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(arguments: Arguments) = apply { - queries = arguments.queries.map { it.toMutableList() } - additionalProperties = arguments.additionalProperties.toMutableMap() - } - - /** The queries to be executed. */ - fun queries(queries: List) = queries(JsonField.of(queries)) - - /** - * Sets [Builder.queries] to an arbitrary JSON value. - * - * You should usually call [Builder.queries] with a well-typed `List` value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun queries(queries: JsonField>) = apply { - this.queries = queries.map { it.toMutableList() } - } - - /** - * Adds a single [String] to [queries]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addQuery(query: String) = apply { - queries = - (queries ?: JsonField.of(mutableListOf())).also { - checkKnown("queries", it).add(query) - } - } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [Arguments]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): Arguments = - Arguments( - (queries ?: JsonMissing.of()).map { it.toImmutable() }, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): Arguments = apply { - if (validated) { - return@apply - } - - queries() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic internal fun validity(): Int = (queries.asKnown().getOrNull()?.size ?: 0) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Arguments && - queries == other.queries && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { Objects.hash(queries, additionalProperties) } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Arguments{queries=$queries, additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is GoogleMapsCallStep && - id == other.id && - type == other.type && - arguments == other.arguments && - signature == other.signature && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { - Objects.hash(id, type, arguments, signature, additionalProperties) - } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "GoogleMapsCallStep{id=$id, type=$type, arguments=$arguments, signature=$signature, additionalProperties=$additionalProperties}" -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/GoogleMapsResult.kt b/src/main/java/com/google/genai/interactions/models/interactions/GoogleMapsResult.kt deleted file mode 100644 index a13c2f537b7..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/GoogleMapsResult.kt +++ /dev/null @@ -1,745 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import com.google.genai.interactions.core.ExcludeMissing -import com.google.genai.interactions.core.JsonField -import com.google.genai.interactions.core.JsonMissing -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.core.checkKnown -import com.google.genai.interactions.core.toImmutable -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.util.Collections -import java.util.Objects -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -/** The result of the Google Maps. */ -class GoogleMapsResult -@JsonCreator(mode = JsonCreator.Mode.DISABLED) -private constructor( - private val places: JsonField>, - private val widgetContextToken: JsonField, - private val additionalProperties: MutableMap, -) { - - @JsonCreator - private constructor( - @JsonProperty("places") @ExcludeMissing places: JsonField> = JsonMissing.of(), - @JsonProperty("widget_context_token") - @ExcludeMissing - widgetContextToken: JsonField = JsonMissing.of(), - ) : this(places, widgetContextToken, mutableMapOf()) - - /** - * The places that were found. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun places(): Optional> = places.getOptional("places") - - /** - * Resource name of the Google Maps widget context token. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun widgetContextToken(): Optional = - widgetContextToken.getOptional("widget_context_token") - - /** - * Returns the raw JSON value of [places]. - * - * Unlike [places], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("places") @ExcludeMissing fun _places(): JsonField> = places - - /** - * Returns the raw JSON value of [widgetContextToken]. - * - * Unlike [widgetContextToken], this method doesn't throw if the JSON field has an unexpected - * type. - */ - @JsonProperty("widget_context_token") - @ExcludeMissing - fun _widgetContextToken(): JsonField = widgetContextToken - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [GoogleMapsResult]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [GoogleMapsResult]. */ - class Builder internal constructor() { - - private var places: JsonField>? = null - private var widgetContextToken: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(googleMapsResult: GoogleMapsResult) = apply { - places = googleMapsResult.places.map { it.toMutableList() } - widgetContextToken = googleMapsResult.widgetContextToken - additionalProperties = googleMapsResult.additionalProperties.toMutableMap() - } - - /** The places that were found. */ - fun places(places: List) = places(JsonField.of(places)) - - /** - * Sets [Builder.places] to an arbitrary JSON value. - * - * You should usually call [Builder.places] with a well-typed `List` value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun places(places: JsonField>) = apply { - this.places = places.map { it.toMutableList() } - } - - /** - * Adds a single [Place] to [places]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addPlace(place: Place) = apply { - places = - (places ?: JsonField.of(mutableListOf())).also { - checkKnown("places", it).add(place) - } - } - - /** Resource name of the Google Maps widget context token. */ - fun widgetContextToken(widgetContextToken: String) = - widgetContextToken(JsonField.of(widgetContextToken)) - - /** - * Sets [Builder.widgetContextToken] to an arbitrary JSON value. - * - * You should usually call [Builder.widgetContextToken] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun widgetContextToken(widgetContextToken: JsonField) = apply { - this.widgetContextToken = widgetContextToken - } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [GoogleMapsResult]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): GoogleMapsResult = - GoogleMapsResult( - (places ?: JsonMissing.of()).map { it.toImmutable() }, - widgetContextToken, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): GoogleMapsResult = apply { - if (validated) { - return@apply - } - - places().ifPresent { it.forEach { it.validate() } } - widgetContextToken() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - (places.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + - (if (widgetContextToken.asKnown().isPresent) 1 else 0) - - class Place - @JsonCreator(mode = JsonCreator.Mode.DISABLED) - private constructor( - private val name: JsonField, - private val placeId: JsonField, - private val reviewSnippets: JsonField>, - private val url: JsonField, - private val additionalProperties: MutableMap, - ) { - - @JsonCreator - private constructor( - @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), - @JsonProperty("place_id") @ExcludeMissing placeId: JsonField = JsonMissing.of(), - @JsonProperty("review_snippets") - @ExcludeMissing - reviewSnippets: JsonField> = JsonMissing.of(), - @JsonProperty("url") @ExcludeMissing url: JsonField = JsonMissing.of(), - ) : this(name, placeId, reviewSnippets, url, mutableMapOf()) - - /** - * Title of the place. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type - * (e.g. if the server responded with an unexpected value). - */ - fun name(): Optional = name.getOptional("name") - - /** - * The ID of the place, in `places/{place_id}` format. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type - * (e.g. if the server responded with an unexpected value). - */ - fun placeId(): Optional = placeId.getOptional("place_id") - - /** - * Snippets of reviews that are used to generate answers about the features of a given place - * in Google Maps. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type - * (e.g. if the server responded with an unexpected value). - */ - fun reviewSnippets(): Optional> = - reviewSnippets.getOptional("review_snippets") - - /** - * URI reference of the place. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type - * (e.g. if the server responded with an unexpected value). - */ - fun url(): Optional = url.getOptional("url") - - /** - * Returns the raw JSON value of [name]. - * - * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name - - /** - * Returns the raw JSON value of [placeId]. - * - * Unlike [placeId], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("place_id") @ExcludeMissing fun _placeId(): JsonField = placeId - - /** - * Returns the raw JSON value of [reviewSnippets]. - * - * Unlike [reviewSnippets], this method doesn't throw if the JSON field has an unexpected - * type. - */ - @JsonProperty("review_snippets") - @ExcludeMissing - fun _reviewSnippets(): JsonField> = reviewSnippets - - /** - * Returns the raw JSON value of [url]. - * - * Unlike [url], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("url") @ExcludeMissing fun _url(): JsonField = url - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [Place]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Place]. */ - class Builder internal constructor() { - - private var name: JsonField = JsonMissing.of() - private var placeId: JsonField = JsonMissing.of() - private var reviewSnippets: JsonField>? = null - private var url: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(place: Place) = apply { - name = place.name - placeId = place.placeId - reviewSnippets = place.reviewSnippets.map { it.toMutableList() } - url = place.url - additionalProperties = place.additionalProperties.toMutableMap() - } - - /** Title of the place. */ - fun name(name: String) = name(JsonField.of(name)) - - /** - * Sets [Builder.name] to an arbitrary JSON value. - * - * You should usually call [Builder.name] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun name(name: JsonField) = apply { this.name = name } - - /** The ID of the place, in `places/{place_id}` format. */ - fun placeId(placeId: String) = placeId(JsonField.of(placeId)) - - /** - * Sets [Builder.placeId] to an arbitrary JSON value. - * - * You should usually call [Builder.placeId] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun placeId(placeId: JsonField) = apply { this.placeId = placeId } - - /** - * Snippets of reviews that are used to generate answers about the features of a given - * place in Google Maps. - */ - fun reviewSnippets(reviewSnippets: List) = - reviewSnippets(JsonField.of(reviewSnippets)) - - /** - * Sets [Builder.reviewSnippets] to an arbitrary JSON value. - * - * You should usually call [Builder.reviewSnippets] with a well-typed - * `List` value instead. This method is primarily for setting the field - * to an undocumented or not yet supported value. - */ - fun reviewSnippets(reviewSnippets: JsonField>) = apply { - this.reviewSnippets = reviewSnippets.map { it.toMutableList() } - } - - /** - * Adds a single [ReviewSnippet] to [reviewSnippets]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addReviewSnippet(reviewSnippet: ReviewSnippet) = apply { - reviewSnippets = - (reviewSnippets ?: JsonField.of(mutableListOf())).also { - checkKnown("reviewSnippets", it).add(reviewSnippet) - } - } - - /** URI reference of the place. */ - fun url(url: String) = url(JsonField.of(url)) - - /** - * Sets [Builder.url] to an arbitrary JSON value. - * - * You should usually call [Builder.url] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun url(url: JsonField) = apply { this.url = url } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [Place]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): Place = - Place( - name, - placeId, - (reviewSnippets ?: JsonMissing.of()).map { it.toImmutable() }, - url, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): Place = apply { - if (validated) { - return@apply - } - - name() - placeId() - reviewSnippets().ifPresent { it.forEach { it.validate() } } - url() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - (if (name.asKnown().isPresent) 1 else 0) + - (if (placeId.asKnown().isPresent) 1 else 0) + - (reviewSnippets.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + - (if (url.asKnown().isPresent) 1 else 0) - - /** - * Encapsulates a snippet of a user review that answers a question about the features of a - * specific place in Google Maps. - */ - class ReviewSnippet - @JsonCreator(mode = JsonCreator.Mode.DISABLED) - private constructor( - private val reviewId: JsonField, - private val title: JsonField, - private val url: JsonField, - private val additionalProperties: MutableMap, - ) { - - @JsonCreator - private constructor( - @JsonProperty("review_id") - @ExcludeMissing - reviewId: JsonField = JsonMissing.of(), - @JsonProperty("title") @ExcludeMissing title: JsonField = JsonMissing.of(), - @JsonProperty("url") @ExcludeMissing url: JsonField = JsonMissing.of(), - ) : this(reviewId, title, url, mutableMapOf()) - - /** - * The ID of the review snippet. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type - * (e.g. if the server responded with an unexpected value). - */ - fun reviewId(): Optional = reviewId.getOptional("review_id") - - /** - * Title of the review. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type - * (e.g. if the server responded with an unexpected value). - */ - fun title(): Optional = title.getOptional("title") - - /** - * A link that corresponds to the user review on Google Maps. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type - * (e.g. if the server responded with an unexpected value). - */ - fun url(): Optional = url.getOptional("url") - - /** - * Returns the raw JSON value of [reviewId]. - * - * Unlike [reviewId], this method doesn't throw if the JSON field has an unexpected - * type. - */ - @JsonProperty("review_id") @ExcludeMissing fun _reviewId(): JsonField = reviewId - - /** - * Returns the raw JSON value of [title]. - * - * Unlike [title], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("title") @ExcludeMissing fun _title(): JsonField = title - - /** - * Returns the raw JSON value of [url]. - * - * Unlike [url], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("url") @ExcludeMissing fun _url(): JsonField = url - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [ReviewSnippet]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [ReviewSnippet]. */ - class Builder internal constructor() { - - private var reviewId: JsonField = JsonMissing.of() - private var title: JsonField = JsonMissing.of() - private var url: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(reviewSnippet: ReviewSnippet) = apply { - reviewId = reviewSnippet.reviewId - title = reviewSnippet.title - url = reviewSnippet.url - additionalProperties = reviewSnippet.additionalProperties.toMutableMap() - } - - /** The ID of the review snippet. */ - fun reviewId(reviewId: String) = reviewId(JsonField.of(reviewId)) - - /** - * Sets [Builder.reviewId] to an arbitrary JSON value. - * - * You should usually call [Builder.reviewId] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not - * yet supported value. - */ - fun reviewId(reviewId: JsonField) = apply { this.reviewId = reviewId } - - /** Title of the review. */ - fun title(title: String) = title(JsonField.of(title)) - - /** - * Sets [Builder.title] to an arbitrary JSON value. - * - * You should usually call [Builder.title] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun title(title: JsonField) = apply { this.title = title } - - /** A link that corresponds to the user review on Google Maps. */ - fun url(url: String) = url(JsonField.of(url)) - - /** - * Sets [Builder.url] to an arbitrary JSON value. - * - * You should usually call [Builder.url] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun url(url: JsonField) = apply { this.url = url } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = - apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { - additionalProperties.remove(key) - } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [ReviewSnippet]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): ReviewSnippet = - ReviewSnippet(reviewId, title, url, additionalProperties.toMutableMap()) - } - - private var validated: Boolean = false - - fun validate(): ReviewSnippet = apply { - if (validated) { - return@apply - } - - reviewId() - title() - url() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - (if (reviewId.asKnown().isPresent) 1 else 0) + - (if (title.asKnown().isPresent) 1 else 0) + - (if (url.asKnown().isPresent) 1 else 0) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is ReviewSnippet && - reviewId == other.reviewId && - title == other.title && - url == other.url && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { - Objects.hash(reviewId, title, url, additionalProperties) - } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "ReviewSnippet{reviewId=$reviewId, title=$title, url=$url, additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Place && - name == other.name && - placeId == other.placeId && - reviewSnippets == other.reviewSnippets && - url == other.url && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { - Objects.hash(name, placeId, reviewSnippets, url, additionalProperties) - } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Place{name=$name, placeId=$placeId, reviewSnippets=$reviewSnippets, url=$url, additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is GoogleMapsResult && - places == other.places && - widgetContextToken == other.widgetContextToken && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { - Objects.hash(places, widgetContextToken, additionalProperties) - } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "GoogleMapsResult{places=$places, widgetContextToken=$widgetContextToken, additionalProperties=$additionalProperties}" -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/GoogleMapsResultStep.kt b/src/main/java/com/google/genai/interactions/models/interactions/GoogleMapsResultStep.kt deleted file mode 100644 index 10f52d8bc75..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/GoogleMapsResultStep.kt +++ /dev/null @@ -1,1021 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import com.google.genai.interactions.core.ExcludeMissing -import com.google.genai.interactions.core.JsonField -import com.google.genai.interactions.core.JsonMissing -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.core.checkKnown -import com.google.genai.interactions.core.checkRequired -import com.google.genai.interactions.core.toImmutable -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.util.Collections -import java.util.Objects -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -/** Google Maps result step. */ -class GoogleMapsResultStep -@JsonCreator(mode = JsonCreator.Mode.DISABLED) -private constructor( - private val callId: JsonField, - private val result: JsonField>, - private val type: JsonValue, - private val signature: JsonField, - private val additionalProperties: MutableMap, -) { - - @JsonCreator - private constructor( - @JsonProperty("call_id") @ExcludeMissing callId: JsonField = JsonMissing.of(), - @JsonProperty("result") @ExcludeMissing result: JsonField> = JsonMissing.of(), - @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), - @JsonProperty("signature") @ExcludeMissing signature: JsonField = JsonMissing.of(), - ) : this(callId, result, type, signature, mutableMapOf()) - - /** - * Required. ID to match the ID from the function call block. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). - */ - fun callId(): String = callId.getRequired("call_id") - - /** - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). - */ - fun result(): List = result.getRequired("result") - - /** - * Expected to always return the following: - * ```java - * JsonValue.from("google_maps_result") - * ``` - * - * However, this method can be useful for debugging and logging (e.g. if the server responded - * with an unexpected value). - */ - @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type - - /** - * A signature hash for backend validation. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun signature(): Optional = signature.getOptional("signature") - - /** - * Returns the raw JSON value of [callId]. - * - * Unlike [callId], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("call_id") @ExcludeMissing fun _callId(): JsonField = callId - - /** - * Returns the raw JSON value of [result]. - * - * Unlike [result], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("result") @ExcludeMissing fun _result(): JsonField> = result - - /** - * Returns the raw JSON value of [signature]. - * - * Unlike [signature], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("signature") @ExcludeMissing fun _signature(): JsonField = signature - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [GoogleMapsResultStep]. - * - * The following fields are required: - * ```java - * .callId() - * .result() - * ``` - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [GoogleMapsResultStep]. */ - class Builder internal constructor() { - - private var callId: JsonField? = null - private var result: JsonField>? = null - private var type: JsonValue = JsonValue.from("google_maps_result") - private var signature: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(googleMapsResultStep: GoogleMapsResultStep) = apply { - callId = googleMapsResultStep.callId - result = googleMapsResultStep.result.map { it.toMutableList() } - type = googleMapsResultStep.type - signature = googleMapsResultStep.signature - additionalProperties = googleMapsResultStep.additionalProperties.toMutableMap() - } - - /** Required. ID to match the ID from the function call block. */ - fun callId(callId: String) = callId(JsonField.of(callId)) - - /** - * Sets [Builder.callId] to an arbitrary JSON value. - * - * You should usually call [Builder.callId] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun callId(callId: JsonField) = apply { this.callId = callId } - - fun result(result: List) = result(JsonField.of(result)) - - /** - * Sets [Builder.result] to an arbitrary JSON value. - * - * You should usually call [Builder.result] with a well-typed `List` value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun result(result: JsonField>) = apply { - this.result = result.map { it.toMutableList() } - } - - /** - * Adds a single [Result] to [Builder.result]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addResult(result: Result) = apply { - this.result = - (this.result ?: JsonField.of(mutableListOf())).also { - checkKnown("result", it).add(result) - } - } - - /** - * Sets the field to an arbitrary JSON value. - * - * It is usually unnecessary to call this method because the field defaults to the - * following: - * ```java - * JsonValue.from("google_maps_result") - * ``` - * - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun type(type: JsonValue) = apply { this.type = type } - - /** A signature hash for backend validation. */ - fun signature(signature: String) = signature(JsonField.of(signature)) - - /** - * Sets [Builder.signature] to an arbitrary JSON value. - * - * You should usually call [Builder.signature] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun signature(signature: JsonField) = apply { this.signature = signature } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [GoogleMapsResultStep]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .callId() - * .result() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): GoogleMapsResultStep = - GoogleMapsResultStep( - checkRequired("callId", callId), - checkRequired("result", result).map { it.toImmutable() }, - type, - signature, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): GoogleMapsResultStep = apply { - if (validated) { - return@apply - } - - callId() - result().forEach { it.validate() } - _type().let { - if (it != JsonValue.from("google_maps_result")) { - throw GeminiNextGenApiInvalidDataException("'type' is invalid, received $it") - } - } - signature() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - (if (callId.asKnown().isPresent) 1 else 0) + - (result.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + - type.let { if (it == JsonValue.from("google_maps_result")) 1 else 0 } + - (if (signature.asKnown().isPresent) 1 else 0) - - /** The result of the Google Maps. */ - class Result - @JsonCreator(mode = JsonCreator.Mode.DISABLED) - private constructor( - private val places: JsonField>, - private val widgetContextToken: JsonField, - private val additionalProperties: MutableMap, - ) { - - @JsonCreator - private constructor( - @JsonProperty("places") - @ExcludeMissing - places: JsonField> = JsonMissing.of(), - @JsonProperty("widget_context_token") - @ExcludeMissing - widgetContextToken: JsonField = JsonMissing.of(), - ) : this(places, widgetContextToken, mutableMapOf()) - - /** - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type - * (e.g. if the server responded with an unexpected value). - */ - fun places(): Optional> = places.getOptional("places") - - /** - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type - * (e.g. if the server responded with an unexpected value). - */ - fun widgetContextToken(): Optional = - widgetContextToken.getOptional("widget_context_token") - - /** - * Returns the raw JSON value of [places]. - * - * Unlike [places], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("places") @ExcludeMissing fun _places(): JsonField> = places - - /** - * Returns the raw JSON value of [widgetContextToken]. - * - * Unlike [widgetContextToken], this method doesn't throw if the JSON field has an - * unexpected type. - */ - @JsonProperty("widget_context_token") - @ExcludeMissing - fun _widgetContextToken(): JsonField = widgetContextToken - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [Result]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Result]. */ - class Builder internal constructor() { - - private var places: JsonField>? = null - private var widgetContextToken: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(result: Result) = apply { - places = result.places.map { it.toMutableList() } - widgetContextToken = result.widgetContextToken - additionalProperties = result.additionalProperties.toMutableMap() - } - - fun places(places: List) = places(JsonField.of(places)) - - /** - * Sets [Builder.places] to an arbitrary JSON value. - * - * You should usually call [Builder.places] with a well-typed `List` value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun places(places: JsonField>) = apply { - this.places = places.map { it.toMutableList() } - } - - /** - * Adds a single [Place] to [places]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addPlace(place: Place) = apply { - places = - (places ?: JsonField.of(mutableListOf())).also { - checkKnown("places", it).add(place) - } - } - - fun widgetContextToken(widgetContextToken: String) = - widgetContextToken(JsonField.of(widgetContextToken)) - - /** - * Sets [Builder.widgetContextToken] to an arbitrary JSON value. - * - * You should usually call [Builder.widgetContextToken] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun widgetContextToken(widgetContextToken: JsonField) = apply { - this.widgetContextToken = widgetContextToken - } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [Result]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): Result = - Result( - (places ?: JsonMissing.of()).map { it.toImmutable() }, - widgetContextToken, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): Result = apply { - if (validated) { - return@apply - } - - places().ifPresent { it.forEach { it.validate() } } - widgetContextToken() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - (places.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + - (if (widgetContextToken.asKnown().isPresent) 1 else 0) - - class Place - @JsonCreator(mode = JsonCreator.Mode.DISABLED) - private constructor( - private val name: JsonField, - private val placeId: JsonField, - private val reviewSnippets: JsonField>, - private val url: JsonField, - private val additionalProperties: MutableMap, - ) { - - @JsonCreator - private constructor( - @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), - @JsonProperty("place_id") - @ExcludeMissing - placeId: JsonField = JsonMissing.of(), - @JsonProperty("review_snippets") - @ExcludeMissing - reviewSnippets: JsonField> = JsonMissing.of(), - @JsonProperty("url") @ExcludeMissing url: JsonField = JsonMissing.of(), - ) : this(name, placeId, reviewSnippets, url, mutableMapOf()) - - /** - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type - * (e.g. if the server responded with an unexpected value). - */ - fun name(): Optional = name.getOptional("name") - - /** - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type - * (e.g. if the server responded with an unexpected value). - */ - fun placeId(): Optional = placeId.getOptional("place_id") - - /** - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type - * (e.g. if the server responded with an unexpected value). - */ - fun reviewSnippets(): Optional> = - reviewSnippets.getOptional("review_snippets") - - /** - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type - * (e.g. if the server responded with an unexpected value). - */ - fun url(): Optional = url.getOptional("url") - - /** - * Returns the raw JSON value of [name]. - * - * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name - - /** - * Returns the raw JSON value of [placeId]. - * - * Unlike [placeId], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("place_id") @ExcludeMissing fun _placeId(): JsonField = placeId - - /** - * Returns the raw JSON value of [reviewSnippets]. - * - * Unlike [reviewSnippets], this method doesn't throw if the JSON field has an - * unexpected type. - */ - @JsonProperty("review_snippets") - @ExcludeMissing - fun _reviewSnippets(): JsonField> = reviewSnippets - - /** - * Returns the raw JSON value of [url]. - * - * Unlike [url], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("url") @ExcludeMissing fun _url(): JsonField = url - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [Place]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Place]. */ - class Builder internal constructor() { - - private var name: JsonField = JsonMissing.of() - private var placeId: JsonField = JsonMissing.of() - private var reviewSnippets: JsonField>? = null - private var url: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(place: Place) = apply { - name = place.name - placeId = place.placeId - reviewSnippets = place.reviewSnippets.map { it.toMutableList() } - url = place.url - additionalProperties = place.additionalProperties.toMutableMap() - } - - fun name(name: String) = name(JsonField.of(name)) - - /** - * Sets [Builder.name] to an arbitrary JSON value. - * - * You should usually call [Builder.name] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun name(name: JsonField) = apply { this.name = name } - - fun placeId(placeId: String) = placeId(JsonField.of(placeId)) - - /** - * Sets [Builder.placeId] to an arbitrary JSON value. - * - * You should usually call [Builder.placeId] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not - * yet supported value. - */ - fun placeId(placeId: JsonField) = apply { this.placeId = placeId } - - fun reviewSnippets(reviewSnippets: List) = - reviewSnippets(JsonField.of(reviewSnippets)) - - /** - * Sets [Builder.reviewSnippets] to an arbitrary JSON value. - * - * You should usually call [Builder.reviewSnippets] with a well-typed - * `List` value instead. This method is primarily for setting the - * field to an undocumented or not yet supported value. - */ - fun reviewSnippets(reviewSnippets: JsonField>) = apply { - this.reviewSnippets = reviewSnippets.map { it.toMutableList() } - } - - /** - * Adds a single [ReviewSnippet] to [reviewSnippets]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addReviewSnippet(reviewSnippet: ReviewSnippet) = apply { - reviewSnippets = - (reviewSnippets ?: JsonField.of(mutableListOf())).also { - checkKnown("reviewSnippets", it).add(reviewSnippet) - } - } - - fun url(url: String) = url(JsonField.of(url)) - - /** - * Sets [Builder.url] to an arbitrary JSON value. - * - * You should usually call [Builder.url] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun url(url: JsonField) = apply { this.url = url } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = - apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { - additionalProperties.remove(key) - } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [Place]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): Place = - Place( - name, - placeId, - (reviewSnippets ?: JsonMissing.of()).map { it.toImmutable() }, - url, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): Place = apply { - if (validated) { - return@apply - } - - name() - placeId() - reviewSnippets().ifPresent { it.forEach { it.validate() } } - url() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - (if (name.asKnown().isPresent) 1 else 0) + - (if (placeId.asKnown().isPresent) 1 else 0) + - (reviewSnippets.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + - (if (url.asKnown().isPresent) 1 else 0) - - /** - * Encapsulates a snippet of a user review that answers a question about the features of - * a specific place in Google Maps. - */ - class ReviewSnippet - @JsonCreator(mode = JsonCreator.Mode.DISABLED) - private constructor( - private val reviewId: JsonField, - private val title: JsonField, - private val url: JsonField, - private val additionalProperties: MutableMap, - ) { - - @JsonCreator - private constructor( - @JsonProperty("review_id") - @ExcludeMissing - reviewId: JsonField = JsonMissing.of(), - @JsonProperty("title") - @ExcludeMissing - title: JsonField = JsonMissing.of(), - @JsonProperty("url") @ExcludeMissing url: JsonField = JsonMissing.of(), - ) : this(reviewId, title, url, mutableMapOf()) - - /** - * The ID of the review snippet. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected - * type (e.g. if the server responded with an unexpected value). - */ - fun reviewId(): Optional = reviewId.getOptional("review_id") - - /** - * Title of the review. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected - * type (e.g. if the server responded with an unexpected value). - */ - fun title(): Optional = title.getOptional("title") - - /** - * A link that corresponds to the user review on Google Maps. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected - * type (e.g. if the server responded with an unexpected value). - */ - fun url(): Optional = url.getOptional("url") - - /** - * Returns the raw JSON value of [reviewId]. - * - * Unlike [reviewId], this method doesn't throw if the JSON field has an unexpected - * type. - */ - @JsonProperty("review_id") - @ExcludeMissing - fun _reviewId(): JsonField = reviewId - - /** - * Returns the raw JSON value of [title]. - * - * Unlike [title], this method doesn't throw if the JSON field has an unexpected - * type. - */ - @JsonProperty("title") @ExcludeMissing fun _title(): JsonField = title - - /** - * Returns the raw JSON value of [url]. - * - * Unlike [url], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("url") @ExcludeMissing fun _url(): JsonField = url - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [ReviewSnippet]. - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [ReviewSnippet]. */ - class Builder internal constructor() { - - private var reviewId: JsonField = JsonMissing.of() - private var title: JsonField = JsonMissing.of() - private var url: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(reviewSnippet: ReviewSnippet) = apply { - reviewId = reviewSnippet.reviewId - title = reviewSnippet.title - url = reviewSnippet.url - additionalProperties = reviewSnippet.additionalProperties.toMutableMap() - } - - /** The ID of the review snippet. */ - fun reviewId(reviewId: String) = reviewId(JsonField.of(reviewId)) - - /** - * Sets [Builder.reviewId] to an arbitrary JSON value. - * - * You should usually call [Builder.reviewId] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or - * not yet supported value. - */ - fun reviewId(reviewId: JsonField) = apply { this.reviewId = reviewId } - - /** Title of the review. */ - fun title(title: String) = title(JsonField.of(title)) - - /** - * Sets [Builder.title] to an arbitrary JSON value. - * - * You should usually call [Builder.title] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or - * not yet supported value. - */ - fun title(title: JsonField) = apply { this.title = title } - - /** A link that corresponds to the user review on Google Maps. */ - fun url(url: String) = url(JsonField.of(url)) - - /** - * Sets [Builder.url] to an arbitrary JSON value. - * - * You should usually call [Builder.url] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or - * not yet supported value. - */ - fun url(url: JsonField) = apply { this.url = url } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = - apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { - additionalProperties.remove(key) - } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [ReviewSnippet]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): ReviewSnippet = - ReviewSnippet(reviewId, title, url, additionalProperties.toMutableMap()) - } - - private var validated: Boolean = false - - fun validate(): ReviewSnippet = apply { - if (validated) { - return@apply - } - - reviewId() - title() - url() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - (if (reviewId.asKnown().isPresent) 1 else 0) + - (if (title.asKnown().isPresent) 1 else 0) + - (if (url.asKnown().isPresent) 1 else 0) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is ReviewSnippet && - reviewId == other.reviewId && - title == other.title && - url == other.url && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { - Objects.hash(reviewId, title, url, additionalProperties) - } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "ReviewSnippet{reviewId=$reviewId, title=$title, url=$url, additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Place && - name == other.name && - placeId == other.placeId && - reviewSnippets == other.reviewSnippets && - url == other.url && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { - Objects.hash(name, placeId, reviewSnippets, url, additionalProperties) - } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Place{name=$name, placeId=$placeId, reviewSnippets=$reviewSnippets, url=$url, additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Result && - places == other.places && - widgetContextToken == other.widgetContextToken && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { - Objects.hash(places, widgetContextToken, additionalProperties) - } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Result{places=$places, widgetContextToken=$widgetContextToken, additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is GoogleMapsResultStep && - callId == other.callId && - result == other.result && - type == other.type && - signature == other.signature && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { - Objects.hash(callId, result, type, signature, additionalProperties) - } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "GoogleMapsResultStep{callId=$callId, result=$result, type=$type, signature=$signature, additionalProperties=$additionalProperties}" -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/GoogleSearchCallArguments.kt b/src/main/java/com/google/genai/interactions/models/interactions/GoogleSearchCallArguments.kt deleted file mode 100644 index 9dcb44dcc91..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/GoogleSearchCallArguments.kt +++ /dev/null @@ -1,196 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import com.google.genai.interactions.core.ExcludeMissing -import com.google.genai.interactions.core.JsonField -import com.google.genai.interactions.core.JsonMissing -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.core.checkKnown -import com.google.genai.interactions.core.toImmutable -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.util.Collections -import java.util.Objects -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -/** The arguments to pass to Google Search. */ -class GoogleSearchCallArguments -@JsonCreator(mode = JsonCreator.Mode.DISABLED) -private constructor( - private val queries: JsonField>, - private val additionalProperties: MutableMap, -) { - - @JsonCreator - private constructor( - @JsonProperty("queries") @ExcludeMissing queries: JsonField> = JsonMissing.of() - ) : this(queries, mutableMapOf()) - - /** - * Web search queries for the following-up web search. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun queries(): Optional> = queries.getOptional("queries") - - /** - * Returns the raw JSON value of [queries]. - * - * Unlike [queries], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("queries") @ExcludeMissing fun _queries(): JsonField> = queries - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [GoogleSearchCallArguments]. - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [GoogleSearchCallArguments]. */ - class Builder internal constructor() { - - private var queries: JsonField>? = null - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(googleSearchCallArguments: GoogleSearchCallArguments) = apply { - queries = googleSearchCallArguments.queries.map { it.toMutableList() } - additionalProperties = googleSearchCallArguments.additionalProperties.toMutableMap() - } - - /** Web search queries for the following-up web search. */ - fun queries(queries: List) = queries(JsonField.of(queries)) - - /** - * Sets [Builder.queries] to an arbitrary JSON value. - * - * You should usually call [Builder.queries] with a well-typed `List` value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun queries(queries: JsonField>) = apply { - this.queries = queries.map { it.toMutableList() } - } - - /** - * Adds a single [String] to [queries]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addQuery(query: String) = apply { - queries = - (queries ?: JsonField.of(mutableListOf())).also { - checkKnown("queries", it).add(query) - } - } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [GoogleSearchCallArguments]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): GoogleSearchCallArguments = - GoogleSearchCallArguments( - (queries ?: JsonMissing.of()).map { it.toImmutable() }, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): GoogleSearchCallArguments = apply { - if (validated) { - return@apply - } - - queries() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic internal fun validity(): Int = (queries.asKnown().getOrNull()?.size ?: 0) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is GoogleSearchCallArguments && - queries == other.queries && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { Objects.hash(queries, additionalProperties) } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "GoogleSearchCallArguments{queries=$queries, additionalProperties=$additionalProperties}" -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/GoogleSearchCallStep.kt b/src/main/java/com/google/genai/interactions/models/interactions/GoogleSearchCallStep.kt deleted file mode 100644 index 57e193606f2..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/GoogleSearchCallStep.kt +++ /dev/null @@ -1,647 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import com.google.genai.interactions.core.Enum -import com.google.genai.interactions.core.ExcludeMissing -import com.google.genai.interactions.core.JsonField -import com.google.genai.interactions.core.JsonMissing -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.core.checkKnown -import com.google.genai.interactions.core.checkRequired -import com.google.genai.interactions.core.toImmutable -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.util.Collections -import java.util.Objects -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -/** Google Search call step. */ -class GoogleSearchCallStep -@JsonCreator(mode = JsonCreator.Mode.DISABLED) -private constructor( - private val id: JsonField, - private val arguments: JsonField, - private val type: JsonValue, - private val searchType: JsonField, - private val signature: JsonField, - private val additionalProperties: MutableMap, -) { - - @JsonCreator - private constructor( - @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), - @JsonProperty("arguments") - @ExcludeMissing - arguments: JsonField = JsonMissing.of(), - @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), - @JsonProperty("search_type") - @ExcludeMissing - searchType: JsonField = JsonMissing.of(), - @JsonProperty("signature") @ExcludeMissing signature: JsonField = JsonMissing.of(), - ) : this(id, arguments, type, searchType, signature, mutableMapOf()) - - /** - * Required. A unique ID for this specific tool call. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). - */ - fun id(): String = id.getRequired("id") - - /** - * Required. The arguments to pass to Google Search. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). - */ - fun arguments(): Arguments = arguments.getRequired("arguments") - - /** - * Expected to always return the following: - * ```java - * JsonValue.from("google_search_call") - * ``` - * - * However, this method can be useful for debugging and logging (e.g. if the server responded - * with an unexpected value). - */ - @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type - - /** - * The type of search grounding enabled. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun searchType(): Optional = searchType.getOptional("search_type") - - /** - * A signature hash for backend validation. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun signature(): Optional = signature.getOptional("signature") - - /** - * Returns the raw JSON value of [id]. - * - * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id - - /** - * Returns the raw JSON value of [arguments]. - * - * Unlike [arguments], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("arguments") @ExcludeMissing fun _arguments(): JsonField = arguments - - /** - * Returns the raw JSON value of [searchType]. - * - * Unlike [searchType], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("search_type") - @ExcludeMissing - fun _searchType(): JsonField = searchType - - /** - * Returns the raw JSON value of [signature]. - * - * Unlike [signature], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("signature") @ExcludeMissing fun _signature(): JsonField = signature - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [GoogleSearchCallStep]. - * - * The following fields are required: - * ```java - * .id() - * .arguments() - * ``` - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [GoogleSearchCallStep]. */ - class Builder internal constructor() { - - private var id: JsonField? = null - private var arguments: JsonField? = null - private var type: JsonValue = JsonValue.from("google_search_call") - private var searchType: JsonField = JsonMissing.of() - private var signature: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(googleSearchCallStep: GoogleSearchCallStep) = apply { - id = googleSearchCallStep.id - arguments = googleSearchCallStep.arguments - type = googleSearchCallStep.type - searchType = googleSearchCallStep.searchType - signature = googleSearchCallStep.signature - additionalProperties = googleSearchCallStep.additionalProperties.toMutableMap() - } - - /** Required. A unique ID for this specific tool call. */ - fun id(id: String) = id(JsonField.of(id)) - - /** - * Sets [Builder.id] to an arbitrary JSON value. - * - * You should usually call [Builder.id] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun id(id: JsonField) = apply { this.id = id } - - /** Required. The arguments to pass to Google Search. */ - fun arguments(arguments: Arguments) = arguments(JsonField.of(arguments)) - - /** - * Sets [Builder.arguments] to an arbitrary JSON value. - * - * You should usually call [Builder.arguments] with a well-typed [Arguments] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun arguments(arguments: JsonField) = apply { this.arguments = arguments } - - /** - * Sets the field to an arbitrary JSON value. - * - * It is usually unnecessary to call this method because the field defaults to the - * following: - * ```java - * JsonValue.from("google_search_call") - * ``` - * - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun type(type: JsonValue) = apply { this.type = type } - - /** The type of search grounding enabled. */ - fun searchType(searchType: SearchType) = searchType(JsonField.of(searchType)) - - /** - * Sets [Builder.searchType] to an arbitrary JSON value. - * - * You should usually call [Builder.searchType] with a well-typed [SearchType] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun searchType(searchType: JsonField) = apply { this.searchType = searchType } - - /** A signature hash for backend validation. */ - fun signature(signature: String) = signature(JsonField.of(signature)) - - /** - * Sets [Builder.signature] to an arbitrary JSON value. - * - * You should usually call [Builder.signature] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun signature(signature: JsonField) = apply { this.signature = signature } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [GoogleSearchCallStep]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .id() - * .arguments() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): GoogleSearchCallStep = - GoogleSearchCallStep( - checkRequired("id", id), - checkRequired("arguments", arguments), - type, - searchType, - signature, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): GoogleSearchCallStep = apply { - if (validated) { - return@apply - } - - id() - arguments().validate() - _type().let { - if (it != JsonValue.from("google_search_call")) { - throw GeminiNextGenApiInvalidDataException("'type' is invalid, received $it") - } - } - searchType().ifPresent { it.validate() } - signature() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - (if (id.asKnown().isPresent) 1 else 0) + - (arguments.asKnown().getOrNull()?.validity() ?: 0) + - type.let { if (it == JsonValue.from("google_search_call")) 1 else 0 } + - (searchType.asKnown().getOrNull()?.validity() ?: 0) + - (if (signature.asKnown().isPresent) 1 else 0) - - /** Required. The arguments to pass to Google Search. */ - class Arguments - @JsonCreator(mode = JsonCreator.Mode.DISABLED) - private constructor( - private val queries: JsonField>, - private val additionalProperties: MutableMap, - ) { - - @JsonCreator - private constructor( - @JsonProperty("queries") - @ExcludeMissing - queries: JsonField> = JsonMissing.of() - ) : this(queries, mutableMapOf()) - - /** - * Web search queries for the following-up web search. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type - * (e.g. if the server responded with an unexpected value). - */ - fun queries(): Optional> = queries.getOptional("queries") - - /** - * Returns the raw JSON value of [queries]. - * - * Unlike [queries], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("queries") @ExcludeMissing fun _queries(): JsonField> = queries - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [Arguments]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Arguments]. */ - class Builder internal constructor() { - - private var queries: JsonField>? = null - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(arguments: Arguments) = apply { - queries = arguments.queries.map { it.toMutableList() } - additionalProperties = arguments.additionalProperties.toMutableMap() - } - - /** Web search queries for the following-up web search. */ - fun queries(queries: List) = queries(JsonField.of(queries)) - - /** - * Sets [Builder.queries] to an arbitrary JSON value. - * - * You should usually call [Builder.queries] with a well-typed `List` value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun queries(queries: JsonField>) = apply { - this.queries = queries.map { it.toMutableList() } - } - - /** - * Adds a single [String] to [queries]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addQuery(query: String) = apply { - queries = - (queries ?: JsonField.of(mutableListOf())).also { - checkKnown("queries", it).add(query) - } - } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [Arguments]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): Arguments = - Arguments( - (queries ?: JsonMissing.of()).map { it.toImmutable() }, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): Arguments = apply { - if (validated) { - return@apply - } - - queries() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic internal fun validity(): Int = (queries.asKnown().getOrNull()?.size ?: 0) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Arguments && - queries == other.queries && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { Objects.hash(queries, additionalProperties) } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Arguments{queries=$queries, additionalProperties=$additionalProperties}" - } - - /** The type of search grounding enabled. */ - class SearchType @JsonCreator private constructor(private val value: JsonField) : Enum { - - /** - * Returns this class instance's raw value. - * - * This is usually only useful if this instance was deserialized from data that doesn't - * match any known member, and you want to know that value. For example, if the SDK is on an - * older version than the API, then the API may respond with new members that the SDK is - * unaware of. - */ - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - companion object { - - @JvmField val WEB_SEARCH = of("web_search") - - @JvmField val IMAGE_SEARCH = of("image_search") - - @JvmField val ENTERPRISE_WEB_SEARCH = of("enterprise_web_search") - - @JvmStatic fun of(value: String) = SearchType(JsonField.of(value)) - } - - /** An enum containing [SearchType]'s known values. */ - enum class Known { - WEB_SEARCH, - IMAGE_SEARCH, - ENTERPRISE_WEB_SEARCH, - } - - /** - * An enum containing [SearchType]'s known values, as well as an [_UNKNOWN] member. - * - * An instance of [SearchType] can contain an unknown value in a couple of cases: - * - It was deserialized from data that doesn't match any known member. For example, if the - * SDK is on an older version than the API, then the API may respond with new members that - * the SDK is unaware of. - * - It was constructed with an arbitrary value using the [of] method. - */ - enum class Value { - WEB_SEARCH, - IMAGE_SEARCH, - ENTERPRISE_WEB_SEARCH, - /** - * An enum member indicating that [SearchType] was instantiated with an unknown value. - */ - _UNKNOWN, - } - - /** - * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] - * if the class was instantiated with an unknown value. - * - * Use the [known] method instead if you're certain the value is always known or if you want - * to throw for the unknown case. - */ - fun value(): Value = - when (this) { - WEB_SEARCH -> Value.WEB_SEARCH - IMAGE_SEARCH -> Value.IMAGE_SEARCH - ENTERPRISE_WEB_SEARCH -> Value.ENTERPRISE_WEB_SEARCH - else -> Value._UNKNOWN - } - - /** - * Returns an enum member corresponding to this class instance's value. - * - * Use the [value] method instead if you're uncertain the value is always known and don't - * want to throw for the unknown case. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value is a not a - * known member. - */ - fun known(): Known = - when (this) { - WEB_SEARCH -> Known.WEB_SEARCH - IMAGE_SEARCH -> Known.IMAGE_SEARCH - ENTERPRISE_WEB_SEARCH -> Known.ENTERPRISE_WEB_SEARCH - else -> throw GeminiNextGenApiInvalidDataException("Unknown SearchType: $value") - } - - /** - * Returns this class instance's primitive wire representation. - * - * This differs from the [toString] method because that method is primarily for debugging - * and generally doesn't throw. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value does not have - * the expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - GeminiNextGenApiInvalidDataException("Value is not a String") - } - - private var validated: Boolean = false - - fun validate(): SearchType = apply { - if (validated) { - return@apply - } - - known() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is SearchType && value == other.value - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is GoogleSearchCallStep && - id == other.id && - arguments == other.arguments && - type == other.type && - searchType == other.searchType && - signature == other.signature && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { - Objects.hash(id, arguments, type, searchType, signature, additionalProperties) - } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "GoogleSearchCallStep{id=$id, arguments=$arguments, type=$type, searchType=$searchType, signature=$signature, additionalProperties=$additionalProperties}" -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/GoogleSearchResult.kt b/src/main/java/com/google/genai/interactions/models/interactions/GoogleSearchResult.kt deleted file mode 100644 index dc573cc7447..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/GoogleSearchResult.kt +++ /dev/null @@ -1,183 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import com.google.genai.interactions.core.ExcludeMissing -import com.google.genai.interactions.core.JsonField -import com.google.genai.interactions.core.JsonMissing -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.util.Collections -import java.util.Objects -import java.util.Optional - -/** The result of the Google Search. */ -class GoogleSearchResult -@JsonCreator(mode = JsonCreator.Mode.DISABLED) -private constructor( - private val searchSuggestions: JsonField, - private val additionalProperties: MutableMap, -) { - - @JsonCreator - private constructor( - @JsonProperty("search_suggestions") - @ExcludeMissing - searchSuggestions: JsonField = JsonMissing.of() - ) : this(searchSuggestions, mutableMapOf()) - - /** - * Web content snippet that can be embedded in a web page or an app webview. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun searchSuggestions(): Optional = searchSuggestions.getOptional("search_suggestions") - - /** - * Returns the raw JSON value of [searchSuggestions]. - * - * Unlike [searchSuggestions], this method doesn't throw if the JSON field has an unexpected - * type. - */ - @JsonProperty("search_suggestions") - @ExcludeMissing - fun _searchSuggestions(): JsonField = searchSuggestions - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [GoogleSearchResult]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [GoogleSearchResult]. */ - class Builder internal constructor() { - - private var searchSuggestions: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(googleSearchResult: GoogleSearchResult) = apply { - searchSuggestions = googleSearchResult.searchSuggestions - additionalProperties = googleSearchResult.additionalProperties.toMutableMap() - } - - /** Web content snippet that can be embedded in a web page or an app webview. */ - fun searchSuggestions(searchSuggestions: String) = - searchSuggestions(JsonField.of(searchSuggestions)) - - /** - * Sets [Builder.searchSuggestions] to an arbitrary JSON value. - * - * You should usually call [Builder.searchSuggestions] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun searchSuggestions(searchSuggestions: JsonField) = apply { - this.searchSuggestions = searchSuggestions - } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [GoogleSearchResult]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): GoogleSearchResult = - GoogleSearchResult(searchSuggestions, additionalProperties.toMutableMap()) - } - - private var validated: Boolean = false - - fun validate(): GoogleSearchResult = apply { - if (validated) { - return@apply - } - - searchSuggestions() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = (if (searchSuggestions.asKnown().isPresent) 1 else 0) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is GoogleSearchResult && - searchSuggestions == other.searchSuggestions && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { Objects.hash(searchSuggestions, additionalProperties) } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "GoogleSearchResult{searchSuggestions=$searchSuggestions, additionalProperties=$additionalProperties}" -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/GoogleSearchResultDelta.kt b/src/main/java/com/google/genai/interactions/models/interactions/GoogleSearchResultDelta.kt deleted file mode 100644 index a8bb30969de..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/GoogleSearchResultDelta.kt +++ /dev/null @@ -1,316 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import com.google.genai.interactions.core.ExcludeMissing -import com.google.genai.interactions.core.JsonField -import com.google.genai.interactions.core.JsonMissing -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.core.checkKnown -import com.google.genai.interactions.core.checkRequired -import com.google.genai.interactions.core.toImmutable -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.util.Collections -import java.util.Objects -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -class GoogleSearchResultDelta -@JsonCreator(mode = JsonCreator.Mode.DISABLED) -private constructor( - private val result: JsonField>, - private val type: JsonValue, - private val isError: JsonField, - private val signature: JsonField, - private val additionalProperties: MutableMap, -) { - - @JsonCreator - private constructor( - @JsonProperty("result") - @ExcludeMissing - result: JsonField> = JsonMissing.of(), - @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), - @JsonProperty("is_error") @ExcludeMissing isError: JsonField = JsonMissing.of(), - @JsonProperty("signature") @ExcludeMissing signature: JsonField = JsonMissing.of(), - ) : this(result, type, isError, signature, mutableMapOf()) - - /** - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). - */ - fun result(): List = result.getRequired("result") - - /** - * Expected to always return the following: - * ```java - * JsonValue.from("google_search_result") - * ``` - * - * However, this method can be useful for debugging and logging (e.g. if the server responded - * with an unexpected value). - */ - @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type - - /** - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun isError(): Optional = isError.getOptional("is_error") - - /** - * A signature hash for backend validation. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun signature(): Optional = signature.getOptional("signature") - - /** - * Returns the raw JSON value of [result]. - * - * Unlike [result], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("result") - @ExcludeMissing - fun _result(): JsonField> = result - - /** - * Returns the raw JSON value of [isError]. - * - * Unlike [isError], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("is_error") @ExcludeMissing fun _isError(): JsonField = isError - - /** - * Returns the raw JSON value of [signature]. - * - * Unlike [signature], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("signature") @ExcludeMissing fun _signature(): JsonField = signature - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [GoogleSearchResultDelta]. - * - * The following fields are required: - * ```java - * .result() - * ``` - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [GoogleSearchResultDelta]. */ - class Builder internal constructor() { - - private var result: JsonField>? = null - private var type: JsonValue = JsonValue.from("google_search_result") - private var isError: JsonField = JsonMissing.of() - private var signature: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(googleSearchResultDelta: GoogleSearchResultDelta) = apply { - result = googleSearchResultDelta.result.map { it.toMutableList() } - type = googleSearchResultDelta.type - isError = googleSearchResultDelta.isError - signature = googleSearchResultDelta.signature - additionalProperties = googleSearchResultDelta.additionalProperties.toMutableMap() - } - - fun result(result: List) = result(JsonField.of(result)) - - /** - * Sets [Builder.result] to an arbitrary JSON value. - * - * You should usually call [Builder.result] with a well-typed `List` - * value instead. This method is primarily for setting the field to an undocumented or not - * yet supported value. - */ - fun result(result: JsonField>) = apply { - this.result = result.map { it.toMutableList() } - } - - /** - * Adds a single [GoogleSearchResult] to [Builder.result]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addResult(result: GoogleSearchResult) = apply { - this.result = - (this.result ?: JsonField.of(mutableListOf())).also { - checkKnown("result", it).add(result) - } - } - - /** - * Sets the field to an arbitrary JSON value. - * - * It is usually unnecessary to call this method because the field defaults to the - * following: - * ```java - * JsonValue.from("google_search_result") - * ``` - * - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun type(type: JsonValue) = apply { this.type = type } - - fun isError(isError: Boolean) = isError(JsonField.of(isError)) - - /** - * Sets [Builder.isError] to an arbitrary JSON value. - * - * You should usually call [Builder.isError] with a well-typed [Boolean] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun isError(isError: JsonField) = apply { this.isError = isError } - - /** A signature hash for backend validation. */ - fun signature(signature: String) = signature(JsonField.of(signature)) - - /** - * Sets [Builder.signature] to an arbitrary JSON value. - * - * You should usually call [Builder.signature] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun signature(signature: JsonField) = apply { this.signature = signature } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [GoogleSearchResultDelta]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .result() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): GoogleSearchResultDelta = - GoogleSearchResultDelta( - checkRequired("result", result).map { it.toImmutable() }, - type, - isError, - signature, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): GoogleSearchResultDelta = apply { - if (validated) { - return@apply - } - - result().forEach { it.validate() } - _type().let { - if (it != JsonValue.from("google_search_result")) { - throw GeminiNextGenApiInvalidDataException("'type' is invalid, received $it") - } - } - isError() - signature() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - (result.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + - type.let { if (it == JsonValue.from("google_search_result")) 1 else 0 } + - (if (isError.asKnown().isPresent) 1 else 0) + - (if (signature.asKnown().isPresent) 1 else 0) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is GoogleSearchResultDelta && - result == other.result && - type == other.type && - isError == other.isError && - signature == other.signature && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { - Objects.hash(result, type, isError, signature, additionalProperties) - } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "GoogleSearchResultDelta{result=$result, type=$type, isError=$isError, signature=$signature, additionalProperties=$additionalProperties}" -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/GoogleSearchResultStep.kt b/src/main/java/com/google/genai/interactions/models/interactions/GoogleSearchResultStep.kt deleted file mode 100644 index a005e39d919..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/GoogleSearchResultStep.kt +++ /dev/null @@ -1,507 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import com.google.genai.interactions.core.ExcludeMissing -import com.google.genai.interactions.core.JsonField -import com.google.genai.interactions.core.JsonMissing -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.core.checkKnown -import com.google.genai.interactions.core.checkRequired -import com.google.genai.interactions.core.toImmutable -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.util.Collections -import java.util.Objects -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -/** Google Search result step. */ -class GoogleSearchResultStep -@JsonCreator(mode = JsonCreator.Mode.DISABLED) -private constructor( - private val callId: JsonField, - private val result: JsonField>, - private val type: JsonValue, - private val isError: JsonField, - private val signature: JsonField, - private val additionalProperties: MutableMap, -) { - - @JsonCreator - private constructor( - @JsonProperty("call_id") @ExcludeMissing callId: JsonField = JsonMissing.of(), - @JsonProperty("result") @ExcludeMissing result: JsonField> = JsonMissing.of(), - @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), - @JsonProperty("is_error") @ExcludeMissing isError: JsonField = JsonMissing.of(), - @JsonProperty("signature") @ExcludeMissing signature: JsonField = JsonMissing.of(), - ) : this(callId, result, type, isError, signature, mutableMapOf()) - - /** - * Required. ID to match the ID from the function call block. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). - */ - fun callId(): String = callId.getRequired("call_id") - - /** - * Required. The results of the Google Search. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). - */ - fun result(): List = result.getRequired("result") - - /** - * Expected to always return the following: - * ```java - * JsonValue.from("google_search_result") - * ``` - * - * However, this method can be useful for debugging and logging (e.g. if the server responded - * with an unexpected value). - */ - @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type - - /** - * Whether the Google Search resulted in an error. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun isError(): Optional = isError.getOptional("is_error") - - /** - * A signature hash for backend validation. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun signature(): Optional = signature.getOptional("signature") - - /** - * Returns the raw JSON value of [callId]. - * - * Unlike [callId], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("call_id") @ExcludeMissing fun _callId(): JsonField = callId - - /** - * Returns the raw JSON value of [result]. - * - * Unlike [result], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("result") @ExcludeMissing fun _result(): JsonField> = result - - /** - * Returns the raw JSON value of [isError]. - * - * Unlike [isError], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("is_error") @ExcludeMissing fun _isError(): JsonField = isError - - /** - * Returns the raw JSON value of [signature]. - * - * Unlike [signature], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("signature") @ExcludeMissing fun _signature(): JsonField = signature - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [GoogleSearchResultStep]. - * - * The following fields are required: - * ```java - * .callId() - * .result() - * ``` - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [GoogleSearchResultStep]. */ - class Builder internal constructor() { - - private var callId: JsonField? = null - private var result: JsonField>? = null - private var type: JsonValue = JsonValue.from("google_search_result") - private var isError: JsonField = JsonMissing.of() - private var signature: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(googleSearchResultStep: GoogleSearchResultStep) = apply { - callId = googleSearchResultStep.callId - result = googleSearchResultStep.result.map { it.toMutableList() } - type = googleSearchResultStep.type - isError = googleSearchResultStep.isError - signature = googleSearchResultStep.signature - additionalProperties = googleSearchResultStep.additionalProperties.toMutableMap() - } - - /** Required. ID to match the ID from the function call block. */ - fun callId(callId: String) = callId(JsonField.of(callId)) - - /** - * Sets [Builder.callId] to an arbitrary JSON value. - * - * You should usually call [Builder.callId] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun callId(callId: JsonField) = apply { this.callId = callId } - - /** Required. The results of the Google Search. */ - fun result(result: List) = result(JsonField.of(result)) - - /** - * Sets [Builder.result] to an arbitrary JSON value. - * - * You should usually call [Builder.result] with a well-typed `List` value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun result(result: JsonField>) = apply { - this.result = result.map { it.toMutableList() } - } - - /** - * Adds a single [Result] to [Builder.result]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addResult(result: Result) = apply { - this.result = - (this.result ?: JsonField.of(mutableListOf())).also { - checkKnown("result", it).add(result) - } - } - - /** - * Sets the field to an arbitrary JSON value. - * - * It is usually unnecessary to call this method because the field defaults to the - * following: - * ```java - * JsonValue.from("google_search_result") - * ``` - * - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun type(type: JsonValue) = apply { this.type = type } - - /** Whether the Google Search resulted in an error. */ - fun isError(isError: Boolean) = isError(JsonField.of(isError)) - - /** - * Sets [Builder.isError] to an arbitrary JSON value. - * - * You should usually call [Builder.isError] with a well-typed [Boolean] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun isError(isError: JsonField) = apply { this.isError = isError } - - /** A signature hash for backend validation. */ - fun signature(signature: String) = signature(JsonField.of(signature)) - - /** - * Sets [Builder.signature] to an arbitrary JSON value. - * - * You should usually call [Builder.signature] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun signature(signature: JsonField) = apply { this.signature = signature } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [GoogleSearchResultStep]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .callId() - * .result() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): GoogleSearchResultStep = - GoogleSearchResultStep( - checkRequired("callId", callId), - checkRequired("result", result).map { it.toImmutable() }, - type, - isError, - signature, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): GoogleSearchResultStep = apply { - if (validated) { - return@apply - } - - callId() - result().forEach { it.validate() } - _type().let { - if (it != JsonValue.from("google_search_result")) { - throw GeminiNextGenApiInvalidDataException("'type' is invalid, received $it") - } - } - isError() - signature() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - (if (callId.asKnown().isPresent) 1 else 0) + - (result.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + - type.let { if (it == JsonValue.from("google_search_result")) 1 else 0 } + - (if (isError.asKnown().isPresent) 1 else 0) + - (if (signature.asKnown().isPresent) 1 else 0) - - /** The result of the Google Search. */ - class Result - @JsonCreator(mode = JsonCreator.Mode.DISABLED) - private constructor( - private val searchSuggestions: JsonField, - private val additionalProperties: MutableMap, - ) { - - @JsonCreator - private constructor( - @JsonProperty("search_suggestions") - @ExcludeMissing - searchSuggestions: JsonField = JsonMissing.of() - ) : this(searchSuggestions, mutableMapOf()) - - /** - * Web content snippet that can be embedded in a web page or an app webview. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type - * (e.g. if the server responded with an unexpected value). - */ - fun searchSuggestions(): Optional = - searchSuggestions.getOptional("search_suggestions") - - /** - * Returns the raw JSON value of [searchSuggestions]. - * - * Unlike [searchSuggestions], this method doesn't throw if the JSON field has an unexpected - * type. - */ - @JsonProperty("search_suggestions") - @ExcludeMissing - fun _searchSuggestions(): JsonField = searchSuggestions - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [Result]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Result]. */ - class Builder internal constructor() { - - private var searchSuggestions: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(result: Result) = apply { - searchSuggestions = result.searchSuggestions - additionalProperties = result.additionalProperties.toMutableMap() - } - - /** Web content snippet that can be embedded in a web page or an app webview. */ - fun searchSuggestions(searchSuggestions: String) = - searchSuggestions(JsonField.of(searchSuggestions)) - - /** - * Sets [Builder.searchSuggestions] to an arbitrary JSON value. - * - * You should usually call [Builder.searchSuggestions] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun searchSuggestions(searchSuggestions: JsonField) = apply { - this.searchSuggestions = searchSuggestions - } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [Result]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): Result = Result(searchSuggestions, additionalProperties.toMutableMap()) - } - - private var validated: Boolean = false - - fun validate(): Result = apply { - if (validated) { - return@apply - } - - searchSuggestions() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = (if (searchSuggestions.asKnown().isPresent) 1 else 0) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Result && - searchSuggestions == other.searchSuggestions && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { Objects.hash(searchSuggestions, additionalProperties) } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Result{searchSuggestions=$searchSuggestions, additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is GoogleSearchResultStep && - callId == other.callId && - result == other.result && - type == other.type && - isError == other.isError && - signature == other.signature && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { - Objects.hash(callId, result, type, isError, signature, additionalProperties) - } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "GoogleSearchResultStep{callId=$callId, result=$result, type=$type, isError=$isError, signature=$signature, additionalProperties=$additionalProperties}" -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/ImageConfig.kt b/src/main/java/com/google/genai/interactions/models/interactions/ImageConfig.kt deleted file mode 100644 index d5ac96967d8..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/ImageConfig.kt +++ /dev/null @@ -1,557 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import com.google.genai.interactions.core.Enum -import com.google.genai.interactions.core.ExcludeMissing -import com.google.genai.interactions.core.JsonField -import com.google.genai.interactions.core.JsonMissing -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.util.Collections -import java.util.Objects -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -/** The configuration for image interaction. */ -class ImageConfig -@JsonCreator(mode = JsonCreator.Mode.DISABLED) -private constructor( - private val aspectRatio: JsonField, - private val imageSize: JsonField, - private val additionalProperties: MutableMap, -) { - - @JsonCreator - private constructor( - @JsonProperty("aspect_ratio") - @ExcludeMissing - aspectRatio: JsonField = JsonMissing.of(), - @JsonProperty("image_size") - @ExcludeMissing - imageSize: JsonField = JsonMissing.of(), - ) : this(aspectRatio, imageSize, mutableMapOf()) - - /** - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun aspectRatio(): Optional = aspectRatio.getOptional("aspect_ratio") - - /** - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun imageSize(): Optional = imageSize.getOptional("image_size") - - /** - * Returns the raw JSON value of [aspectRatio]. - * - * Unlike [aspectRatio], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("aspect_ratio") - @ExcludeMissing - fun _aspectRatio(): JsonField = aspectRatio - - /** - * Returns the raw JSON value of [imageSize]. - * - * Unlike [imageSize], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("image_size") @ExcludeMissing fun _imageSize(): JsonField = imageSize - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [ImageConfig]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [ImageConfig]. */ - class Builder internal constructor() { - - private var aspectRatio: JsonField = JsonMissing.of() - private var imageSize: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(imageConfig: ImageConfig) = apply { - aspectRatio = imageConfig.aspectRatio - imageSize = imageConfig.imageSize - additionalProperties = imageConfig.additionalProperties.toMutableMap() - } - - fun aspectRatio(aspectRatio: AspectRatio) = aspectRatio(JsonField.of(aspectRatio)) - - /** - * Sets [Builder.aspectRatio] to an arbitrary JSON value. - * - * You should usually call [Builder.aspectRatio] with a well-typed [AspectRatio] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun aspectRatio(aspectRatio: JsonField) = apply { - this.aspectRatio = aspectRatio - } - - fun imageSize(imageSize: ImageSize) = imageSize(JsonField.of(imageSize)) - - /** - * Sets [Builder.imageSize] to an arbitrary JSON value. - * - * You should usually call [Builder.imageSize] with a well-typed [ImageSize] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun imageSize(imageSize: JsonField) = apply { this.imageSize = imageSize } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [ImageConfig]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): ImageConfig = - ImageConfig(aspectRatio, imageSize, additionalProperties.toMutableMap()) - } - - private var validated: Boolean = false - - fun validate(): ImageConfig = apply { - if (validated) { - return@apply - } - - aspectRatio().ifPresent { it.validate() } - imageSize().ifPresent { it.validate() } - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - (aspectRatio.asKnown().getOrNull()?.validity() ?: 0) + - (imageSize.asKnown().getOrNull()?.validity() ?: 0) - - class AspectRatio @JsonCreator private constructor(private val value: JsonField) : - Enum { - - /** - * Returns this class instance's raw value. - * - * This is usually only useful if this instance was deserialized from data that doesn't - * match any known member, and you want to know that value. For example, if the SDK is on an - * older version than the API, then the API may respond with new members that the SDK is - * unaware of. - */ - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - companion object { - - @JvmField val _1_1 = of("1:1") - - @JvmField val _2_3 = of("2:3") - - @JvmField val _3_2 = of("3:2") - - @JvmField val _3_4 = of("3:4") - - @JvmField val _4_3 = of("4:3") - - @JvmField val _4_5 = of("4:5") - - @JvmField val _5_4 = of("5:4") - - @JvmField val _9_16 = of("9:16") - - @JvmField val _16_9 = of("16:9") - - @JvmField val _21_9 = of("21:9") - - @JvmField val _1_8 = of("1:8") - - @JvmField val _8_1 = of("8:1") - - @JvmField val _1_4 = of("1:4") - - @JvmField val _4_1 = of("4:1") - - @JvmStatic fun of(value: String) = AspectRatio(JsonField.of(value)) - } - - /** An enum containing [AspectRatio]'s known values. */ - enum class Known { - _1_1, - _2_3, - _3_2, - _3_4, - _4_3, - _4_5, - _5_4, - _9_16, - _16_9, - _21_9, - _1_8, - _8_1, - _1_4, - _4_1, - } - - /** - * An enum containing [AspectRatio]'s known values, as well as an [_UNKNOWN] member. - * - * An instance of [AspectRatio] can contain an unknown value in a couple of cases: - * - It was deserialized from data that doesn't match any known member. For example, if the - * SDK is on an older version than the API, then the API may respond with new members that - * the SDK is unaware of. - * - It was constructed with an arbitrary value using the [of] method. - */ - enum class Value { - _1_1, - _2_3, - _3_2, - _3_4, - _4_3, - _4_5, - _5_4, - _9_16, - _16_9, - _21_9, - _1_8, - _8_1, - _1_4, - _4_1, - /** - * An enum member indicating that [AspectRatio] was instantiated with an unknown value. - */ - _UNKNOWN, - } - - /** - * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] - * if the class was instantiated with an unknown value. - * - * Use the [known] method instead if you're certain the value is always known or if you want - * to throw for the unknown case. - */ - fun value(): Value = - when (this) { - _1_1 -> Value._1_1 - _2_3 -> Value._2_3 - _3_2 -> Value._3_2 - _3_4 -> Value._3_4 - _4_3 -> Value._4_3 - _4_5 -> Value._4_5 - _5_4 -> Value._5_4 - _9_16 -> Value._9_16 - _16_9 -> Value._16_9 - _21_9 -> Value._21_9 - _1_8 -> Value._1_8 - _8_1 -> Value._8_1 - _1_4 -> Value._1_4 - _4_1 -> Value._4_1 - else -> Value._UNKNOWN - } - - /** - * Returns an enum member corresponding to this class instance's value. - * - * Use the [value] method instead if you're uncertain the value is always known and don't - * want to throw for the unknown case. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value is a not a - * known member. - */ - fun known(): Known = - when (this) { - _1_1 -> Known._1_1 - _2_3 -> Known._2_3 - _3_2 -> Known._3_2 - _3_4 -> Known._3_4 - _4_3 -> Known._4_3 - _4_5 -> Known._4_5 - _5_4 -> Known._5_4 - _9_16 -> Known._9_16 - _16_9 -> Known._16_9 - _21_9 -> Known._21_9 - _1_8 -> Known._1_8 - _8_1 -> Known._8_1 - _1_4 -> Known._1_4 - _4_1 -> Known._4_1 - else -> throw GeminiNextGenApiInvalidDataException("Unknown AspectRatio: $value") - } - - /** - * Returns this class instance's primitive wire representation. - * - * This differs from the [toString] method because that method is primarily for debugging - * and generally doesn't throw. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value does not have - * the expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - GeminiNextGenApiInvalidDataException("Value is not a String") - } - - private var validated: Boolean = false - - fun validate(): AspectRatio = apply { - if (validated) { - return@apply - } - - known() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is AspectRatio && value == other.value - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - class ImageSize @JsonCreator private constructor(private val value: JsonField) : Enum { - - /** - * Returns this class instance's raw value. - * - * This is usually only useful if this instance was deserialized from data that doesn't - * match any known member, and you want to know that value. For example, if the SDK is on an - * older version than the API, then the API may respond with new members that the SDK is - * unaware of. - */ - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - companion object { - - @JvmField val _1_K = of("1K") - - @JvmField val _2_K = of("2K") - - @JvmField val _4_K = of("4K") - - @JvmField val _512 = of("512") - - @JvmStatic fun of(value: String) = ImageSize(JsonField.of(value)) - } - - /** An enum containing [ImageSize]'s known values. */ - enum class Known { - _1_K, - _2_K, - _4_K, - _512, - } - - /** - * An enum containing [ImageSize]'s known values, as well as an [_UNKNOWN] member. - * - * An instance of [ImageSize] can contain an unknown value in a couple of cases: - * - It was deserialized from data that doesn't match any known member. For example, if the - * SDK is on an older version than the API, then the API may respond with new members that - * the SDK is unaware of. - * - It was constructed with an arbitrary value using the [of] method. - */ - enum class Value { - _1_K, - _2_K, - _4_K, - _512, - /** - * An enum member indicating that [ImageSize] was instantiated with an unknown value. - */ - _UNKNOWN, - } - - /** - * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] - * if the class was instantiated with an unknown value. - * - * Use the [known] method instead if you're certain the value is always known or if you want - * to throw for the unknown case. - */ - fun value(): Value = - when (this) { - _1_K -> Value._1_K - _2_K -> Value._2_K - _4_K -> Value._4_K - _512 -> Value._512 - else -> Value._UNKNOWN - } - - /** - * Returns an enum member corresponding to this class instance's value. - * - * Use the [value] method instead if you're uncertain the value is always known and don't - * want to throw for the unknown case. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value is a not a - * known member. - */ - fun known(): Known = - when (this) { - _1_K -> Known._1_K - _2_K -> Known._2_K - _4_K -> Known._4_K - _512 -> Known._512 - else -> throw GeminiNextGenApiInvalidDataException("Unknown ImageSize: $value") - } - - /** - * Returns this class instance's primitive wire representation. - * - * This differs from the [toString] method because that method is primarily for debugging - * and generally doesn't throw. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value does not have - * the expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - GeminiNextGenApiInvalidDataException("Value is not a String") - } - - private var validated: Boolean = false - - fun validate(): ImageSize = apply { - if (validated) { - return@apply - } - - known() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is ImageSize && value == other.value - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is ImageConfig && - aspectRatio == other.aspectRatio && - imageSize == other.imageSize && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { Objects.hash(aspectRatio, imageSize, additionalProperties) } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "ImageConfig{aspectRatio=$aspectRatio, imageSize=$imageSize, additionalProperties=$additionalProperties}" -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/ImageContent.kt b/src/main/java/com/google/genai/interactions/models/interactions/ImageContent.kt deleted file mode 100644 index 97508e65c5c..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/ImageContent.kt +++ /dev/null @@ -1,626 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import com.google.genai.interactions.core.Enum -import com.google.genai.interactions.core.ExcludeMissing -import com.google.genai.interactions.core.JsonField -import com.google.genai.interactions.core.JsonMissing -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.util.Collections -import java.util.Objects -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -/** An image content block. */ -class ImageContent -@JsonCreator(mode = JsonCreator.Mode.DISABLED) -private constructor( - private val type: JsonValue, - private val data: JsonField, - private val mimeType: JsonField, - private val resolution: JsonField, - private val uri: JsonField, - private val additionalProperties: MutableMap, -) { - - @JsonCreator - private constructor( - @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), - @JsonProperty("data") @ExcludeMissing data: JsonField = JsonMissing.of(), - @JsonProperty("mime_type") @ExcludeMissing mimeType: JsonField = JsonMissing.of(), - @JsonProperty("resolution") - @ExcludeMissing - resolution: JsonField = JsonMissing.of(), - @JsonProperty("uri") @ExcludeMissing uri: JsonField = JsonMissing.of(), - ) : this(type, data, mimeType, resolution, uri, mutableMapOf()) - - /** - * Expected to always return the following: - * ```java - * JsonValue.from("image") - * ``` - * - * However, this method can be useful for debugging and logging (e.g. if the server responded - * with an unexpected value). - */ - @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type - - /** - * The image content. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun data(): Optional = data.getOptional("data") - - /** - * The mime type of the image. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun mimeType(): Optional = mimeType.getOptional("mime_type") - - /** - * The resolution of the media. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun resolution(): Optional = resolution.getOptional("resolution") - - /** - * The URI of the image. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun uri(): Optional = uri.getOptional("uri") - - /** - * Returns the raw JSON value of [data]. - * - * Unlike [data], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("data") @ExcludeMissing fun _data(): JsonField = data - - /** - * Returns the raw JSON value of [mimeType]. - * - * Unlike [mimeType], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("mime_type") @ExcludeMissing fun _mimeType(): JsonField = mimeType - - /** - * Returns the raw JSON value of [resolution]. - * - * Unlike [resolution], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("resolution") - @ExcludeMissing - fun _resolution(): JsonField = resolution - - /** - * Returns the raw JSON value of [uri]. - * - * Unlike [uri], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("uri") @ExcludeMissing fun _uri(): JsonField = uri - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [ImageContent]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [ImageContent]. */ - class Builder internal constructor() { - - private var type: JsonValue = JsonValue.from("image") - private var data: JsonField = JsonMissing.of() - private var mimeType: JsonField = JsonMissing.of() - private var resolution: JsonField = JsonMissing.of() - private var uri: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(imageContent: ImageContent) = apply { - type = imageContent.type - data = imageContent.data - mimeType = imageContent.mimeType - resolution = imageContent.resolution - uri = imageContent.uri - additionalProperties = imageContent.additionalProperties.toMutableMap() - } - - /** - * Sets the field to an arbitrary JSON value. - * - * It is usually unnecessary to call this method because the field defaults to the - * following: - * ```java - * JsonValue.from("image") - * ``` - * - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun type(type: JsonValue) = apply { this.type = type } - - /** The image content. */ - fun data(data: String) = data(JsonField.of(data)) - - /** - * Sets [Builder.data] to an arbitrary JSON value. - * - * You should usually call [Builder.data] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun data(data: JsonField) = apply { this.data = data } - - /** The mime type of the image. */ - fun mimeType(mimeType: MimeType) = mimeType(JsonField.of(mimeType)) - - /** - * Sets [Builder.mimeType] to an arbitrary JSON value. - * - * You should usually call [Builder.mimeType] with a well-typed [MimeType] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun mimeType(mimeType: JsonField) = apply { this.mimeType = mimeType } - - /** The resolution of the media. */ - fun resolution(resolution: Resolution) = resolution(JsonField.of(resolution)) - - /** - * Sets [Builder.resolution] to an arbitrary JSON value. - * - * You should usually call [Builder.resolution] with a well-typed [Resolution] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun resolution(resolution: JsonField) = apply { this.resolution = resolution } - - /** The URI of the image. */ - fun uri(uri: String) = uri(JsonField.of(uri)) - - /** - * Sets [Builder.uri] to an arbitrary JSON value. - * - * You should usually call [Builder.uri] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun uri(uri: JsonField) = apply { this.uri = uri } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [ImageContent]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): ImageContent = - ImageContent(type, data, mimeType, resolution, uri, additionalProperties.toMutableMap()) - } - - private var validated: Boolean = false - - fun validate(): ImageContent = apply { - if (validated) { - return@apply - } - - _type().let { - if (it != JsonValue.from("image")) { - throw GeminiNextGenApiInvalidDataException("'type' is invalid, received $it") - } - } - data() - mimeType().ifPresent { it.validate() } - resolution().ifPresent { it.validate() } - uri() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - type.let { if (it == JsonValue.from("image")) 1 else 0 } + - (if (data.asKnown().isPresent) 1 else 0) + - (mimeType.asKnown().getOrNull()?.validity() ?: 0) + - (resolution.asKnown().getOrNull()?.validity() ?: 0) + - (if (uri.asKnown().isPresent) 1 else 0) - - /** The mime type of the image. */ - class MimeType @JsonCreator private constructor(private val value: JsonField) : Enum { - - /** - * Returns this class instance's raw value. - * - * This is usually only useful if this instance was deserialized from data that doesn't - * match any known member, and you want to know that value. For example, if the SDK is on an - * older version than the API, then the API may respond with new members that the SDK is - * unaware of. - */ - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - companion object { - - @JvmField val IMAGE_PNG = of("image/png") - - @JvmField val IMAGE_JPEG = of("image/jpeg") - - @JvmField val IMAGE_WEBP = of("image/webp") - - @JvmField val IMAGE_HEIC = of("image/heic") - - @JvmField val IMAGE_HEIF = of("image/heif") - - @JvmField val IMAGE_GIF = of("image/gif") - - @JvmField val IMAGE_BMP = of("image/bmp") - - @JvmField val IMAGE_TIFF = of("image/tiff") - - @JvmStatic fun of(value: String) = MimeType(JsonField.of(value)) - } - - /** An enum containing [MimeType]'s known values. */ - enum class Known { - IMAGE_PNG, - IMAGE_JPEG, - IMAGE_WEBP, - IMAGE_HEIC, - IMAGE_HEIF, - IMAGE_GIF, - IMAGE_BMP, - IMAGE_TIFF, - } - - /** - * An enum containing [MimeType]'s known values, as well as an [_UNKNOWN] member. - * - * An instance of [MimeType] can contain an unknown value in a couple of cases: - * - It was deserialized from data that doesn't match any known member. For example, if the - * SDK is on an older version than the API, then the API may respond with new members that - * the SDK is unaware of. - * - It was constructed with an arbitrary value using the [of] method. - */ - enum class Value { - IMAGE_PNG, - IMAGE_JPEG, - IMAGE_WEBP, - IMAGE_HEIC, - IMAGE_HEIF, - IMAGE_GIF, - IMAGE_BMP, - IMAGE_TIFF, - /** An enum member indicating that [MimeType] was instantiated with an unknown value. */ - _UNKNOWN, - } - - /** - * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] - * if the class was instantiated with an unknown value. - * - * Use the [known] method instead if you're certain the value is always known or if you want - * to throw for the unknown case. - */ - fun value(): Value = - when (this) { - IMAGE_PNG -> Value.IMAGE_PNG - IMAGE_JPEG -> Value.IMAGE_JPEG - IMAGE_WEBP -> Value.IMAGE_WEBP - IMAGE_HEIC -> Value.IMAGE_HEIC - IMAGE_HEIF -> Value.IMAGE_HEIF - IMAGE_GIF -> Value.IMAGE_GIF - IMAGE_BMP -> Value.IMAGE_BMP - IMAGE_TIFF -> Value.IMAGE_TIFF - else -> Value._UNKNOWN - } - - /** - * Returns an enum member corresponding to this class instance's value. - * - * Use the [value] method instead if you're uncertain the value is always known and don't - * want to throw for the unknown case. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value is a not a - * known member. - */ - fun known(): Known = - when (this) { - IMAGE_PNG -> Known.IMAGE_PNG - IMAGE_JPEG -> Known.IMAGE_JPEG - IMAGE_WEBP -> Known.IMAGE_WEBP - IMAGE_HEIC -> Known.IMAGE_HEIC - IMAGE_HEIF -> Known.IMAGE_HEIF - IMAGE_GIF -> Known.IMAGE_GIF - IMAGE_BMP -> Known.IMAGE_BMP - IMAGE_TIFF -> Known.IMAGE_TIFF - else -> throw GeminiNextGenApiInvalidDataException("Unknown MimeType: $value") - } - - /** - * Returns this class instance's primitive wire representation. - * - * This differs from the [toString] method because that method is primarily for debugging - * and generally doesn't throw. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value does not have - * the expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - GeminiNextGenApiInvalidDataException("Value is not a String") - } - - private var validated: Boolean = false - - fun validate(): MimeType = apply { - if (validated) { - return@apply - } - - known() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is MimeType && value == other.value - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - /** The resolution of the media. */ - class Resolution @JsonCreator private constructor(private val value: JsonField) : Enum { - - /** - * Returns this class instance's raw value. - * - * This is usually only useful if this instance was deserialized from data that doesn't - * match any known member, and you want to know that value. For example, if the SDK is on an - * older version than the API, then the API may respond with new members that the SDK is - * unaware of. - */ - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - companion object { - - @JvmField val LOW = of("low") - - @JvmField val MEDIUM = of("medium") - - @JvmField val HIGH = of("high") - - @JvmField val ULTRA_HIGH = of("ultra_high") - - @JvmStatic fun of(value: String) = Resolution(JsonField.of(value)) - } - - /** An enum containing [Resolution]'s known values. */ - enum class Known { - LOW, - MEDIUM, - HIGH, - ULTRA_HIGH, - } - - /** - * An enum containing [Resolution]'s known values, as well as an [_UNKNOWN] member. - * - * An instance of [Resolution] can contain an unknown value in a couple of cases: - * - It was deserialized from data that doesn't match any known member. For example, if the - * SDK is on an older version than the API, then the API may respond with new members that - * the SDK is unaware of. - * - It was constructed with an arbitrary value using the [of] method. - */ - enum class Value { - LOW, - MEDIUM, - HIGH, - ULTRA_HIGH, - /** - * An enum member indicating that [Resolution] was instantiated with an unknown value. - */ - _UNKNOWN, - } - - /** - * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] - * if the class was instantiated with an unknown value. - * - * Use the [known] method instead if you're certain the value is always known or if you want - * to throw for the unknown case. - */ - fun value(): Value = - when (this) { - LOW -> Value.LOW - MEDIUM -> Value.MEDIUM - HIGH -> Value.HIGH - ULTRA_HIGH -> Value.ULTRA_HIGH - else -> Value._UNKNOWN - } - - /** - * Returns an enum member corresponding to this class instance's value. - * - * Use the [value] method instead if you're uncertain the value is always known and don't - * want to throw for the unknown case. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value is a not a - * known member. - */ - fun known(): Known = - when (this) { - LOW -> Known.LOW - MEDIUM -> Known.MEDIUM - HIGH -> Known.HIGH - ULTRA_HIGH -> Known.ULTRA_HIGH - else -> throw GeminiNextGenApiInvalidDataException("Unknown Resolution: $value") - } - - /** - * Returns this class instance's primitive wire representation. - * - * This differs from the [toString] method because that method is primarily for debugging - * and generally doesn't throw. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value does not have - * the expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - GeminiNextGenApiInvalidDataException("Value is not a String") - } - - private var validated: Boolean = false - - fun validate(): Resolution = apply { - if (validated) { - return@apply - } - - known() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Resolution && value == other.value - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is ImageContent && - type == other.type && - data == other.data && - mimeType == other.mimeType && - resolution == other.resolution && - uri == other.uri && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { - Objects.hash(type, data, mimeType, resolution, uri, additionalProperties) - } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "ImageContent{type=$type, data=$data, mimeType=$mimeType, resolution=$resolution, uri=$uri, additionalProperties=$additionalProperties}" -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/ImageResponseFormat.kt b/src/main/java/com/google/genai/interactions/models/interactions/ImageResponseFormat.kt deleted file mode 100644 index 8a95c1eb4d3..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/ImageResponseFormat.kt +++ /dev/null @@ -1,928 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import com.google.genai.interactions.core.Enum -import com.google.genai.interactions.core.ExcludeMissing -import com.google.genai.interactions.core.JsonField -import com.google.genai.interactions.core.JsonMissing -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.util.Collections -import java.util.Objects -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -/** Configuration for image output format. */ -class ImageResponseFormat -@JsonCreator(mode = JsonCreator.Mode.DISABLED) -private constructor( - private val type: JsonValue, - private val aspectRatio: JsonField, - private val delivery: JsonField, - private val imageSize: JsonField, - private val mimeType: JsonField, - private val additionalProperties: MutableMap, -) { - - @JsonCreator - private constructor( - @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), - @JsonProperty("aspect_ratio") - @ExcludeMissing - aspectRatio: JsonField = JsonMissing.of(), - @JsonProperty("delivery") @ExcludeMissing delivery: JsonField = JsonMissing.of(), - @JsonProperty("image_size") - @ExcludeMissing - imageSize: JsonField = JsonMissing.of(), - @JsonProperty("mime_type") @ExcludeMissing mimeType: JsonField = JsonMissing.of(), - ) : this(type, aspectRatio, delivery, imageSize, mimeType, mutableMapOf()) - - /** - * Expected to always return the following: - * ```java - * JsonValue.from("image") - * ``` - * - * However, this method can be useful for debugging and logging (e.g. if the server responded - * with an unexpected value). - */ - @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type - - /** - * The aspect ratio for the image output. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun aspectRatio(): Optional = aspectRatio.getOptional("aspect_ratio") - - /** - * The delivery mode for the image output. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun delivery(): Optional = delivery.getOptional("delivery") - - /** - * The size of the image output. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun imageSize(): Optional = imageSize.getOptional("image_size") - - /** - * The MIME type of the image output. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun mimeType(): Optional = mimeType.getOptional("mime_type") - - /** - * Returns the raw JSON value of [aspectRatio]. - * - * Unlike [aspectRatio], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("aspect_ratio") - @ExcludeMissing - fun _aspectRatio(): JsonField = aspectRatio - - /** - * Returns the raw JSON value of [delivery]. - * - * Unlike [delivery], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("delivery") @ExcludeMissing fun _delivery(): JsonField = delivery - - /** - * Returns the raw JSON value of [imageSize]. - * - * Unlike [imageSize], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("image_size") @ExcludeMissing fun _imageSize(): JsonField = imageSize - - /** - * Returns the raw JSON value of [mimeType]. - * - * Unlike [mimeType], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("mime_type") @ExcludeMissing fun _mimeType(): JsonField = mimeType - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [ImageResponseFormat]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [ImageResponseFormat]. */ - class Builder internal constructor() { - - private var type: JsonValue = JsonValue.from("image") - private var aspectRatio: JsonField = JsonMissing.of() - private var delivery: JsonField = JsonMissing.of() - private var imageSize: JsonField = JsonMissing.of() - private var mimeType: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(imageResponseFormat: ImageResponseFormat) = apply { - type = imageResponseFormat.type - aspectRatio = imageResponseFormat.aspectRatio - delivery = imageResponseFormat.delivery - imageSize = imageResponseFormat.imageSize - mimeType = imageResponseFormat.mimeType - additionalProperties = imageResponseFormat.additionalProperties.toMutableMap() - } - - /** - * Sets the field to an arbitrary JSON value. - * - * It is usually unnecessary to call this method because the field defaults to the - * following: - * ```java - * JsonValue.from("image") - * ``` - * - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun type(type: JsonValue) = apply { this.type = type } - - /** The aspect ratio for the image output. */ - fun aspectRatio(aspectRatio: AspectRatio) = aspectRatio(JsonField.of(aspectRatio)) - - /** - * Sets [Builder.aspectRatio] to an arbitrary JSON value. - * - * You should usually call [Builder.aspectRatio] with a well-typed [AspectRatio] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun aspectRatio(aspectRatio: JsonField) = apply { - this.aspectRatio = aspectRatio - } - - /** The delivery mode for the image output. */ - fun delivery(delivery: Delivery) = delivery(JsonField.of(delivery)) - - /** - * Sets [Builder.delivery] to an arbitrary JSON value. - * - * You should usually call [Builder.delivery] with a well-typed [Delivery] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun delivery(delivery: JsonField) = apply { this.delivery = delivery } - - /** The size of the image output. */ - fun imageSize(imageSize: ImageSize) = imageSize(JsonField.of(imageSize)) - - /** - * Sets [Builder.imageSize] to an arbitrary JSON value. - * - * You should usually call [Builder.imageSize] with a well-typed [ImageSize] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun imageSize(imageSize: JsonField) = apply { this.imageSize = imageSize } - - /** The MIME type of the image output. */ - fun mimeType(mimeType: MimeType) = mimeType(JsonField.of(mimeType)) - - /** - * Sets [Builder.mimeType] to an arbitrary JSON value. - * - * You should usually call [Builder.mimeType] with a well-typed [MimeType] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun mimeType(mimeType: JsonField) = apply { this.mimeType = mimeType } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [ImageResponseFormat]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): ImageResponseFormat = - ImageResponseFormat( - type, - aspectRatio, - delivery, - imageSize, - mimeType, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): ImageResponseFormat = apply { - if (validated) { - return@apply - } - - _type().let { - if (it != JsonValue.from("image")) { - throw GeminiNextGenApiInvalidDataException("'type' is invalid, received $it") - } - } - aspectRatio().ifPresent { it.validate() } - delivery().ifPresent { it.validate() } - imageSize().ifPresent { it.validate() } - mimeType().ifPresent { it.validate() } - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - type.let { if (it == JsonValue.from("image")) 1 else 0 } + - (aspectRatio.asKnown().getOrNull()?.validity() ?: 0) + - (delivery.asKnown().getOrNull()?.validity() ?: 0) + - (imageSize.asKnown().getOrNull()?.validity() ?: 0) + - (mimeType.asKnown().getOrNull()?.validity() ?: 0) - - /** The aspect ratio for the image output. */ - class AspectRatio @JsonCreator private constructor(private val value: JsonField) : - Enum { - - /** - * Returns this class instance's raw value. - * - * This is usually only useful if this instance was deserialized from data that doesn't - * match any known member, and you want to know that value. For example, if the SDK is on an - * older version than the API, then the API may respond with new members that the SDK is - * unaware of. - */ - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - companion object { - - @JvmField val _1_1 = of("1:1") - - @JvmField val _2_3 = of("2:3") - - @JvmField val _3_2 = of("3:2") - - @JvmField val _3_4 = of("3:4") - - @JvmField val _4_3 = of("4:3") - - @JvmField val _4_5 = of("4:5") - - @JvmField val _5_4 = of("5:4") - - @JvmField val _9_16 = of("9:16") - - @JvmField val _16_9 = of("16:9") - - @JvmField val _21_9 = of("21:9") - - @JvmField val _1_8 = of("1:8") - - @JvmField val _8_1 = of("8:1") - - @JvmField val _1_4 = of("1:4") - - @JvmField val _4_1 = of("4:1") - - @JvmStatic fun of(value: String) = AspectRatio(JsonField.of(value)) - } - - /** An enum containing [AspectRatio]'s known values. */ - enum class Known { - _1_1, - _2_3, - _3_2, - _3_4, - _4_3, - _4_5, - _5_4, - _9_16, - _16_9, - _21_9, - _1_8, - _8_1, - _1_4, - _4_1, - } - - /** - * An enum containing [AspectRatio]'s known values, as well as an [_UNKNOWN] member. - * - * An instance of [AspectRatio] can contain an unknown value in a couple of cases: - * - It was deserialized from data that doesn't match any known member. For example, if the - * SDK is on an older version than the API, then the API may respond with new members that - * the SDK is unaware of. - * - It was constructed with an arbitrary value using the [of] method. - */ - enum class Value { - _1_1, - _2_3, - _3_2, - _3_4, - _4_3, - _4_5, - _5_4, - _9_16, - _16_9, - _21_9, - _1_8, - _8_1, - _1_4, - _4_1, - /** - * An enum member indicating that [AspectRatio] was instantiated with an unknown value. - */ - _UNKNOWN, - } - - /** - * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] - * if the class was instantiated with an unknown value. - * - * Use the [known] method instead if you're certain the value is always known or if you want - * to throw for the unknown case. - */ - fun value(): Value = - when (this) { - _1_1 -> Value._1_1 - _2_3 -> Value._2_3 - _3_2 -> Value._3_2 - _3_4 -> Value._3_4 - _4_3 -> Value._4_3 - _4_5 -> Value._4_5 - _5_4 -> Value._5_4 - _9_16 -> Value._9_16 - _16_9 -> Value._16_9 - _21_9 -> Value._21_9 - _1_8 -> Value._1_8 - _8_1 -> Value._8_1 - _1_4 -> Value._1_4 - _4_1 -> Value._4_1 - else -> Value._UNKNOWN - } - - /** - * Returns an enum member corresponding to this class instance's value. - * - * Use the [value] method instead if you're uncertain the value is always known and don't - * want to throw for the unknown case. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value is a not a - * known member. - */ - fun known(): Known = - when (this) { - _1_1 -> Known._1_1 - _2_3 -> Known._2_3 - _3_2 -> Known._3_2 - _3_4 -> Known._3_4 - _4_3 -> Known._4_3 - _4_5 -> Known._4_5 - _5_4 -> Known._5_4 - _9_16 -> Known._9_16 - _16_9 -> Known._16_9 - _21_9 -> Known._21_9 - _1_8 -> Known._1_8 - _8_1 -> Known._8_1 - _1_4 -> Known._1_4 - _4_1 -> Known._4_1 - else -> throw GeminiNextGenApiInvalidDataException("Unknown AspectRatio: $value") - } - - /** - * Returns this class instance's primitive wire representation. - * - * This differs from the [toString] method because that method is primarily for debugging - * and generally doesn't throw. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value does not have - * the expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - GeminiNextGenApiInvalidDataException("Value is not a String") - } - - private var validated: Boolean = false - - fun validate(): AspectRatio = apply { - if (validated) { - return@apply - } - - known() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is AspectRatio && value == other.value - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - /** The delivery mode for the image output. */ - class Delivery @JsonCreator private constructor(private val value: JsonField) : Enum { - - /** - * Returns this class instance's raw value. - * - * This is usually only useful if this instance was deserialized from data that doesn't - * match any known member, and you want to know that value. For example, if the SDK is on an - * older version than the API, then the API may respond with new members that the SDK is - * unaware of. - */ - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - companion object { - - @JvmField val INLINE = of("inline") - - @JvmField val URI = of("uri") - - @JvmStatic fun of(value: String) = Delivery(JsonField.of(value)) - } - - /** An enum containing [Delivery]'s known values. */ - enum class Known { - INLINE, - URI, - } - - /** - * An enum containing [Delivery]'s known values, as well as an [_UNKNOWN] member. - * - * An instance of [Delivery] can contain an unknown value in a couple of cases: - * - It was deserialized from data that doesn't match any known member. For example, if the - * SDK is on an older version than the API, then the API may respond with new members that - * the SDK is unaware of. - * - It was constructed with an arbitrary value using the [of] method. - */ - enum class Value { - INLINE, - URI, - /** An enum member indicating that [Delivery] was instantiated with an unknown value. */ - _UNKNOWN, - } - - /** - * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] - * if the class was instantiated with an unknown value. - * - * Use the [known] method instead if you're certain the value is always known or if you want - * to throw for the unknown case. - */ - fun value(): Value = - when (this) { - INLINE -> Value.INLINE - URI -> Value.URI - else -> Value._UNKNOWN - } - - /** - * Returns an enum member corresponding to this class instance's value. - * - * Use the [value] method instead if you're uncertain the value is always known and don't - * want to throw for the unknown case. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value is a not a - * known member. - */ - fun known(): Known = - when (this) { - INLINE -> Known.INLINE - URI -> Known.URI - else -> throw GeminiNextGenApiInvalidDataException("Unknown Delivery: $value") - } - - /** - * Returns this class instance's primitive wire representation. - * - * This differs from the [toString] method because that method is primarily for debugging - * and generally doesn't throw. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value does not have - * the expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - GeminiNextGenApiInvalidDataException("Value is not a String") - } - - private var validated: Boolean = false - - fun validate(): Delivery = apply { - if (validated) { - return@apply - } - - known() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Delivery && value == other.value - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - /** The size of the image output. */ - class ImageSize @JsonCreator private constructor(private val value: JsonField) : Enum { - - /** - * Returns this class instance's raw value. - * - * This is usually only useful if this instance was deserialized from data that doesn't - * match any known member, and you want to know that value. For example, if the SDK is on an - * older version than the API, then the API may respond with new members that the SDK is - * unaware of. - */ - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - companion object { - - @JvmField val _512 = of("512") - - @JvmField val _1_K = of("1K") - - @JvmField val _2_K = of("2K") - - @JvmField val _4_K = of("4K") - - @JvmStatic fun of(value: String) = ImageSize(JsonField.of(value)) - } - - /** An enum containing [ImageSize]'s known values. */ - enum class Known { - _512, - _1_K, - _2_K, - _4_K, - } - - /** - * An enum containing [ImageSize]'s known values, as well as an [_UNKNOWN] member. - * - * An instance of [ImageSize] can contain an unknown value in a couple of cases: - * - It was deserialized from data that doesn't match any known member. For example, if the - * SDK is on an older version than the API, then the API may respond with new members that - * the SDK is unaware of. - * - It was constructed with an arbitrary value using the [of] method. - */ - enum class Value { - _512, - _1_K, - _2_K, - _4_K, - /** - * An enum member indicating that [ImageSize] was instantiated with an unknown value. - */ - _UNKNOWN, - } - - /** - * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] - * if the class was instantiated with an unknown value. - * - * Use the [known] method instead if you're certain the value is always known or if you want - * to throw for the unknown case. - */ - fun value(): Value = - when (this) { - _512 -> Value._512 - _1_K -> Value._1_K - _2_K -> Value._2_K - _4_K -> Value._4_K - else -> Value._UNKNOWN - } - - /** - * Returns an enum member corresponding to this class instance's value. - * - * Use the [value] method instead if you're uncertain the value is always known and don't - * want to throw for the unknown case. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value is a not a - * known member. - */ - fun known(): Known = - when (this) { - _512 -> Known._512 - _1_K -> Known._1_K - _2_K -> Known._2_K - _4_K -> Known._4_K - else -> throw GeminiNextGenApiInvalidDataException("Unknown ImageSize: $value") - } - - /** - * Returns this class instance's primitive wire representation. - * - * This differs from the [toString] method because that method is primarily for debugging - * and generally doesn't throw. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value does not have - * the expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - GeminiNextGenApiInvalidDataException("Value is not a String") - } - - private var validated: Boolean = false - - fun validate(): ImageSize = apply { - if (validated) { - return@apply - } - - known() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is ImageSize && value == other.value - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - /** The MIME type of the image output. */ - class MimeType @JsonCreator private constructor(private val value: JsonField) : Enum { - - /** - * Returns this class instance's raw value. - * - * This is usually only useful if this instance was deserialized from data that doesn't - * match any known member, and you want to know that value. For example, if the SDK is on an - * older version than the API, then the API may respond with new members that the SDK is - * unaware of. - */ - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - companion object { - - @JvmField val IMAGE_JPEG = of("image/jpeg") - - @JvmStatic fun of(value: String) = MimeType(JsonField.of(value)) - } - - /** An enum containing [MimeType]'s known values. */ - enum class Known { - IMAGE_JPEG - } - - /** - * An enum containing [MimeType]'s known values, as well as an [_UNKNOWN] member. - * - * An instance of [MimeType] can contain an unknown value in a couple of cases: - * - It was deserialized from data that doesn't match any known member. For example, if the - * SDK is on an older version than the API, then the API may respond with new members that - * the SDK is unaware of. - * - It was constructed with an arbitrary value using the [of] method. - */ - enum class Value { - IMAGE_JPEG, - /** An enum member indicating that [MimeType] was instantiated with an unknown value. */ - _UNKNOWN, - } - - /** - * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] - * if the class was instantiated with an unknown value. - * - * Use the [known] method instead if you're certain the value is always known or if you want - * to throw for the unknown case. - */ - fun value(): Value = - when (this) { - IMAGE_JPEG -> Value.IMAGE_JPEG - else -> Value._UNKNOWN - } - - /** - * Returns an enum member corresponding to this class instance's value. - * - * Use the [value] method instead if you're uncertain the value is always known and don't - * want to throw for the unknown case. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value is a not a - * known member. - */ - fun known(): Known = - when (this) { - IMAGE_JPEG -> Known.IMAGE_JPEG - else -> throw GeminiNextGenApiInvalidDataException("Unknown MimeType: $value") - } - - /** - * Returns this class instance's primitive wire representation. - * - * This differs from the [toString] method because that method is primarily for debugging - * and generally doesn't throw. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value does not have - * the expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - GeminiNextGenApiInvalidDataException("Value is not a String") - } - - private var validated: Boolean = false - - fun validate(): MimeType = apply { - if (validated) { - return@apply - } - - known() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is MimeType && value == other.value - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is ImageResponseFormat && - type == other.type && - aspectRatio == other.aspectRatio && - delivery == other.delivery && - imageSize == other.imageSize && - mimeType == other.mimeType && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { - Objects.hash(type, aspectRatio, delivery, imageSize, mimeType, additionalProperties) - } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "ImageResponseFormat{type=$type, aspectRatio=$aspectRatio, delivery=$delivery, imageSize=$imageSize, mimeType=$mimeType, additionalProperties=$additionalProperties}" -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/Interaction.kt b/src/main/java/com/google/genai/interactions/models/interactions/Interaction.kt deleted file mode 100644 index a107dbfeec0..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/Interaction.kt +++ /dev/null @@ -1,3187 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import com.fasterxml.jackson.core.JsonGenerator -import com.fasterxml.jackson.core.ObjectCodec -import com.fasterxml.jackson.databind.JsonNode -import com.fasterxml.jackson.databind.SerializerProvider -import com.fasterxml.jackson.databind.annotation.JsonDeserialize -import com.fasterxml.jackson.databind.annotation.JsonSerialize -import com.fasterxml.jackson.module.kotlin.jacksonTypeRef -import com.google.genai.interactions.core.BaseDeserializer -import com.google.genai.interactions.core.BaseSerializer -import com.google.genai.interactions.core.Enum -import com.google.genai.interactions.core.ExcludeMissing -import com.google.genai.interactions.core.JsonField -import com.google.genai.interactions.core.JsonMissing -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.core.allMaxBy -import com.google.genai.interactions.core.checkKnown -import com.google.genai.interactions.core.checkRequired -import com.google.genai.interactions.core.getOrThrow -import com.google.genai.interactions.core.toImmutable -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.time.OffsetDateTime -import java.util.Collections -import java.util.Objects -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -/** The Interaction resource. */ -class Interaction -@JsonCreator(mode = JsonCreator.Mode.DISABLED) -private constructor( - private val id: JsonField, - private val created: JsonField, - private val status: JsonField, - private val steps: JsonField>, - private val updated: JsonField, - private val agent: JsonField, - private val agentConfig: JsonField, - private val generationConfig: JsonField, - private val input: JsonField, - private val model: JsonField, - private val previousInteractionId: JsonField, - private val responseFormat: JsonField, - private val responseMimeType: JsonField, - private val responseModalities: JsonField>, - private val role: JsonField, - private val serviceTier: JsonField, - private val systemInstruction: JsonField, - private val tools: JsonField>, - private val usage: JsonField, - private val webhookConfig: JsonField, - private val additionalProperties: MutableMap, -) { - - @JsonCreator - private constructor( - @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), - @JsonProperty("created") - @ExcludeMissing - created: JsonField = JsonMissing.of(), - @JsonProperty("status") @ExcludeMissing status: JsonField = JsonMissing.of(), - @JsonProperty("steps") @ExcludeMissing steps: JsonField> = JsonMissing.of(), - @JsonProperty("updated") - @ExcludeMissing - updated: JsonField = JsonMissing.of(), - @JsonProperty("agent") @ExcludeMissing agent: JsonField = JsonMissing.of(), - @JsonProperty("agent_config") - @ExcludeMissing - agentConfig: JsonField = JsonMissing.of(), - @JsonProperty("generation_config") - @ExcludeMissing - generationConfig: JsonField = JsonMissing.of(), - @JsonProperty("input") @ExcludeMissing input: JsonField = JsonMissing.of(), - @JsonProperty("model") @ExcludeMissing model: JsonField = JsonMissing.of(), - @JsonProperty("previous_interaction_id") - @ExcludeMissing - previousInteractionId: JsonField = JsonMissing.of(), - @JsonProperty("response_format") - @ExcludeMissing - responseFormat: JsonField = JsonMissing.of(), - @JsonProperty("response_mime_type") - @ExcludeMissing - responseMimeType: JsonField = JsonMissing.of(), - @JsonProperty("response_modalities") - @ExcludeMissing - responseModalities: JsonField> = JsonMissing.of(), - @JsonProperty("role") @ExcludeMissing role: JsonField = JsonMissing.of(), - @JsonProperty("service_tier") - @ExcludeMissing - serviceTier: JsonField = JsonMissing.of(), - @JsonProperty("system_instruction") - @ExcludeMissing - systemInstruction: JsonField = JsonMissing.of(), - @JsonProperty("tools") @ExcludeMissing tools: JsonField> = JsonMissing.of(), - @JsonProperty("usage") @ExcludeMissing usage: JsonField = JsonMissing.of(), - @JsonProperty("webhook_config") - @ExcludeMissing - webhookConfig: JsonField = JsonMissing.of(), - ) : this( - id, - created, - status, - steps, - updated, - agent, - agentConfig, - generationConfig, - input, - model, - previousInteractionId, - responseFormat, - responseMimeType, - responseModalities, - role, - serviceTier, - systemInstruction, - tools, - usage, - webhookConfig, - mutableMapOf(), - ) - - /** - * Required. Output only. A unique identifier for the interaction completion. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). - */ - fun id(): String = id.getRequired("id") - - /** - * Required. Output only. The time at which the response was created in ISO 8601 format - * (YYYY-MM-DDThh:mm:ssZ). - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). - */ - fun created(): OffsetDateTime = created.getRequired("created") - - /** - * Required. Output only. The status of the interaction. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). - */ - fun status(): Status = status.getRequired("status") - - /** - * Required. Output only. The steps that make up the interaction. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). - */ - fun steps(): List = steps.getRequired("steps") - - /** - * Required. Output only. The time at which the response was last updated in ISO 8601 format - * (YYYY-MM-DDThh:mm:ssZ). - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). - */ - fun updated(): OffsetDateTime = updated.getRequired("updated") - - /** - * The name of the `Agent` used for generating the interaction. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun agent(): Optional = agent.getOptional("agent") - - /** - * Configuration parameters for the agent interaction. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun agentConfig(): Optional = agentConfig.getOptional("agent_config") - - /** - * Input only. Configuration parameters for the model interaction. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun generationConfig(): Optional = - generationConfig.getOptional("generation_config") - - /** - * The input for the interaction. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun input(): Optional = input.getOptional("input") - - /** - * The model that will complete your prompt.\n\nSee - * [models](https://ai.google.dev/gemini-api/docs/models) for additional details. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun model(): Optional = model.getOptional("model") - - /** - * The ID of the previous interaction, if any. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun previousInteractionId(): Optional = - previousInteractionId.getOptional("previous_interaction_id") - - /** - * Enforces that the generated response is a JSON object that complies with the JSON schema - * specified in this field. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun responseFormat(): Optional = responseFormat.getOptional("response_format") - - /** - * The mime type of the response. This is required if response_format is set. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun responseMimeType(): Optional = responseMimeType.getOptional("response_mime_type") - - /** - * The requested modalities of the response (TEXT, IMAGE, AUDIO). - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun responseModalities(): Optional> = - responseModalities.getOptional("response_modalities") - - /** - * Output only. The role of the interaction. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - @Deprecated("deprecated") fun role(): Optional = role.getOptional("role") - - /** - * The service tier for the interaction. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun serviceTier(): Optional = serviceTier.getOptional("service_tier") - - /** - * System instruction for the interaction. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun systemInstruction(): Optional = systemInstruction.getOptional("system_instruction") - - /** - * A list of tool declarations the model may call during interaction. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun tools(): Optional> = tools.getOptional("tools") - - /** - * Output only. Statistics on the interaction request's token usage. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun usage(): Optional = usage.getOptional("usage") - - /** - * Optional. Webhook configuration for receiving notifications when the interaction completes. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun webhookConfig(): Optional = webhookConfig.getOptional("webhook_config") - - /** - * Returns the raw JSON value of [id]. - * - * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id - - /** - * Returns the raw JSON value of [created]. - * - * Unlike [created], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("created") @ExcludeMissing fun _created(): JsonField = created - - /** - * Returns the raw JSON value of [status]. - * - * Unlike [status], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("status") @ExcludeMissing fun _status(): JsonField = status - - /** - * Returns the raw JSON value of [steps]. - * - * Unlike [steps], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("steps") @ExcludeMissing fun _steps(): JsonField> = steps - - /** - * Returns the raw JSON value of [updated]. - * - * Unlike [updated], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("updated") @ExcludeMissing fun _updated(): JsonField = updated - - /** - * Returns the raw JSON value of [agent]. - * - * Unlike [agent], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("agent") @ExcludeMissing fun _agent(): JsonField = agent - - /** - * Returns the raw JSON value of [agentConfig]. - * - * Unlike [agentConfig], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("agent_config") - @ExcludeMissing - fun _agentConfig(): JsonField = agentConfig - - /** - * Returns the raw JSON value of [generationConfig]. - * - * Unlike [generationConfig], this method doesn't throw if the JSON field has an unexpected - * type. - */ - @JsonProperty("generation_config") - @ExcludeMissing - fun _generationConfig(): JsonField = generationConfig - - /** - * Returns the raw JSON value of [input]. - * - * Unlike [input], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("input") @ExcludeMissing fun _input(): JsonField = input - - /** - * Returns the raw JSON value of [model]. - * - * Unlike [model], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("model") @ExcludeMissing fun _model(): JsonField = model - - /** - * Returns the raw JSON value of [previousInteractionId]. - * - * Unlike [previousInteractionId], this method doesn't throw if the JSON field has an unexpected - * type. - */ - @JsonProperty("previous_interaction_id") - @ExcludeMissing - fun _previousInteractionId(): JsonField = previousInteractionId - - /** - * Returns the raw JSON value of [responseFormat]. - * - * Unlike [responseFormat], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("response_format") - @ExcludeMissing - fun _responseFormat(): JsonField = responseFormat - - /** - * Returns the raw JSON value of [responseMimeType]. - * - * Unlike [responseMimeType], this method doesn't throw if the JSON field has an unexpected - * type. - */ - @JsonProperty("response_mime_type") - @ExcludeMissing - fun _responseMimeType(): JsonField = responseMimeType - - /** - * Returns the raw JSON value of [responseModalities]. - * - * Unlike [responseModalities], this method doesn't throw if the JSON field has an unexpected - * type. - */ - @JsonProperty("response_modalities") - @ExcludeMissing - fun _responseModalities(): JsonField> = responseModalities - - /** - * Returns the raw JSON value of [role]. - * - * Unlike [role], this method doesn't throw if the JSON field has an unexpected type. - */ - @Deprecated("deprecated") - @JsonProperty("role") - @ExcludeMissing - fun _role(): JsonField = role - - /** - * Returns the raw JSON value of [serviceTier]. - * - * Unlike [serviceTier], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("service_tier") - @ExcludeMissing - fun _serviceTier(): JsonField = serviceTier - - /** - * Returns the raw JSON value of [systemInstruction]. - * - * Unlike [systemInstruction], this method doesn't throw if the JSON field has an unexpected - * type. - */ - @JsonProperty("system_instruction") - @ExcludeMissing - fun _systemInstruction(): JsonField = systemInstruction - - /** - * Returns the raw JSON value of [tools]. - * - * Unlike [tools], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("tools") @ExcludeMissing fun _tools(): JsonField> = tools - - /** - * Returns the raw JSON value of [usage]. - * - * Unlike [usage], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("usage") @ExcludeMissing fun _usage(): JsonField = usage - - /** - * Returns the raw JSON value of [webhookConfig]. - * - * Unlike [webhookConfig], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("webhook_config") - @ExcludeMissing - fun _webhookConfig(): JsonField = webhookConfig - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [Interaction]. - * - * The following fields are required: - * ```java - * .id() - * .created() - * .status() - * .steps() - * .updated() - * ``` - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Interaction]. */ - class Builder internal constructor() { - - private var id: JsonField? = null - private var created: JsonField? = null - private var status: JsonField? = null - private var steps: JsonField>? = null - private var updated: JsonField? = null - private var agent: JsonField = JsonMissing.of() - private var agentConfig: JsonField = JsonMissing.of() - private var generationConfig: JsonField = JsonMissing.of() - private var input: JsonField = JsonMissing.of() - private var model: JsonField = JsonMissing.of() - private var previousInteractionId: JsonField = JsonMissing.of() - private var responseFormat: JsonField = JsonMissing.of() - private var responseMimeType: JsonField = JsonMissing.of() - private var responseModalities: JsonField>? = null - private var role: JsonField = JsonMissing.of() - private var serviceTier: JsonField = JsonMissing.of() - private var systemInstruction: JsonField = JsonMissing.of() - private var tools: JsonField>? = null - private var usage: JsonField = JsonMissing.of() - private var webhookConfig: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(interaction: Interaction) = apply { - id = interaction.id - created = interaction.created - status = interaction.status - steps = interaction.steps.map { it.toMutableList() } - updated = interaction.updated - agent = interaction.agent - agentConfig = interaction.agentConfig - generationConfig = interaction.generationConfig - input = interaction.input - model = interaction.model - previousInteractionId = interaction.previousInteractionId - responseFormat = interaction.responseFormat - responseMimeType = interaction.responseMimeType - responseModalities = interaction.responseModalities.map { it.toMutableList() } - role = interaction.role - serviceTier = interaction.serviceTier - systemInstruction = interaction.systemInstruction - tools = interaction.tools.map { it.toMutableList() } - usage = interaction.usage - webhookConfig = interaction.webhookConfig - additionalProperties = interaction.additionalProperties.toMutableMap() - } - - /** Required. Output only. A unique identifier for the interaction completion. */ - fun id(id: String) = id(JsonField.of(id)) - - /** - * Sets [Builder.id] to an arbitrary JSON value. - * - * You should usually call [Builder.id] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun id(id: JsonField) = apply { this.id = id } - - /** - * Required. Output only. The time at which the response was created in ISO 8601 format - * (YYYY-MM-DDThh:mm:ssZ). - */ - fun created(created: OffsetDateTime) = created(JsonField.of(created)) - - /** - * Sets [Builder.created] to an arbitrary JSON value. - * - * You should usually call [Builder.created] with a well-typed [OffsetDateTime] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun created(created: JsonField) = apply { this.created = created } - - /** Required. Output only. The status of the interaction. */ - fun status(status: Status) = status(JsonField.of(status)) - - /** - * Sets [Builder.status] to an arbitrary JSON value. - * - * You should usually call [Builder.status] with a well-typed [Status] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun status(status: JsonField) = apply { this.status = status } - - /** Required. Output only. The steps that make up the interaction. */ - fun steps(steps: List) = steps(JsonField.of(steps)) - - /** - * Sets [Builder.steps] to an arbitrary JSON value. - * - * You should usually call [Builder.steps] with a well-typed `List` value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun steps(steps: JsonField>) = apply { - this.steps = steps.map { it.toMutableList() } - } - - /** - * Adds a single [Step] to [steps]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addStep(step: Step) = apply { - steps = - (steps ?: JsonField.of(mutableListOf())).also { checkKnown("steps", it).add(step) } - } - - /** Alias for calling [addStep] with `Step.ofUserInput(userInput)`. */ - fun addStep(userInput: UserInputStep) = addStep(Step.ofUserInput(userInput)) - - /** Alias for calling [addStep] with `Step.ofModelOutput(modelOutput)`. */ - fun addStep(modelOutput: ModelOutputStep) = addStep(Step.ofModelOutput(modelOutput)) - - /** Alias for calling [addStep] with `Step.ofThought(thought)`. */ - fun addStep(thought: ThoughtStep) = addStep(Step.ofThought(thought)) - - /** Alias for calling [addStep] with `Step.ofFunctionCall(functionCall)`. */ - fun addStep(functionCall: FunctionCallStep) = addStep(Step.ofFunctionCall(functionCall)) - - /** Alias for calling [addStep] with `Step.ofCodeExecutionCall(codeExecutionCall)`. */ - fun addStep(codeExecutionCall: CodeExecutionCallStep) = - addStep(Step.ofCodeExecutionCall(codeExecutionCall)) - - /** Alias for calling [addStep] with `Step.ofUrlContextCall(urlContextCall)`. */ - fun addStep(urlContextCall: UrlContextCallStep) = - addStep(Step.ofUrlContextCall(urlContextCall)) - - /** Alias for calling [addStep] with `Step.ofMcpServerToolCall(mcpServerToolCall)`. */ - fun addStep(mcpServerToolCall: McpServerToolCallStep) = - addStep(Step.ofMcpServerToolCall(mcpServerToolCall)) - - /** Alias for calling [addStep] with `Step.ofGoogleSearchCall(googleSearchCall)`. */ - fun addStep(googleSearchCall: GoogleSearchCallStep) = - addStep(Step.ofGoogleSearchCall(googleSearchCall)) - - /** Alias for calling [addStep] with `Step.ofFileSearchCall(fileSearchCall)`. */ - fun addStep(fileSearchCall: FileSearchCallStep) = - addStep(Step.ofFileSearchCall(fileSearchCall)) - - /** - * Alias for calling [addStep] with the following: - * ```java - * FileSearchCallStep.builder() - * .id(id) - * .build() - * ``` - */ - fun addFileSearchCallStep(id: String) = addStep(FileSearchCallStep.builder().id(id).build()) - - /** Alias for calling [addStep] with `Step.ofGoogleMapsCall(googleMapsCall)`. */ - fun addStep(googleMapsCall: GoogleMapsCallStep) = - addStep(Step.ofGoogleMapsCall(googleMapsCall)) - - /** - * Alias for calling [addStep] with the following: - * ```java - * GoogleMapsCallStep.builder() - * .id(id) - * .build() - * ``` - */ - fun addGoogleMapsCallStep(id: String) = addStep(GoogleMapsCallStep.builder().id(id).build()) - - /** Alias for calling [addStep] with `Step.ofFunctionResult(functionResult)`. */ - fun addStep(functionResult: FunctionResultStep) = - addStep(Step.ofFunctionResult(functionResult)) - - /** Alias for calling [addStep] with `Step.ofCodeExecutionResult(codeExecutionResult)`. */ - fun addStep(codeExecutionResult: CodeExecutionResultStep) = - addStep(Step.ofCodeExecutionResult(codeExecutionResult)) - - /** Alias for calling [addStep] with `Step.ofUrlContextResult(urlContextResult)`. */ - fun addStep(urlContextResult: UrlContextResultStep) = - addStep(Step.ofUrlContextResult(urlContextResult)) - - /** Alias for calling [addStep] with `Step.ofGoogleSearchResult(googleSearchResult)`. */ - fun addStep(googleSearchResult: GoogleSearchResultStep) = - addStep(Step.ofGoogleSearchResult(googleSearchResult)) - - /** Alias for calling [addStep] with `Step.ofMcpServerToolResult(mcpServerToolResult)`. */ - fun addStep(mcpServerToolResult: McpServerToolResultStep) = - addStep(Step.ofMcpServerToolResult(mcpServerToolResult)) - - /** Alias for calling [addStep] with `Step.ofFileSearchResult(fileSearchResult)`. */ - fun addStep(fileSearchResult: FileSearchResultStep) = - addStep(Step.ofFileSearchResult(fileSearchResult)) - - /** - * Alias for calling [addStep] with the following: - * ```java - * FileSearchResultStep.builder() - * .callId(callId) - * .build() - * ``` - */ - fun addFileSearchResultStep(callId: String) = - addStep(FileSearchResultStep.builder().callId(callId).build()) - - /** Alias for calling [addStep] with `Step.ofGoogleMapsResult(googleMapsResult)`. */ - fun addStep(googleMapsResult: GoogleMapsResultStep) = - addStep(Step.ofGoogleMapsResult(googleMapsResult)) - - /** - * Required. Output only. The time at which the response was last updated in ISO 8601 format - * (YYYY-MM-DDThh:mm:ssZ). - */ - fun updated(updated: OffsetDateTime) = updated(JsonField.of(updated)) - - /** - * Sets [Builder.updated] to an arbitrary JSON value. - * - * You should usually call [Builder.updated] with a well-typed [OffsetDateTime] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun updated(updated: JsonField) = apply { this.updated = updated } - - /** The name of the `Agent` used for generating the interaction. */ - fun agent(agent: Agent) = agent(JsonField.of(agent)) - - /** - * Sets [Builder.agent] to an arbitrary JSON value. - * - * You should usually call [Builder.agent] with a well-typed [Agent] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun agent(agent: JsonField) = apply { this.agent = agent } - - /** - * Sets [agent] to an arbitrary [String]. - * - * You should usually call [agent] with a well-typed [Agent] constant instead. This method - * is primarily for setting the field to an undocumented or not yet supported value. - */ - fun agent(value: String) = agent(Agent.of(value)) - - /** Configuration parameters for the agent interaction. */ - fun agentConfig(agentConfig: AgentConfig) = agentConfig(JsonField.of(agentConfig)) - - /** - * Sets [Builder.agentConfig] to an arbitrary JSON value. - * - * You should usually call [Builder.agentConfig] with a well-typed [AgentConfig] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun agentConfig(agentConfig: JsonField) = apply { - this.agentConfig = agentConfig - } - - /** Alias for calling [agentConfig] with `AgentConfig.ofDynamic(dynamic)`. */ - fun agentConfig(dynamic: DynamicAgentConfig) = agentConfig(AgentConfig.ofDynamic(dynamic)) - - /** Alias for calling [agentConfig] with `AgentConfig.ofDeepResearch(deepResearch)`. */ - fun agentConfig(deepResearch: DeepResearchAgentConfig) = - agentConfig(AgentConfig.ofDeepResearch(deepResearch)) - - /** Input only. Configuration parameters for the model interaction. */ - fun generationConfig(generationConfig: GenerationConfig) = - generationConfig(JsonField.of(generationConfig)) - - /** - * Sets [Builder.generationConfig] to an arbitrary JSON value. - * - * You should usually call [Builder.generationConfig] with a well-typed [GenerationConfig] - * value instead. This method is primarily for setting the field to an undocumented or not - * yet supported value. - */ - fun generationConfig(generationConfig: JsonField) = apply { - this.generationConfig = generationConfig - } - - /** The input for the interaction. */ - fun input(input: Input) = input(JsonField.of(input)) - - /** - * Sets [Builder.input] to an arbitrary JSON value. - * - * You should usually call [Builder.input] with a well-typed [Input] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun input(input: JsonField) = apply { this.input = input } - - /** Alias for calling [input] with `Input.ofString(string)`. */ - fun input(string: String) = input(Input.ofString(string)) - - /** Alias for calling [input] with `Input.ofStepList(stepList)`. */ - fun inputOfStepList(stepList: List) = input(Input.ofStepList(stepList)) - - /** Alias for calling [input] with `Input.ofContentList(contentList)`. */ - fun inputOfContentList(contentList: List) = input(Input.ofContentList(contentList)) - - /** Alias for calling [input] with `Input.ofTextContent(textContent)`. */ - fun input(textContent: TextContent) = input(Input.ofTextContent(textContent)) - - /** Alias for calling [input] with `Input.ofImageContent(imageContent)`. */ - fun input(imageContent: ImageContent) = input(Input.ofImageContent(imageContent)) - - /** Alias for calling [input] with `Input.ofAudioContent(audioContent)`. */ - fun input(audioContent: AudioContent) = input(Input.ofAudioContent(audioContent)) - - /** Alias for calling [input] with `Input.ofDocumentContent(documentContent)`. */ - fun input(documentContent: DocumentContent) = - input(Input.ofDocumentContent(documentContent)) - - /** Alias for calling [input] with `Input.ofVideoContent(videoContent)`. */ - fun input(videoContent: VideoContent) = input(Input.ofVideoContent(videoContent)) - - /** - * The model that will complete your prompt.\n\nSee - * [models](https://ai.google.dev/gemini-api/docs/models) for additional details. - */ - fun model(model: Model) = model(JsonField.of(model)) - - /** - * Sets [Builder.model] to an arbitrary JSON value. - * - * You should usually call [Builder.model] with a well-typed [Model] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun model(model: JsonField) = apply { this.model = model } - - /** - * Sets [model] to an arbitrary [String]. - * - * You should usually call [model] with a well-typed [Model] constant instead. This method - * is primarily for setting the field to an undocumented or not yet supported value. - */ - fun model(value: String) = model(Model.of(value)) - - /** The ID of the previous interaction, if any. */ - fun previousInteractionId(previousInteractionId: String) = - previousInteractionId(JsonField.of(previousInteractionId)) - - /** - * Sets [Builder.previousInteractionId] to an arbitrary JSON value. - * - * You should usually call [Builder.previousInteractionId] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun previousInteractionId(previousInteractionId: JsonField) = apply { - this.previousInteractionId = previousInteractionId - } - - /** - * Enforces that the generated response is a JSON object that complies with the JSON schema - * specified in this field. - */ - fun responseFormat(responseFormat: ResponseFormat) = - responseFormat(JsonField.of(responseFormat)) - - /** - * Sets [Builder.responseFormat] to an arbitrary JSON value. - * - * You should usually call [Builder.responseFormat] with a well-typed [ResponseFormat] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun responseFormat(responseFormat: JsonField) = apply { - this.responseFormat = responseFormat - } - - /** Alias for calling [responseFormat] with `ResponseFormat.ofList(list)`. */ - fun responseFormatOfList(list: List) = - responseFormat(ResponseFormat.ofList(list)) - - /** Alias for calling [responseFormat] with `ResponseFormat.ofAudio(audio)`. */ - fun responseFormat(audio: AudioResponseFormat) = - responseFormat(ResponseFormat.ofAudio(audio)) - - /** Alias for calling [responseFormat] with `ResponseFormat.ofText(text)`. */ - fun responseFormat(text: TextResponseFormat) = responseFormat(ResponseFormat.ofText(text)) - - /** Alias for calling [responseFormat] with `ResponseFormat.ofImage(image)`. */ - fun responseFormat(image: ImageResponseFormat) = - responseFormat(ResponseFormat.ofImage(image)) - - /** Alias for calling [responseFormat] with `ResponseFormat.ofJsonValue(jsonValue)`. */ - fun responseFormat(jsonValue: JsonValue) = - responseFormat(ResponseFormat.ofJsonValue(jsonValue)) - - /** The mime type of the response. This is required if response_format is set. */ - fun responseMimeType(responseMimeType: String) = - responseMimeType(JsonField.of(responseMimeType)) - - /** - * Sets [Builder.responseMimeType] to an arbitrary JSON value. - * - * You should usually call [Builder.responseMimeType] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun responseMimeType(responseMimeType: JsonField) = apply { - this.responseMimeType = responseMimeType - } - - /** The requested modalities of the response (TEXT, IMAGE, AUDIO). */ - fun responseModalities(responseModalities: List) = - responseModalities(JsonField.of(responseModalities)) - - /** - * Sets [Builder.responseModalities] to an arbitrary JSON value. - * - * You should usually call [Builder.responseModalities] with a well-typed - * `List` value instead. This method is primarily for setting the field to - * an undocumented or not yet supported value. - */ - fun responseModalities(responseModalities: JsonField>) = apply { - this.responseModalities = responseModalities.map { it.toMutableList() } - } - - /** - * Adds a single [ResponseModality] to [responseModalities]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addResponseModality(responseModality: ResponseModality) = apply { - responseModalities = - (responseModalities ?: JsonField.of(mutableListOf())).also { - checkKnown("responseModalities", it).add(responseModality) - } - } - - /** Output only. The role of the interaction. */ - @Deprecated("deprecated") fun role(role: String) = role(JsonField.of(role)) - - /** - * Sets [Builder.role] to an arbitrary JSON value. - * - * You should usually call [Builder.role] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - @Deprecated("deprecated") fun role(role: JsonField) = apply { this.role = role } - - /** The service tier for the interaction. */ - fun serviceTier(serviceTier: ServiceTier) = serviceTier(JsonField.of(serviceTier)) - - /** - * Sets [Builder.serviceTier] to an arbitrary JSON value. - * - * You should usually call [Builder.serviceTier] with a well-typed [ServiceTier] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun serviceTier(serviceTier: JsonField) = apply { - this.serviceTier = serviceTier - } - - /** System instruction for the interaction. */ - fun systemInstruction(systemInstruction: String) = - systemInstruction(JsonField.of(systemInstruction)) - - /** - * Sets [Builder.systemInstruction] to an arbitrary JSON value. - * - * You should usually call [Builder.systemInstruction] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun systemInstruction(systemInstruction: JsonField) = apply { - this.systemInstruction = systemInstruction - } - - /** A list of tool declarations the model may call during interaction. */ - fun tools(tools: List) = tools(JsonField.of(tools)) - - /** - * Sets [Builder.tools] to an arbitrary JSON value. - * - * You should usually call [Builder.tools] with a well-typed `List` value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun tools(tools: JsonField>) = apply { - this.tools = tools.map { it.toMutableList() } - } - - /** - * Adds a single [Tool] to [tools]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addTool(tool: Tool) = apply { - tools = - (tools ?: JsonField.of(mutableListOf())).also { checkKnown("tools", it).add(tool) } - } - - /** Alias for calling [addTool] with `Tool.ofFunction(function)`. */ - fun addTool(function: Function) = addTool(Tool.ofFunction(function)) - - /** Alias for calling [addTool] with `Tool.ofCodeExecution()`. */ - fun addToolCodeExecution() = addTool(Tool.ofCodeExecution()) - - /** Alias for calling [addTool] with `Tool.ofUrlContext()`. */ - fun addToolUrlContext() = addTool(Tool.ofUrlContext()) - - /** Alias for calling [addTool] with `Tool.ofComputerUse(computerUse)`. */ - fun addTool(computerUse: Tool.ComputerUse) = addTool(Tool.ofComputerUse(computerUse)) - - /** Alias for calling [addTool] with `Tool.ofMcpServer(mcpServer)`. */ - fun addTool(mcpServer: Tool.McpServer) = addTool(Tool.ofMcpServer(mcpServer)) - - /** Alias for calling [addTool] with `Tool.ofGoogleSearch(googleSearch)`. */ - fun addTool(googleSearch: Tool.GoogleSearch) = addTool(Tool.ofGoogleSearch(googleSearch)) - - /** Alias for calling [addTool] with `Tool.ofFileSearch(fileSearch)`. */ - fun addTool(fileSearch: Tool.FileSearch) = addTool(Tool.ofFileSearch(fileSearch)) - - /** Alias for calling [addTool] with `Tool.ofGoogleMaps(googleMaps)`. */ - fun addTool(googleMaps: Tool.GoogleMaps) = addTool(Tool.ofGoogleMaps(googleMaps)) - - /** Alias for calling [addTool] with `Tool.ofRetrieval(retrieval)`. */ - fun addTool(retrieval: Tool.Retrieval) = addTool(Tool.ofRetrieval(retrieval)) - - /** Output only. Statistics on the interaction request's token usage. */ - fun usage(usage: Usage) = usage(JsonField.of(usage)) - - /** - * Sets [Builder.usage] to an arbitrary JSON value. - * - * You should usually call [Builder.usage] with a well-typed [Usage] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun usage(usage: JsonField) = apply { this.usage = usage } - - /** - * Optional. Webhook configuration for receiving notifications when the interaction - * completes. - */ - fun webhookConfig(webhookConfig: WebhookConfig) = webhookConfig(JsonField.of(webhookConfig)) - - /** - * Sets [Builder.webhookConfig] to an arbitrary JSON value. - * - * You should usually call [Builder.webhookConfig] with a well-typed [WebhookConfig] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun webhookConfig(webhookConfig: JsonField) = apply { - this.webhookConfig = webhookConfig - } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [Interaction]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .id() - * .created() - * .status() - * .steps() - * .updated() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): Interaction = - Interaction( - checkRequired("id", id), - checkRequired("created", created), - checkRequired("status", status), - checkRequired("steps", steps).map { it.toImmutable() }, - checkRequired("updated", updated), - agent, - agentConfig, - generationConfig, - input, - model, - previousInteractionId, - responseFormat, - responseMimeType, - (responseModalities ?: JsonMissing.of()).map { it.toImmutable() }, - role, - serviceTier, - systemInstruction, - (tools ?: JsonMissing.of()).map { it.toImmutable() }, - usage, - webhookConfig, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): Interaction = apply { - if (validated) { - return@apply - } - - id() - created() - status().validate() - steps().forEach { it.validate() } - updated() - agent() - agentConfig().ifPresent { it.validate() } - generationConfig().ifPresent { it.validate() } - input().ifPresent { it.validate() } - model() - previousInteractionId() - responseFormat().ifPresent { it.validate() } - responseMimeType() - responseModalities().ifPresent { it.forEach { it.validate() } } - role() - serviceTier().ifPresent { it.validate() } - systemInstruction() - tools().ifPresent { it.forEach { it.validate() } } - usage().ifPresent { it.validate() } - webhookConfig().ifPresent { it.validate() } - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - (if (id.asKnown().isPresent) 1 else 0) + - (if (created.asKnown().isPresent) 1 else 0) + - (status.asKnown().getOrNull()?.validity() ?: 0) + - (steps.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + - (if (updated.asKnown().isPresent) 1 else 0) + - (if (agent.asKnown().isPresent) 1 else 0) + - (agentConfig.asKnown().getOrNull()?.validity() ?: 0) + - (generationConfig.asKnown().getOrNull()?.validity() ?: 0) + - (input.asKnown().getOrNull()?.validity() ?: 0) + - (if (model.asKnown().isPresent) 1 else 0) + - (if (previousInteractionId.asKnown().isPresent) 1 else 0) + - (responseFormat.asKnown().getOrNull()?.validity() ?: 0) + - (if (responseMimeType.asKnown().isPresent) 1 else 0) + - (responseModalities.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + - (if (role.asKnown().isPresent) 1 else 0) + - (serviceTier.asKnown().getOrNull()?.validity() ?: 0) + - (if (systemInstruction.asKnown().isPresent) 1 else 0) + - (tools.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + - (usage.asKnown().getOrNull()?.validity() ?: 0) + - (webhookConfig.asKnown().getOrNull()?.validity() ?: 0) - - /** Required. Output only. The status of the interaction. */ - class Status @JsonCreator private constructor(private val value: JsonField) : Enum { - - /** - * Returns this class instance's raw value. - * - * This is usually only useful if this instance was deserialized from data that doesn't - * match any known member, and you want to know that value. For example, if the SDK is on an - * older version than the API, then the API may respond with new members that the SDK is - * unaware of. - */ - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - companion object { - - @JvmField val IN_PROGRESS = of("in_progress") - - @JvmField val REQUIRES_ACTION = of("requires_action") - - @JvmField val COMPLETED = of("completed") - - @JvmField val FAILED = of("failed") - - @JvmField val CANCELLED = of("cancelled") - - @JvmField val INCOMPLETE = of("incomplete") - - @JvmStatic fun of(value: String) = Status(JsonField.of(value)) - } - - /** An enum containing [Status]'s known values. */ - enum class Known { - IN_PROGRESS, - REQUIRES_ACTION, - COMPLETED, - FAILED, - CANCELLED, - INCOMPLETE, - } - - /** - * An enum containing [Status]'s known values, as well as an [_UNKNOWN] member. - * - * An instance of [Status] can contain an unknown value in a couple of cases: - * - It was deserialized from data that doesn't match any known member. For example, if the - * SDK is on an older version than the API, then the API may respond with new members that - * the SDK is unaware of. - * - It was constructed with an arbitrary value using the [of] method. - */ - enum class Value { - IN_PROGRESS, - REQUIRES_ACTION, - COMPLETED, - FAILED, - CANCELLED, - INCOMPLETE, - /** An enum member indicating that [Status] was instantiated with an unknown value. */ - _UNKNOWN, - } - - /** - * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] - * if the class was instantiated with an unknown value. - * - * Use the [known] method instead if you're certain the value is always known or if you want - * to throw for the unknown case. - */ - fun value(): Value = - when (this) { - IN_PROGRESS -> Value.IN_PROGRESS - REQUIRES_ACTION -> Value.REQUIRES_ACTION - COMPLETED -> Value.COMPLETED - FAILED -> Value.FAILED - CANCELLED -> Value.CANCELLED - INCOMPLETE -> Value.INCOMPLETE - else -> Value._UNKNOWN - } - - /** - * Returns an enum member corresponding to this class instance's value. - * - * Use the [value] method instead if you're uncertain the value is always known and don't - * want to throw for the unknown case. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value is a not a - * known member. - */ - fun known(): Known = - when (this) { - IN_PROGRESS -> Known.IN_PROGRESS - REQUIRES_ACTION -> Known.REQUIRES_ACTION - COMPLETED -> Known.COMPLETED - FAILED -> Known.FAILED - CANCELLED -> Known.CANCELLED - INCOMPLETE -> Known.INCOMPLETE - else -> throw GeminiNextGenApiInvalidDataException("Unknown Status: $value") - } - - /** - * Returns this class instance's primitive wire representation. - * - * This differs from the [toString] method because that method is primarily for debugging - * and generally doesn't throw. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value does not have - * the expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - GeminiNextGenApiInvalidDataException("Value is not a String") - } - - private var validated: Boolean = false - - fun validate(): Status = apply { - if (validated) { - return@apply - } - - known() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Status && value == other.value - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - /** The name of the `Agent` used for generating the interaction. */ - class Agent @JsonCreator private constructor(private val value: JsonField) : Enum { - - /** - * Returns this class instance's raw value. - * - * This is usually only useful if this instance was deserialized from data that doesn't - * match any known member, and you want to know that value. For example, if the SDK is on an - * older version than the API, then the API may respond with new members that the SDK is - * unaware of. - */ - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - companion object { - - /** Gemini Deep Research Agent */ - @JvmField - val DEEP_RESEARCH_PRO_PREVIEW_12_2025 = of("deep-research-pro-preview-12-2025") - - /** Gemini Deep Research Agent */ - @JvmField val DEEP_RESEARCH_PREVIEW_04_2026 = of("deep-research-preview-04-2026") - - /** Gemini Deep Research Max Agent */ - @JvmField - val DEEP_RESEARCH_MAX_PREVIEW_04_2026 = of("deep-research-max-preview-04-2026") - - @JvmStatic fun of(value: String) = Agent(JsonField.of(value)) - } - - /** An enum containing [Agent]'s known values. */ - enum class Known { - /** Gemini Deep Research Agent */ - DEEP_RESEARCH_PRO_PREVIEW_12_2025, - /** Gemini Deep Research Agent */ - DEEP_RESEARCH_PREVIEW_04_2026, - /** Gemini Deep Research Max Agent */ - DEEP_RESEARCH_MAX_PREVIEW_04_2026, - } - - /** - * An enum containing [Agent]'s known values, as well as an [_UNKNOWN] member. - * - * An instance of [Agent] can contain an unknown value in a couple of cases: - * - It was deserialized from data that doesn't match any known member. For example, if the - * SDK is on an older version than the API, then the API may respond with new members that - * the SDK is unaware of. - * - It was constructed with an arbitrary value using the [of] method. - */ - enum class Value { - /** Gemini Deep Research Agent */ - DEEP_RESEARCH_PRO_PREVIEW_12_2025, - /** Gemini Deep Research Agent */ - DEEP_RESEARCH_PREVIEW_04_2026, - /** Gemini Deep Research Max Agent */ - DEEP_RESEARCH_MAX_PREVIEW_04_2026, - /** An enum member indicating that [Agent] was instantiated with an unknown value. */ - _UNKNOWN, - } - - /** - * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] - * if the class was instantiated with an unknown value. - * - * Use the [known] method instead if you're certain the value is always known or if you want - * to throw for the unknown case. - */ - fun value(): Value = - when (this) { - DEEP_RESEARCH_PRO_PREVIEW_12_2025 -> Value.DEEP_RESEARCH_PRO_PREVIEW_12_2025 - DEEP_RESEARCH_PREVIEW_04_2026 -> Value.DEEP_RESEARCH_PREVIEW_04_2026 - DEEP_RESEARCH_MAX_PREVIEW_04_2026 -> Value.DEEP_RESEARCH_MAX_PREVIEW_04_2026 - else -> Value._UNKNOWN - } - - /** - * Returns an enum member corresponding to this class instance's value. - * - * Use the [value] method instead if you're uncertain the value is always known and don't - * want to throw for the unknown case. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value is a not a - * known member. - */ - fun known(): Known = - when (this) { - DEEP_RESEARCH_PRO_PREVIEW_12_2025 -> Known.DEEP_RESEARCH_PRO_PREVIEW_12_2025 - DEEP_RESEARCH_PREVIEW_04_2026 -> Known.DEEP_RESEARCH_PREVIEW_04_2026 - DEEP_RESEARCH_MAX_PREVIEW_04_2026 -> Known.DEEP_RESEARCH_MAX_PREVIEW_04_2026 - else -> throw GeminiNextGenApiInvalidDataException("Unknown Agent: $value") - } - - /** - * Returns this class instance's primitive wire representation. - * - * This differs from the [toString] method because that method is primarily for debugging - * and generally doesn't throw. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value does not have - * the expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - GeminiNextGenApiInvalidDataException("Value is not a String") - } - - private var validated: Boolean = false - - fun validate(): Agent = apply { - if (validated) { - return@apply - } - - known() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Agent && value == other.value - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - /** Configuration parameters for the agent interaction. */ - @JsonDeserialize(using = AgentConfig.Deserializer::class) - @JsonSerialize(using = AgentConfig.Serializer::class) - class AgentConfig - private constructor( - private val dynamic: DynamicAgentConfig? = null, - private val deepResearch: DeepResearchAgentConfig? = null, - private val _json: JsonValue? = null, - ) { - - /** Configuration for dynamic agents. */ - fun dynamic(): Optional = Optional.ofNullable(dynamic) - - /** Configuration for the Deep Research agent. */ - fun deepResearch(): Optional = Optional.ofNullable(deepResearch) - - fun isDynamic(): Boolean = dynamic != null - - fun isDeepResearch(): Boolean = deepResearch != null - - /** Configuration for dynamic agents. */ - fun asDynamic(): DynamicAgentConfig = dynamic.getOrThrow("dynamic") - - /** Configuration for the Deep Research agent. */ - fun asDeepResearch(): DeepResearchAgentConfig = deepResearch.getOrThrow("deepResearch") - - fun _json(): Optional = Optional.ofNullable(_json) - - fun accept(visitor: Visitor): T = - when { - dynamic != null -> visitor.visitDynamic(dynamic) - deepResearch != null -> visitor.visitDeepResearch(deepResearch) - else -> visitor.unknown(_json) - } - - private var validated: Boolean = false - - fun validate(): AgentConfig = apply { - if (validated) { - return@apply - } - - accept( - object : Visitor { - override fun visitDynamic(dynamic: DynamicAgentConfig) { - dynamic.validate() - } - - override fun visitDeepResearch(deepResearch: DeepResearchAgentConfig) { - deepResearch.validate() - } - } - ) - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - accept( - object : Visitor { - override fun visitDynamic(dynamic: DynamicAgentConfig) = dynamic.validity() - - override fun visitDeepResearch(deepResearch: DeepResearchAgentConfig) = - deepResearch.validity() - - override fun unknown(json: JsonValue?) = 0 - } - ) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is AgentConfig && - dynamic == other.dynamic && - deepResearch == other.deepResearch - } - - override fun hashCode(): Int = Objects.hash(dynamic, deepResearch) - - override fun toString(): String = - when { - dynamic != null -> "AgentConfig{dynamic=$dynamic}" - deepResearch != null -> "AgentConfig{deepResearch=$deepResearch}" - _json != null -> "AgentConfig{_unknown=$_json}" - else -> throw IllegalStateException("Invalid AgentConfig") - } - - companion object { - - /** Configuration for dynamic agents. */ - @JvmStatic fun ofDynamic(dynamic: DynamicAgentConfig) = AgentConfig(dynamic = dynamic) - - /** Configuration for the Deep Research agent. */ - @JvmStatic - fun ofDeepResearch(deepResearch: DeepResearchAgentConfig) = - AgentConfig(deepResearch = deepResearch) - } - - /** - * An interface that defines how to map each variant of [AgentConfig] to a value of type - * [T]. - */ - interface Visitor { - - /** Configuration for dynamic agents. */ - fun visitDynamic(dynamic: DynamicAgentConfig): T - - /** Configuration for the Deep Research agent. */ - fun visitDeepResearch(deepResearch: DeepResearchAgentConfig): T - - /** - * Maps an unknown variant of [AgentConfig] to a value of type [T]. - * - * An instance of [AgentConfig] can contain an unknown variant if it was deserialized - * from data that doesn't match any known variant. For example, if the SDK is on an - * older version than the API, then the API may respond with new variants that the SDK - * is unaware of. - * - * @throws GeminiNextGenApiInvalidDataException in the default implementation. - */ - fun unknown(json: JsonValue?): T { - throw GeminiNextGenApiInvalidDataException("Unknown AgentConfig: $json") - } - } - - internal class Deserializer : BaseDeserializer(AgentConfig::class) { - - override fun ObjectCodec.deserialize(node: JsonNode): AgentConfig { - val json = JsonValue.fromJsonNode(node) - val type = json.asObject().getOrNull()?.get("type")?.asString()?.getOrNull() - - when (type) { - "dynamic" -> { - return tryDeserialize(node, jacksonTypeRef())?.let { - AgentConfig(dynamic = it, _json = json) - } ?: AgentConfig(_json = json) - } - "deep-research" -> { - return tryDeserialize(node, jacksonTypeRef()) - ?.let { AgentConfig(deepResearch = it, _json = json) } - ?: AgentConfig(_json = json) - } - } - - return AgentConfig(_json = json) - } - } - - internal class Serializer : BaseSerializer(AgentConfig::class) { - - override fun serialize( - value: AgentConfig, - generator: JsonGenerator, - provider: SerializerProvider, - ) { - when { - value.dynamic != null -> generator.writeObject(value.dynamic) - value.deepResearch != null -> generator.writeObject(value.deepResearch) - value._json != null -> generator.writeObject(value._json) - else -> throw IllegalStateException("Invalid AgentConfig") - } - } - } - } - - /** The input for the interaction. */ - @JsonDeserialize(using = Input.Deserializer::class) - @JsonSerialize(using = Input.Serializer::class) - class Input - private constructor( - private val string: String? = null, - private val stepList: List? = null, - private val contentList: List? = null, - private val textContent: TextContent? = null, - private val imageContent: ImageContent? = null, - private val audioContent: AudioContent? = null, - private val documentContent: DocumentContent? = null, - private val videoContent: VideoContent? = null, - private val _json: JsonValue? = null, - ) { - - fun string(): Optional = Optional.ofNullable(string) - - fun stepList(): Optional> = Optional.ofNullable(stepList) - - fun contentList(): Optional> = Optional.ofNullable(contentList) - - /** A text content block. */ - fun textContent(): Optional = Optional.ofNullable(textContent) - - /** An image content block. */ - fun imageContent(): Optional = Optional.ofNullable(imageContent) - - /** An audio content block. */ - fun audioContent(): Optional = Optional.ofNullable(audioContent) - - /** A document content block. */ - fun documentContent(): Optional = Optional.ofNullable(documentContent) - - /** A video content block. */ - fun videoContent(): Optional = Optional.ofNullable(videoContent) - - fun isString(): Boolean = string != null - - fun isStepList(): Boolean = stepList != null - - fun isContentList(): Boolean = contentList != null - - fun isTextContent(): Boolean = textContent != null - - fun isImageContent(): Boolean = imageContent != null - - fun isAudioContent(): Boolean = audioContent != null - - fun isDocumentContent(): Boolean = documentContent != null - - fun isVideoContent(): Boolean = videoContent != null - - fun asString(): String = string.getOrThrow("string") - - fun asStepList(): List = stepList.getOrThrow("stepList") - - fun asContentList(): List = contentList.getOrThrow("contentList") - - /** A text content block. */ - fun asTextContent(): TextContent = textContent.getOrThrow("textContent") - - /** An image content block. */ - fun asImageContent(): ImageContent = imageContent.getOrThrow("imageContent") - - /** An audio content block. */ - fun asAudioContent(): AudioContent = audioContent.getOrThrow("audioContent") - - /** A document content block. */ - fun asDocumentContent(): DocumentContent = documentContent.getOrThrow("documentContent") - - /** A video content block. */ - fun asVideoContent(): VideoContent = videoContent.getOrThrow("videoContent") - - fun _json(): Optional = Optional.ofNullable(_json) - - fun accept(visitor: Visitor): T = - when { - string != null -> visitor.visitString(string) - stepList != null -> visitor.visitStepList(stepList) - contentList != null -> visitor.visitContentList(contentList) - textContent != null -> visitor.visitTextContent(textContent) - imageContent != null -> visitor.visitImageContent(imageContent) - audioContent != null -> visitor.visitAudioContent(audioContent) - documentContent != null -> visitor.visitDocumentContent(documentContent) - videoContent != null -> visitor.visitVideoContent(videoContent) - else -> visitor.unknown(_json) - } - - private var validated: Boolean = false - - fun validate(): Input = apply { - if (validated) { - return@apply - } - - accept( - object : Visitor { - override fun visitString(string: String) {} - - override fun visitStepList(stepList: List) { - stepList.forEach { it.validate() } - } - - override fun visitContentList(contentList: List) { - contentList.forEach { it.validate() } - } - - override fun visitTextContent(textContent: TextContent) { - textContent.validate() - } - - override fun visitImageContent(imageContent: ImageContent) { - imageContent.validate() - } - - override fun visitAudioContent(audioContent: AudioContent) { - audioContent.validate() - } - - override fun visitDocumentContent(documentContent: DocumentContent) { - documentContent.validate() - } - - override fun visitVideoContent(videoContent: VideoContent) { - videoContent.validate() - } - } - ) - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - accept( - object : Visitor { - override fun visitString(string: String) = 1 - - override fun visitStepList(stepList: List) = - stepList.sumOf { it.validity().toInt() } - - override fun visitContentList(contentList: List) = - contentList.sumOf { it.validity().toInt() } - - override fun visitTextContent(textContent: TextContent) = textContent.validity() - - override fun visitImageContent(imageContent: ImageContent) = - imageContent.validity() - - override fun visitAudioContent(audioContent: AudioContent) = - audioContent.validity() - - override fun visitDocumentContent(documentContent: DocumentContent) = - documentContent.validity() - - override fun visitVideoContent(videoContent: VideoContent) = - videoContent.validity() - - override fun unknown(json: JsonValue?) = 0 - } - ) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Input && - string == other.string && - stepList == other.stepList && - contentList == other.contentList && - textContent == other.textContent && - imageContent == other.imageContent && - audioContent == other.audioContent && - documentContent == other.documentContent && - videoContent == other.videoContent - } - - override fun hashCode(): Int = - Objects.hash( - string, - stepList, - contentList, - textContent, - imageContent, - audioContent, - documentContent, - videoContent, - ) - - override fun toString(): String = - when { - string != null -> "Input{string=$string}" - stepList != null -> "Input{stepList=$stepList}" - contentList != null -> "Input{contentList=$contentList}" - textContent != null -> "Input{textContent=$textContent}" - imageContent != null -> "Input{imageContent=$imageContent}" - audioContent != null -> "Input{audioContent=$audioContent}" - documentContent != null -> "Input{documentContent=$documentContent}" - videoContent != null -> "Input{videoContent=$videoContent}" - _json != null -> "Input{_unknown=$_json}" - else -> throw IllegalStateException("Invalid Input") - } - - companion object { - - @JvmStatic fun ofString(string: String) = Input(string = string) - - @JvmStatic - fun ofStepList(stepList: List) = Input(stepList = stepList.toImmutable()) - - @JvmStatic - fun ofContentList(contentList: List) = - Input(contentList = contentList.toImmutable()) - - /** A text content block. */ - @JvmStatic - fun ofTextContent(textContent: TextContent) = Input(textContent = textContent) - - /** An image content block. */ - @JvmStatic - fun ofImageContent(imageContent: ImageContent) = Input(imageContent = imageContent) - - /** An audio content block. */ - @JvmStatic - fun ofAudioContent(audioContent: AudioContent) = Input(audioContent = audioContent) - - /** A document content block. */ - @JvmStatic - fun ofDocumentContent(documentContent: DocumentContent) = - Input(documentContent = documentContent) - - /** A video content block. */ - @JvmStatic - fun ofVideoContent(videoContent: VideoContent) = Input(videoContent = videoContent) - } - - /** An interface that defines how to map each variant of [Input] to a value of type [T]. */ - interface Visitor { - - fun visitString(string: String): T - - fun visitStepList(stepList: List): T - - fun visitContentList(contentList: List): T - - /** A text content block. */ - fun visitTextContent(textContent: TextContent): T - - /** An image content block. */ - fun visitImageContent(imageContent: ImageContent): T - - /** An audio content block. */ - fun visitAudioContent(audioContent: AudioContent): T - - /** A document content block. */ - fun visitDocumentContent(documentContent: DocumentContent): T - - /** A video content block. */ - fun visitVideoContent(videoContent: VideoContent): T - - /** - * Maps an unknown variant of [Input] to a value of type [T]. - * - * An instance of [Input] can contain an unknown variant if it was deserialized from - * data that doesn't match any known variant. For example, if the SDK is on an older - * version than the API, then the API may respond with new variants that the SDK is - * unaware of. - * - * @throws GeminiNextGenApiInvalidDataException in the default implementation. - */ - fun unknown(json: JsonValue?): T { - throw GeminiNextGenApiInvalidDataException("Unknown Input: $json") - } - } - - internal class Deserializer : BaseDeserializer(Input::class) { - - override fun ObjectCodec.deserialize(node: JsonNode): Input { - val json = JsonValue.fromJsonNode(node) - - val bestMatches = - sequenceOf( - tryDeserialize(node, jacksonTypeRef())?.let { - Input(textContent = it, _json = json) - }, - tryDeserialize(node, jacksonTypeRef())?.let { - Input(imageContent = it, _json = json) - }, - tryDeserialize(node, jacksonTypeRef())?.let { - Input(audioContent = it, _json = json) - }, - tryDeserialize(node, jacksonTypeRef())?.let { - Input(documentContent = it, _json = json) - }, - tryDeserialize(node, jacksonTypeRef())?.let { - Input(videoContent = it, _json = json) - }, - tryDeserialize(node, jacksonTypeRef())?.let { - Input(string = it, _json = json) - }, - tryDeserialize(node, jacksonTypeRef>())?.let { - Input(stepList = it, _json = json) - }, - tryDeserialize(node, jacksonTypeRef>())?.let { - Input(contentList = it, _json = json) - }, - ) - .filterNotNull() - .allMaxBy { it.validity() } - .toList() - return when (bestMatches.size) { - // This can happen if what we're deserializing is completely incompatible with - // all the possible variants (e.g. deserializing from boolean). - 0 -> Input(_json = json) - 1 -> bestMatches.single() - // If there's more than one match with the highest validity, then use the first - // completely valid match, or simply the first match if none are completely - // valid. - else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() - } - } - } - - internal class Serializer : BaseSerializer(Input::class) { - - override fun serialize( - value: Input, - generator: JsonGenerator, - provider: SerializerProvider, - ) { - when { - value.string != null -> generator.writeObject(value.string) - value.stepList != null -> generator.writeObject(value.stepList) - value.contentList != null -> generator.writeObject(value.contentList) - value.textContent != null -> generator.writeObject(value.textContent) - value.imageContent != null -> generator.writeObject(value.imageContent) - value.audioContent != null -> generator.writeObject(value.audioContent) - value.documentContent != null -> generator.writeObject(value.documentContent) - value.videoContent != null -> generator.writeObject(value.videoContent) - value._json != null -> generator.writeObject(value._json) - else -> throw IllegalStateException("Invalid Input") - } - } - } - } - - /** - * Enforces that the generated response is a JSON object that complies with the JSON schema - * specified in this field. - */ - @JsonDeserialize(using = ResponseFormat.Deserializer::class) - @JsonSerialize(using = ResponseFormat.Serializer::class) - class ResponseFormat - private constructor( - private val list: List? = null, - private val audio: AudioResponseFormat? = null, - private val text: TextResponseFormat? = null, - private val image: ImageResponseFormat? = null, - private val jsonValue: JsonValue? = null, - private val _json: JsonValue? = null, - ) { - - fun list(): Optional> = Optional.ofNullable(list) - - /** Configuration for audio output format. */ - fun audio(): Optional = Optional.ofNullable(audio) - - /** Configuration for text output format. */ - fun text(): Optional = Optional.ofNullable(text) - - /** Configuration for image output format. */ - fun image(): Optional = Optional.ofNullable(image) - - fun jsonValue(): Optional = Optional.ofNullable(jsonValue) - - fun isList(): Boolean = list != null - - fun isAudio(): Boolean = audio != null - - fun isText(): Boolean = text != null - - fun isImage(): Boolean = image != null - - fun isJsonValue(): Boolean = jsonValue != null - - fun asList(): List = list.getOrThrow("list") - - /** Configuration for audio output format. */ - fun asAudio(): AudioResponseFormat = audio.getOrThrow("audio") - - /** Configuration for text output format. */ - fun asText(): TextResponseFormat = text.getOrThrow("text") - - /** Configuration for image output format. */ - fun asImage(): ImageResponseFormat = image.getOrThrow("image") - - fun asJsonValue(): JsonValue = jsonValue.getOrThrow("jsonValue") - - fun _json(): Optional = Optional.ofNullable(_json) - - fun accept(visitor: Visitor): T = - when { - list != null -> visitor.visitList(list) - audio != null -> visitor.visitAudio(audio) - text != null -> visitor.visitText(text) - image != null -> visitor.visitImage(image) - jsonValue != null -> visitor.visitJsonValue(jsonValue) - else -> visitor.unknown(_json) - } - - private var validated: Boolean = false - - fun validate(): ResponseFormat = apply { - if (validated) { - return@apply - } - - accept( - object : Visitor { - override fun visitList(list: List) { - list.forEach { it.validate() } - } - - override fun visitAudio(audio: AudioResponseFormat) { - audio.validate() - } - - override fun visitText(text: TextResponseFormat) { - text.validate() - } - - override fun visitImage(image: ImageResponseFormat) { - image.validate() - } - - override fun visitJsonValue(jsonValue: JsonValue) {} - } - ) - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - accept( - object : Visitor { - override fun visitList(list: List) = - list.sumOf { it.validity().toInt() } - - override fun visitAudio(audio: AudioResponseFormat) = audio.validity() - - override fun visitText(text: TextResponseFormat) = text.validity() - - override fun visitImage(image: ImageResponseFormat) = image.validity() - - override fun visitJsonValue(jsonValue: JsonValue) = 1 - - override fun unknown(json: JsonValue?) = 0 - } - ) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is ResponseFormat && - list == other.list && - audio == other.audio && - text == other.text && - image == other.image && - jsonValue == other.jsonValue - } - - override fun hashCode(): Int = Objects.hash(list, audio, text, image, jsonValue) - - override fun toString(): String = - when { - list != null -> "ResponseFormat{list=$list}" - audio != null -> "ResponseFormat{audio=$audio}" - text != null -> "ResponseFormat{text=$text}" - image != null -> "ResponseFormat{image=$image}" - jsonValue != null -> "ResponseFormat{jsonValue=$jsonValue}" - _json != null -> "ResponseFormat{_unknown=$_json}" - else -> throw IllegalStateException("Invalid ResponseFormat") - } - - companion object { - - @JvmStatic - fun ofList(list: List) = ResponseFormat(list = list.toImmutable()) - - /** Configuration for audio output format. */ - @JvmStatic fun ofAudio(audio: AudioResponseFormat) = ResponseFormat(audio = audio) - - /** Configuration for text output format. */ - @JvmStatic fun ofText(text: TextResponseFormat) = ResponseFormat(text = text) - - /** Configuration for image output format. */ - @JvmStatic fun ofImage(image: ImageResponseFormat) = ResponseFormat(image = image) - - @JvmStatic fun ofJsonValue(jsonValue: JsonValue) = ResponseFormat(jsonValue = jsonValue) - } - - /** - * An interface that defines how to map each variant of [ResponseFormat] to a value of type - * [T]. - */ - interface Visitor { - - fun visitList(list: List): T - - /** Configuration for audio output format. */ - fun visitAudio(audio: AudioResponseFormat): T - - /** Configuration for text output format. */ - fun visitText(text: TextResponseFormat): T - - /** Configuration for image output format. */ - fun visitImage(image: ImageResponseFormat): T - - fun visitJsonValue(jsonValue: JsonValue): T - - /** - * Maps an unknown variant of [ResponseFormat] to a value of type [T]. - * - * An instance of [ResponseFormat] can contain an unknown variant if it was deserialized - * from data that doesn't match any known variant. For example, if the SDK is on an - * older version than the API, then the API may respond with new variants that the SDK - * is unaware of. - * - * @throws GeminiNextGenApiInvalidDataException in the default implementation. - */ - fun unknown(json: JsonValue?): T { - throw GeminiNextGenApiInvalidDataException("Unknown ResponseFormat: $json") - } - } - - internal class Deserializer : BaseDeserializer(ResponseFormat::class) { - - override fun ObjectCodec.deserialize(node: JsonNode): ResponseFormat { - val json = JsonValue.fromJsonNode(node) - - val bestMatches = - sequenceOf( - tryDeserialize(node, jacksonTypeRef())?.let { - ResponseFormat(audio = it, _json = json) - }, - tryDeserialize(node, jacksonTypeRef())?.let { - ResponseFormat(text = it, _json = json) - }, - tryDeserialize(node, jacksonTypeRef())?.let { - ResponseFormat(image = it, _json = json) - }, - tryDeserialize(node, jacksonTypeRef>())?.let { - ResponseFormat(list = it, _json = json) - }, - tryDeserialize(node, jacksonTypeRef())?.let { - ResponseFormat(jsonValue = it, _json = json) - }, - ) - .filterNotNull() - .allMaxBy { it.validity() } - .toList() - return when (bestMatches.size) { - // This can happen if what we're deserializing is completely incompatible with - // all the possible variants. - 0 -> ResponseFormat(_json = json) - 1 -> bestMatches.single() - // If there's more than one match with the highest validity, then use the first - // completely valid match, or simply the first match if none are completely - // valid. - else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() - } - } - } - - internal class Serializer : BaseSerializer(ResponseFormat::class) { - - override fun serialize( - value: ResponseFormat, - generator: JsonGenerator, - provider: SerializerProvider, - ) { - when { - value.list != null -> generator.writeObject(value.list) - value.audio != null -> generator.writeObject(value.audio) - value.text != null -> generator.writeObject(value.text) - value.image != null -> generator.writeObject(value.image) - value.jsonValue != null -> generator.writeObject(value.jsonValue) - value._json != null -> generator.writeObject(value._json) - else -> throw IllegalStateException("Invalid ResponseFormat") - } - } - } - - /** Configuration for audio output format. */ - @JsonDeserialize(using = InnerResponseFormat.Deserializer::class) - @JsonSerialize(using = InnerResponseFormat.Serializer::class) - class InnerResponseFormat - private constructor( - private val audio: AudioResponseFormat? = null, - private val text: TextResponseFormat? = null, - private val image: ImageResponseFormat? = null, - private val jsonValue: JsonValue? = null, - private val _json: JsonValue? = null, - ) { - - /** Configuration for audio output format. */ - fun audio(): Optional = Optional.ofNullable(audio) - - /** Configuration for text output format. */ - fun text(): Optional = Optional.ofNullable(text) - - /** Configuration for image output format. */ - fun image(): Optional = Optional.ofNullable(image) - - fun jsonValue(): Optional = Optional.ofNullable(jsonValue) - - fun isAudio(): Boolean = audio != null - - fun isText(): Boolean = text != null - - fun isImage(): Boolean = image != null - - fun isJsonValue(): Boolean = jsonValue != null - - /** Configuration for audio output format. */ - fun asAudio(): AudioResponseFormat = audio.getOrThrow("audio") - - /** Configuration for text output format. */ - fun asText(): TextResponseFormat = text.getOrThrow("text") - - /** Configuration for image output format. */ - fun asImage(): ImageResponseFormat = image.getOrThrow("image") - - fun asJsonValue(): JsonValue = jsonValue.getOrThrow("jsonValue") - - fun _json(): Optional = Optional.ofNullable(_json) - - fun accept(visitor: Visitor): T = - when { - audio != null -> visitor.visitAudio(audio) - text != null -> visitor.visitText(text) - image != null -> visitor.visitImage(image) - jsonValue != null -> visitor.visitJsonValue(jsonValue) - else -> visitor.unknown(_json) - } - - private var validated: Boolean = false - - fun validate(): InnerResponseFormat = apply { - if (validated) { - return@apply - } - - accept( - object : Visitor { - override fun visitAudio(audio: AudioResponseFormat) { - audio.validate() - } - - override fun visitText(text: TextResponseFormat) { - text.validate() - } - - override fun visitImage(image: ImageResponseFormat) { - image.validate() - } - - override fun visitJsonValue(jsonValue: JsonValue) {} - } - ) - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - accept( - object : Visitor { - override fun visitAudio(audio: AudioResponseFormat) = audio.validity() - - override fun visitText(text: TextResponseFormat) = text.validity() - - override fun visitImage(image: ImageResponseFormat) = image.validity() - - override fun visitJsonValue(jsonValue: JsonValue) = 1 - - override fun unknown(json: JsonValue?) = 0 - } - ) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is InnerResponseFormat && - audio == other.audio && - text == other.text && - image == other.image && - jsonValue == other.jsonValue - } - - override fun hashCode(): Int = Objects.hash(audio, text, image, jsonValue) - - override fun toString(): String = - when { - audio != null -> "InnerResponseFormat{audio=$audio}" - text != null -> "InnerResponseFormat{text=$text}" - image != null -> "InnerResponseFormat{image=$image}" - jsonValue != null -> "InnerResponseFormat{jsonValue=$jsonValue}" - _json != null -> "InnerResponseFormat{_unknown=$_json}" - else -> throw IllegalStateException("Invalid InnerResponseFormat") - } - - companion object { - - /** Configuration for audio output format. */ - @JvmStatic - fun ofAudio(audio: AudioResponseFormat) = InnerResponseFormat(audio = audio) - - /** Configuration for text output format. */ - @JvmStatic fun ofText(text: TextResponseFormat) = InnerResponseFormat(text = text) - - /** Configuration for image output format. */ - @JvmStatic - fun ofImage(image: ImageResponseFormat) = InnerResponseFormat(image = image) - - @JvmStatic - fun ofJsonValue(jsonValue: JsonValue) = InnerResponseFormat(jsonValue = jsonValue) - } - - /** - * An interface that defines how to map each variant of [InnerResponseFormat] to a value - * of type [T]. - */ - interface Visitor { - - /** Configuration for audio output format. */ - fun visitAudio(audio: AudioResponseFormat): T - - /** Configuration for text output format. */ - fun visitText(text: TextResponseFormat): T - - /** Configuration for image output format. */ - fun visitImage(image: ImageResponseFormat): T - - fun visitJsonValue(jsonValue: JsonValue): T - - /** - * Maps an unknown variant of [InnerResponseFormat] to a value of type [T]. - * - * An instance of [InnerResponseFormat] can contain an unknown variant if it was - * deserialized from data that doesn't match any known variant. For example, if the - * SDK is on an older version than the API, then the API may respond with new - * variants that the SDK is unaware of. - * - * @throws GeminiNextGenApiInvalidDataException in the default implementation. - */ - fun unknown(json: JsonValue?): T { - throw GeminiNextGenApiInvalidDataException("Unknown InnerResponseFormat: $json") - } - } - - internal class Deserializer : - BaseDeserializer(InnerResponseFormat::class) { - - override fun ObjectCodec.deserialize(node: JsonNode): InnerResponseFormat { - val json = JsonValue.fromJsonNode(node) - - val bestMatches = - sequenceOf( - tryDeserialize(node, jacksonTypeRef())?.let { - InnerResponseFormat(audio = it, _json = json) - }, - tryDeserialize(node, jacksonTypeRef())?.let { - InnerResponseFormat(text = it, _json = json) - }, - tryDeserialize(node, jacksonTypeRef())?.let { - InnerResponseFormat(image = it, _json = json) - }, - tryDeserialize(node, jacksonTypeRef())?.let { - InnerResponseFormat(jsonValue = it, _json = json) - }, - ) - .filterNotNull() - .allMaxBy { it.validity() } - .toList() - return when (bestMatches.size) { - // This can happen if what we're deserializing is completely incompatible - // with all the possible variants. - 0 -> InnerResponseFormat(_json = json) - 1 -> bestMatches.single() - // If there's more than one match with the highest validity, then use the - // first completely valid match, or simply the first match if none are - // completely valid. - else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() - } - } - } - - internal class Serializer : - BaseSerializer(InnerResponseFormat::class) { - - override fun serialize( - value: InnerResponseFormat, - generator: JsonGenerator, - provider: SerializerProvider, - ) { - when { - value.audio != null -> generator.writeObject(value.audio) - value.text != null -> generator.writeObject(value.text) - value.image != null -> generator.writeObject(value.image) - value.jsonValue != null -> generator.writeObject(value.jsonValue) - value._json != null -> generator.writeObject(value._json) - else -> throw IllegalStateException("Invalid InnerResponseFormat") - } - } - } - } - } - - class ResponseModality @JsonCreator private constructor(private val value: JsonField) : - Enum { - - /** - * Returns this class instance's raw value. - * - * This is usually only useful if this instance was deserialized from data that doesn't - * match any known member, and you want to know that value. For example, if the SDK is on an - * older version than the API, then the API may respond with new members that the SDK is - * unaware of. - */ - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - companion object { - - @JvmField val TEXT = of("text") - - @JvmField val IMAGE = of("image") - - @JvmField val AUDIO = of("audio") - - @JvmField val VIDEO = of("video") - - @JvmField val DOCUMENT = of("document") - - @JvmStatic fun of(value: String) = ResponseModality(JsonField.of(value)) - } - - /** An enum containing [ResponseModality]'s known values. */ - enum class Known { - TEXT, - IMAGE, - AUDIO, - VIDEO, - DOCUMENT, - } - - /** - * An enum containing [ResponseModality]'s known values, as well as an [_UNKNOWN] member. - * - * An instance of [ResponseModality] can contain an unknown value in a couple of cases: - * - It was deserialized from data that doesn't match any known member. For example, if the - * SDK is on an older version than the API, then the API may respond with new members that - * the SDK is unaware of. - * - It was constructed with an arbitrary value using the [of] method. - */ - enum class Value { - TEXT, - IMAGE, - AUDIO, - VIDEO, - DOCUMENT, - /** - * An enum member indicating that [ResponseModality] was instantiated with an unknown - * value. - */ - _UNKNOWN, - } - - /** - * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] - * if the class was instantiated with an unknown value. - * - * Use the [known] method instead if you're certain the value is always known or if you want - * to throw for the unknown case. - */ - fun value(): Value = - when (this) { - TEXT -> Value.TEXT - IMAGE -> Value.IMAGE - AUDIO -> Value.AUDIO - VIDEO -> Value.VIDEO - DOCUMENT -> Value.DOCUMENT - else -> Value._UNKNOWN - } - - /** - * Returns an enum member corresponding to this class instance's value. - * - * Use the [value] method instead if you're uncertain the value is always known and don't - * want to throw for the unknown case. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value is a not a - * known member. - */ - fun known(): Known = - when (this) { - TEXT -> Known.TEXT - IMAGE -> Known.IMAGE - AUDIO -> Known.AUDIO - VIDEO -> Known.VIDEO - DOCUMENT -> Known.DOCUMENT - else -> - throw GeminiNextGenApiInvalidDataException("Unknown ResponseModality: $value") - } - - /** - * Returns this class instance's primitive wire representation. - * - * This differs from the [toString] method because that method is primarily for debugging - * and generally doesn't throw. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value does not have - * the expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - GeminiNextGenApiInvalidDataException("Value is not a String") - } - - private var validated: Boolean = false - - fun validate(): ResponseModality = apply { - if (validated) { - return@apply - } - - known() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is ResponseModality && value == other.value - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - /** The service tier for the interaction. */ - class ServiceTier @JsonCreator private constructor(private val value: JsonField) : - Enum { - - /** - * Returns this class instance's raw value. - * - * This is usually only useful if this instance was deserialized from data that doesn't - * match any known member, and you want to know that value. For example, if the SDK is on an - * older version than the API, then the API may respond with new members that the SDK is - * unaware of. - */ - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - companion object { - - @JvmField val FLEX = of("flex") - - @JvmField val STANDARD = of("standard") - - @JvmField val PRIORITY = of("priority") - - @JvmStatic fun of(value: String) = ServiceTier(JsonField.of(value)) - } - - /** An enum containing [ServiceTier]'s known values. */ - enum class Known { - FLEX, - STANDARD, - PRIORITY, - } - - /** - * An enum containing [ServiceTier]'s known values, as well as an [_UNKNOWN] member. - * - * An instance of [ServiceTier] can contain an unknown value in a couple of cases: - * - It was deserialized from data that doesn't match any known member. For example, if the - * SDK is on an older version than the API, then the API may respond with new members that - * the SDK is unaware of. - * - It was constructed with an arbitrary value using the [of] method. - */ - enum class Value { - FLEX, - STANDARD, - PRIORITY, - /** - * An enum member indicating that [ServiceTier] was instantiated with an unknown value. - */ - _UNKNOWN, - } - - /** - * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] - * if the class was instantiated with an unknown value. - * - * Use the [known] method instead if you're certain the value is always known or if you want - * to throw for the unknown case. - */ - fun value(): Value = - when (this) { - FLEX -> Value.FLEX - STANDARD -> Value.STANDARD - PRIORITY -> Value.PRIORITY - else -> Value._UNKNOWN - } - - /** - * Returns an enum member corresponding to this class instance's value. - * - * Use the [value] method instead if you're uncertain the value is always known and don't - * want to throw for the unknown case. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value is a not a - * known member. - */ - fun known(): Known = - when (this) { - FLEX -> Known.FLEX - STANDARD -> Known.STANDARD - PRIORITY -> Known.PRIORITY - else -> throw GeminiNextGenApiInvalidDataException("Unknown ServiceTier: $value") - } - - /** - * Returns this class instance's primitive wire representation. - * - * This differs from the [toString] method because that method is primarily for debugging - * and generally doesn't throw. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value does not have - * the expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - GeminiNextGenApiInvalidDataException("Value is not a String") - } - - private var validated: Boolean = false - - fun validate(): ServiceTier = apply { - if (validated) { - return@apply - } - - known() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is ServiceTier && value == other.value - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - /** Message for configuring webhook events for a request. */ - class WebhookConfig - @JsonCreator(mode = JsonCreator.Mode.DISABLED) - private constructor( - private val uris: JsonField>, - private val userMetadata: JsonField, - private val additionalProperties: MutableMap, - ) { - - @JsonCreator - private constructor( - @JsonProperty("uris") @ExcludeMissing uris: JsonField> = JsonMissing.of(), - @JsonProperty("user_metadata") - @ExcludeMissing - userMetadata: JsonField = JsonMissing.of(), - ) : this(uris, userMetadata, mutableMapOf()) - - /** - * Optional. If set, these webhook URIs will be used for webhook events instead of the - * registered webhooks. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type - * (e.g. if the server responded with an unexpected value). - */ - fun uris(): Optional> = uris.getOptional("uris") - - /** - * Optional. The user metadata that will be returned on each event emission to the webhooks. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type - * (e.g. if the server responded with an unexpected value). - */ - fun userMetadata(): Optional = userMetadata.getOptional("user_metadata") - - /** - * Returns the raw JSON value of [uris]. - * - * Unlike [uris], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("uris") @ExcludeMissing fun _uris(): JsonField> = uris - - /** - * Returns the raw JSON value of [userMetadata]. - * - * Unlike [userMetadata], this method doesn't throw if the JSON field has an unexpected - * type. - */ - @JsonProperty("user_metadata") - @ExcludeMissing - fun _userMetadata(): JsonField = userMetadata - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [WebhookConfig]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [WebhookConfig]. */ - class Builder internal constructor() { - - private var uris: JsonField>? = null - private var userMetadata: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(webhookConfig: WebhookConfig) = apply { - uris = webhookConfig.uris.map { it.toMutableList() } - userMetadata = webhookConfig.userMetadata - additionalProperties = webhookConfig.additionalProperties.toMutableMap() - } - - /** - * Optional. If set, these webhook URIs will be used for webhook events instead of the - * registered webhooks. - */ - fun uris(uris: List) = uris(JsonField.of(uris)) - - /** - * Sets [Builder.uris] to an arbitrary JSON value. - * - * You should usually call [Builder.uris] with a well-typed `List` value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun uris(uris: JsonField>) = apply { - this.uris = uris.map { it.toMutableList() } - } - - /** - * Adds a single [String] to [Builder.uris]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addUris(uris: String) = apply { - this.uris = - (this.uris ?: JsonField.of(mutableListOf())).also { - checkKnown("uris", it).add(uris) - } - } - - /** - * Optional. The user metadata that will be returned on each event emission to the - * webhooks. - */ - fun userMetadata(userMetadata: UserMetadata) = userMetadata(JsonField.of(userMetadata)) - - /** - * Sets [Builder.userMetadata] to an arbitrary JSON value. - * - * You should usually call [Builder.userMetadata] with a well-typed [UserMetadata] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun userMetadata(userMetadata: JsonField) = apply { - this.userMetadata = userMetadata - } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [WebhookConfig]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): WebhookConfig = - WebhookConfig( - (uris ?: JsonMissing.of()).map { it.toImmutable() }, - userMetadata, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): WebhookConfig = apply { - if (validated) { - return@apply - } - - uris() - userMetadata().ifPresent { it.validate() } - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - (uris.asKnown().getOrNull()?.size ?: 0) + - (userMetadata.asKnown().getOrNull()?.validity() ?: 0) - - /** - * Optional. The user metadata that will be returned on each event emission to the webhooks. - */ - class UserMetadata - @JsonCreator - private constructor( - @com.fasterxml.jackson.annotation.JsonValue - private val additionalProperties: Map - ) { - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [UserMetadata]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [UserMetadata]. */ - class Builder internal constructor() { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(userMetadata: UserMetadata) = apply { - additionalProperties = userMetadata.additionalProperties.toMutableMap() - } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = - apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { - additionalProperties.remove(key) - } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [UserMetadata]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): UserMetadata = UserMetadata(additionalProperties.toImmutable()) - } - - private var validated: Boolean = false - - fun validate(): UserMetadata = apply { - if (validated) { - return@apply - } - - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is UserMetadata && additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - - override fun hashCode(): Int = hashCode - - override fun toString() = "UserMetadata{additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is WebhookConfig && - uris == other.uris && - userMetadata == other.userMetadata && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { Objects.hash(uris, userMetadata, additionalProperties) } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "WebhookConfig{uris=$uris, userMetadata=$userMetadata, additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Interaction && - id == other.id && - created == other.created && - status == other.status && - steps == other.steps && - updated == other.updated && - agent == other.agent && - agentConfig == other.agentConfig && - generationConfig == other.generationConfig && - input == other.input && - model == other.model && - previousInteractionId == other.previousInteractionId && - responseFormat == other.responseFormat && - responseMimeType == other.responseMimeType && - responseModalities == other.responseModalities && - role == other.role && - serviceTier == other.serviceTier && - systemInstruction == other.systemInstruction && - tools == other.tools && - usage == other.usage && - webhookConfig == other.webhookConfig && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { - Objects.hash( - id, - created, - status, - steps, - updated, - agent, - agentConfig, - generationConfig, - input, - model, - previousInteractionId, - responseFormat, - responseMimeType, - responseModalities, - role, - serviceTier, - systemInstruction, - tools, - usage, - webhookConfig, - additionalProperties, - ) - } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Interaction{id=$id, created=$created, status=$status, steps=$steps, updated=$updated, agent=$agent, agentConfig=$agentConfig, generationConfig=$generationConfig, input=$input, model=$model, previousInteractionId=$previousInteractionId, responseFormat=$responseFormat, responseMimeType=$responseMimeType, responseModalities=$responseModalities, role=$role, serviceTier=$serviceTier, systemInstruction=$systemInstruction, tools=$tools, usage=$usage, webhookConfig=$webhookConfig, additionalProperties=$additionalProperties}" -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/InteractionCancelParams.kt b/src/main/java/com/google/genai/interactions/models/interactions/InteractionCancelParams.kt deleted file mode 100644 index 4bda8c0db5c..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/InteractionCancelParams.kt +++ /dev/null @@ -1,268 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.core.Params -import com.google.genai.interactions.core.http.Headers -import com.google.genai.interactions.core.http.QueryParams -import com.google.genai.interactions.core.toImmutable -import java.util.Objects -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -/** - * Cancels an interaction by id. This only applies to background interactions that are still - * running. - */ -class InteractionCancelParams -private constructor( - private val apiVersion: String?, - private val id: String?, - private val additionalHeaders: Headers, - private val additionalQueryParams: QueryParams, - private val additionalBodyProperties: Map, -) : Params { - - fun apiVersion(): Optional = Optional.ofNullable(apiVersion) - - fun id(): Optional = Optional.ofNullable(id) - - /** Additional body properties to send with the request. */ - fun _additionalBodyProperties(): Map = additionalBodyProperties - - /** Additional headers to send with the request. */ - fun _additionalHeaders(): Headers = additionalHeaders - - /** Additional query param to send with the request. */ - fun _additionalQueryParams(): QueryParams = additionalQueryParams - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun none(): InteractionCancelParams = builder().build() - - /** Returns a mutable builder for constructing an instance of [InteractionCancelParams]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [InteractionCancelParams]. */ - class Builder internal constructor() { - - private var apiVersion: String? = null - private var id: String? = null - private var additionalHeaders: Headers.Builder = Headers.builder() - private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() - private var additionalBodyProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(interactionCancelParams: InteractionCancelParams) = apply { - apiVersion = interactionCancelParams.apiVersion - id = interactionCancelParams.id - additionalHeaders = interactionCancelParams.additionalHeaders.toBuilder() - additionalQueryParams = interactionCancelParams.additionalQueryParams.toBuilder() - additionalBodyProperties = - interactionCancelParams.additionalBodyProperties.toMutableMap() - } - - fun apiVersion(apiVersion: String?) = apply { this.apiVersion = apiVersion } - - /** Alias for calling [Builder.apiVersion] with `apiVersion.orElse(null)`. */ - fun apiVersion(apiVersion: Optional) = apiVersion(apiVersion.getOrNull()) - - fun id(id: String?) = apply { this.id = id } - - /** Alias for calling [Builder.id] with `id.orElse(null)`. */ - fun id(id: Optional) = id(id.getOrNull()) - - fun additionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } - - fun additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } - - fun putAdditionalHeader(name: String, value: String) = apply { - additionalHeaders.put(name, value) - } - - fun putAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.put(name, values) - } - - fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } - - fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } - - fun replaceAdditionalHeaders(name: String, value: String) = apply { - additionalHeaders.replace(name, value) - } - - fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.replace(name, values) - } - - fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } - - fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } - - fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } - - fun removeAllAdditionalHeaders(names: Set) = apply { - additionalHeaders.removeAll(names) - } - - fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } - - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } - - fun putAdditionalQueryParam(key: String, value: String) = apply { - additionalQueryParams.put(key, value) - } - - fun putAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.put(key, values) - } - - fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.putAll(additionalQueryParams) - } - - fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.putAll(additionalQueryParams) - } - - fun replaceAdditionalQueryParams(key: String, value: String) = apply { - additionalQueryParams.replace(key, value) - } - - fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.replace(key, values) - } - - fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) - } - - fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) - } - - fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } - - fun removeAllAdditionalQueryParams(keys: Set) = apply { - additionalQueryParams.removeAll(keys) - } - - fun additionalBodyProperties(additionalBodyProperties: Map) = apply { - this.additionalBodyProperties.clear() - putAllAdditionalBodyProperties(additionalBodyProperties) - } - - fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { - additionalBodyProperties.put(key, value) - } - - fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = - apply { - this.additionalBodyProperties.putAll(additionalBodyProperties) - } - - fun removeAdditionalBodyProperty(key: String) = apply { - additionalBodyProperties.remove(key) - } - - fun removeAllAdditionalBodyProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalBodyProperty) - } - - /** - * Returns an immutable instance of [InteractionCancelParams]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): InteractionCancelParams = - InteractionCancelParams( - apiVersion, - id, - additionalHeaders.build(), - additionalQueryParams.build(), - additionalBodyProperties.toImmutable(), - ) - } - - fun _body(): Optional> = - Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) - - fun _pathParam(index: Int): String = - when (index) { - 0 -> apiVersion ?: "" - 1 -> id ?: "" - else -> "" - } - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is InteractionCancelParams && - apiVersion == other.apiVersion && - id == other.id && - additionalHeaders == other.additionalHeaders && - additionalQueryParams == other.additionalQueryParams && - additionalBodyProperties == other.additionalBodyProperties - } - - override fun hashCode(): Int = - Objects.hash( - apiVersion, - id, - additionalHeaders, - additionalQueryParams, - additionalBodyProperties, - ) - - override fun toString() = - "InteractionCancelParams{apiVersion=$apiVersion, id=$id, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/InteractionCompletedEvent.kt b/src/main/java/com/google/genai/interactions/models/interactions/InteractionCompletedEvent.kt deleted file mode 100644 index 166ed7a6599..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/InteractionCompletedEvent.kt +++ /dev/null @@ -1,277 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import com.google.genai.interactions.core.ExcludeMissing -import com.google.genai.interactions.core.JsonField -import com.google.genai.interactions.core.JsonMissing -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.core.checkRequired -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.util.Collections -import java.util.Objects -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -class InteractionCompletedEvent -@JsonCreator(mode = JsonCreator.Mode.DISABLED) -private constructor( - private val eventType: JsonValue, - private val interaction: JsonField, - private val eventId: JsonField, - private val additionalProperties: MutableMap, -) { - - @JsonCreator - private constructor( - @JsonProperty("event_type") @ExcludeMissing eventType: JsonValue = JsonMissing.of(), - @JsonProperty("interaction") - @ExcludeMissing - interaction: JsonField = JsonMissing.of(), - @JsonProperty("event_id") @ExcludeMissing eventId: JsonField = JsonMissing.of(), - ) : this(eventType, interaction, eventId, mutableMapOf()) - - /** - * Expected to always return the following: - * ```java - * JsonValue.from("interaction.completed") - * ``` - * - * However, this method can be useful for debugging and logging (e.g. if the server responded - * with an unexpected value). - */ - @JsonProperty("event_type") @ExcludeMissing fun _eventType(): JsonValue = eventType - - /** - * Required. The completed interaction with empty outputs to reduce the payload size. Use the - * preceding ContentDelta events for the actual output. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). - */ - fun interaction(): Interaction = interaction.getRequired("interaction") - - /** - * The event_id token to be used to resume the interaction stream, from this event. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun eventId(): Optional = eventId.getOptional("event_id") - - /** - * Returns the raw JSON value of [interaction]. - * - * Unlike [interaction], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("interaction") - @ExcludeMissing - fun _interaction(): JsonField = interaction - - /** - * Returns the raw JSON value of [eventId]. - * - * Unlike [eventId], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("event_id") @ExcludeMissing fun _eventId(): JsonField = eventId - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [InteractionCompletedEvent]. - * - * The following fields are required: - * ```java - * .interaction() - * ``` - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [InteractionCompletedEvent]. */ - class Builder internal constructor() { - - private var eventType: JsonValue = JsonValue.from("interaction.completed") - private var interaction: JsonField? = null - private var eventId: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(interactionCompletedEvent: InteractionCompletedEvent) = apply { - eventType = interactionCompletedEvent.eventType - interaction = interactionCompletedEvent.interaction - eventId = interactionCompletedEvent.eventId - additionalProperties = interactionCompletedEvent.additionalProperties.toMutableMap() - } - - /** - * Sets the field to an arbitrary JSON value. - * - * It is usually unnecessary to call this method because the field defaults to the - * following: - * ```java - * JsonValue.from("interaction.completed") - * ``` - * - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun eventType(eventType: JsonValue) = apply { this.eventType = eventType } - - /** - * Required. The completed interaction with empty outputs to reduce the payload size. Use - * the preceding ContentDelta events for the actual output. - */ - fun interaction(interaction: Interaction) = interaction(JsonField.of(interaction)) - - /** - * Sets [Builder.interaction] to an arbitrary JSON value. - * - * You should usually call [Builder.interaction] with a well-typed [Interaction] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun interaction(interaction: JsonField) = apply { - this.interaction = interaction - } - - /** The event_id token to be used to resume the interaction stream, from this event. */ - fun eventId(eventId: String) = eventId(JsonField.of(eventId)) - - /** - * Sets [Builder.eventId] to an arbitrary JSON value. - * - * You should usually call [Builder.eventId] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun eventId(eventId: JsonField) = apply { this.eventId = eventId } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [InteractionCompletedEvent]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .interaction() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): InteractionCompletedEvent = - InteractionCompletedEvent( - eventType, - checkRequired("interaction", interaction), - eventId, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): InteractionCompletedEvent = apply { - if (validated) { - return@apply - } - - _eventType().let { - if (it != JsonValue.from("interaction.completed")) { - throw GeminiNextGenApiInvalidDataException("'eventType' is invalid, received $it") - } - } - interaction().validate() - eventId() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - eventType.let { if (it == JsonValue.from("interaction.completed")) 1 else 0 } + - (interaction.asKnown().getOrNull()?.validity() ?: 0) + - (if (eventId.asKnown().isPresent) 1 else 0) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is InteractionCompletedEvent && - eventType == other.eventType && - interaction == other.interaction && - eventId == other.eventId && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { - Objects.hash(eventType, interaction, eventId, additionalProperties) - } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "InteractionCompletedEvent{eventType=$eventType, interaction=$interaction, eventId=$eventId, additionalProperties=$additionalProperties}" -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/InteractionCreateParams.kt b/src/main/java/com/google/genai/interactions/models/interactions/InteractionCreateParams.kt deleted file mode 100644 index 9a2e05239f2..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/InteractionCreateParams.kt +++ /dev/null @@ -1,471 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.core.JsonGenerator -import com.fasterxml.jackson.core.ObjectCodec -import com.fasterxml.jackson.databind.JsonNode -import com.fasterxml.jackson.databind.SerializerProvider -import com.fasterxml.jackson.databind.annotation.JsonDeserialize -import com.fasterxml.jackson.databind.annotation.JsonSerialize -import com.fasterxml.jackson.module.kotlin.jacksonTypeRef -import com.google.genai.interactions.core.BaseDeserializer -import com.google.genai.interactions.core.BaseSerializer -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.core.Params -import com.google.genai.interactions.core.allMaxBy -import com.google.genai.interactions.core.checkRequired -import com.google.genai.interactions.core.getOrThrow -import com.google.genai.interactions.core.http.Headers -import com.google.genai.interactions.core.http.QueryParams -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.util.Objects -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -/** Creates a new interaction. */ -class InteractionCreateParams -private constructor( - private val apiVersion: String?, - private val body: Body, - private val additionalHeaders: Headers, - private val additionalQueryParams: QueryParams, -) : Params { - - fun apiVersion(): Optional = Optional.ofNullable(apiVersion) - - /** Parameters for creating model interactions */ - fun body(): Body = body - - /** Additional headers to send with the request. */ - fun _additionalHeaders(): Headers = additionalHeaders - - /** Additional query param to send with the request. */ - fun _additionalQueryParams(): QueryParams = additionalQueryParams - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [InteractionCreateParams]. - * - * The following fields are required: - * ```java - * .body() - * ``` - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [InteractionCreateParams]. */ - class Builder internal constructor() { - - private var apiVersion: String? = null - private var body: Body? = null - private var additionalHeaders: Headers.Builder = Headers.builder() - private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() - - @JvmSynthetic - internal fun from(interactionCreateParams: InteractionCreateParams) = apply { - apiVersion = interactionCreateParams.apiVersion - body = interactionCreateParams.body - additionalHeaders = interactionCreateParams.additionalHeaders.toBuilder() - additionalQueryParams = interactionCreateParams.additionalQueryParams.toBuilder() - } - - fun apiVersion(apiVersion: String?) = apply { this.apiVersion = apiVersion } - - /** Alias for calling [Builder.apiVersion] with `apiVersion.orElse(null)`. */ - fun apiVersion(apiVersion: Optional) = apiVersion(apiVersion.getOrNull()) - - /** Parameters for creating model interactions */ - fun body(body: Body) = apply { this.body = body } - - /** - * Alias for calling [body] with - * `Body.ofCreateModelInteractionParams(createModelInteractionParams)`. - */ - fun body(createModelInteractionParams: CreateModelInteractionParams) = - body(Body.ofCreateModelInteractionParams(createModelInteractionParams)) - - /** - * Alias for calling [body] with - * `Body.ofCreateAgentInteractionParams(createAgentInteractionParams)`. - */ - fun body(createAgentInteractionParams: CreateAgentInteractionParams) = - body(Body.ofCreateAgentInteractionParams(createAgentInteractionParams)) - - fun additionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } - - fun additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } - - fun putAdditionalHeader(name: String, value: String) = apply { - additionalHeaders.put(name, value) - } - - fun putAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.put(name, values) - } - - fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } - - fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } - - fun replaceAdditionalHeaders(name: String, value: String) = apply { - additionalHeaders.replace(name, value) - } - - fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.replace(name, values) - } - - fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } - - fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } - - fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } - - fun removeAllAdditionalHeaders(names: Set) = apply { - additionalHeaders.removeAll(names) - } - - fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } - - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } - - fun putAdditionalQueryParam(key: String, value: String) = apply { - additionalQueryParams.put(key, value) - } - - fun putAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.put(key, values) - } - - fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.putAll(additionalQueryParams) - } - - fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.putAll(additionalQueryParams) - } - - fun replaceAdditionalQueryParams(key: String, value: String) = apply { - additionalQueryParams.replace(key, value) - } - - fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.replace(key, values) - } - - fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) - } - - fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) - } - - fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } - - fun removeAllAdditionalQueryParams(keys: Set) = apply { - additionalQueryParams.removeAll(keys) - } - - /** - * Returns an immutable instance of [InteractionCreateParams]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .body() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): InteractionCreateParams = - InteractionCreateParams( - apiVersion, - checkRequired("body", body), - additionalHeaders.build(), - additionalQueryParams.build(), - ) - } - - fun _body(): Body = body - - fun _pathParam(index: Int): String = - when (index) { - 0 -> apiVersion ?: "" - else -> "" - } - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - /** Parameters for creating model interactions */ - @JsonDeserialize(using = Body.Deserializer::class) - @JsonSerialize(using = Body.Serializer::class) - class Body - private constructor( - private val createModelInteractionParams: CreateModelInteractionParams? = null, - private val createAgentInteractionParams: CreateAgentInteractionParams? = null, - private val _json: JsonValue? = null, - ) { - - /** Parameters for creating model interactions */ - fun createModelInteractionParams(): Optional = - Optional.ofNullable(createModelInteractionParams) - - /** Parameters for creating agent interactions */ - fun createAgentInteractionParams(): Optional = - Optional.ofNullable(createAgentInteractionParams) - - fun isCreateModelInteractionParams(): Boolean = createModelInteractionParams != null - - fun isCreateAgentInteractionParams(): Boolean = createAgentInteractionParams != null - - /** Parameters for creating model interactions */ - fun asCreateModelInteractionParams(): CreateModelInteractionParams = - createModelInteractionParams.getOrThrow("createModelInteractionParams") - - /** Parameters for creating agent interactions */ - fun asCreateAgentInteractionParams(): CreateAgentInteractionParams = - createAgentInteractionParams.getOrThrow("createAgentInteractionParams") - - fun _json(): Optional = Optional.ofNullable(_json) - - fun accept(visitor: Visitor): T = - when { - createModelInteractionParams != null -> - visitor.visitCreateModelInteractionParams(createModelInteractionParams) - createAgentInteractionParams != null -> - visitor.visitCreateAgentInteractionParams(createAgentInteractionParams) - else -> visitor.unknown(_json) - } - - private var validated: Boolean = false - - fun validate(): Body = apply { - if (validated) { - return@apply - } - - accept( - object : Visitor { - override fun visitCreateModelInteractionParams( - createModelInteractionParams: CreateModelInteractionParams - ) { - createModelInteractionParams.validate() - } - - override fun visitCreateAgentInteractionParams( - createAgentInteractionParams: CreateAgentInteractionParams - ) { - createAgentInteractionParams.validate() - } - } - ) - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - accept( - object : Visitor { - override fun visitCreateModelInteractionParams( - createModelInteractionParams: CreateModelInteractionParams - ) = createModelInteractionParams.validity() - - override fun visitCreateAgentInteractionParams( - createAgentInteractionParams: CreateAgentInteractionParams - ) = createAgentInteractionParams.validity() - - override fun unknown(json: JsonValue?) = 0 - } - ) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Body && - createModelInteractionParams == other.createModelInteractionParams && - createAgentInteractionParams == other.createAgentInteractionParams - } - - override fun hashCode(): Int = - Objects.hash(createModelInteractionParams, createAgentInteractionParams) - - override fun toString(): String = - when { - createModelInteractionParams != null -> - "Body{createModelInteractionParams=$createModelInteractionParams}" - createAgentInteractionParams != null -> - "Body{createAgentInteractionParams=$createAgentInteractionParams}" - _json != null -> "Body{_unknown=$_json}" - else -> throw IllegalStateException("Invalid Body") - } - - companion object { - - /** Parameters for creating model interactions */ - @JvmStatic - fun ofCreateModelInteractionParams( - createModelInteractionParams: CreateModelInteractionParams - ) = Body(createModelInteractionParams = createModelInteractionParams) - - /** Parameters for creating agent interactions */ - @JvmStatic - fun ofCreateAgentInteractionParams( - createAgentInteractionParams: CreateAgentInteractionParams - ) = Body(createAgentInteractionParams = createAgentInteractionParams) - } - - /** An interface that defines how to map each variant of [Body] to a value of type [T]. */ - interface Visitor { - - /** Parameters for creating model interactions */ - fun visitCreateModelInteractionParams( - createModelInteractionParams: CreateModelInteractionParams - ): T - - /** Parameters for creating agent interactions */ - fun visitCreateAgentInteractionParams( - createAgentInteractionParams: CreateAgentInteractionParams - ): T - - /** - * Maps an unknown variant of [Body] to a value of type [T]. - * - * An instance of [Body] can contain an unknown variant if it was deserialized from data - * that doesn't match any known variant. For example, if the SDK is on an older version - * than the API, then the API may respond with new variants that the SDK is unaware of. - * - * @throws GeminiNextGenApiInvalidDataException in the default implementation. - */ - fun unknown(json: JsonValue?): T { - throw GeminiNextGenApiInvalidDataException("Unknown Body: $json") - } - } - - internal class Deserializer : BaseDeserializer(Body::class) { - - override fun ObjectCodec.deserialize(node: JsonNode): Body { - val json = JsonValue.fromJsonNode(node) - - val bestMatches = - sequenceOf( - tryDeserialize(node, jacksonTypeRef()) - ?.let { Body(createModelInteractionParams = it, _json = json) }, - tryDeserialize(node, jacksonTypeRef()) - ?.let { Body(createAgentInteractionParams = it, _json = json) }, - ) - .filterNotNull() - .allMaxBy { it.validity() } - .toList() - return when (bestMatches.size) { - // This can happen if what we're deserializing is completely incompatible with - // all the possible variants (e.g. deserializing from boolean). - 0 -> Body(_json = json) - 1 -> bestMatches.single() - // If there's more than one match with the highest validity, then use the first - // completely valid match, or simply the first match if none are completely - // valid. - else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() - } - } - } - - internal class Serializer : BaseSerializer(Body::class) { - - override fun serialize( - value: Body, - generator: JsonGenerator, - provider: SerializerProvider, - ) { - when { - value.createModelInteractionParams != null -> - generator.writeObject(value.createModelInteractionParams) - value.createAgentInteractionParams != null -> - generator.writeObject(value.createAgentInteractionParams) - value._json != null -> generator.writeObject(value._json) - else -> throw IllegalStateException("Invalid Body") - } - } - } - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is InteractionCreateParams && - apiVersion == other.apiVersion && - body == other.body && - additionalHeaders == other.additionalHeaders && - additionalQueryParams == other.additionalQueryParams - } - - override fun hashCode(): Int = - Objects.hash(apiVersion, body, additionalHeaders, additionalQueryParams) - - override fun toString() = - "InteractionCreateParams{apiVersion=$apiVersion, body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/InteractionCreatedEvent.kt b/src/main/java/com/google/genai/interactions/models/interactions/InteractionCreatedEvent.kt deleted file mode 100644 index 22e8a9ba0f0..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/InteractionCreatedEvent.kt +++ /dev/null @@ -1,273 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import com.google.genai.interactions.core.ExcludeMissing -import com.google.genai.interactions.core.JsonField -import com.google.genai.interactions.core.JsonMissing -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.core.checkRequired -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.util.Collections -import java.util.Objects -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -class InteractionCreatedEvent -@JsonCreator(mode = JsonCreator.Mode.DISABLED) -private constructor( - private val eventType: JsonValue, - private val interaction: JsonField, - private val eventId: JsonField, - private val additionalProperties: MutableMap, -) { - - @JsonCreator - private constructor( - @JsonProperty("event_type") @ExcludeMissing eventType: JsonValue = JsonMissing.of(), - @JsonProperty("interaction") - @ExcludeMissing - interaction: JsonField = JsonMissing.of(), - @JsonProperty("event_id") @ExcludeMissing eventId: JsonField = JsonMissing.of(), - ) : this(eventType, interaction, eventId, mutableMapOf()) - - /** - * Expected to always return the following: - * ```java - * JsonValue.from("interaction.created") - * ``` - * - * However, this method can be useful for debugging and logging (e.g. if the server responded - * with an unexpected value). - */ - @JsonProperty("event_type") @ExcludeMissing fun _eventType(): JsonValue = eventType - - /** - * The Interaction resource. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). - */ - fun interaction(): Interaction = interaction.getRequired("interaction") - - /** - * The event_id token to be used to resume the interaction stream, from this event. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun eventId(): Optional = eventId.getOptional("event_id") - - /** - * Returns the raw JSON value of [interaction]. - * - * Unlike [interaction], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("interaction") - @ExcludeMissing - fun _interaction(): JsonField = interaction - - /** - * Returns the raw JSON value of [eventId]. - * - * Unlike [eventId], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("event_id") @ExcludeMissing fun _eventId(): JsonField = eventId - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [InteractionCreatedEvent]. - * - * The following fields are required: - * ```java - * .interaction() - * ``` - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [InteractionCreatedEvent]. */ - class Builder internal constructor() { - - private var eventType: JsonValue = JsonValue.from("interaction.created") - private var interaction: JsonField? = null - private var eventId: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(interactionCreatedEvent: InteractionCreatedEvent) = apply { - eventType = interactionCreatedEvent.eventType - interaction = interactionCreatedEvent.interaction - eventId = interactionCreatedEvent.eventId - additionalProperties = interactionCreatedEvent.additionalProperties.toMutableMap() - } - - /** - * Sets the field to an arbitrary JSON value. - * - * It is usually unnecessary to call this method because the field defaults to the - * following: - * ```java - * JsonValue.from("interaction.created") - * ``` - * - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun eventType(eventType: JsonValue) = apply { this.eventType = eventType } - - /** The Interaction resource. */ - fun interaction(interaction: Interaction) = interaction(JsonField.of(interaction)) - - /** - * Sets [Builder.interaction] to an arbitrary JSON value. - * - * You should usually call [Builder.interaction] with a well-typed [Interaction] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun interaction(interaction: JsonField) = apply { - this.interaction = interaction - } - - /** The event_id token to be used to resume the interaction stream, from this event. */ - fun eventId(eventId: String) = eventId(JsonField.of(eventId)) - - /** - * Sets [Builder.eventId] to an arbitrary JSON value. - * - * You should usually call [Builder.eventId] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun eventId(eventId: JsonField) = apply { this.eventId = eventId } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [InteractionCreatedEvent]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .interaction() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): InteractionCreatedEvent = - InteractionCreatedEvent( - eventType, - checkRequired("interaction", interaction), - eventId, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): InteractionCreatedEvent = apply { - if (validated) { - return@apply - } - - _eventType().let { - if (it != JsonValue.from("interaction.created")) { - throw GeminiNextGenApiInvalidDataException("'eventType' is invalid, received $it") - } - } - interaction().validate() - eventId() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - eventType.let { if (it == JsonValue.from("interaction.created")) 1 else 0 } + - (interaction.asKnown().getOrNull()?.validity() ?: 0) + - (if (eventId.asKnown().isPresent) 1 else 0) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is InteractionCreatedEvent && - eventType == other.eventType && - interaction == other.interaction && - eventId == other.eventId && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { - Objects.hash(eventType, interaction, eventId, additionalProperties) - } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "InteractionCreatedEvent{eventType=$eventType, interaction=$interaction, eventId=$eventId, additionalProperties=$additionalProperties}" -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/InteractionDeleteParams.kt b/src/main/java/com/google/genai/interactions/models/interactions/InteractionDeleteParams.kt deleted file mode 100644 index 7c54f379e4a..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/InteractionDeleteParams.kt +++ /dev/null @@ -1,265 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.core.Params -import com.google.genai.interactions.core.http.Headers -import com.google.genai.interactions.core.http.QueryParams -import com.google.genai.interactions.core.toImmutable -import java.util.Objects -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -/** Deletes the interaction by id. */ -class InteractionDeleteParams -private constructor( - private val apiVersion: String?, - private val id: String?, - private val additionalHeaders: Headers, - private val additionalQueryParams: QueryParams, - private val additionalBodyProperties: Map, -) : Params { - - fun apiVersion(): Optional = Optional.ofNullable(apiVersion) - - fun id(): Optional = Optional.ofNullable(id) - - /** Additional body properties to send with the request. */ - fun _additionalBodyProperties(): Map = additionalBodyProperties - - /** Additional headers to send with the request. */ - fun _additionalHeaders(): Headers = additionalHeaders - - /** Additional query param to send with the request. */ - fun _additionalQueryParams(): QueryParams = additionalQueryParams - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun none(): InteractionDeleteParams = builder().build() - - /** Returns a mutable builder for constructing an instance of [InteractionDeleteParams]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [InteractionDeleteParams]. */ - class Builder internal constructor() { - - private var apiVersion: String? = null - private var id: String? = null - private var additionalHeaders: Headers.Builder = Headers.builder() - private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() - private var additionalBodyProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(interactionDeleteParams: InteractionDeleteParams) = apply { - apiVersion = interactionDeleteParams.apiVersion - id = interactionDeleteParams.id - additionalHeaders = interactionDeleteParams.additionalHeaders.toBuilder() - additionalQueryParams = interactionDeleteParams.additionalQueryParams.toBuilder() - additionalBodyProperties = - interactionDeleteParams.additionalBodyProperties.toMutableMap() - } - - fun apiVersion(apiVersion: String?) = apply { this.apiVersion = apiVersion } - - /** Alias for calling [Builder.apiVersion] with `apiVersion.orElse(null)`. */ - fun apiVersion(apiVersion: Optional) = apiVersion(apiVersion.getOrNull()) - - fun id(id: String?) = apply { this.id = id } - - /** Alias for calling [Builder.id] with `id.orElse(null)`. */ - fun id(id: Optional) = id(id.getOrNull()) - - fun additionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } - - fun additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } - - fun putAdditionalHeader(name: String, value: String) = apply { - additionalHeaders.put(name, value) - } - - fun putAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.put(name, values) - } - - fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } - - fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } - - fun replaceAdditionalHeaders(name: String, value: String) = apply { - additionalHeaders.replace(name, value) - } - - fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.replace(name, values) - } - - fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } - - fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } - - fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } - - fun removeAllAdditionalHeaders(names: Set) = apply { - additionalHeaders.removeAll(names) - } - - fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } - - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } - - fun putAdditionalQueryParam(key: String, value: String) = apply { - additionalQueryParams.put(key, value) - } - - fun putAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.put(key, values) - } - - fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.putAll(additionalQueryParams) - } - - fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.putAll(additionalQueryParams) - } - - fun replaceAdditionalQueryParams(key: String, value: String) = apply { - additionalQueryParams.replace(key, value) - } - - fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.replace(key, values) - } - - fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) - } - - fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) - } - - fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } - - fun removeAllAdditionalQueryParams(keys: Set) = apply { - additionalQueryParams.removeAll(keys) - } - - fun additionalBodyProperties(additionalBodyProperties: Map) = apply { - this.additionalBodyProperties.clear() - putAllAdditionalBodyProperties(additionalBodyProperties) - } - - fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { - additionalBodyProperties.put(key, value) - } - - fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = - apply { - this.additionalBodyProperties.putAll(additionalBodyProperties) - } - - fun removeAdditionalBodyProperty(key: String) = apply { - additionalBodyProperties.remove(key) - } - - fun removeAllAdditionalBodyProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalBodyProperty) - } - - /** - * Returns an immutable instance of [InteractionDeleteParams]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): InteractionDeleteParams = - InteractionDeleteParams( - apiVersion, - id, - additionalHeaders.build(), - additionalQueryParams.build(), - additionalBodyProperties.toImmutable(), - ) - } - - fun _body(): Optional> = - Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) - - fun _pathParam(index: Int): String = - when (index) { - 0 -> apiVersion ?: "" - 1 -> id ?: "" - else -> "" - } - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is InteractionDeleteParams && - apiVersion == other.apiVersion && - id == other.id && - additionalHeaders == other.additionalHeaders && - additionalQueryParams == other.additionalQueryParams && - additionalBodyProperties == other.additionalBodyProperties - } - - override fun hashCode(): Int = - Objects.hash( - apiVersion, - id, - additionalHeaders, - additionalQueryParams, - additionalBodyProperties, - ) - - override fun toString() = - "InteractionDeleteParams{apiVersion=$apiVersion, id=$id, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/InteractionDeleteResponse.kt b/src/main/java/com/google/genai/interactions/models/interactions/InteractionDeleteResponse.kt deleted file mode 100644 index fdba67a230a..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/InteractionDeleteResponse.kt +++ /dev/null @@ -1,134 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.google.genai.interactions.core.ExcludeMissing -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.util.Collections -import java.util.Objects - -class InteractionDeleteResponse -@JsonCreator(mode = JsonCreator.Mode.DISABLED) -private constructor(private val additionalProperties: MutableMap) { - - @JsonCreator private constructor() : this(mutableMapOf()) - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [InteractionDeleteResponse]. - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [InteractionDeleteResponse]. */ - class Builder internal constructor() { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(interactionDeleteResponse: InteractionDeleteResponse) = apply { - additionalProperties = interactionDeleteResponse.additionalProperties.toMutableMap() - } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [InteractionDeleteResponse]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): InteractionDeleteResponse = - InteractionDeleteResponse(additionalProperties.toMutableMap()) - } - - private var validated: Boolean = false - - fun validate(): InteractionDeleteResponse = apply { - if (validated) { - return@apply - } - - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic internal fun validity(): Int = 0 - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is InteractionDeleteResponse && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "InteractionDeleteResponse{additionalProperties=$additionalProperties}" -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/InteractionGetParams.kt b/src/main/java/com/google/genai/interactions/models/interactions/InteractionGetParams.kt deleted file mode 100644 index 8473288cacc..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/InteractionGetParams.kt +++ /dev/null @@ -1,278 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.google.genai.interactions.core.Params -import com.google.genai.interactions.core.http.Headers -import com.google.genai.interactions.core.http.QueryParams -import java.util.Objects -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -/** Retrieves the full details of a single interaction based on its `Interaction.id`. */ -class InteractionGetParams -private constructor( - private val apiVersion: String?, - private val id: String?, - private val includeInput: Boolean?, - private val lastEventId: String?, - private val additionalHeaders: Headers, - private val additionalQueryParams: QueryParams, -) : Params { - - fun apiVersion(): Optional = Optional.ofNullable(apiVersion) - - fun id(): Optional = Optional.ofNullable(id) - - /** If set to true, includes the input in the response. */ - fun includeInput(): Optional = Optional.ofNullable(includeInput) - - /** - * Optional. If set, resumes the interaction stream from the next chunk after the event marked - * by the event id. Can only be used if `stream` is true. - */ - fun lastEventId(): Optional = Optional.ofNullable(lastEventId) - - /** Additional headers to send with the request. */ - fun _additionalHeaders(): Headers = additionalHeaders - - /** Additional query param to send with the request. */ - fun _additionalQueryParams(): QueryParams = additionalQueryParams - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun none(): InteractionGetParams = builder().build() - - /** Returns a mutable builder for constructing an instance of [InteractionGetParams]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [InteractionGetParams]. */ - class Builder internal constructor() { - - private var apiVersion: String? = null - private var id: String? = null - private var includeInput: Boolean? = null - private var lastEventId: String? = null - private var additionalHeaders: Headers.Builder = Headers.builder() - private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() - - @JvmSynthetic - internal fun from(interactionGetParams: InteractionGetParams) = apply { - apiVersion = interactionGetParams.apiVersion - id = interactionGetParams.id - includeInput = interactionGetParams.includeInput - lastEventId = interactionGetParams.lastEventId - additionalHeaders = interactionGetParams.additionalHeaders.toBuilder() - additionalQueryParams = interactionGetParams.additionalQueryParams.toBuilder() - } - - fun apiVersion(apiVersion: String?) = apply { this.apiVersion = apiVersion } - - /** Alias for calling [Builder.apiVersion] with `apiVersion.orElse(null)`. */ - fun apiVersion(apiVersion: Optional) = apiVersion(apiVersion.getOrNull()) - - fun id(id: String?) = apply { this.id = id } - - /** Alias for calling [Builder.id] with `id.orElse(null)`. */ - fun id(id: Optional) = id(id.getOrNull()) - - /** If set to true, includes the input in the response. */ - fun includeInput(includeInput: Boolean?) = apply { this.includeInput = includeInput } - - /** - * Alias for [Builder.includeInput]. - * - * This unboxed primitive overload exists for backwards compatibility. - */ - fun includeInput(includeInput: Boolean) = includeInput(includeInput as Boolean?) - - /** Alias for calling [Builder.includeInput] with `includeInput.orElse(null)`. */ - fun includeInput(includeInput: Optional) = includeInput(includeInput.getOrNull()) - - /** - * Optional. If set, resumes the interaction stream from the next chunk after the event - * marked by the event id. Can only be used if `stream` is true. - */ - fun lastEventId(lastEventId: String?) = apply { this.lastEventId = lastEventId } - - /** Alias for calling [Builder.lastEventId] with `lastEventId.orElse(null)`. */ - fun lastEventId(lastEventId: Optional) = lastEventId(lastEventId.getOrNull()) - - fun additionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } - - fun additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } - - fun putAdditionalHeader(name: String, value: String) = apply { - additionalHeaders.put(name, value) - } - - fun putAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.put(name, values) - } - - fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } - - fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } - - fun replaceAdditionalHeaders(name: String, value: String) = apply { - additionalHeaders.replace(name, value) - } - - fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.replace(name, values) - } - - fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } - - fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } - - fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } - - fun removeAllAdditionalHeaders(names: Set) = apply { - additionalHeaders.removeAll(names) - } - - fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } - - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } - - fun putAdditionalQueryParam(key: String, value: String) = apply { - additionalQueryParams.put(key, value) - } - - fun putAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.put(key, values) - } - - fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.putAll(additionalQueryParams) - } - - fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.putAll(additionalQueryParams) - } - - fun replaceAdditionalQueryParams(key: String, value: String) = apply { - additionalQueryParams.replace(key, value) - } - - fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.replace(key, values) - } - - fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) - } - - fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) - } - - fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } - - fun removeAllAdditionalQueryParams(keys: Set) = apply { - additionalQueryParams.removeAll(keys) - } - - /** - * Returns an immutable instance of [InteractionGetParams]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): InteractionGetParams = - InteractionGetParams( - apiVersion, - id, - includeInput, - lastEventId, - additionalHeaders.build(), - additionalQueryParams.build(), - ) - } - - fun _pathParam(index: Int): String = - when (index) { - 0 -> apiVersion ?: "" - 1 -> id ?: "" - else -> "" - } - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = - QueryParams.builder() - .apply { - includeInput?.let { put("include_input", it.toString()) } - lastEventId?.let { put("last_event_id", it) } - putAll(additionalQueryParams) - } - .build() - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is InteractionGetParams && - apiVersion == other.apiVersion && - id == other.id && - includeInput == other.includeInput && - lastEventId == other.lastEventId && - additionalHeaders == other.additionalHeaders && - additionalQueryParams == other.additionalQueryParams - } - - override fun hashCode(): Int = - Objects.hash( - apiVersion, - id, - includeInput, - lastEventId, - additionalHeaders, - additionalQueryParams, - ) - - override fun toString() = - "InteractionGetParams{apiVersion=$apiVersion, id=$id, includeInput=$includeInput, lastEventId=$lastEventId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/InteractionSseEvent.kt b/src/main/java/com/google/genai/interactions/models/interactions/InteractionSseEvent.kt deleted file mode 100644 index 97700613749..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/InteractionSseEvent.kt +++ /dev/null @@ -1,344 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.core.JsonGenerator -import com.fasterxml.jackson.core.ObjectCodec -import com.fasterxml.jackson.databind.JsonNode -import com.fasterxml.jackson.databind.SerializerProvider -import com.fasterxml.jackson.databind.annotation.JsonDeserialize -import com.fasterxml.jackson.databind.annotation.JsonSerialize -import com.fasterxml.jackson.module.kotlin.jacksonTypeRef -import com.google.genai.interactions.core.BaseDeserializer -import com.google.genai.interactions.core.BaseSerializer -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.core.getOrThrow -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.util.Objects -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -@JsonDeserialize(using = InteractionSseEvent.Deserializer::class) -@JsonSerialize(using = InteractionSseEvent.Serializer::class) -class InteractionSseEvent -private constructor( - private val created: InteractionCreatedEvent? = null, - private val completed: InteractionCompletedEvent? = null, - private val statusUpdate: InteractionStatusUpdate? = null, - private val error: ErrorEvent? = null, - private val stepStart: StepStart? = null, - private val stepDelta: StepDelta? = null, - private val stepStop: StepStop? = null, - private val _json: JsonValue? = null, -) { - - fun created(): Optional = Optional.ofNullable(created) - - fun completed(): Optional = Optional.ofNullable(completed) - - fun statusUpdate(): Optional = Optional.ofNullable(statusUpdate) - - fun error(): Optional = Optional.ofNullable(error) - - fun stepStart(): Optional = Optional.ofNullable(stepStart) - - fun stepDelta(): Optional = Optional.ofNullable(stepDelta) - - fun stepStop(): Optional = Optional.ofNullable(stepStop) - - fun isCreated(): Boolean = created != null - - fun isCompleted(): Boolean = completed != null - - fun isStatusUpdate(): Boolean = statusUpdate != null - - fun isError(): Boolean = error != null - - fun isStepStart(): Boolean = stepStart != null - - fun isStepDelta(): Boolean = stepDelta != null - - fun isStepStop(): Boolean = stepStop != null - - fun asCreated(): InteractionCreatedEvent = created.getOrThrow("created") - - fun asCompleted(): InteractionCompletedEvent = completed.getOrThrow("completed") - - fun asStatusUpdate(): InteractionStatusUpdate = statusUpdate.getOrThrow("statusUpdate") - - fun asError(): ErrorEvent = error.getOrThrow("error") - - fun asStepStart(): StepStart = stepStart.getOrThrow("stepStart") - - fun asStepDelta(): StepDelta = stepDelta.getOrThrow("stepDelta") - - fun asStepStop(): StepStop = stepStop.getOrThrow("stepStop") - - fun _json(): Optional = Optional.ofNullable(_json) - - fun accept(visitor: Visitor): T = - when { - created != null -> visitor.visitCreated(created) - completed != null -> visitor.visitCompleted(completed) - statusUpdate != null -> visitor.visitStatusUpdate(statusUpdate) - error != null -> visitor.visitError(error) - stepStart != null -> visitor.visitStepStart(stepStart) - stepDelta != null -> visitor.visitStepDelta(stepDelta) - stepStop != null -> visitor.visitStepStop(stepStop) - else -> visitor.unknown(_json) - } - - private var validated: Boolean = false - - fun validate(): InteractionSseEvent = apply { - if (validated) { - return@apply - } - - accept( - object : Visitor { - override fun visitCreated(created: InteractionCreatedEvent) { - created.validate() - } - - override fun visitCompleted(completed: InteractionCompletedEvent) { - completed.validate() - } - - override fun visitStatusUpdate(statusUpdate: InteractionStatusUpdate) { - statusUpdate.validate() - } - - override fun visitError(error: ErrorEvent) { - error.validate() - } - - override fun visitStepStart(stepStart: StepStart) { - stepStart.validate() - } - - override fun visitStepDelta(stepDelta: StepDelta) { - stepDelta.validate() - } - - override fun visitStepStop(stepStop: StepStop) { - stepStop.validate() - } - } - ) - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - accept( - object : Visitor { - override fun visitCreated(created: InteractionCreatedEvent) = created.validity() - - override fun visitCompleted(completed: InteractionCompletedEvent) = - completed.validity() - - override fun visitStatusUpdate(statusUpdate: InteractionStatusUpdate) = - statusUpdate.validity() - - override fun visitError(error: ErrorEvent) = error.validity() - - override fun visitStepStart(stepStart: StepStart) = stepStart.validity() - - override fun visitStepDelta(stepDelta: StepDelta) = stepDelta.validity() - - override fun visitStepStop(stepStop: StepStop) = stepStop.validity() - - override fun unknown(json: JsonValue?) = 0 - } - ) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is InteractionSseEvent && - created == other.created && - completed == other.completed && - statusUpdate == other.statusUpdate && - error == other.error && - stepStart == other.stepStart && - stepDelta == other.stepDelta && - stepStop == other.stepStop - } - - override fun hashCode(): Int = - Objects.hash(created, completed, statusUpdate, error, stepStart, stepDelta, stepStop) - - override fun toString(): String = - when { - created != null -> "InteractionSseEvent{created=$created}" - completed != null -> "InteractionSseEvent{completed=$completed}" - statusUpdate != null -> "InteractionSseEvent{statusUpdate=$statusUpdate}" - error != null -> "InteractionSseEvent{error=$error}" - stepStart != null -> "InteractionSseEvent{stepStart=$stepStart}" - stepDelta != null -> "InteractionSseEvent{stepDelta=$stepDelta}" - stepStop != null -> "InteractionSseEvent{stepStop=$stepStop}" - _json != null -> "InteractionSseEvent{_unknown=$_json}" - else -> throw IllegalStateException("Invalid InteractionSseEvent") - } - - companion object { - - @JvmStatic - fun ofCreated(created: InteractionCreatedEvent) = InteractionSseEvent(created = created) - - @JvmStatic - fun ofCompleted(completed: InteractionCompletedEvent) = - InteractionSseEvent(completed = completed) - - @JvmStatic - fun ofStatusUpdate(statusUpdate: InteractionStatusUpdate) = - InteractionSseEvent(statusUpdate = statusUpdate) - - @JvmStatic fun ofError(error: ErrorEvent) = InteractionSseEvent(error = error) - - @JvmStatic - fun ofStepStart(stepStart: StepStart) = InteractionSseEvent(stepStart = stepStart) - - @JvmStatic - fun ofStepDelta(stepDelta: StepDelta) = InteractionSseEvent(stepDelta = stepDelta) - - @JvmStatic fun ofStepStop(stepStop: StepStop) = InteractionSseEvent(stepStop = stepStop) - } - - /** - * An interface that defines how to map each variant of [InteractionSseEvent] to a value of type - * [T]. - */ - interface Visitor { - - fun visitCreated(created: InteractionCreatedEvent): T - - fun visitCompleted(completed: InteractionCompletedEvent): T - - fun visitStatusUpdate(statusUpdate: InteractionStatusUpdate): T - - fun visitError(error: ErrorEvent): T - - fun visitStepStart(stepStart: StepStart): T - - fun visitStepDelta(stepDelta: StepDelta): T - - fun visitStepStop(stepStop: StepStop): T - - /** - * Maps an unknown variant of [InteractionSseEvent] to a value of type [T]. - * - * An instance of [InteractionSseEvent] can contain an unknown variant if it was - * deserialized from data that doesn't match any known variant. For example, if the SDK is - * on an older version than the API, then the API may respond with new variants that the SDK - * is unaware of. - * - * @throws GeminiNextGenApiInvalidDataException in the default implementation. - */ - fun unknown(json: JsonValue?): T { - throw GeminiNextGenApiInvalidDataException("Unknown InteractionSseEvent: $json") - } - } - - internal class Deserializer : - BaseDeserializer(InteractionSseEvent::class) { - - override fun ObjectCodec.deserialize(node: JsonNode): InteractionSseEvent { - val json = JsonValue.fromJsonNode(node) - val eventType = json.asObject().getOrNull()?.get("event_type")?.asString()?.getOrNull() - - when (eventType) { - "interaction.created" -> { - return tryDeserialize(node, jacksonTypeRef())?.let { - InteractionSseEvent(created = it, _json = json) - } ?: InteractionSseEvent(_json = json) - } - "interaction.completed" -> { - return tryDeserialize(node, jacksonTypeRef())?.let { - InteractionSseEvent(completed = it, _json = json) - } ?: InteractionSseEvent(_json = json) - } - "interaction.status_update" -> { - return tryDeserialize(node, jacksonTypeRef())?.let { - InteractionSseEvent(statusUpdate = it, _json = json) - } ?: InteractionSseEvent(_json = json) - } - "error" -> { - return tryDeserialize(node, jacksonTypeRef())?.let { - InteractionSseEvent(error = it, _json = json) - } ?: InteractionSseEvent(_json = json) - } - "step.start" -> { - return tryDeserialize(node, jacksonTypeRef())?.let { - InteractionSseEvent(stepStart = it, _json = json) - } ?: InteractionSseEvent(_json = json) - } - "step.delta" -> { - return tryDeserialize(node, jacksonTypeRef())?.let { - InteractionSseEvent(stepDelta = it, _json = json) - } ?: InteractionSseEvent(_json = json) - } - "step.stop" -> { - return tryDeserialize(node, jacksonTypeRef())?.let { - InteractionSseEvent(stepStop = it, _json = json) - } ?: InteractionSseEvent(_json = json) - } - } - - return InteractionSseEvent(_json = json) - } - } - - internal class Serializer : BaseSerializer(InteractionSseEvent::class) { - - override fun serialize( - value: InteractionSseEvent, - generator: JsonGenerator, - provider: SerializerProvider, - ) { - when { - value.created != null -> generator.writeObject(value.created) - value.completed != null -> generator.writeObject(value.completed) - value.statusUpdate != null -> generator.writeObject(value.statusUpdate) - value.error != null -> generator.writeObject(value.error) - value.stepStart != null -> generator.writeObject(value.stepStart) - value.stepDelta != null -> generator.writeObject(value.stepDelta) - value.stepStop != null -> generator.writeObject(value.stepStop) - value._json != null -> generator.writeObject(value._json) - else -> throw IllegalStateException("Invalid InteractionSseEvent") - } - } - } -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/InteractionStatusUpdate.kt b/src/main/java/com/google/genai/interactions/models/interactions/InteractionStatusUpdate.kt deleted file mode 100644 index feee3434fb9..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/InteractionStatusUpdate.kt +++ /dev/null @@ -1,455 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import com.google.genai.interactions.core.Enum -import com.google.genai.interactions.core.ExcludeMissing -import com.google.genai.interactions.core.JsonField -import com.google.genai.interactions.core.JsonMissing -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.core.checkRequired -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.util.Collections -import java.util.Objects -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -class InteractionStatusUpdate -@JsonCreator(mode = JsonCreator.Mode.DISABLED) -private constructor( - private val eventType: JsonValue, - private val interactionId: JsonField, - private val status: JsonField, - private val eventId: JsonField, - private val additionalProperties: MutableMap, -) { - - @JsonCreator - private constructor( - @JsonProperty("event_type") @ExcludeMissing eventType: JsonValue = JsonMissing.of(), - @JsonProperty("interaction_id") - @ExcludeMissing - interactionId: JsonField = JsonMissing.of(), - @JsonProperty("status") @ExcludeMissing status: JsonField = JsonMissing.of(), - @JsonProperty("event_id") @ExcludeMissing eventId: JsonField = JsonMissing.of(), - ) : this(eventType, interactionId, status, eventId, mutableMapOf()) - - /** - * Expected to always return the following: - * ```java - * JsonValue.from("interaction.status_update") - * ``` - * - * However, this method can be useful for debugging and logging (e.g. if the server responded - * with an unexpected value). - */ - @JsonProperty("event_type") @ExcludeMissing fun _eventType(): JsonValue = eventType - - /** - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). - */ - fun interactionId(): String = interactionId.getRequired("interaction_id") - - /** - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). - */ - fun status(): Status = status.getRequired("status") - - /** - * The event_id token to be used to resume the interaction stream, from this event. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun eventId(): Optional = eventId.getOptional("event_id") - - /** - * Returns the raw JSON value of [interactionId]. - * - * Unlike [interactionId], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("interaction_id") - @ExcludeMissing - fun _interactionId(): JsonField = interactionId - - /** - * Returns the raw JSON value of [status]. - * - * Unlike [status], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("status") @ExcludeMissing fun _status(): JsonField = status - - /** - * Returns the raw JSON value of [eventId]. - * - * Unlike [eventId], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("event_id") @ExcludeMissing fun _eventId(): JsonField = eventId - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [InteractionStatusUpdate]. - * - * The following fields are required: - * ```java - * .interactionId() - * .status() - * ``` - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [InteractionStatusUpdate]. */ - class Builder internal constructor() { - - private var eventType: JsonValue = JsonValue.from("interaction.status_update") - private var interactionId: JsonField? = null - private var status: JsonField? = null - private var eventId: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(interactionStatusUpdate: InteractionStatusUpdate) = apply { - eventType = interactionStatusUpdate.eventType - interactionId = interactionStatusUpdate.interactionId - status = interactionStatusUpdate.status - eventId = interactionStatusUpdate.eventId - additionalProperties = interactionStatusUpdate.additionalProperties.toMutableMap() - } - - /** - * Sets the field to an arbitrary JSON value. - * - * It is usually unnecessary to call this method because the field defaults to the - * following: - * ```java - * JsonValue.from("interaction.status_update") - * ``` - * - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun eventType(eventType: JsonValue) = apply { this.eventType = eventType } - - fun interactionId(interactionId: String) = interactionId(JsonField.of(interactionId)) - - /** - * Sets [Builder.interactionId] to an arbitrary JSON value. - * - * You should usually call [Builder.interactionId] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun interactionId(interactionId: JsonField) = apply { - this.interactionId = interactionId - } - - fun status(status: Status) = status(JsonField.of(status)) - - /** - * Sets [Builder.status] to an arbitrary JSON value. - * - * You should usually call [Builder.status] with a well-typed [Status] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun status(status: JsonField) = apply { this.status = status } - - /** The event_id token to be used to resume the interaction stream, from this event. */ - fun eventId(eventId: String) = eventId(JsonField.of(eventId)) - - /** - * Sets [Builder.eventId] to an arbitrary JSON value. - * - * You should usually call [Builder.eventId] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun eventId(eventId: JsonField) = apply { this.eventId = eventId } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [InteractionStatusUpdate]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .interactionId() - * .status() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): InteractionStatusUpdate = - InteractionStatusUpdate( - eventType, - checkRequired("interactionId", interactionId), - checkRequired("status", status), - eventId, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): InteractionStatusUpdate = apply { - if (validated) { - return@apply - } - - _eventType().let { - if (it != JsonValue.from("interaction.status_update")) { - throw GeminiNextGenApiInvalidDataException("'eventType' is invalid, received $it") - } - } - interactionId() - status().validate() - eventId() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - eventType.let { if (it == JsonValue.from("interaction.status_update")) 1 else 0 } + - (if (interactionId.asKnown().isPresent) 1 else 0) + - (status.asKnown().getOrNull()?.validity() ?: 0) + - (if (eventId.asKnown().isPresent) 1 else 0) - - class Status @JsonCreator private constructor(private val value: JsonField) : Enum { - - /** - * Returns this class instance's raw value. - * - * This is usually only useful if this instance was deserialized from data that doesn't - * match any known member, and you want to know that value. For example, if the SDK is on an - * older version than the API, then the API may respond with new members that the SDK is - * unaware of. - */ - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - companion object { - - @JvmField val IN_PROGRESS = of("in_progress") - - @JvmField val REQUIRES_ACTION = of("requires_action") - - @JvmField val COMPLETED = of("completed") - - @JvmField val FAILED = of("failed") - - @JvmField val CANCELLED = of("cancelled") - - @JvmField val INCOMPLETE = of("incomplete") - - @JvmStatic fun of(value: String) = Status(JsonField.of(value)) - } - - /** An enum containing [Status]'s known values. */ - enum class Known { - IN_PROGRESS, - REQUIRES_ACTION, - COMPLETED, - FAILED, - CANCELLED, - INCOMPLETE, - } - - /** - * An enum containing [Status]'s known values, as well as an [_UNKNOWN] member. - * - * An instance of [Status] can contain an unknown value in a couple of cases: - * - It was deserialized from data that doesn't match any known member. For example, if the - * SDK is on an older version than the API, then the API may respond with new members that - * the SDK is unaware of. - * - It was constructed with an arbitrary value using the [of] method. - */ - enum class Value { - IN_PROGRESS, - REQUIRES_ACTION, - COMPLETED, - FAILED, - CANCELLED, - INCOMPLETE, - /** An enum member indicating that [Status] was instantiated with an unknown value. */ - _UNKNOWN, - } - - /** - * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] - * if the class was instantiated with an unknown value. - * - * Use the [known] method instead if you're certain the value is always known or if you want - * to throw for the unknown case. - */ - fun value(): Value = - when (this) { - IN_PROGRESS -> Value.IN_PROGRESS - REQUIRES_ACTION -> Value.REQUIRES_ACTION - COMPLETED -> Value.COMPLETED - FAILED -> Value.FAILED - CANCELLED -> Value.CANCELLED - INCOMPLETE -> Value.INCOMPLETE - else -> Value._UNKNOWN - } - - /** - * Returns an enum member corresponding to this class instance's value. - * - * Use the [value] method instead if you're uncertain the value is always known and don't - * want to throw for the unknown case. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value is a not a - * known member. - */ - fun known(): Known = - when (this) { - IN_PROGRESS -> Known.IN_PROGRESS - REQUIRES_ACTION -> Known.REQUIRES_ACTION - COMPLETED -> Known.COMPLETED - FAILED -> Known.FAILED - CANCELLED -> Known.CANCELLED - INCOMPLETE -> Known.INCOMPLETE - else -> throw GeminiNextGenApiInvalidDataException("Unknown Status: $value") - } - - /** - * Returns this class instance's primitive wire representation. - * - * This differs from the [toString] method because that method is primarily for debugging - * and generally doesn't throw. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value does not have - * the expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - GeminiNextGenApiInvalidDataException("Value is not a String") - } - - private var validated: Boolean = false - - fun validate(): Status = apply { - if (validated) { - return@apply - } - - known() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Status && value == other.value - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is InteractionStatusUpdate && - eventType == other.eventType && - interactionId == other.interactionId && - status == other.status && - eventId == other.eventId && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { - Objects.hash(eventType, interactionId, status, eventId, additionalProperties) - } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "InteractionStatusUpdate{eventType=$eventType, interactionId=$interactionId, status=$status, eventId=$eventId, additionalProperties=$additionalProperties}" -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/McpServerToolCallStep.kt b/src/main/java/com/google/genai/interactions/models/interactions/McpServerToolCallStep.kt deleted file mode 100644 index 670b6a1a036..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/McpServerToolCallStep.kt +++ /dev/null @@ -1,483 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import com.google.genai.interactions.core.ExcludeMissing -import com.google.genai.interactions.core.JsonField -import com.google.genai.interactions.core.JsonMissing -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.core.checkRequired -import com.google.genai.interactions.core.toImmutable -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.util.Collections -import java.util.Objects -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -/** MCPServer tool call step. */ -class McpServerToolCallStep -@JsonCreator(mode = JsonCreator.Mode.DISABLED) -private constructor( - private val id: JsonField, - private val arguments: JsonField, - private val name: JsonField, - private val serverName: JsonField, - private val type: JsonValue, - private val signature: JsonField, - private val additionalProperties: MutableMap, -) { - - @JsonCreator - private constructor( - @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), - @JsonProperty("arguments") - @ExcludeMissing - arguments: JsonField = JsonMissing.of(), - @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), - @JsonProperty("server_name") - @ExcludeMissing - serverName: JsonField = JsonMissing.of(), - @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), - @JsonProperty("signature") @ExcludeMissing signature: JsonField = JsonMissing.of(), - ) : this(id, arguments, name, serverName, type, signature, mutableMapOf()) - - /** - * Required. A unique ID for this specific tool call. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). - */ - fun id(): String = id.getRequired("id") - - /** - * Required. The JSON object of arguments for the function. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). - */ - fun arguments(): Arguments = arguments.getRequired("arguments") - - /** - * Required. The name of the tool which was called. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). - */ - fun name(): String = name.getRequired("name") - - /** - * Required. The name of the used MCP server. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). - */ - fun serverName(): String = serverName.getRequired("server_name") - - /** - * Expected to always return the following: - * ```java - * JsonValue.from("mcp_server_tool_call") - * ``` - * - * However, this method can be useful for debugging and logging (e.g. if the server responded - * with an unexpected value). - */ - @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type - - /** - * A signature hash for backend validation. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun signature(): Optional = signature.getOptional("signature") - - /** - * Returns the raw JSON value of [id]. - * - * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id - - /** - * Returns the raw JSON value of [arguments]. - * - * Unlike [arguments], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("arguments") @ExcludeMissing fun _arguments(): JsonField = arguments - - /** - * Returns the raw JSON value of [name]. - * - * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name - - /** - * Returns the raw JSON value of [serverName]. - * - * Unlike [serverName], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("server_name") @ExcludeMissing fun _serverName(): JsonField = serverName - - /** - * Returns the raw JSON value of [signature]. - * - * Unlike [signature], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("signature") @ExcludeMissing fun _signature(): JsonField = signature - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [McpServerToolCallStep]. - * - * The following fields are required: - * ```java - * .id() - * .arguments() - * .name() - * .serverName() - * ``` - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [McpServerToolCallStep]. */ - class Builder internal constructor() { - - private var id: JsonField? = null - private var arguments: JsonField? = null - private var name: JsonField? = null - private var serverName: JsonField? = null - private var type: JsonValue = JsonValue.from("mcp_server_tool_call") - private var signature: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(mcpServerToolCallStep: McpServerToolCallStep) = apply { - id = mcpServerToolCallStep.id - arguments = mcpServerToolCallStep.arguments - name = mcpServerToolCallStep.name - serverName = mcpServerToolCallStep.serverName - type = mcpServerToolCallStep.type - signature = mcpServerToolCallStep.signature - additionalProperties = mcpServerToolCallStep.additionalProperties.toMutableMap() - } - - /** Required. A unique ID for this specific tool call. */ - fun id(id: String) = id(JsonField.of(id)) - - /** - * Sets [Builder.id] to an arbitrary JSON value. - * - * You should usually call [Builder.id] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun id(id: JsonField) = apply { this.id = id } - - /** Required. The JSON object of arguments for the function. */ - fun arguments(arguments: Arguments) = arguments(JsonField.of(arguments)) - - /** - * Sets [Builder.arguments] to an arbitrary JSON value. - * - * You should usually call [Builder.arguments] with a well-typed [Arguments] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun arguments(arguments: JsonField) = apply { this.arguments = arguments } - - /** Required. The name of the tool which was called. */ - fun name(name: String) = name(JsonField.of(name)) - - /** - * Sets [Builder.name] to an arbitrary JSON value. - * - * You should usually call [Builder.name] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun name(name: JsonField) = apply { this.name = name } - - /** Required. The name of the used MCP server. */ - fun serverName(serverName: String) = serverName(JsonField.of(serverName)) - - /** - * Sets [Builder.serverName] to an arbitrary JSON value. - * - * You should usually call [Builder.serverName] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun serverName(serverName: JsonField) = apply { this.serverName = serverName } - - /** - * Sets the field to an arbitrary JSON value. - * - * It is usually unnecessary to call this method because the field defaults to the - * following: - * ```java - * JsonValue.from("mcp_server_tool_call") - * ``` - * - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun type(type: JsonValue) = apply { this.type = type } - - /** A signature hash for backend validation. */ - fun signature(signature: String) = signature(JsonField.of(signature)) - - /** - * Sets [Builder.signature] to an arbitrary JSON value. - * - * You should usually call [Builder.signature] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun signature(signature: JsonField) = apply { this.signature = signature } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [McpServerToolCallStep]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .id() - * .arguments() - * .name() - * .serverName() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): McpServerToolCallStep = - McpServerToolCallStep( - checkRequired("id", id), - checkRequired("arguments", arguments), - checkRequired("name", name), - checkRequired("serverName", serverName), - type, - signature, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): McpServerToolCallStep = apply { - if (validated) { - return@apply - } - - id() - arguments().validate() - name() - serverName() - _type().let { - if (it != JsonValue.from("mcp_server_tool_call")) { - throw GeminiNextGenApiInvalidDataException("'type' is invalid, received $it") - } - } - signature() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - (if (id.asKnown().isPresent) 1 else 0) + - (arguments.asKnown().getOrNull()?.validity() ?: 0) + - (if (name.asKnown().isPresent) 1 else 0) + - (if (serverName.asKnown().isPresent) 1 else 0) + - type.let { if (it == JsonValue.from("mcp_server_tool_call")) 1 else 0 } + - (if (signature.asKnown().isPresent) 1 else 0) - - /** Required. The JSON object of arguments for the function. */ - class Arguments - @JsonCreator - private constructor( - @com.fasterxml.jackson.annotation.JsonValue - private val additionalProperties: Map - ) { - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [Arguments]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Arguments]. */ - class Builder internal constructor() { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(arguments: Arguments) = apply { - additionalProperties = arguments.additionalProperties.toMutableMap() - } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [Arguments]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): Arguments = Arguments(additionalProperties.toImmutable()) - } - - private var validated: Boolean = false - - fun validate(): Arguments = apply { - if (validated) { - return@apply - } - - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Arguments && additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - - override fun hashCode(): Int = hashCode - - override fun toString() = "Arguments{additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is McpServerToolCallStep && - id == other.id && - arguments == other.arguments && - name == other.name && - serverName == other.serverName && - type == other.type && - signature == other.signature && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { - Objects.hash(id, arguments, name, serverName, type, signature, additionalProperties) - } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "McpServerToolCallStep{id=$id, arguments=$arguments, name=$name, serverName=$serverName, type=$type, signature=$signature, additionalProperties=$additionalProperties}" -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/McpServerToolResultStep.kt b/src/main/java/com/google/genai/interactions/models/interactions/McpServerToolResultStep.kt deleted file mode 100644 index 81da5319e81..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/McpServerToolResultStep.kt +++ /dev/null @@ -1,791 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import com.fasterxml.jackson.core.JsonGenerator -import com.fasterxml.jackson.core.ObjectCodec -import com.fasterxml.jackson.databind.JsonNode -import com.fasterxml.jackson.databind.SerializerProvider -import com.fasterxml.jackson.databind.annotation.JsonDeserialize -import com.fasterxml.jackson.databind.annotation.JsonSerialize -import com.fasterxml.jackson.module.kotlin.jacksonTypeRef -import com.google.genai.interactions.core.BaseDeserializer -import com.google.genai.interactions.core.BaseSerializer -import com.google.genai.interactions.core.ExcludeMissing -import com.google.genai.interactions.core.JsonField -import com.google.genai.interactions.core.JsonMissing -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.core.allMaxBy -import com.google.genai.interactions.core.checkRequired -import com.google.genai.interactions.core.getOrThrow -import com.google.genai.interactions.core.toImmutable -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.util.Collections -import java.util.Objects -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -/** MCPServer tool result step. */ -class McpServerToolResultStep -@JsonCreator(mode = JsonCreator.Mode.DISABLED) -private constructor( - private val callId: JsonField, - private val result: JsonField, - private val type: JsonValue, - private val name: JsonField, - private val serverName: JsonField, - private val signature: JsonField, - private val additionalProperties: MutableMap, -) { - - @JsonCreator - private constructor( - @JsonProperty("call_id") @ExcludeMissing callId: JsonField = JsonMissing.of(), - @JsonProperty("result") @ExcludeMissing result: JsonField = JsonMissing.of(), - @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), - @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), - @JsonProperty("server_name") - @ExcludeMissing - serverName: JsonField = JsonMissing.of(), - @JsonProperty("signature") @ExcludeMissing signature: JsonField = JsonMissing.of(), - ) : this(callId, result, type, name, serverName, signature, mutableMapOf()) - - /** - * Required. ID to match the ID from the function call block. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). - */ - fun callId(): String = callId.getRequired("call_id") - - /** - * The output from the MCP server call. Can be simple text or rich content. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). - */ - fun result(): Result = result.getRequired("result") - - /** - * Expected to always return the following: - * ```java - * JsonValue.from("mcp_server_tool_result") - * ``` - * - * However, this method can be useful for debugging and logging (e.g. if the server responded - * with an unexpected value). - */ - @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type - - /** - * Name of the tool which is called for this specific tool call. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun name(): Optional = name.getOptional("name") - - /** - * The name of the used MCP server. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun serverName(): Optional = serverName.getOptional("server_name") - - /** - * A signature hash for backend validation. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun signature(): Optional = signature.getOptional("signature") - - /** - * Returns the raw JSON value of [callId]. - * - * Unlike [callId], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("call_id") @ExcludeMissing fun _callId(): JsonField = callId - - /** - * Returns the raw JSON value of [result]. - * - * Unlike [result], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("result") @ExcludeMissing fun _result(): JsonField = result - - /** - * Returns the raw JSON value of [name]. - * - * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name - - /** - * Returns the raw JSON value of [serverName]. - * - * Unlike [serverName], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("server_name") @ExcludeMissing fun _serverName(): JsonField = serverName - - /** - * Returns the raw JSON value of [signature]. - * - * Unlike [signature], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("signature") @ExcludeMissing fun _signature(): JsonField = signature - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [McpServerToolResultStep]. - * - * The following fields are required: - * ```java - * .callId() - * .result() - * ``` - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [McpServerToolResultStep]. */ - class Builder internal constructor() { - - private var callId: JsonField? = null - private var result: JsonField? = null - private var type: JsonValue = JsonValue.from("mcp_server_tool_result") - private var name: JsonField = JsonMissing.of() - private var serverName: JsonField = JsonMissing.of() - private var signature: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(mcpServerToolResultStep: McpServerToolResultStep) = apply { - callId = mcpServerToolResultStep.callId - result = mcpServerToolResultStep.result - type = mcpServerToolResultStep.type - name = mcpServerToolResultStep.name - serverName = mcpServerToolResultStep.serverName - signature = mcpServerToolResultStep.signature - additionalProperties = mcpServerToolResultStep.additionalProperties.toMutableMap() - } - - /** Required. ID to match the ID from the function call block. */ - fun callId(callId: String) = callId(JsonField.of(callId)) - - /** - * Sets [Builder.callId] to an arbitrary JSON value. - * - * You should usually call [Builder.callId] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun callId(callId: JsonField) = apply { this.callId = callId } - - /** The output from the MCP server call. Can be simple text or rich content. */ - fun result(result: Result) = result(JsonField.of(result)) - - /** - * Sets [Builder.result] to an arbitrary JSON value. - * - * You should usually call [Builder.result] with a well-typed [Result] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun result(result: JsonField) = apply { this.result = result } - - /** Alias for calling [result] with `Result.ofJsonValue(jsonValue)`. */ - fun result(jsonValue: JsonValue) = result(Result.ofJsonValue(jsonValue)) - - /** Alias for calling [result] with `Result.ofString(string)`. */ - fun result(string: String) = result(Result.ofString(string)) - - /** - * Alias for calling [result] with - * `Result.ofFunctionResultSubcontentList(functionResultSubcontentList)`. - */ - fun resultOfFunctionResultSubcontentList( - functionResultSubcontentList: List - ) = result(Result.ofFunctionResultSubcontentList(functionResultSubcontentList)) - - /** - * Sets the field to an arbitrary JSON value. - * - * It is usually unnecessary to call this method because the field defaults to the - * following: - * ```java - * JsonValue.from("mcp_server_tool_result") - * ``` - * - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun type(type: JsonValue) = apply { this.type = type } - - /** Name of the tool which is called for this specific tool call. */ - fun name(name: String) = name(JsonField.of(name)) - - /** - * Sets [Builder.name] to an arbitrary JSON value. - * - * You should usually call [Builder.name] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun name(name: JsonField) = apply { this.name = name } - - /** The name of the used MCP server. */ - fun serverName(serverName: String) = serverName(JsonField.of(serverName)) - - /** - * Sets [Builder.serverName] to an arbitrary JSON value. - * - * You should usually call [Builder.serverName] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun serverName(serverName: JsonField) = apply { this.serverName = serverName } - - /** A signature hash for backend validation. */ - fun signature(signature: String) = signature(JsonField.of(signature)) - - /** - * Sets [Builder.signature] to an arbitrary JSON value. - * - * You should usually call [Builder.signature] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun signature(signature: JsonField) = apply { this.signature = signature } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [McpServerToolResultStep]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .callId() - * .result() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): McpServerToolResultStep = - McpServerToolResultStep( - checkRequired("callId", callId), - checkRequired("result", result), - type, - name, - serverName, - signature, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): McpServerToolResultStep = apply { - if (validated) { - return@apply - } - - callId() - result().validate() - _type().let { - if (it != JsonValue.from("mcp_server_tool_result")) { - throw GeminiNextGenApiInvalidDataException("'type' is invalid, received $it") - } - } - name() - serverName() - signature() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - (if (callId.asKnown().isPresent) 1 else 0) + - (result.asKnown().getOrNull()?.validity() ?: 0) + - type.let { if (it == JsonValue.from("mcp_server_tool_result")) 1 else 0 } + - (if (name.asKnown().isPresent) 1 else 0) + - (if (serverName.asKnown().isPresent) 1 else 0) + - (if (signature.asKnown().isPresent) 1 else 0) - - /** The output from the MCP server call. Can be simple text or rich content. */ - @JsonDeserialize(using = Result.Deserializer::class) - @JsonSerialize(using = Result.Serializer::class) - class Result - private constructor( - private val jsonValue: JsonValue? = null, - private val string: String? = null, - private val functionResultSubcontentList: List? = null, - private val _json: JsonValue? = null, - ) { - - fun jsonValue(): Optional = Optional.ofNullable(jsonValue) - - fun string(): Optional = Optional.ofNullable(string) - - fun functionResultSubcontentList(): Optional> = - Optional.ofNullable(functionResultSubcontentList) - - fun isJsonValue(): Boolean = jsonValue != null - - fun isString(): Boolean = string != null - - fun isFunctionResultSubcontentList(): Boolean = functionResultSubcontentList != null - - fun asJsonValue(): JsonValue = jsonValue.getOrThrow("jsonValue") - - fun asString(): String = string.getOrThrow("string") - - fun asFunctionResultSubcontentList(): List = - functionResultSubcontentList.getOrThrow("functionResultSubcontentList") - - fun _json(): Optional = Optional.ofNullable(_json) - - fun accept(visitor: Visitor): T = - when { - jsonValue != null -> visitor.visitJsonValue(jsonValue) - string != null -> visitor.visitString(string) - functionResultSubcontentList != null -> - visitor.visitFunctionResultSubcontentList(functionResultSubcontentList) - else -> visitor.unknown(_json) - } - - private var validated: Boolean = false - - fun validate(): Result = apply { - if (validated) { - return@apply - } - - accept( - object : Visitor { - override fun visitJsonValue(jsonValue: JsonValue) {} - - override fun visitString(string: String) {} - - override fun visitFunctionResultSubcontentList( - functionResultSubcontentList: List - ) { - functionResultSubcontentList.forEach { it.validate() } - } - } - ) - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - accept( - object : Visitor { - override fun visitJsonValue(jsonValue: JsonValue) = 1 - - override fun visitString(string: String) = 1 - - override fun visitFunctionResultSubcontentList( - functionResultSubcontentList: List - ) = functionResultSubcontentList.sumOf { it.validity().toInt() } - - override fun unknown(json: JsonValue?) = 0 - } - ) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Result && - jsonValue == other.jsonValue && - string == other.string && - functionResultSubcontentList == other.functionResultSubcontentList - } - - override fun hashCode(): Int = Objects.hash(jsonValue, string, functionResultSubcontentList) - - override fun toString(): String = - when { - jsonValue != null -> "Result{jsonValue=$jsonValue}" - string != null -> "Result{string=$string}" - functionResultSubcontentList != null -> - "Result{functionResultSubcontentList=$functionResultSubcontentList}" - _json != null -> "Result{_unknown=$_json}" - else -> throw IllegalStateException("Invalid Result") - } - - companion object { - - @JvmStatic fun ofJsonValue(jsonValue: JsonValue) = Result(jsonValue = jsonValue) - - @JvmStatic fun ofString(string: String) = Result(string = string) - - @JvmStatic - fun ofFunctionResultSubcontentList( - functionResultSubcontentList: List - ) = Result(functionResultSubcontentList = functionResultSubcontentList.toImmutable()) - } - - /** An interface that defines how to map each variant of [Result] to a value of type [T]. */ - interface Visitor { - - fun visitJsonValue(jsonValue: JsonValue): T - - fun visitString(string: String): T - - fun visitFunctionResultSubcontentList( - functionResultSubcontentList: List - ): T - - /** - * Maps an unknown variant of [Result] to a value of type [T]. - * - * An instance of [Result] can contain an unknown variant if it was deserialized from - * data that doesn't match any known variant. For example, if the SDK is on an older - * version than the API, then the API may respond with new variants that the SDK is - * unaware of. - * - * @throws GeminiNextGenApiInvalidDataException in the default implementation. - */ - fun unknown(json: JsonValue?): T { - throw GeminiNextGenApiInvalidDataException("Unknown Result: $json") - } - } - - internal class Deserializer : BaseDeserializer(Result::class) { - - override fun ObjectCodec.deserialize(node: JsonNode): Result { - val json = JsonValue.fromJsonNode(node) - - val bestMatches = - sequenceOf( - tryDeserialize(node, jacksonTypeRef())?.let { - Result(string = it, _json = json) - }, - tryDeserialize(node, jacksonTypeRef>()) - ?.let { Result(functionResultSubcontentList = it, _json = json) }, - tryDeserialize(node, jacksonTypeRef())?.let { - Result(jsonValue = it, _json = json) - }, - ) - .filterNotNull() - .allMaxBy { it.validity() } - .toList() - return when (bestMatches.size) { - // This can happen if what we're deserializing is completely incompatible with - // all the possible variants. - 0 -> Result(_json = json) - 1 -> bestMatches.single() - // If there's more than one match with the highest validity, then use the first - // completely valid match, or simply the first match if none are completely - // valid. - else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() - } - } - } - - internal class Serializer : BaseSerializer(Result::class) { - - override fun serialize( - value: Result, - generator: JsonGenerator, - provider: SerializerProvider, - ) { - when { - value.jsonValue != null -> generator.writeObject(value.jsonValue) - value.string != null -> generator.writeObject(value.string) - value.functionResultSubcontentList != null -> - generator.writeObject(value.functionResultSubcontentList) - value._json != null -> generator.writeObject(value._json) - else -> throw IllegalStateException("Invalid Result") - } - } - } - - /** A text content block. */ - @JsonDeserialize(using = FunctionResultSubcontent.Deserializer::class) - @JsonSerialize(using = FunctionResultSubcontent.Serializer::class) - class FunctionResultSubcontent - private constructor( - private val text: TextContent? = null, - private val image: ImageContent? = null, - private val _json: JsonValue? = null, - ) { - - /** A text content block. */ - fun text(): Optional = Optional.ofNullable(text) - - /** An image content block. */ - fun image(): Optional = Optional.ofNullable(image) - - fun isText(): Boolean = text != null - - fun isImage(): Boolean = image != null - - /** A text content block. */ - fun asText(): TextContent = text.getOrThrow("text") - - /** An image content block. */ - fun asImage(): ImageContent = image.getOrThrow("image") - - fun _json(): Optional = Optional.ofNullable(_json) - - fun accept(visitor: Visitor): T = - when { - text != null -> visitor.visitText(text) - image != null -> visitor.visitImage(image) - else -> visitor.unknown(_json) - } - - private var validated: Boolean = false - - fun validate(): FunctionResultSubcontent = apply { - if (validated) { - return@apply - } - - accept( - object : Visitor { - override fun visitText(text: TextContent) { - text.validate() - } - - override fun visitImage(image: ImageContent) { - image.validate() - } - } - ) - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - accept( - object : Visitor { - override fun visitText(text: TextContent) = text.validity() - - override fun visitImage(image: ImageContent) = image.validity() - - override fun unknown(json: JsonValue?) = 0 - } - ) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is FunctionResultSubcontent && - text == other.text && - image == other.image - } - - override fun hashCode(): Int = Objects.hash(text, image) - - override fun toString(): String = - when { - text != null -> "FunctionResultSubcontent{text=$text}" - image != null -> "FunctionResultSubcontent{image=$image}" - _json != null -> "FunctionResultSubcontent{_unknown=$_json}" - else -> throw IllegalStateException("Invalid FunctionResultSubcontent") - } - - companion object { - - /** A text content block. */ - @JvmStatic fun ofText(text: TextContent) = FunctionResultSubcontent(text = text) - - /** An image content block. */ - @JvmStatic - fun ofImage(image: ImageContent) = FunctionResultSubcontent(image = image) - } - - /** - * An interface that defines how to map each variant of [FunctionResultSubcontent] to a - * value of type [T]. - */ - interface Visitor { - - /** A text content block. */ - fun visitText(text: TextContent): T - - /** An image content block. */ - fun visitImage(image: ImageContent): T - - /** - * Maps an unknown variant of [FunctionResultSubcontent] to a value of type [T]. - * - * An instance of [FunctionResultSubcontent] can contain an unknown variant if it - * was deserialized from data that doesn't match any known variant. For example, if - * the SDK is on an older version than the API, then the API may respond with new - * variants that the SDK is unaware of. - * - * @throws GeminiNextGenApiInvalidDataException in the default implementation. - */ - fun unknown(json: JsonValue?): T { - throw GeminiNextGenApiInvalidDataException( - "Unknown FunctionResultSubcontent: $json" - ) - } - } - - internal class Deserializer : - BaseDeserializer(FunctionResultSubcontent::class) { - - override fun ObjectCodec.deserialize(node: JsonNode): FunctionResultSubcontent { - val json = JsonValue.fromJsonNode(node) - val type = json.asObject().getOrNull()?.get("type")?.asString()?.getOrNull() - - when (type) { - "text" -> { - return tryDeserialize(node, jacksonTypeRef())?.let { - FunctionResultSubcontent(text = it, _json = json) - } ?: FunctionResultSubcontent(_json = json) - } - "image" -> { - return tryDeserialize(node, jacksonTypeRef())?.let { - FunctionResultSubcontent(image = it, _json = json) - } ?: FunctionResultSubcontent(_json = json) - } - } - - return FunctionResultSubcontent(_json = json) - } - } - - internal class Serializer : - BaseSerializer(FunctionResultSubcontent::class) { - - override fun serialize( - value: FunctionResultSubcontent, - generator: JsonGenerator, - provider: SerializerProvider, - ) { - when { - value.text != null -> generator.writeObject(value.text) - value.image != null -> generator.writeObject(value.image) - value._json != null -> generator.writeObject(value._json) - else -> throw IllegalStateException("Invalid FunctionResultSubcontent") - } - } - } - } - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is McpServerToolResultStep && - callId == other.callId && - result == other.result && - type == other.type && - name == other.name && - serverName == other.serverName && - signature == other.signature && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { - Objects.hash(callId, result, type, name, serverName, signature, additionalProperties) - } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "McpServerToolResultStep{callId=$callId, result=$result, type=$type, name=$name, serverName=$serverName, signature=$signature, additionalProperties=$additionalProperties}" -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/Model.kt b/src/main/java/com/google/genai/interactions/models/interactions/Model.kt deleted file mode 100644 index 5f4aa864ca8..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/Model.kt +++ /dev/null @@ -1,489 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.annotation.JsonCreator -import com.google.genai.interactions.core.Enum -import com.google.genai.interactions.core.JsonField -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException - -/** - * The model that will complete your prompt.\n\nSee - * [models](https://ai.google.dev/gemini-api/docs/models) for additional details. - */ -class Model @JsonCreator private constructor(private val value: JsonField) : Enum { - - /** - * Returns this class instance's raw value. - * - * This is usually only useful if this instance was deserialized from data that doesn't match - * any known member, and you want to know that value. For example, if the SDK is on an older - * version than the API, then the API may respond with new members that the SDK is unaware of. - */ - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - companion object { - - /** - * An agentic capability model designed for direct interface interaction, allowing Gemini to - * perceive and navigate digital environments. - */ - @JvmField - val GEMINI_2_5_COMPUTER_USE_PREVIEW_10_2025 = of("gemini-2.5-computer-use-preview-10-2025") - - /** - * Our first hybrid reasoning model which supports a 1M token context window and has - * thinking budgets. - */ - @JvmField val GEMINI_2_5_FLASH = of("gemini-2.5-flash") - - /** - * Our native image generation model, optimized for speed, flexibility, and contextual - * understanding. Text input and output is priced the same as 2.5 Flash. - */ - @JvmField val GEMINI_2_5_FLASH_IMAGE = of("gemini-2.5-flash-image") - - /** Our smallest and most cost effective model, built for at scale usage. */ - @JvmField val GEMINI_2_5_FLASH_LITE = of("gemini-2.5-flash-lite") - - /** - * The latest model based on Gemini 2.5 Flash lite optimized for cost-efficiency, high - * throughput and high quality. - */ - @JvmField - val GEMINI_2_5_FLASH_LITE_PREVIEW_09_2025 = of("gemini-2.5-flash-lite-preview-09-2025") - - /** - * Our native audio models optimized for higher quality audio outputs with better pacing, - * voice naturalness, verbosity, and mood. - */ - @JvmField - val GEMINI_2_5_FLASH_NATIVE_AUDIO_PREVIEW_12_2025 = - of("gemini-2.5-flash-native-audio-preview-12-2025") - - /** - * The latest model based on the 2.5 Flash model. 2.5 Flash Preview is best for large scale - * processing, low-latency, high volume tasks that require thinking, and agentic use cases. - */ - @JvmField val GEMINI_2_5_FLASH_PREVIEW_09_2025 = of("gemini-2.5-flash-preview-09-2025") - - /** - * Our 2.5 Flash text-to-speech model optimized for powerful, low-latency controllable - * speech generation. - */ - @JvmField val GEMINI_2_5_FLASH_PREVIEW_TTS = of("gemini-2.5-flash-preview-tts") - - /** - * Our state-of-the-art multipurpose model, which excels at coding and complex reasoning - * tasks. - */ - @JvmField val GEMINI_2_5_PRO = of("gemini-2.5-pro") - - /** - * Our 2.5 Pro text-to-speech audio model optimized for powerful, low-latency speech - * generation for more natural outputs and easier to steer prompts. - */ - @JvmField val GEMINI_2_5_PRO_PREVIEW_TTS = of("gemini-2.5-pro-preview-tts") - - /** - * Our most intelligent model built for speed, combining frontier intelligence with superior - * search and grounding. - */ - @JvmField val GEMINI_3_FLASH_PREVIEW = of("gemini-3-flash-preview") - - /** State-of-the-art image generation and editing model. */ - @JvmField val GEMINI_3_PRO_IMAGE_PREVIEW = of("gemini-3-pro-image-preview") - - /** - * Our most intelligent model with SOTA reasoning and multimodal understanding, and powerful - * agentic and vibe coding capabilities. - */ - @JvmField val GEMINI_3_PRO_PREVIEW = of("gemini-3-pro-preview") - - /** - * Our latest SOTA reasoning model with unprecedented depth and nuance, and powerful - * multimodal understanding and coding capabilities. - */ - @JvmField val GEMINI_3_1_PRO_PREVIEW = of("gemini-3.1-pro-preview") - - /** - * Pro-level visual intelligence with Flash-speed efficiency and reality-grounded generation - * capabilities. - */ - @JvmField val GEMINI_3_1_FLASH_IMAGE_PREVIEW = of("gemini-3.1-flash-image-preview") - - /** - * Our most cost-efficient model, optimized for high-volume agentic tasks, translation, and - * simple data processing. - */ - @JvmField val GEMINI_3_1_FLASH_LITE = of("gemini-3.1-flash-lite") - - /** - * Our most cost-efficient model, optimized for high-volume agentic tasks, translation, and - * simple data processing. - */ - @JvmField val GEMINI_3_1_FLASH_LITE_PREVIEW = of("gemini-3.1-flash-lite-preview") - - /** - * Gemini 3.1 Flash TTS: Powerful, low-latency speech generation. Enjoy natural outputs, - * steerable prompts, and new expressive audio tags for precise narration control. - */ - @JvmField val GEMINI_3_1_FLASH_TTS_PREVIEW = of("gemini-3.1-flash-tts-preview") - - /** - * Our low-latency, music generation model optimized for high-fidelity audio clips and - * precise rhythmic control. - */ - @JvmField val LYRIA_3_CLIP_PREVIEW = of("lyria-3-clip-preview") - - /** - * Our advanced, full-song generative model with deep compositional understanding, optimized - * for precise structural control and complex transitions across diverse musical styles. - */ - @JvmField val LYRIA_3_PRO_PREVIEW = of("lyria-3-pro-preview") - - @JvmStatic fun of(value: String) = Model(JsonField.of(value)) - } - - /** An enum containing [Model]'s known values. */ - enum class Known { - /** - * An agentic capability model designed for direct interface interaction, allowing Gemini to - * perceive and navigate digital environments. - */ - GEMINI_2_5_COMPUTER_USE_PREVIEW_10_2025, - /** - * Our first hybrid reasoning model which supports a 1M token context window and has - * thinking budgets. - */ - GEMINI_2_5_FLASH, - /** - * Our native image generation model, optimized for speed, flexibility, and contextual - * understanding. Text input and output is priced the same as 2.5 Flash. - */ - GEMINI_2_5_FLASH_IMAGE, - /** Our smallest and most cost effective model, built for at scale usage. */ - GEMINI_2_5_FLASH_LITE, - /** - * The latest model based on Gemini 2.5 Flash lite optimized for cost-efficiency, high - * throughput and high quality. - */ - GEMINI_2_5_FLASH_LITE_PREVIEW_09_2025, - /** - * Our native audio models optimized for higher quality audio outputs with better pacing, - * voice naturalness, verbosity, and mood. - */ - GEMINI_2_5_FLASH_NATIVE_AUDIO_PREVIEW_12_2025, - /** - * The latest model based on the 2.5 Flash model. 2.5 Flash Preview is best for large scale - * processing, low-latency, high volume tasks that require thinking, and agentic use cases. - */ - GEMINI_2_5_FLASH_PREVIEW_09_2025, - /** - * Our 2.5 Flash text-to-speech model optimized for powerful, low-latency controllable - * speech generation. - */ - GEMINI_2_5_FLASH_PREVIEW_TTS, - /** - * Our state-of-the-art multipurpose model, which excels at coding and complex reasoning - * tasks. - */ - GEMINI_2_5_PRO, - /** - * Our 2.5 Pro text-to-speech audio model optimized for powerful, low-latency speech - * generation for more natural outputs and easier to steer prompts. - */ - GEMINI_2_5_PRO_PREVIEW_TTS, - /** - * Our most intelligent model built for speed, combining frontier intelligence with superior - * search and grounding. - */ - GEMINI_3_FLASH_PREVIEW, - /** State-of-the-art image generation and editing model. */ - GEMINI_3_PRO_IMAGE_PREVIEW, - /** - * Our most intelligent model with SOTA reasoning and multimodal understanding, and powerful - * agentic and vibe coding capabilities. - */ - GEMINI_3_PRO_PREVIEW, - /** - * Our latest SOTA reasoning model with unprecedented depth and nuance, and powerful - * multimodal understanding and coding capabilities. - */ - GEMINI_3_1_PRO_PREVIEW, - /** - * Pro-level visual intelligence with Flash-speed efficiency and reality-grounded generation - * capabilities. - */ - GEMINI_3_1_FLASH_IMAGE_PREVIEW, - /** - * Our most cost-efficient model, optimized for high-volume agentic tasks, translation, and - * simple data processing. - */ - GEMINI_3_1_FLASH_LITE, - /** - * Our most cost-efficient model, optimized for high-volume agentic tasks, translation, and - * simple data processing. - */ - GEMINI_3_1_FLASH_LITE_PREVIEW, - /** - * Gemini 3.1 Flash TTS: Powerful, low-latency speech generation. Enjoy natural outputs, - * steerable prompts, and new expressive audio tags for precise narration control. - */ - GEMINI_3_1_FLASH_TTS_PREVIEW, - /** - * Our low-latency, music generation model optimized for high-fidelity audio clips and - * precise rhythmic control. - */ - LYRIA_3_CLIP_PREVIEW, - /** - * Our advanced, full-song generative model with deep compositional understanding, optimized - * for precise structural control and complex transitions across diverse musical styles. - */ - LYRIA_3_PRO_PREVIEW, - } - - /** - * An enum containing [Model]'s known values, as well as an [_UNKNOWN] member. - * - * An instance of [Model] can contain an unknown value in a couple of cases: - * - It was deserialized from data that doesn't match any known member. For example, if the SDK - * is on an older version than the API, then the API may respond with new members that the SDK - * is unaware of. - * - It was constructed with an arbitrary value using the [of] method. - */ - enum class Value { - /** - * An agentic capability model designed for direct interface interaction, allowing Gemini to - * perceive and navigate digital environments. - */ - GEMINI_2_5_COMPUTER_USE_PREVIEW_10_2025, - /** - * Our first hybrid reasoning model which supports a 1M token context window and has - * thinking budgets. - */ - GEMINI_2_5_FLASH, - /** - * Our native image generation model, optimized for speed, flexibility, and contextual - * understanding. Text input and output is priced the same as 2.5 Flash. - */ - GEMINI_2_5_FLASH_IMAGE, - /** Our smallest and most cost effective model, built for at scale usage. */ - GEMINI_2_5_FLASH_LITE, - /** - * The latest model based on Gemini 2.5 Flash lite optimized for cost-efficiency, high - * throughput and high quality. - */ - GEMINI_2_5_FLASH_LITE_PREVIEW_09_2025, - /** - * Our native audio models optimized for higher quality audio outputs with better pacing, - * voice naturalness, verbosity, and mood. - */ - GEMINI_2_5_FLASH_NATIVE_AUDIO_PREVIEW_12_2025, - /** - * The latest model based on the 2.5 Flash model. 2.5 Flash Preview is best for large scale - * processing, low-latency, high volume tasks that require thinking, and agentic use cases. - */ - GEMINI_2_5_FLASH_PREVIEW_09_2025, - /** - * Our 2.5 Flash text-to-speech model optimized for powerful, low-latency controllable - * speech generation. - */ - GEMINI_2_5_FLASH_PREVIEW_TTS, - /** - * Our state-of-the-art multipurpose model, which excels at coding and complex reasoning - * tasks. - */ - GEMINI_2_5_PRO, - /** - * Our 2.5 Pro text-to-speech audio model optimized for powerful, low-latency speech - * generation for more natural outputs and easier to steer prompts. - */ - GEMINI_2_5_PRO_PREVIEW_TTS, - /** - * Our most intelligent model built for speed, combining frontier intelligence with superior - * search and grounding. - */ - GEMINI_3_FLASH_PREVIEW, - /** State-of-the-art image generation and editing model. */ - GEMINI_3_PRO_IMAGE_PREVIEW, - /** - * Our most intelligent model with SOTA reasoning and multimodal understanding, and powerful - * agentic and vibe coding capabilities. - */ - GEMINI_3_PRO_PREVIEW, - /** - * Our latest SOTA reasoning model with unprecedented depth and nuance, and powerful - * multimodal understanding and coding capabilities. - */ - GEMINI_3_1_PRO_PREVIEW, - /** - * Pro-level visual intelligence with Flash-speed efficiency and reality-grounded generation - * capabilities. - */ - GEMINI_3_1_FLASH_IMAGE_PREVIEW, - /** - * Our most cost-efficient model, optimized for high-volume agentic tasks, translation, and - * simple data processing. - */ - GEMINI_3_1_FLASH_LITE, - /** - * Our most cost-efficient model, optimized for high-volume agentic tasks, translation, and - * simple data processing. - */ - GEMINI_3_1_FLASH_LITE_PREVIEW, - /** - * Gemini 3.1 Flash TTS: Powerful, low-latency speech generation. Enjoy natural outputs, - * steerable prompts, and new expressive audio tags for precise narration control. - */ - GEMINI_3_1_FLASH_TTS_PREVIEW, - /** - * Our low-latency, music generation model optimized for high-fidelity audio clips and - * precise rhythmic control. - */ - LYRIA_3_CLIP_PREVIEW, - /** - * Our advanced, full-song generative model with deep compositional understanding, optimized - * for precise structural control and complex transitions across diverse musical styles. - */ - LYRIA_3_PRO_PREVIEW, - /** An enum member indicating that [Model] was instantiated with an unknown value. */ - _UNKNOWN, - } - - /** - * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] if - * the class was instantiated with an unknown value. - * - * Use the [known] method instead if you're certain the value is always known or if you want to - * throw for the unknown case. - */ - fun value(): Value = - when (this) { - GEMINI_2_5_COMPUTER_USE_PREVIEW_10_2025 -> Value.GEMINI_2_5_COMPUTER_USE_PREVIEW_10_2025 - GEMINI_2_5_FLASH -> Value.GEMINI_2_5_FLASH - GEMINI_2_5_FLASH_IMAGE -> Value.GEMINI_2_5_FLASH_IMAGE - GEMINI_2_5_FLASH_LITE -> Value.GEMINI_2_5_FLASH_LITE - GEMINI_2_5_FLASH_LITE_PREVIEW_09_2025 -> Value.GEMINI_2_5_FLASH_LITE_PREVIEW_09_2025 - GEMINI_2_5_FLASH_NATIVE_AUDIO_PREVIEW_12_2025 -> - Value.GEMINI_2_5_FLASH_NATIVE_AUDIO_PREVIEW_12_2025 - GEMINI_2_5_FLASH_PREVIEW_09_2025 -> Value.GEMINI_2_5_FLASH_PREVIEW_09_2025 - GEMINI_2_5_FLASH_PREVIEW_TTS -> Value.GEMINI_2_5_FLASH_PREVIEW_TTS - GEMINI_2_5_PRO -> Value.GEMINI_2_5_PRO - GEMINI_2_5_PRO_PREVIEW_TTS -> Value.GEMINI_2_5_PRO_PREVIEW_TTS - GEMINI_3_FLASH_PREVIEW -> Value.GEMINI_3_FLASH_PREVIEW - GEMINI_3_PRO_IMAGE_PREVIEW -> Value.GEMINI_3_PRO_IMAGE_PREVIEW - GEMINI_3_PRO_PREVIEW -> Value.GEMINI_3_PRO_PREVIEW - GEMINI_3_1_PRO_PREVIEW -> Value.GEMINI_3_1_PRO_PREVIEW - GEMINI_3_1_FLASH_IMAGE_PREVIEW -> Value.GEMINI_3_1_FLASH_IMAGE_PREVIEW - GEMINI_3_1_FLASH_LITE -> Value.GEMINI_3_1_FLASH_LITE - GEMINI_3_1_FLASH_LITE_PREVIEW -> Value.GEMINI_3_1_FLASH_LITE_PREVIEW - GEMINI_3_1_FLASH_TTS_PREVIEW -> Value.GEMINI_3_1_FLASH_TTS_PREVIEW - LYRIA_3_CLIP_PREVIEW -> Value.LYRIA_3_CLIP_PREVIEW - LYRIA_3_PRO_PREVIEW -> Value.LYRIA_3_PRO_PREVIEW - else -> Value._UNKNOWN - } - - /** - * Returns an enum member corresponding to this class instance's value. - * - * Use the [value] method instead if you're uncertain the value is always known and don't want - * to throw for the unknown case. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value is a not a known - * member. - */ - fun known(): Known = - when (this) { - GEMINI_2_5_COMPUTER_USE_PREVIEW_10_2025 -> Known.GEMINI_2_5_COMPUTER_USE_PREVIEW_10_2025 - GEMINI_2_5_FLASH -> Known.GEMINI_2_5_FLASH - GEMINI_2_5_FLASH_IMAGE -> Known.GEMINI_2_5_FLASH_IMAGE - GEMINI_2_5_FLASH_LITE -> Known.GEMINI_2_5_FLASH_LITE - GEMINI_2_5_FLASH_LITE_PREVIEW_09_2025 -> Known.GEMINI_2_5_FLASH_LITE_PREVIEW_09_2025 - GEMINI_2_5_FLASH_NATIVE_AUDIO_PREVIEW_12_2025 -> - Known.GEMINI_2_5_FLASH_NATIVE_AUDIO_PREVIEW_12_2025 - GEMINI_2_5_FLASH_PREVIEW_09_2025 -> Known.GEMINI_2_5_FLASH_PREVIEW_09_2025 - GEMINI_2_5_FLASH_PREVIEW_TTS -> Known.GEMINI_2_5_FLASH_PREVIEW_TTS - GEMINI_2_5_PRO -> Known.GEMINI_2_5_PRO - GEMINI_2_5_PRO_PREVIEW_TTS -> Known.GEMINI_2_5_PRO_PREVIEW_TTS - GEMINI_3_FLASH_PREVIEW -> Known.GEMINI_3_FLASH_PREVIEW - GEMINI_3_PRO_IMAGE_PREVIEW -> Known.GEMINI_3_PRO_IMAGE_PREVIEW - GEMINI_3_PRO_PREVIEW -> Known.GEMINI_3_PRO_PREVIEW - GEMINI_3_1_PRO_PREVIEW -> Known.GEMINI_3_1_PRO_PREVIEW - GEMINI_3_1_FLASH_IMAGE_PREVIEW -> Known.GEMINI_3_1_FLASH_IMAGE_PREVIEW - GEMINI_3_1_FLASH_LITE -> Known.GEMINI_3_1_FLASH_LITE - GEMINI_3_1_FLASH_LITE_PREVIEW -> Known.GEMINI_3_1_FLASH_LITE_PREVIEW - GEMINI_3_1_FLASH_TTS_PREVIEW -> Known.GEMINI_3_1_FLASH_TTS_PREVIEW - LYRIA_3_CLIP_PREVIEW -> Known.LYRIA_3_CLIP_PREVIEW - LYRIA_3_PRO_PREVIEW -> Known.LYRIA_3_PRO_PREVIEW - else -> throw GeminiNextGenApiInvalidDataException("Unknown Model: $value") - } - - /** - * Returns this class instance's primitive wire representation. - * - * This differs from the [toString] method because that method is primarily for debugging and - * generally doesn't throw. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value does not have the - * expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - GeminiNextGenApiInvalidDataException("Value is not a String") - } - - private var validated: Boolean = false - - fun validate(): Model = apply { - if (validated) { - return@apply - } - - known() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Model && value == other.value - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/ModelOutputStep.kt b/src/main/java/com/google/genai/interactions/models/interactions/ModelOutputStep.kt deleted file mode 100644 index af80efd5203..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/ModelOutputStep.kt +++ /dev/null @@ -1,257 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import com.google.genai.interactions.core.ExcludeMissing -import com.google.genai.interactions.core.JsonField -import com.google.genai.interactions.core.JsonMissing -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.core.checkKnown -import com.google.genai.interactions.core.toImmutable -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.util.Collections -import java.util.Objects -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -/** Output generated by the model. */ -class ModelOutputStep -@JsonCreator(mode = JsonCreator.Mode.DISABLED) -private constructor( - private val type: JsonValue, - private val content: JsonField>, - private val additionalProperties: MutableMap, -) { - - @JsonCreator - private constructor( - @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), - @JsonProperty("content") - @ExcludeMissing - content: JsonField> = JsonMissing.of(), - ) : this(type, content, mutableMapOf()) - - /** - * Expected to always return the following: - * ```java - * JsonValue.from("model_output") - * ``` - * - * However, this method can be useful for debugging and logging (e.g. if the server responded - * with an unexpected value). - */ - @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type - - /** - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun content(): Optional> = content.getOptional("content") - - /** - * Returns the raw JSON value of [content]. - * - * Unlike [content], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("content") @ExcludeMissing fun _content(): JsonField> = content - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [ModelOutputStep]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [ModelOutputStep]. */ - class Builder internal constructor() { - - private var type: JsonValue = JsonValue.from("model_output") - private var content: JsonField>? = null - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(modelOutputStep: ModelOutputStep) = apply { - type = modelOutputStep.type - content = modelOutputStep.content.map { it.toMutableList() } - additionalProperties = modelOutputStep.additionalProperties.toMutableMap() - } - - /** - * Sets the field to an arbitrary JSON value. - * - * It is usually unnecessary to call this method because the field defaults to the - * following: - * ```java - * JsonValue.from("model_output") - * ``` - * - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun type(type: JsonValue) = apply { this.type = type } - - fun content(content: List) = content(JsonField.of(content)) - - /** - * Sets [Builder.content] to an arbitrary JSON value. - * - * You should usually call [Builder.content] with a well-typed `List` value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun content(content: JsonField>) = apply { - this.content = content.map { it.toMutableList() } - } - - /** - * Adds a single [Content] to [Builder.content]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addContent(content: Content) = apply { - this.content = - (this.content ?: JsonField.of(mutableListOf())).also { - checkKnown("content", it).add(content) - } - } - - /** Alias for calling [addContent] with `Content.ofText(text)`. */ - fun addContent(text: TextContent) = addContent(Content.ofText(text)) - - /** - * Alias for calling [addContent] with the following: - * ```java - * TextContent.builder() - * .text(text) - * .build() - * ``` - */ - fun addTextContent(text: String) = addContent(TextContent.builder().text(text).build()) - - /** Alias for calling [addContent] with `Content.ofImage(image)`. */ - fun addContent(image: ImageContent) = addContent(Content.ofImage(image)) - - /** Alias for calling [addContent] with `Content.ofAudio(audio)`. */ - fun addContent(audio: AudioContent) = addContent(Content.ofAudio(audio)) - - /** Alias for calling [addContent] with `Content.ofDocument(document)`. */ - fun addContent(document: DocumentContent) = addContent(Content.ofDocument(document)) - - /** Alias for calling [addContent] with `Content.ofVideo(video)`. */ - fun addContent(video: VideoContent) = addContent(Content.ofVideo(video)) - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [ModelOutputStep]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): ModelOutputStep = - ModelOutputStep( - type, - (content ?: JsonMissing.of()).map { it.toImmutable() }, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): ModelOutputStep = apply { - if (validated) { - return@apply - } - - _type().let { - if (it != JsonValue.from("model_output")) { - throw GeminiNextGenApiInvalidDataException("'type' is invalid, received $it") - } - } - content().ifPresent { it.forEach { it.validate() } } - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - type.let { if (it == JsonValue.from("model_output")) 1 else 0 } + - (content.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is ModelOutputStep && - type == other.type && - content == other.content && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { Objects.hash(type, content, additionalProperties) } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "ModelOutputStep{type=$type, content=$content, additionalProperties=$additionalProperties}" -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/PlaceCitation.kt b/src/main/java/com/google/genai/interactions/models/interactions/PlaceCitation.kt deleted file mode 100644 index 7ba3d176eb1..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/PlaceCitation.kt +++ /dev/null @@ -1,650 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import com.google.genai.interactions.core.ExcludeMissing -import com.google.genai.interactions.core.JsonField -import com.google.genai.interactions.core.JsonMissing -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.core.checkKnown -import com.google.genai.interactions.core.toImmutable -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.util.Collections -import java.util.Objects -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -/** A place citation annotation. */ -class PlaceCitation -@JsonCreator(mode = JsonCreator.Mode.DISABLED) -private constructor( - private val type: JsonValue, - private val endIndex: JsonField, - private val name: JsonField, - private val placeId: JsonField, - private val reviewSnippets: JsonField>, - private val startIndex: JsonField, - private val url: JsonField, - private val additionalProperties: MutableMap, -) { - - @JsonCreator - private constructor( - @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), - @JsonProperty("end_index") @ExcludeMissing endIndex: JsonField = JsonMissing.of(), - @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), - @JsonProperty("place_id") @ExcludeMissing placeId: JsonField = JsonMissing.of(), - @JsonProperty("review_snippets") - @ExcludeMissing - reviewSnippets: JsonField> = JsonMissing.of(), - @JsonProperty("start_index") @ExcludeMissing startIndex: JsonField = JsonMissing.of(), - @JsonProperty("url") @ExcludeMissing url: JsonField = JsonMissing.of(), - ) : this(type, endIndex, name, placeId, reviewSnippets, startIndex, url, mutableMapOf()) - - /** - * Expected to always return the following: - * ```java - * JsonValue.from("place_citation") - * ``` - * - * However, this method can be useful for debugging and logging (e.g. if the server responded - * with an unexpected value). - */ - @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type - - /** - * End of the attributed segment, exclusive. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun endIndex(): Optional = endIndex.getOptional("end_index") - - /** - * Title of the place. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun name(): Optional = name.getOptional("name") - - /** - * The ID of the place, in `places/{place_id}` format. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun placeId(): Optional = placeId.getOptional("place_id") - - /** - * Snippets of reviews that are used to generate answers about the features of a given place in - * Google Maps. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun reviewSnippets(): Optional> = - reviewSnippets.getOptional("review_snippets") - - /** - * Start of segment of the response that is attributed to this source. - * - * Index indicates the start of the segment, measured in bytes. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun startIndex(): Optional = startIndex.getOptional("start_index") - - /** - * URI reference of the place. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun url(): Optional = url.getOptional("url") - - /** - * Returns the raw JSON value of [endIndex]. - * - * Unlike [endIndex], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("end_index") @ExcludeMissing fun _endIndex(): JsonField = endIndex - - /** - * Returns the raw JSON value of [name]. - * - * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name - - /** - * Returns the raw JSON value of [placeId]. - * - * Unlike [placeId], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("place_id") @ExcludeMissing fun _placeId(): JsonField = placeId - - /** - * Returns the raw JSON value of [reviewSnippets]. - * - * Unlike [reviewSnippets], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("review_snippets") - @ExcludeMissing - fun _reviewSnippets(): JsonField> = reviewSnippets - - /** - * Returns the raw JSON value of [startIndex]. - * - * Unlike [startIndex], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("start_index") @ExcludeMissing fun _startIndex(): JsonField = startIndex - - /** - * Returns the raw JSON value of [url]. - * - * Unlike [url], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("url") @ExcludeMissing fun _url(): JsonField = url - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [PlaceCitation]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [PlaceCitation]. */ - class Builder internal constructor() { - - private var type: JsonValue = JsonValue.from("place_citation") - private var endIndex: JsonField = JsonMissing.of() - private var name: JsonField = JsonMissing.of() - private var placeId: JsonField = JsonMissing.of() - private var reviewSnippets: JsonField>? = null - private var startIndex: JsonField = JsonMissing.of() - private var url: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(placeCitation: PlaceCitation) = apply { - type = placeCitation.type - endIndex = placeCitation.endIndex - name = placeCitation.name - placeId = placeCitation.placeId - reviewSnippets = placeCitation.reviewSnippets.map { it.toMutableList() } - startIndex = placeCitation.startIndex - url = placeCitation.url - additionalProperties = placeCitation.additionalProperties.toMutableMap() - } - - /** - * Sets the field to an arbitrary JSON value. - * - * It is usually unnecessary to call this method because the field defaults to the - * following: - * ```java - * JsonValue.from("place_citation") - * ``` - * - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun type(type: JsonValue) = apply { this.type = type } - - /** End of the attributed segment, exclusive. */ - fun endIndex(endIndex: Int) = endIndex(JsonField.of(endIndex)) - - /** - * Sets [Builder.endIndex] to an arbitrary JSON value. - * - * You should usually call [Builder.endIndex] with a well-typed [Int] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun endIndex(endIndex: JsonField) = apply { this.endIndex = endIndex } - - /** Title of the place. */ - fun name(name: String) = name(JsonField.of(name)) - - /** - * Sets [Builder.name] to an arbitrary JSON value. - * - * You should usually call [Builder.name] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun name(name: JsonField) = apply { this.name = name } - - /** The ID of the place, in `places/{place_id}` format. */ - fun placeId(placeId: String) = placeId(JsonField.of(placeId)) - - /** - * Sets [Builder.placeId] to an arbitrary JSON value. - * - * You should usually call [Builder.placeId] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun placeId(placeId: JsonField) = apply { this.placeId = placeId } - - /** - * Snippets of reviews that are used to generate answers about the features of a given place - * in Google Maps. - */ - fun reviewSnippets(reviewSnippets: List) = - reviewSnippets(JsonField.of(reviewSnippets)) - - /** - * Sets [Builder.reviewSnippets] to an arbitrary JSON value. - * - * You should usually call [Builder.reviewSnippets] with a well-typed `List` - * value instead. This method is primarily for setting the field to an undocumented or not - * yet supported value. - */ - fun reviewSnippets(reviewSnippets: JsonField>) = apply { - this.reviewSnippets = reviewSnippets.map { it.toMutableList() } - } - - /** - * Adds a single [ReviewSnippet] to [reviewSnippets]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addReviewSnippet(reviewSnippet: ReviewSnippet) = apply { - reviewSnippets = - (reviewSnippets ?: JsonField.of(mutableListOf())).also { - checkKnown("reviewSnippets", it).add(reviewSnippet) - } - } - - /** - * Start of segment of the response that is attributed to this source. - * - * Index indicates the start of the segment, measured in bytes. - */ - fun startIndex(startIndex: Int) = startIndex(JsonField.of(startIndex)) - - /** - * Sets [Builder.startIndex] to an arbitrary JSON value. - * - * You should usually call [Builder.startIndex] with a well-typed [Int] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun startIndex(startIndex: JsonField) = apply { this.startIndex = startIndex } - - /** URI reference of the place. */ - fun url(url: String) = url(JsonField.of(url)) - - /** - * Sets [Builder.url] to an arbitrary JSON value. - * - * You should usually call [Builder.url] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun url(url: JsonField) = apply { this.url = url } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [PlaceCitation]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): PlaceCitation = - PlaceCitation( - type, - endIndex, - name, - placeId, - (reviewSnippets ?: JsonMissing.of()).map { it.toImmutable() }, - startIndex, - url, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): PlaceCitation = apply { - if (validated) { - return@apply - } - - _type().let { - if (it != JsonValue.from("place_citation")) { - throw GeminiNextGenApiInvalidDataException("'type' is invalid, received $it") - } - } - endIndex() - name() - placeId() - reviewSnippets().ifPresent { it.forEach { it.validate() } } - startIndex() - url() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - type.let { if (it == JsonValue.from("place_citation")) 1 else 0 } + - (if (endIndex.asKnown().isPresent) 1 else 0) + - (if (name.asKnown().isPresent) 1 else 0) + - (if (placeId.asKnown().isPresent) 1 else 0) + - (reviewSnippets.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + - (if (startIndex.asKnown().isPresent) 1 else 0) + - (if (url.asKnown().isPresent) 1 else 0) - - /** - * Encapsulates a snippet of a user review that answers a question about the features of a - * specific place in Google Maps. - */ - class ReviewSnippet - @JsonCreator(mode = JsonCreator.Mode.DISABLED) - private constructor( - private val reviewId: JsonField, - private val title: JsonField, - private val url: JsonField, - private val additionalProperties: MutableMap, - ) { - - @JsonCreator - private constructor( - @JsonProperty("review_id") - @ExcludeMissing - reviewId: JsonField = JsonMissing.of(), - @JsonProperty("title") @ExcludeMissing title: JsonField = JsonMissing.of(), - @JsonProperty("url") @ExcludeMissing url: JsonField = JsonMissing.of(), - ) : this(reviewId, title, url, mutableMapOf()) - - /** - * The ID of the review snippet. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type - * (e.g. if the server responded with an unexpected value). - */ - fun reviewId(): Optional = reviewId.getOptional("review_id") - - /** - * Title of the review. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type - * (e.g. if the server responded with an unexpected value). - */ - fun title(): Optional = title.getOptional("title") - - /** - * A link that corresponds to the user review on Google Maps. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type - * (e.g. if the server responded with an unexpected value). - */ - fun url(): Optional = url.getOptional("url") - - /** - * Returns the raw JSON value of [reviewId]. - * - * Unlike [reviewId], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("review_id") @ExcludeMissing fun _reviewId(): JsonField = reviewId - - /** - * Returns the raw JSON value of [title]. - * - * Unlike [title], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("title") @ExcludeMissing fun _title(): JsonField = title - - /** - * Returns the raw JSON value of [url]. - * - * Unlike [url], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("url") @ExcludeMissing fun _url(): JsonField = url - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [ReviewSnippet]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [ReviewSnippet]. */ - class Builder internal constructor() { - - private var reviewId: JsonField = JsonMissing.of() - private var title: JsonField = JsonMissing.of() - private var url: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(reviewSnippet: ReviewSnippet) = apply { - reviewId = reviewSnippet.reviewId - title = reviewSnippet.title - url = reviewSnippet.url - additionalProperties = reviewSnippet.additionalProperties.toMutableMap() - } - - /** The ID of the review snippet. */ - fun reviewId(reviewId: String) = reviewId(JsonField.of(reviewId)) - - /** - * Sets [Builder.reviewId] to an arbitrary JSON value. - * - * You should usually call [Builder.reviewId] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun reviewId(reviewId: JsonField) = apply { this.reviewId = reviewId } - - /** Title of the review. */ - fun title(title: String) = title(JsonField.of(title)) - - /** - * Sets [Builder.title] to an arbitrary JSON value. - * - * You should usually call [Builder.title] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun title(title: JsonField) = apply { this.title = title } - - /** A link that corresponds to the user review on Google Maps. */ - fun url(url: String) = url(JsonField.of(url)) - - /** - * Sets [Builder.url] to an arbitrary JSON value. - * - * You should usually call [Builder.url] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun url(url: JsonField) = apply { this.url = url } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [ReviewSnippet]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): ReviewSnippet = - ReviewSnippet(reviewId, title, url, additionalProperties.toMutableMap()) - } - - private var validated: Boolean = false - - fun validate(): ReviewSnippet = apply { - if (validated) { - return@apply - } - - reviewId() - title() - url() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - (if (reviewId.asKnown().isPresent) 1 else 0) + - (if (title.asKnown().isPresent) 1 else 0) + - (if (url.asKnown().isPresent) 1 else 0) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is ReviewSnippet && - reviewId == other.reviewId && - title == other.title && - url == other.url && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { - Objects.hash(reviewId, title, url, additionalProperties) - } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "ReviewSnippet{reviewId=$reviewId, title=$title, url=$url, additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is PlaceCitation && - type == other.type && - endIndex == other.endIndex && - name == other.name && - placeId == other.placeId && - reviewSnippets == other.reviewSnippets && - startIndex == other.startIndex && - url == other.url && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { - Objects.hash( - type, - endIndex, - name, - placeId, - reviewSnippets, - startIndex, - url, - additionalProperties, - ) - } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "PlaceCitation{type=$type, endIndex=$endIndex, name=$name, placeId=$placeId, reviewSnippets=$reviewSnippets, startIndex=$startIndex, url=$url, additionalProperties=$additionalProperties}" -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/SpeechConfig.kt b/src/main/java/com/google/genai/interactions/models/interactions/SpeechConfig.kt deleted file mode 100644 index 06f6adbb66c..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/SpeechConfig.kt +++ /dev/null @@ -1,243 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import com.google.genai.interactions.core.ExcludeMissing -import com.google.genai.interactions.core.JsonField -import com.google.genai.interactions.core.JsonMissing -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.util.Collections -import java.util.Objects -import java.util.Optional - -/** The configuration for speech interaction. */ -class SpeechConfig -@JsonCreator(mode = JsonCreator.Mode.DISABLED) -private constructor( - private val language: JsonField, - private val speaker: JsonField, - private val voice: JsonField, - private val additionalProperties: MutableMap, -) { - - @JsonCreator - private constructor( - @JsonProperty("language") @ExcludeMissing language: JsonField = JsonMissing.of(), - @JsonProperty("speaker") @ExcludeMissing speaker: JsonField = JsonMissing.of(), - @JsonProperty("voice") @ExcludeMissing voice: JsonField = JsonMissing.of(), - ) : this(language, speaker, voice, mutableMapOf()) - - /** - * The language of the speech. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun language(): Optional = language.getOptional("language") - - /** - * The speaker's name, it should match the speaker name given in the prompt. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun speaker(): Optional = speaker.getOptional("speaker") - - /** - * The voice of the speaker. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun voice(): Optional = voice.getOptional("voice") - - /** - * Returns the raw JSON value of [language]. - * - * Unlike [language], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("language") @ExcludeMissing fun _language(): JsonField = language - - /** - * Returns the raw JSON value of [speaker]. - * - * Unlike [speaker], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("speaker") @ExcludeMissing fun _speaker(): JsonField = speaker - - /** - * Returns the raw JSON value of [voice]. - * - * Unlike [voice], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("voice") @ExcludeMissing fun _voice(): JsonField = voice - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [SpeechConfig]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [SpeechConfig]. */ - class Builder internal constructor() { - - private var language: JsonField = JsonMissing.of() - private var speaker: JsonField = JsonMissing.of() - private var voice: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(speechConfig: SpeechConfig) = apply { - language = speechConfig.language - speaker = speechConfig.speaker - voice = speechConfig.voice - additionalProperties = speechConfig.additionalProperties.toMutableMap() - } - - /** The language of the speech. */ - fun language(language: String) = language(JsonField.of(language)) - - /** - * Sets [Builder.language] to an arbitrary JSON value. - * - * You should usually call [Builder.language] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun language(language: JsonField) = apply { this.language = language } - - /** The speaker's name, it should match the speaker name given in the prompt. */ - fun speaker(speaker: String) = speaker(JsonField.of(speaker)) - - /** - * Sets [Builder.speaker] to an arbitrary JSON value. - * - * You should usually call [Builder.speaker] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun speaker(speaker: JsonField) = apply { this.speaker = speaker } - - /** The voice of the speaker. */ - fun voice(voice: String) = voice(JsonField.of(voice)) - - /** - * Sets [Builder.voice] to an arbitrary JSON value. - * - * You should usually call [Builder.voice] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun voice(voice: JsonField) = apply { this.voice = voice } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [SpeechConfig]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): SpeechConfig = - SpeechConfig(language, speaker, voice, additionalProperties.toMutableMap()) - } - - private var validated: Boolean = false - - fun validate(): SpeechConfig = apply { - if (validated) { - return@apply - } - - language() - speaker() - voice() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - (if (language.asKnown().isPresent) 1 else 0) + - (if (speaker.asKnown().isPresent) 1 else 0) + - (if (voice.asKnown().isPresent) 1 else 0) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is SpeechConfig && - language == other.language && - speaker == other.speaker && - voice == other.voice && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { - Objects.hash(language, speaker, voice, additionalProperties) - } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "SpeechConfig{language=$language, speaker=$speaker, voice=$voice, additionalProperties=$additionalProperties}" -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/Step.kt b/src/main/java/com/google/genai/interactions/models/interactions/Step.kt deleted file mode 100644 index 973fe6d71b4..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/Step.kt +++ /dev/null @@ -1,736 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.core.JsonGenerator -import com.fasterxml.jackson.core.ObjectCodec -import com.fasterxml.jackson.databind.JsonNode -import com.fasterxml.jackson.databind.SerializerProvider -import com.fasterxml.jackson.databind.annotation.JsonDeserialize -import com.fasterxml.jackson.databind.annotation.JsonSerialize -import com.fasterxml.jackson.module.kotlin.jacksonTypeRef -import com.google.genai.interactions.core.BaseDeserializer -import com.google.genai.interactions.core.BaseSerializer -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.core.getOrThrow -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.util.Objects -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -/** A step in the interaction. */ -@JsonDeserialize(using = Step.Deserializer::class) -@JsonSerialize(using = Step.Serializer::class) -class Step -private constructor( - private val userInput: UserInputStep? = null, - private val modelOutput: ModelOutputStep? = null, - private val thought: ThoughtStep? = null, - private val functionCall: FunctionCallStep? = null, - private val codeExecutionCall: CodeExecutionCallStep? = null, - private val urlContextCall: UrlContextCallStep? = null, - private val mcpServerToolCall: McpServerToolCallStep? = null, - private val googleSearchCall: GoogleSearchCallStep? = null, - private val fileSearchCall: FileSearchCallStep? = null, - private val googleMapsCall: GoogleMapsCallStep? = null, - private val functionResult: FunctionResultStep? = null, - private val codeExecutionResult: CodeExecutionResultStep? = null, - private val urlContextResult: UrlContextResultStep? = null, - private val googleSearchResult: GoogleSearchResultStep? = null, - private val mcpServerToolResult: McpServerToolResultStep? = null, - private val fileSearchResult: FileSearchResultStep? = null, - private val googleMapsResult: GoogleMapsResultStep? = null, - private val _json: JsonValue? = null, -) { - - /** Input provided by the user. */ - fun userInput(): Optional = Optional.ofNullable(userInput) - - /** Output generated by the model. */ - fun modelOutput(): Optional = Optional.ofNullable(modelOutput) - - /** A thought step. */ - fun thought(): Optional = Optional.ofNullable(thought) - - /** A function tool call step. */ - fun functionCall(): Optional = Optional.ofNullable(functionCall) - - /** Code execution call step. */ - fun codeExecutionCall(): Optional = - Optional.ofNullable(codeExecutionCall) - - /** URL context call step. */ - fun urlContextCall(): Optional = Optional.ofNullable(urlContextCall) - - /** MCPServer tool call step. */ - fun mcpServerToolCall(): Optional = - Optional.ofNullable(mcpServerToolCall) - - /** Google Search call step. */ - fun googleSearchCall(): Optional = Optional.ofNullable(googleSearchCall) - - /** File Search call step. */ - fun fileSearchCall(): Optional = Optional.ofNullable(fileSearchCall) - - /** Google Maps call step. */ - fun googleMapsCall(): Optional = Optional.ofNullable(googleMapsCall) - - /** Result of a function tool call. */ - fun functionResult(): Optional = Optional.ofNullable(functionResult) - - /** Code execution result step. */ - fun codeExecutionResult(): Optional = - Optional.ofNullable(codeExecutionResult) - - /** URL context result step. */ - fun urlContextResult(): Optional = Optional.ofNullable(urlContextResult) - - /** Google Search result step. */ - fun googleSearchResult(): Optional = - Optional.ofNullable(googleSearchResult) - - /** MCPServer tool result step. */ - fun mcpServerToolResult(): Optional = - Optional.ofNullable(mcpServerToolResult) - - /** File Search result step. */ - fun fileSearchResult(): Optional = Optional.ofNullable(fileSearchResult) - - /** Google Maps result step. */ - fun googleMapsResult(): Optional = Optional.ofNullable(googleMapsResult) - - fun isUserInput(): Boolean = userInput != null - - fun isModelOutput(): Boolean = modelOutput != null - - fun isThought(): Boolean = thought != null - - fun isFunctionCall(): Boolean = functionCall != null - - fun isCodeExecutionCall(): Boolean = codeExecutionCall != null - - fun isUrlContextCall(): Boolean = urlContextCall != null - - fun isMcpServerToolCall(): Boolean = mcpServerToolCall != null - - fun isGoogleSearchCall(): Boolean = googleSearchCall != null - - fun isFileSearchCall(): Boolean = fileSearchCall != null - - fun isGoogleMapsCall(): Boolean = googleMapsCall != null - - fun isFunctionResult(): Boolean = functionResult != null - - fun isCodeExecutionResult(): Boolean = codeExecutionResult != null - - fun isUrlContextResult(): Boolean = urlContextResult != null - - fun isGoogleSearchResult(): Boolean = googleSearchResult != null - - fun isMcpServerToolResult(): Boolean = mcpServerToolResult != null - - fun isFileSearchResult(): Boolean = fileSearchResult != null - - fun isGoogleMapsResult(): Boolean = googleMapsResult != null - - /** Input provided by the user. */ - fun asUserInput(): UserInputStep = userInput.getOrThrow("userInput") - - /** Output generated by the model. */ - fun asModelOutput(): ModelOutputStep = modelOutput.getOrThrow("modelOutput") - - /** A thought step. */ - fun asThought(): ThoughtStep = thought.getOrThrow("thought") - - /** A function tool call step. */ - fun asFunctionCall(): FunctionCallStep = functionCall.getOrThrow("functionCall") - - /** Code execution call step. */ - fun asCodeExecutionCall(): CodeExecutionCallStep = - codeExecutionCall.getOrThrow("codeExecutionCall") - - /** URL context call step. */ - fun asUrlContextCall(): UrlContextCallStep = urlContextCall.getOrThrow("urlContextCall") - - /** MCPServer tool call step. */ - fun asMcpServerToolCall(): McpServerToolCallStep = - mcpServerToolCall.getOrThrow("mcpServerToolCall") - - /** Google Search call step. */ - fun asGoogleSearchCall(): GoogleSearchCallStep = googleSearchCall.getOrThrow("googleSearchCall") - - /** File Search call step. */ - fun asFileSearchCall(): FileSearchCallStep = fileSearchCall.getOrThrow("fileSearchCall") - - /** Google Maps call step. */ - fun asGoogleMapsCall(): GoogleMapsCallStep = googleMapsCall.getOrThrow("googleMapsCall") - - /** Result of a function tool call. */ - fun asFunctionResult(): FunctionResultStep = functionResult.getOrThrow("functionResult") - - /** Code execution result step. */ - fun asCodeExecutionResult(): CodeExecutionResultStep = - codeExecutionResult.getOrThrow("codeExecutionResult") - - /** URL context result step. */ - fun asUrlContextResult(): UrlContextResultStep = urlContextResult.getOrThrow("urlContextResult") - - /** Google Search result step. */ - fun asGoogleSearchResult(): GoogleSearchResultStep = - googleSearchResult.getOrThrow("googleSearchResult") - - /** MCPServer tool result step. */ - fun asMcpServerToolResult(): McpServerToolResultStep = - mcpServerToolResult.getOrThrow("mcpServerToolResult") - - /** File Search result step. */ - fun asFileSearchResult(): FileSearchResultStep = fileSearchResult.getOrThrow("fileSearchResult") - - /** Google Maps result step. */ - fun asGoogleMapsResult(): GoogleMapsResultStep = googleMapsResult.getOrThrow("googleMapsResult") - - fun _json(): Optional = Optional.ofNullable(_json) - - fun accept(visitor: Visitor): T = - when { - userInput != null -> visitor.visitUserInput(userInput) - modelOutput != null -> visitor.visitModelOutput(modelOutput) - thought != null -> visitor.visitThought(thought) - functionCall != null -> visitor.visitFunctionCall(functionCall) - codeExecutionCall != null -> visitor.visitCodeExecutionCall(codeExecutionCall) - urlContextCall != null -> visitor.visitUrlContextCall(urlContextCall) - mcpServerToolCall != null -> visitor.visitMcpServerToolCall(mcpServerToolCall) - googleSearchCall != null -> visitor.visitGoogleSearchCall(googleSearchCall) - fileSearchCall != null -> visitor.visitFileSearchCall(fileSearchCall) - googleMapsCall != null -> visitor.visitGoogleMapsCall(googleMapsCall) - functionResult != null -> visitor.visitFunctionResult(functionResult) - codeExecutionResult != null -> visitor.visitCodeExecutionResult(codeExecutionResult) - urlContextResult != null -> visitor.visitUrlContextResult(urlContextResult) - googleSearchResult != null -> visitor.visitGoogleSearchResult(googleSearchResult) - mcpServerToolResult != null -> visitor.visitMcpServerToolResult(mcpServerToolResult) - fileSearchResult != null -> visitor.visitFileSearchResult(fileSearchResult) - googleMapsResult != null -> visitor.visitGoogleMapsResult(googleMapsResult) - else -> visitor.unknown(_json) - } - - private var validated: Boolean = false - - fun validate(): Step = apply { - if (validated) { - return@apply - } - - accept( - object : Visitor { - override fun visitUserInput(userInput: UserInputStep) { - userInput.validate() - } - - override fun visitModelOutput(modelOutput: ModelOutputStep) { - modelOutput.validate() - } - - override fun visitThought(thought: ThoughtStep) { - thought.validate() - } - - override fun visitFunctionCall(functionCall: FunctionCallStep) { - functionCall.validate() - } - - override fun visitCodeExecutionCall(codeExecutionCall: CodeExecutionCallStep) { - codeExecutionCall.validate() - } - - override fun visitUrlContextCall(urlContextCall: UrlContextCallStep) { - urlContextCall.validate() - } - - override fun visitMcpServerToolCall(mcpServerToolCall: McpServerToolCallStep) { - mcpServerToolCall.validate() - } - - override fun visitGoogleSearchCall(googleSearchCall: GoogleSearchCallStep) { - googleSearchCall.validate() - } - - override fun visitFileSearchCall(fileSearchCall: FileSearchCallStep) { - fileSearchCall.validate() - } - - override fun visitGoogleMapsCall(googleMapsCall: GoogleMapsCallStep) { - googleMapsCall.validate() - } - - override fun visitFunctionResult(functionResult: FunctionResultStep) { - functionResult.validate() - } - - override fun visitCodeExecutionResult( - codeExecutionResult: CodeExecutionResultStep - ) { - codeExecutionResult.validate() - } - - override fun visitUrlContextResult(urlContextResult: UrlContextResultStep) { - urlContextResult.validate() - } - - override fun visitGoogleSearchResult(googleSearchResult: GoogleSearchResultStep) { - googleSearchResult.validate() - } - - override fun visitMcpServerToolResult( - mcpServerToolResult: McpServerToolResultStep - ) { - mcpServerToolResult.validate() - } - - override fun visitFileSearchResult(fileSearchResult: FileSearchResultStep) { - fileSearchResult.validate() - } - - override fun visitGoogleMapsResult(googleMapsResult: GoogleMapsResultStep) { - googleMapsResult.validate() - } - } - ) - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - accept( - object : Visitor { - override fun visitUserInput(userInput: UserInputStep) = userInput.validity() - - override fun visitModelOutput(modelOutput: ModelOutputStep) = modelOutput.validity() - - override fun visitThought(thought: ThoughtStep) = thought.validity() - - override fun visitFunctionCall(functionCall: FunctionCallStep) = - functionCall.validity() - - override fun visitCodeExecutionCall(codeExecutionCall: CodeExecutionCallStep) = - codeExecutionCall.validity() - - override fun visitUrlContextCall(urlContextCall: UrlContextCallStep) = - urlContextCall.validity() - - override fun visitMcpServerToolCall(mcpServerToolCall: McpServerToolCallStep) = - mcpServerToolCall.validity() - - override fun visitGoogleSearchCall(googleSearchCall: GoogleSearchCallStep) = - googleSearchCall.validity() - - override fun visitFileSearchCall(fileSearchCall: FileSearchCallStep) = - fileSearchCall.validity() - - override fun visitGoogleMapsCall(googleMapsCall: GoogleMapsCallStep) = - googleMapsCall.validity() - - override fun visitFunctionResult(functionResult: FunctionResultStep) = - functionResult.validity() - - override fun visitCodeExecutionResult( - codeExecutionResult: CodeExecutionResultStep - ) = codeExecutionResult.validity() - - override fun visitUrlContextResult(urlContextResult: UrlContextResultStep) = - urlContextResult.validity() - - override fun visitGoogleSearchResult(googleSearchResult: GoogleSearchResultStep) = - googleSearchResult.validity() - - override fun visitMcpServerToolResult( - mcpServerToolResult: McpServerToolResultStep - ) = mcpServerToolResult.validity() - - override fun visitFileSearchResult(fileSearchResult: FileSearchResultStep) = - fileSearchResult.validity() - - override fun visitGoogleMapsResult(googleMapsResult: GoogleMapsResultStep) = - googleMapsResult.validity() - - override fun unknown(json: JsonValue?) = 0 - } - ) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Step && - userInput == other.userInput && - modelOutput == other.modelOutput && - thought == other.thought && - functionCall == other.functionCall && - codeExecutionCall == other.codeExecutionCall && - urlContextCall == other.urlContextCall && - mcpServerToolCall == other.mcpServerToolCall && - googleSearchCall == other.googleSearchCall && - fileSearchCall == other.fileSearchCall && - googleMapsCall == other.googleMapsCall && - functionResult == other.functionResult && - codeExecutionResult == other.codeExecutionResult && - urlContextResult == other.urlContextResult && - googleSearchResult == other.googleSearchResult && - mcpServerToolResult == other.mcpServerToolResult && - fileSearchResult == other.fileSearchResult && - googleMapsResult == other.googleMapsResult - } - - override fun hashCode(): Int = - Objects.hash( - userInput, - modelOutput, - thought, - functionCall, - codeExecutionCall, - urlContextCall, - mcpServerToolCall, - googleSearchCall, - fileSearchCall, - googleMapsCall, - functionResult, - codeExecutionResult, - urlContextResult, - googleSearchResult, - mcpServerToolResult, - fileSearchResult, - googleMapsResult, - ) - - override fun toString(): String = - when { - userInput != null -> "Step{userInput=$userInput}" - modelOutput != null -> "Step{modelOutput=$modelOutput}" - thought != null -> "Step{thought=$thought}" - functionCall != null -> "Step{functionCall=$functionCall}" - codeExecutionCall != null -> "Step{codeExecutionCall=$codeExecutionCall}" - urlContextCall != null -> "Step{urlContextCall=$urlContextCall}" - mcpServerToolCall != null -> "Step{mcpServerToolCall=$mcpServerToolCall}" - googleSearchCall != null -> "Step{googleSearchCall=$googleSearchCall}" - fileSearchCall != null -> "Step{fileSearchCall=$fileSearchCall}" - googleMapsCall != null -> "Step{googleMapsCall=$googleMapsCall}" - functionResult != null -> "Step{functionResult=$functionResult}" - codeExecutionResult != null -> "Step{codeExecutionResult=$codeExecutionResult}" - urlContextResult != null -> "Step{urlContextResult=$urlContextResult}" - googleSearchResult != null -> "Step{googleSearchResult=$googleSearchResult}" - mcpServerToolResult != null -> "Step{mcpServerToolResult=$mcpServerToolResult}" - fileSearchResult != null -> "Step{fileSearchResult=$fileSearchResult}" - googleMapsResult != null -> "Step{googleMapsResult=$googleMapsResult}" - _json != null -> "Step{_unknown=$_json}" - else -> throw IllegalStateException("Invalid Step") - } - - companion object { - - /** Input provided by the user. */ - @JvmStatic fun ofUserInput(userInput: UserInputStep) = Step(userInput = userInput) - - /** Output generated by the model. */ - @JvmStatic fun ofModelOutput(modelOutput: ModelOutputStep) = Step(modelOutput = modelOutput) - - /** A thought step. */ - @JvmStatic fun ofThought(thought: ThoughtStep) = Step(thought = thought) - - /** A function tool call step. */ - @JvmStatic - fun ofFunctionCall(functionCall: FunctionCallStep) = Step(functionCall = functionCall) - - /** Code execution call step. */ - @JvmStatic - fun ofCodeExecutionCall(codeExecutionCall: CodeExecutionCallStep) = - Step(codeExecutionCall = codeExecutionCall) - - /** URL context call step. */ - @JvmStatic - fun ofUrlContextCall(urlContextCall: UrlContextCallStep) = - Step(urlContextCall = urlContextCall) - - /** MCPServer tool call step. */ - @JvmStatic - fun ofMcpServerToolCall(mcpServerToolCall: McpServerToolCallStep) = - Step(mcpServerToolCall = mcpServerToolCall) - - /** Google Search call step. */ - @JvmStatic - fun ofGoogleSearchCall(googleSearchCall: GoogleSearchCallStep) = - Step(googleSearchCall = googleSearchCall) - - /** File Search call step. */ - @JvmStatic - fun ofFileSearchCall(fileSearchCall: FileSearchCallStep) = - Step(fileSearchCall = fileSearchCall) - - /** Google Maps call step. */ - @JvmStatic - fun ofGoogleMapsCall(googleMapsCall: GoogleMapsCallStep) = - Step(googleMapsCall = googleMapsCall) - - /** Result of a function tool call. */ - @JvmStatic - fun ofFunctionResult(functionResult: FunctionResultStep) = - Step(functionResult = functionResult) - - /** Code execution result step. */ - @JvmStatic - fun ofCodeExecutionResult(codeExecutionResult: CodeExecutionResultStep) = - Step(codeExecutionResult = codeExecutionResult) - - /** URL context result step. */ - @JvmStatic - fun ofUrlContextResult(urlContextResult: UrlContextResultStep) = - Step(urlContextResult = urlContextResult) - - /** Google Search result step. */ - @JvmStatic - fun ofGoogleSearchResult(googleSearchResult: GoogleSearchResultStep) = - Step(googleSearchResult = googleSearchResult) - - /** MCPServer tool result step. */ - @JvmStatic - fun ofMcpServerToolResult(mcpServerToolResult: McpServerToolResultStep) = - Step(mcpServerToolResult = mcpServerToolResult) - - /** File Search result step. */ - @JvmStatic - fun ofFileSearchResult(fileSearchResult: FileSearchResultStep) = - Step(fileSearchResult = fileSearchResult) - - /** Google Maps result step. */ - @JvmStatic - fun ofGoogleMapsResult(googleMapsResult: GoogleMapsResultStep) = - Step(googleMapsResult = googleMapsResult) - } - - /** An interface that defines how to map each variant of [Step] to a value of type [T]. */ - interface Visitor { - - /** Input provided by the user. */ - fun visitUserInput(userInput: UserInputStep): T - - /** Output generated by the model. */ - fun visitModelOutput(modelOutput: ModelOutputStep): T - - /** A thought step. */ - fun visitThought(thought: ThoughtStep): T - - /** A function tool call step. */ - fun visitFunctionCall(functionCall: FunctionCallStep): T - - /** Code execution call step. */ - fun visitCodeExecutionCall(codeExecutionCall: CodeExecutionCallStep): T - - /** URL context call step. */ - fun visitUrlContextCall(urlContextCall: UrlContextCallStep): T - - /** MCPServer tool call step. */ - fun visitMcpServerToolCall(mcpServerToolCall: McpServerToolCallStep): T - - /** Google Search call step. */ - fun visitGoogleSearchCall(googleSearchCall: GoogleSearchCallStep): T - - /** File Search call step. */ - fun visitFileSearchCall(fileSearchCall: FileSearchCallStep): T - - /** Google Maps call step. */ - fun visitGoogleMapsCall(googleMapsCall: GoogleMapsCallStep): T - - /** Result of a function tool call. */ - fun visitFunctionResult(functionResult: FunctionResultStep): T - - /** Code execution result step. */ - fun visitCodeExecutionResult(codeExecutionResult: CodeExecutionResultStep): T - - /** URL context result step. */ - fun visitUrlContextResult(urlContextResult: UrlContextResultStep): T - - /** Google Search result step. */ - fun visitGoogleSearchResult(googleSearchResult: GoogleSearchResultStep): T - - /** MCPServer tool result step. */ - fun visitMcpServerToolResult(mcpServerToolResult: McpServerToolResultStep): T - - /** File Search result step. */ - fun visitFileSearchResult(fileSearchResult: FileSearchResultStep): T - - /** Google Maps result step. */ - fun visitGoogleMapsResult(googleMapsResult: GoogleMapsResultStep): T - - /** - * Maps an unknown variant of [Step] to a value of type [T]. - * - * An instance of [Step] can contain an unknown variant if it was deserialized from data - * that doesn't match any known variant. For example, if the SDK is on an older version than - * the API, then the API may respond with new variants that the SDK is unaware of. - * - * @throws GeminiNextGenApiInvalidDataException in the default implementation. - */ - fun unknown(json: JsonValue?): T { - throw GeminiNextGenApiInvalidDataException("Unknown Step: $json") - } - } - - internal class Deserializer : BaseDeserializer(Step::class) { - - override fun ObjectCodec.deserialize(node: JsonNode): Step { - val json = JsonValue.fromJsonNode(node) - val type = json.asObject().getOrNull()?.get("type")?.asString()?.getOrNull() - - when (type) { - "user_input" -> { - return tryDeserialize(node, jacksonTypeRef())?.let { - Step(userInput = it, _json = json) - } ?: Step(_json = json) - } - "model_output" -> { - return tryDeserialize(node, jacksonTypeRef())?.let { - Step(modelOutput = it, _json = json) - } ?: Step(_json = json) - } - "thought" -> { - return tryDeserialize(node, jacksonTypeRef())?.let { - Step(thought = it, _json = json) - } ?: Step(_json = json) - } - "function_call" -> { - return tryDeserialize(node, jacksonTypeRef())?.let { - Step(functionCall = it, _json = json) - } ?: Step(_json = json) - } - "code_execution_call" -> { - return tryDeserialize(node, jacksonTypeRef())?.let { - Step(codeExecutionCall = it, _json = json) - } ?: Step(_json = json) - } - "url_context_call" -> { - return tryDeserialize(node, jacksonTypeRef())?.let { - Step(urlContextCall = it, _json = json) - } ?: Step(_json = json) - } - "mcp_server_tool_call" -> { - return tryDeserialize(node, jacksonTypeRef())?.let { - Step(mcpServerToolCall = it, _json = json) - } ?: Step(_json = json) - } - "google_search_call" -> { - return tryDeserialize(node, jacksonTypeRef())?.let { - Step(googleSearchCall = it, _json = json) - } ?: Step(_json = json) - } - "file_search_call" -> { - return tryDeserialize(node, jacksonTypeRef())?.let { - Step(fileSearchCall = it, _json = json) - } ?: Step(_json = json) - } - "google_maps_call" -> { - return tryDeserialize(node, jacksonTypeRef())?.let { - Step(googleMapsCall = it, _json = json) - } ?: Step(_json = json) - } - "function_result" -> { - return tryDeserialize(node, jacksonTypeRef())?.let { - Step(functionResult = it, _json = json) - } ?: Step(_json = json) - } - "code_execution_result" -> { - return tryDeserialize(node, jacksonTypeRef())?.let { - Step(codeExecutionResult = it, _json = json) - } ?: Step(_json = json) - } - "url_context_result" -> { - return tryDeserialize(node, jacksonTypeRef())?.let { - Step(urlContextResult = it, _json = json) - } ?: Step(_json = json) - } - "google_search_result" -> { - return tryDeserialize(node, jacksonTypeRef())?.let { - Step(googleSearchResult = it, _json = json) - } ?: Step(_json = json) - } - "mcp_server_tool_result" -> { - return tryDeserialize(node, jacksonTypeRef())?.let { - Step(mcpServerToolResult = it, _json = json) - } ?: Step(_json = json) - } - "file_search_result" -> { - return tryDeserialize(node, jacksonTypeRef())?.let { - Step(fileSearchResult = it, _json = json) - } ?: Step(_json = json) - } - "google_maps_result" -> { - return tryDeserialize(node, jacksonTypeRef())?.let { - Step(googleMapsResult = it, _json = json) - } ?: Step(_json = json) - } - } - - return Step(_json = json) - } - } - - internal class Serializer : BaseSerializer(Step::class) { - - override fun serialize( - value: Step, - generator: JsonGenerator, - provider: SerializerProvider, - ) { - when { - value.userInput != null -> generator.writeObject(value.userInput) - value.modelOutput != null -> generator.writeObject(value.modelOutput) - value.thought != null -> generator.writeObject(value.thought) - value.functionCall != null -> generator.writeObject(value.functionCall) - value.codeExecutionCall != null -> generator.writeObject(value.codeExecutionCall) - value.urlContextCall != null -> generator.writeObject(value.urlContextCall) - value.mcpServerToolCall != null -> generator.writeObject(value.mcpServerToolCall) - value.googleSearchCall != null -> generator.writeObject(value.googleSearchCall) - value.fileSearchCall != null -> generator.writeObject(value.fileSearchCall) - value.googleMapsCall != null -> generator.writeObject(value.googleMapsCall) - value.functionResult != null -> generator.writeObject(value.functionResult) - value.codeExecutionResult != null -> - generator.writeObject(value.codeExecutionResult) - value.urlContextResult != null -> generator.writeObject(value.urlContextResult) - value.googleSearchResult != null -> generator.writeObject(value.googleSearchResult) - value.mcpServerToolResult != null -> - generator.writeObject(value.mcpServerToolResult) - value.fileSearchResult != null -> generator.writeObject(value.fileSearchResult) - value.googleMapsResult != null -> generator.writeObject(value.googleMapsResult) - value._json != null -> generator.writeObject(value._json) - else -> throw IllegalStateException("Invalid Step") - } - } - } -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/StepDelta.kt b/src/main/java/com/google/genai/interactions/models/interactions/StepDelta.kt deleted file mode 100644 index e4cdb60a6a2..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/StepDelta.kt +++ /dev/null @@ -1,7635 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import com.fasterxml.jackson.core.JsonGenerator -import com.fasterxml.jackson.core.ObjectCodec -import com.fasterxml.jackson.databind.JsonNode -import com.fasterxml.jackson.databind.SerializerProvider -import com.fasterxml.jackson.databind.annotation.JsonDeserialize -import com.fasterxml.jackson.databind.annotation.JsonSerialize -import com.fasterxml.jackson.module.kotlin.jacksonTypeRef -import com.google.genai.interactions.core.BaseDeserializer -import com.google.genai.interactions.core.BaseSerializer -import com.google.genai.interactions.core.Enum -import com.google.genai.interactions.core.ExcludeMissing -import com.google.genai.interactions.core.JsonField -import com.google.genai.interactions.core.JsonMissing -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.core.allMaxBy -import com.google.genai.interactions.core.checkKnown -import com.google.genai.interactions.core.checkRequired -import com.google.genai.interactions.core.getOrThrow -import com.google.genai.interactions.core.toImmutable -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.util.Collections -import java.util.Objects -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -class StepDelta -@JsonCreator(mode = JsonCreator.Mode.DISABLED) -private constructor( - private val delta: JsonField, - private val eventType: JsonValue, - private val index: JsonField, - private val eventId: JsonField, - private val additionalProperties: MutableMap, -) { - - @JsonCreator - private constructor( - @JsonProperty("delta") @ExcludeMissing delta: JsonField = JsonMissing.of(), - @JsonProperty("event_type") @ExcludeMissing eventType: JsonValue = JsonMissing.of(), - @JsonProperty("index") @ExcludeMissing index: JsonField = JsonMissing.of(), - @JsonProperty("event_id") @ExcludeMissing eventId: JsonField = JsonMissing.of(), - ) : this(delta, eventType, index, eventId, mutableMapOf()) - - /** - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). - */ - fun delta(): Delta = delta.getRequired("delta") - - /** - * Expected to always return the following: - * ```java - * JsonValue.from("step.delta") - * ``` - * - * However, this method can be useful for debugging and logging (e.g. if the server responded - * with an unexpected value). - */ - @JsonProperty("event_type") @ExcludeMissing fun _eventType(): JsonValue = eventType - - /** - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). - */ - fun index(): Int = index.getRequired("index") - - /** - * The event_id token to be used to resume the interaction stream, from this event. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun eventId(): Optional = eventId.getOptional("event_id") - - /** - * Returns the raw JSON value of [delta]. - * - * Unlike [delta], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("delta") @ExcludeMissing fun _delta(): JsonField = delta - - /** - * Returns the raw JSON value of [index]. - * - * Unlike [index], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("index") @ExcludeMissing fun _index(): JsonField = index - - /** - * Returns the raw JSON value of [eventId]. - * - * Unlike [eventId], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("event_id") @ExcludeMissing fun _eventId(): JsonField = eventId - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [StepDelta]. - * - * The following fields are required: - * ```java - * .delta() - * .index() - * ``` - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [StepDelta]. */ - class Builder internal constructor() { - - private var delta: JsonField? = null - private var eventType: JsonValue = JsonValue.from("step.delta") - private var index: JsonField? = null - private var eventId: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(stepDelta: StepDelta) = apply { - delta = stepDelta.delta - eventType = stepDelta.eventType - index = stepDelta.index - eventId = stepDelta.eventId - additionalProperties = stepDelta.additionalProperties.toMutableMap() - } - - fun delta(delta: Delta) = delta(JsonField.of(delta)) - - /** - * Sets [Builder.delta] to an arbitrary JSON value. - * - * You should usually call [Builder.delta] with a well-typed [Delta] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun delta(delta: JsonField) = apply { this.delta = delta } - - /** Alias for calling [delta] with `Delta.ofText(text)`. */ - fun delta(text: Delta.Text) = delta(Delta.ofText(text)) - - /** - * Alias for calling [delta] with the following: - * ```java - * Delta.Text.builder() - * .text(text) - * .build() - * ``` - */ - fun textDelta(text: String) = delta(Delta.Text.builder().text(text).build()) - - /** Alias for calling [delta] with `Delta.ofImage(image)`. */ - fun delta(image: Delta.Image) = delta(Delta.ofImage(image)) - - /** Alias for calling [delta] with `Delta.ofAudio(audio)`. */ - fun delta(audio: Delta.Audio) = delta(Delta.ofAudio(audio)) - - /** Alias for calling [delta] with `Delta.ofDocument(document)`. */ - fun delta(document: Delta.Document) = delta(Delta.ofDocument(document)) - - /** Alias for calling [delta] with `Delta.ofVideo(video)`. */ - fun delta(video: Delta.Video) = delta(Delta.ofVideo(video)) - - /** Alias for calling [delta] with `Delta.ofThoughtSummary(thoughtSummary)`. */ - fun delta(thoughtSummary: Delta.ThoughtSummary) = - delta(Delta.ofThoughtSummary(thoughtSummary)) - - /** Alias for calling [delta] with `Delta.ofThoughtSignature(thoughtSignature)`. */ - fun delta(thoughtSignature: Delta.ThoughtSignature) = - delta(Delta.ofThoughtSignature(thoughtSignature)) - - /** Alias for calling [delta] with `Delta.ofTextAnnotation(textAnnotation)`. */ - fun delta(textAnnotation: Delta.TextAnnotationDelta) = - delta(Delta.ofTextAnnotation(textAnnotation)) - - /** Alias for calling [delta] with `Delta.ofArguments(arguments)`. */ - fun delta(arguments: ArgumentsDelta) = delta(Delta.ofArguments(arguments)) - - /** Alias for calling [delta] with `Delta.ofCodeExecutionCall(codeExecutionCall)`. */ - fun delta(codeExecutionCall: Delta.CodeExecutionCall) = - delta(Delta.ofCodeExecutionCall(codeExecutionCall)) - - /** - * Alias for calling [delta] with the following: - * ```java - * Delta.CodeExecutionCall.builder() - * .arguments(arguments) - * .build() - * ``` - */ - fun codeExecutionCallDelta(arguments: CodeExecutionCallArguments) = - delta(Delta.CodeExecutionCall.builder().arguments(arguments).build()) - - /** Alias for calling [delta] with `Delta.ofUrlContextCall(urlContextCall)`. */ - fun delta(urlContextCall: Delta.UrlContextCall) = - delta(Delta.ofUrlContextCall(urlContextCall)) - - /** - * Alias for calling [delta] with the following: - * ```java - * Delta.UrlContextCall.builder() - * .arguments(arguments) - * .build() - * ``` - */ - fun urlContextCallDelta(arguments: UrlContextCallArguments) = - delta(Delta.UrlContextCall.builder().arguments(arguments).build()) - - /** Alias for calling [delta] with `Delta.ofGoogleSearchCall(googleSearchCall)`. */ - fun delta(googleSearchCall: Delta.GoogleSearchCall) = - delta(Delta.ofGoogleSearchCall(googleSearchCall)) - - /** - * Alias for calling [delta] with the following: - * ```java - * Delta.GoogleSearchCall.builder() - * .arguments(arguments) - * .build() - * ``` - */ - fun googleSearchCallDelta(arguments: GoogleSearchCallArguments) = - delta(Delta.GoogleSearchCall.builder().arguments(arguments).build()) - - /** Alias for calling [delta] with `Delta.ofMcpServerToolCall(mcpServerToolCall)`. */ - fun delta(mcpServerToolCall: Delta.McpServerToolCall) = - delta(Delta.ofMcpServerToolCall(mcpServerToolCall)) - - /** Alias for calling [delta] with `Delta.ofFileSearchCall(fileSearchCall)`. */ - fun delta(fileSearchCall: Delta.FileSearchCall) = - delta(Delta.ofFileSearchCall(fileSearchCall)) - - /** Alias for calling [delta] with `Delta.ofGoogleMapsCall(googleMapsCall)`. */ - fun delta(googleMapsCall: Delta.GoogleMapsCall) = - delta(Delta.ofGoogleMapsCall(googleMapsCall)) - - /** Alias for calling [delta] with `Delta.ofCodeExecutionResult(codeExecutionResult)`. */ - fun delta(codeExecutionResult: Delta.CodeExecutionResult) = - delta(Delta.ofCodeExecutionResult(codeExecutionResult)) - - /** - * Alias for calling [delta] with the following: - * ```java - * Delta.CodeExecutionResult.builder() - * .result(result) - * .build() - * ``` - */ - fun codeExecutionResultDelta(result: String) = - delta(Delta.CodeExecutionResult.builder().result(result).build()) - - /** Alias for calling [delta] with `Delta.ofUrlContextResult(urlContextResult)`. */ - fun delta(urlContextResult: UrlContextResultDelta) = - delta(Delta.ofUrlContextResult(urlContextResult)) - - /** - * Alias for calling [delta] with the following: - * ```java - * UrlContextResultDelta.builder() - * .result(result) - * .build() - * ``` - */ - fun urlContextResultDelta(result: List) = - delta(UrlContextResultDelta.builder().result(result).build()) - - /** Alias for calling [delta] with `Delta.ofGoogleSearchResult(googleSearchResult)`. */ - fun delta(googleSearchResult: GoogleSearchResultDelta) = - delta(Delta.ofGoogleSearchResult(googleSearchResult)) - - /** - * Alias for calling [delta] with the following: - * ```java - * GoogleSearchResultDelta.builder() - * .result(result) - * .build() - * ``` - */ - fun googleSearchResultDelta(result: List) = - delta(GoogleSearchResultDelta.builder().result(result).build()) - - /** Alias for calling [delta] with `Delta.ofMcpServerToolResult(mcpServerToolResult)`. */ - fun delta(mcpServerToolResult: Delta.McpServerToolResult) = - delta(Delta.ofMcpServerToolResult(mcpServerToolResult)) - - /** - * Alias for calling [delta] with the following: - * ```java - * Delta.McpServerToolResult.builder() - * .result(result) - * .build() - * ``` - */ - fun mcpServerToolResultDelta(result: Delta.McpServerToolResult.Result) = - delta(Delta.McpServerToolResult.builder().result(result).build()) - - /** - * Alias for calling [mcpServerToolResultDelta] with - * `Delta.McpServerToolResult.Result.ofJsonValue(jsonValue)`. - */ - fun mcpServerToolResultDelta(jsonValue: JsonValue) = - mcpServerToolResultDelta(Delta.McpServerToolResult.Result.ofJsonValue(jsonValue)) - - /** - * Alias for calling [mcpServerToolResultDelta] with - * `Delta.McpServerToolResult.Result.ofFunctionResultSubcontentList(functionResultSubcontentList)`. - */ - fun mcpServerToolResultDeltaOfFunctionResultSubcontentList( - functionResultSubcontentList: - List - ) = - mcpServerToolResultDelta( - Delta.McpServerToolResult.Result.ofFunctionResultSubcontentList( - functionResultSubcontentList - ) - ) - - /** - * Alias for calling [mcpServerToolResultDelta] with - * `Delta.McpServerToolResult.Result.ofString(string)`. - */ - fun mcpServerToolResultDelta(string: String) = - mcpServerToolResultDelta(Delta.McpServerToolResult.Result.ofString(string)) - - /** Alias for calling [delta] with `Delta.ofFileSearchResult(fileSearchResult)`. */ - fun delta(fileSearchResult: Delta.FileSearchResult) = - delta(Delta.ofFileSearchResult(fileSearchResult)) - - /** - * Alias for calling [delta] with the following: - * ```java - * Delta.FileSearchResult.builder() - * .result(result) - * .build() - * ``` - */ - fun fileSearchResultDelta(result: List) = - delta(Delta.FileSearchResult.builder().result(result).build()) - - /** Alias for calling [delta] with `Delta.ofGoogleMapsResult(googleMapsResult)`. */ - fun delta(googleMapsResult: Delta.GoogleMapsResult) = - delta(Delta.ofGoogleMapsResult(googleMapsResult)) - - /** Alias for calling [delta] with `Delta.ofFunctionResult(functionResult)`. */ - fun delta(functionResult: FunctionResultDelta) = - delta(Delta.ofFunctionResult(functionResult)) - - /** - * Sets the field to an arbitrary JSON value. - * - * It is usually unnecessary to call this method because the field defaults to the - * following: - * ```java - * JsonValue.from("step.delta") - * ``` - * - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun eventType(eventType: JsonValue) = apply { this.eventType = eventType } - - fun index(index: Int) = index(JsonField.of(index)) - - /** - * Sets [Builder.index] to an arbitrary JSON value. - * - * You should usually call [Builder.index] with a well-typed [Int] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun index(index: JsonField) = apply { this.index = index } - - /** The event_id token to be used to resume the interaction stream, from this event. */ - fun eventId(eventId: String) = eventId(JsonField.of(eventId)) - - /** - * Sets [Builder.eventId] to an arbitrary JSON value. - * - * You should usually call [Builder.eventId] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun eventId(eventId: JsonField) = apply { this.eventId = eventId } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [StepDelta]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .delta() - * .index() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): StepDelta = - StepDelta( - checkRequired("delta", delta), - eventType, - checkRequired("index", index), - eventId, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): StepDelta = apply { - if (validated) { - return@apply - } - - delta().validate() - _eventType().let { - if (it != JsonValue.from("step.delta")) { - throw GeminiNextGenApiInvalidDataException("'eventType' is invalid, received $it") - } - } - index() - eventId() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - (delta.asKnown().getOrNull()?.validity() ?: 0) + - eventType.let { if (it == JsonValue.from("step.delta")) 1 else 0 } + - (if (index.asKnown().isPresent) 1 else 0) + - (if (eventId.asKnown().isPresent) 1 else 0) - - @JsonDeserialize(using = Delta.Deserializer::class) - @JsonSerialize(using = Delta.Serializer::class) - class Delta - private constructor( - private val text: Text? = null, - private val image: Image? = null, - private val audio: Audio? = null, - private val document: Document? = null, - private val video: Video? = null, - private val thoughtSummary: ThoughtSummary? = null, - private val thoughtSignature: ThoughtSignature? = null, - private val textAnnotation: TextAnnotationDelta? = null, - private val arguments: ArgumentsDelta? = null, - private val codeExecutionCall: CodeExecutionCall? = null, - private val urlContextCall: UrlContextCall? = null, - private val googleSearchCall: GoogleSearchCall? = null, - private val mcpServerToolCall: McpServerToolCall? = null, - private val fileSearchCall: FileSearchCall? = null, - private val googleMapsCall: GoogleMapsCall? = null, - private val codeExecutionResult: CodeExecutionResult? = null, - private val urlContextResult: UrlContextResultDelta? = null, - private val googleSearchResult: GoogleSearchResultDelta? = null, - private val mcpServerToolResult: McpServerToolResult? = null, - private val fileSearchResult: FileSearchResult? = null, - private val googleMapsResult: GoogleMapsResult? = null, - private val functionResult: FunctionResultDelta? = null, - private val _json: JsonValue? = null, - ) { - - fun text(): Optional = Optional.ofNullable(text) - - fun image(): Optional = Optional.ofNullable(image) - - fun audio(): Optional

) = summary(JsonField.of(summary)) - - /** - * Sets [Builder.summary] to an arbitrary JSON value. - * - * You should usually call [Builder.summary] with a well-typed `List` value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun summary(summary: JsonField>) = apply { - this.summary = summary.map { it.toMutableList() } - } - - /** - * Adds a single [Summary] to [Builder.summary]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addSummary(summary: Summary) = apply { - this.summary = - (this.summary ?: JsonField.of(mutableListOf())).also { - checkKnown("summary", it).add(summary) - } - } - - /** Alias for calling [addSummary] with `Summary.ofText(text)`. */ - fun addSummary(text: TextContent) = addSummary(Summary.ofText(text)) - - /** - * Alias for calling [addSummary] with the following: - * ```java - * TextContent.builder() - * .text(text) - * .build() - * ``` - */ - fun addTextSummary(text: String) = addSummary(TextContent.builder().text(text).build()) - - /** Alias for calling [addSummary] with `Summary.ofImage(image)`. */ - fun addSummary(image: ImageContent) = addSummary(Summary.ofImage(image)) - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [ThoughtStep]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): ThoughtStep = - ThoughtStep( - type, - signature, - (summary ?: JsonMissing.of()).map { it.toImmutable() }, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): ThoughtStep = apply { - if (validated) { - return@apply - } - - _type().let { - if (it != JsonValue.from("thought")) { - throw GeminiNextGenApiInvalidDataException("'type' is invalid, received $it") - } - } - signature() - summary().ifPresent { it.forEach { it.validate() } } - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - type.let { if (it == JsonValue.from("thought")) 1 else 0 } + - (if (signature.asKnown().isPresent) 1 else 0) + - (summary.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) - - /** A text content block. */ - @JsonDeserialize(using = Summary.Deserializer::class) - @JsonSerialize(using = Summary.Serializer::class) - class Summary - private constructor( - private val text: TextContent? = null, - private val image: ImageContent? = null, - private val _json: JsonValue? = null, - ) { - - /** A text content block. */ - fun text(): Optional = Optional.ofNullable(text) - - /** An image content block. */ - fun image(): Optional = Optional.ofNullable(image) - - fun isText(): Boolean = text != null - - fun isImage(): Boolean = image != null - - /** A text content block. */ - fun asText(): TextContent = text.getOrThrow("text") - - /** An image content block. */ - fun asImage(): ImageContent = image.getOrThrow("image") - - fun _json(): Optional = Optional.ofNullable(_json) - - fun accept(visitor: Visitor): T = - when { - text != null -> visitor.visitText(text) - image != null -> visitor.visitImage(image) - else -> visitor.unknown(_json) - } - - private var validated: Boolean = false - - fun validate(): Summary = apply { - if (validated) { - return@apply - } - - accept( - object : Visitor { - override fun visitText(text: TextContent) { - text.validate() - } - - override fun visitImage(image: ImageContent) { - image.validate() - } - } - ) - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - accept( - object : Visitor { - override fun visitText(text: TextContent) = text.validity() - - override fun visitImage(image: ImageContent) = image.validity() - - override fun unknown(json: JsonValue?) = 0 - } - ) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Summary && text == other.text && image == other.image - } - - override fun hashCode(): Int = Objects.hash(text, image) - - override fun toString(): String = - when { - text != null -> "Summary{text=$text}" - image != null -> "Summary{image=$image}" - _json != null -> "Summary{_unknown=$_json}" - else -> throw IllegalStateException("Invalid Summary") - } - - companion object { - - /** A text content block. */ - @JvmStatic fun ofText(text: TextContent) = Summary(text = text) - - /** An image content block. */ - @JvmStatic fun ofImage(image: ImageContent) = Summary(image = image) - } - - /** - * An interface that defines how to map each variant of [Summary] to a value of type [T]. - */ - interface Visitor { - - /** A text content block. */ - fun visitText(text: TextContent): T - - /** An image content block. */ - fun visitImage(image: ImageContent): T - - /** - * Maps an unknown variant of [Summary] to a value of type [T]. - * - * An instance of [Summary] can contain an unknown variant if it was deserialized from - * data that doesn't match any known variant. For example, if the SDK is on an older - * version than the API, then the API may respond with new variants that the SDK is - * unaware of. - * - * @throws GeminiNextGenApiInvalidDataException in the default implementation. - */ - fun unknown(json: JsonValue?): T { - throw GeminiNextGenApiInvalidDataException("Unknown Summary: $json") - } - } - - internal class Deserializer : BaseDeserializer(Summary::class) { - - override fun ObjectCodec.deserialize(node: JsonNode): Summary { - val json = JsonValue.fromJsonNode(node) - val type = json.asObject().getOrNull()?.get("type")?.asString()?.getOrNull() - - when (type) { - "text" -> { - return tryDeserialize(node, jacksonTypeRef())?.let { - Summary(text = it, _json = json) - } ?: Summary(_json = json) - } - "image" -> { - return tryDeserialize(node, jacksonTypeRef())?.let { - Summary(image = it, _json = json) - } ?: Summary(_json = json) - } - } - - return Summary(_json = json) - } - } - - internal class Serializer : BaseSerializer(Summary::class) { - - override fun serialize( - value: Summary, - generator: JsonGenerator, - provider: SerializerProvider, - ) { - when { - value.text != null -> generator.writeObject(value.text) - value.image != null -> generator.writeObject(value.image) - value._json != null -> generator.writeObject(value._json) - else -> throw IllegalStateException("Invalid Summary") - } - } - } - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is ThoughtStep && - type == other.type && - signature == other.signature && - summary == other.summary && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { - Objects.hash(type, signature, summary, additionalProperties) - } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "ThoughtStep{type=$type, signature=$signature, summary=$summary, additionalProperties=$additionalProperties}" -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/Tool.kt b/src/main/java/com/google/genai/interactions/models/interactions/Tool.kt deleted file mode 100644 index af19e02a3dd..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/Tool.kt +++ /dev/null @@ -1,2739 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import com.fasterxml.jackson.core.JsonGenerator -import com.fasterxml.jackson.core.ObjectCodec -import com.fasterxml.jackson.databind.JsonNode -import com.fasterxml.jackson.databind.SerializerProvider -import com.fasterxml.jackson.databind.annotation.JsonDeserialize -import com.fasterxml.jackson.databind.annotation.JsonSerialize -import com.fasterxml.jackson.module.kotlin.jacksonTypeRef -import com.google.genai.interactions.core.BaseDeserializer -import com.google.genai.interactions.core.BaseSerializer -import com.google.genai.interactions.core.Enum -import com.google.genai.interactions.core.ExcludeMissing -import com.google.genai.interactions.core.JsonField -import com.google.genai.interactions.core.JsonMissing -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.core.checkKnown -import com.google.genai.interactions.core.getOrThrow -import com.google.genai.interactions.core.toImmutable -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.util.Collections -import java.util.Objects -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -/** A tool that can be used by the model. */ -@JsonDeserialize(using = Tool.Deserializer::class) -@JsonSerialize(using = Tool.Serializer::class) -class Tool -private constructor( - private val function: Function? = null, - private val codeExecution: JsonValue? = null, - private val urlContext: JsonValue? = null, - private val computerUse: ComputerUse? = null, - private val mcpServer: McpServer? = null, - private val googleSearch: GoogleSearch? = null, - private val fileSearch: FileSearch? = null, - private val googleMaps: GoogleMaps? = null, - private val retrieval: Retrieval? = null, - private val _json: JsonValue? = null, -) { - - /** A tool that can be used by the model. */ - fun function(): Optional = Optional.ofNullable(function) - - /** A tool that can be used by the model to execute code. */ - fun codeExecution(): Optional = Optional.ofNullable(codeExecution) - - /** A tool that can be used by the model to fetch URL context. */ - fun urlContext(): Optional = Optional.ofNullable(urlContext) - - /** A tool that can be used by the model to interact with the computer. */ - fun computerUse(): Optional = Optional.ofNullable(computerUse) - - /** A MCPServer is a server that can be called by the model to perform actions. */ - fun mcpServer(): Optional = Optional.ofNullable(mcpServer) - - /** A tool that can be used by the model to search Google. */ - fun googleSearch(): Optional = Optional.ofNullable(googleSearch) - - /** A tool that can be used by the model to search files. */ - fun fileSearch(): Optional = Optional.ofNullable(fileSearch) - - /** A tool that can be used by the model to call Google Maps. */ - fun googleMaps(): Optional = Optional.ofNullable(googleMaps) - - /** A tool that can be used by the model to retrieve files. */ - fun retrieval(): Optional = Optional.ofNullable(retrieval) - - fun isFunction(): Boolean = function != null - - fun isCodeExecution(): Boolean = codeExecution != null - - fun isUrlContext(): Boolean = urlContext != null - - fun isComputerUse(): Boolean = computerUse != null - - fun isMcpServer(): Boolean = mcpServer != null - - fun isGoogleSearch(): Boolean = googleSearch != null - - fun isFileSearch(): Boolean = fileSearch != null - - fun isGoogleMaps(): Boolean = googleMaps != null - - fun isRetrieval(): Boolean = retrieval != null - - /** A tool that can be used by the model. */ - fun asFunction(): Function = function.getOrThrow("function") - - /** A tool that can be used by the model to execute code. */ - fun asCodeExecution(): JsonValue = codeExecution.getOrThrow("codeExecution") - - /** A tool that can be used by the model to fetch URL context. */ - fun asUrlContext(): JsonValue = urlContext.getOrThrow("urlContext") - - /** A tool that can be used by the model to interact with the computer. */ - fun asComputerUse(): ComputerUse = computerUse.getOrThrow("computerUse") - - /** A MCPServer is a server that can be called by the model to perform actions. */ - fun asMcpServer(): McpServer = mcpServer.getOrThrow("mcpServer") - - /** A tool that can be used by the model to search Google. */ - fun asGoogleSearch(): GoogleSearch = googleSearch.getOrThrow("googleSearch") - - /** A tool that can be used by the model to search files. */ - fun asFileSearch(): FileSearch = fileSearch.getOrThrow("fileSearch") - - /** A tool that can be used by the model to call Google Maps. */ - fun asGoogleMaps(): GoogleMaps = googleMaps.getOrThrow("googleMaps") - - /** A tool that can be used by the model to retrieve files. */ - fun asRetrieval(): Retrieval = retrieval.getOrThrow("retrieval") - - fun _json(): Optional = Optional.ofNullable(_json) - - fun accept(visitor: Visitor): T = - when { - function != null -> visitor.visitFunction(function) - codeExecution != null -> visitor.visitCodeExecution(codeExecution) - urlContext != null -> visitor.visitUrlContext(urlContext) - computerUse != null -> visitor.visitComputerUse(computerUse) - mcpServer != null -> visitor.visitMcpServer(mcpServer) - googleSearch != null -> visitor.visitGoogleSearch(googleSearch) - fileSearch != null -> visitor.visitFileSearch(fileSearch) - googleMaps != null -> visitor.visitGoogleMaps(googleMaps) - retrieval != null -> visitor.visitRetrieval(retrieval) - else -> visitor.unknown(_json) - } - - private var validated: Boolean = false - - fun validate(): Tool = apply { - if (validated) { - return@apply - } - - accept( - object : Visitor { - override fun visitFunction(function: Function) { - function.validate() - } - - override fun visitCodeExecution(codeExecution: JsonValue) { - codeExecution.let { - if (it != JsonValue.from(mapOf("type" to "code_execution"))) { - throw GeminiNextGenApiInvalidDataException( - "'codeExecution' is invalid, received $it" - ) - } - } - } - - override fun visitUrlContext(urlContext: JsonValue) { - urlContext.let { - if (it != JsonValue.from(mapOf("type" to "url_context"))) { - throw GeminiNextGenApiInvalidDataException( - "'urlContext' is invalid, received $it" - ) - } - } - } - - override fun visitComputerUse(computerUse: ComputerUse) { - computerUse.validate() - } - - override fun visitMcpServer(mcpServer: McpServer) { - mcpServer.validate() - } - - override fun visitGoogleSearch(googleSearch: GoogleSearch) { - googleSearch.validate() - } - - override fun visitFileSearch(fileSearch: FileSearch) { - fileSearch.validate() - } - - override fun visitGoogleMaps(googleMaps: GoogleMaps) { - googleMaps.validate() - } - - override fun visitRetrieval(retrieval: Retrieval) { - retrieval.validate() - } - } - ) - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - accept( - object : Visitor { - override fun visitFunction(function: Function) = function.validity() - - override fun visitCodeExecution(codeExecution: JsonValue) = - codeExecution.let { - if (it == JsonValue.from(mapOf("type" to "code_execution"))) 1 else 0 - } - - override fun visitUrlContext(urlContext: JsonValue) = - urlContext.let { - if (it == JsonValue.from(mapOf("type" to "url_context"))) 1 else 0 - } - - override fun visitComputerUse(computerUse: ComputerUse) = computerUse.validity() - - override fun visitMcpServer(mcpServer: McpServer) = mcpServer.validity() - - override fun visitGoogleSearch(googleSearch: GoogleSearch) = googleSearch.validity() - - override fun visitFileSearch(fileSearch: FileSearch) = fileSearch.validity() - - override fun visitGoogleMaps(googleMaps: GoogleMaps) = googleMaps.validity() - - override fun visitRetrieval(retrieval: Retrieval) = retrieval.validity() - - override fun unknown(json: JsonValue?) = 0 - } - ) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Tool && - function == other.function && - codeExecution == other.codeExecution && - urlContext == other.urlContext && - computerUse == other.computerUse && - mcpServer == other.mcpServer && - googleSearch == other.googleSearch && - fileSearch == other.fileSearch && - googleMaps == other.googleMaps && - retrieval == other.retrieval - } - - override fun hashCode(): Int = - Objects.hash( - function, - codeExecution, - urlContext, - computerUse, - mcpServer, - googleSearch, - fileSearch, - googleMaps, - retrieval, - ) - - override fun toString(): String = - when { - function != null -> "Tool{function=$function}" - codeExecution != null -> "Tool{codeExecution=$codeExecution}" - urlContext != null -> "Tool{urlContext=$urlContext}" - computerUse != null -> "Tool{computerUse=$computerUse}" - mcpServer != null -> "Tool{mcpServer=$mcpServer}" - googleSearch != null -> "Tool{googleSearch=$googleSearch}" - fileSearch != null -> "Tool{fileSearch=$fileSearch}" - googleMaps != null -> "Tool{googleMaps=$googleMaps}" - retrieval != null -> "Tool{retrieval=$retrieval}" - _json != null -> "Tool{_unknown=$_json}" - else -> throw IllegalStateException("Invalid Tool") - } - - companion object { - - /** A tool that can be used by the model. */ - @JvmStatic fun ofFunction(function: Function) = Tool(function = function) - - /** A tool that can be used by the model to execute code. */ - @JvmStatic - fun ofCodeExecution() = - Tool(codeExecution = JsonValue.from(mapOf("type" to "code_execution"))) - - /** A tool that can be used by the model to fetch URL context. */ - @JvmStatic - fun ofUrlContext() = Tool(urlContext = JsonValue.from(mapOf("type" to "url_context"))) - - /** A tool that can be used by the model to interact with the computer. */ - @JvmStatic fun ofComputerUse(computerUse: ComputerUse) = Tool(computerUse = computerUse) - - /** A MCPServer is a server that can be called by the model to perform actions. */ - @JvmStatic fun ofMcpServer(mcpServer: McpServer) = Tool(mcpServer = mcpServer) - - /** A tool that can be used by the model to search Google. */ - @JvmStatic - fun ofGoogleSearch(googleSearch: GoogleSearch) = Tool(googleSearch = googleSearch) - - /** A tool that can be used by the model to search files. */ - @JvmStatic fun ofFileSearch(fileSearch: FileSearch) = Tool(fileSearch = fileSearch) - - /** A tool that can be used by the model to call Google Maps. */ - @JvmStatic fun ofGoogleMaps(googleMaps: GoogleMaps) = Tool(googleMaps = googleMaps) - - /** A tool that can be used by the model to retrieve files. */ - @JvmStatic fun ofRetrieval(retrieval: Retrieval) = Tool(retrieval = retrieval) - } - - /** An interface that defines how to map each variant of [Tool] to a value of type [T]. */ - interface Visitor { - - /** A tool that can be used by the model. */ - fun visitFunction(function: Function): T - - /** A tool that can be used by the model to execute code. */ - fun visitCodeExecution(codeExecution: JsonValue): T - - /** A tool that can be used by the model to fetch URL context. */ - fun visitUrlContext(urlContext: JsonValue): T - - /** A tool that can be used by the model to interact with the computer. */ - fun visitComputerUse(computerUse: ComputerUse): T - - /** A MCPServer is a server that can be called by the model to perform actions. */ - fun visitMcpServer(mcpServer: McpServer): T - - /** A tool that can be used by the model to search Google. */ - fun visitGoogleSearch(googleSearch: GoogleSearch): T - - /** A tool that can be used by the model to search files. */ - fun visitFileSearch(fileSearch: FileSearch): T - - /** A tool that can be used by the model to call Google Maps. */ - fun visitGoogleMaps(googleMaps: GoogleMaps): T - - /** A tool that can be used by the model to retrieve files. */ - fun visitRetrieval(retrieval: Retrieval): T - - /** - * Maps an unknown variant of [Tool] to a value of type [T]. - * - * An instance of [Tool] can contain an unknown variant if it was deserialized from data - * that doesn't match any known variant. For example, if the SDK is on an older version than - * the API, then the API may respond with new variants that the SDK is unaware of. - * - * @throws GeminiNextGenApiInvalidDataException in the default implementation. - */ - fun unknown(json: JsonValue?): T { - throw GeminiNextGenApiInvalidDataException("Unknown Tool: $json") - } - } - - internal class Deserializer : BaseDeserializer(Tool::class) { - - override fun ObjectCodec.deserialize(node: JsonNode): Tool { - val json = JsonValue.fromJsonNode(node) - val type = json.asObject().getOrNull()?.get("type")?.asString()?.getOrNull() - - when (type) { - "function" -> { - return tryDeserialize(node, jacksonTypeRef())?.let { - Tool(function = it, _json = json) - } ?: Tool(_json = json) - } - "code_execution" -> { - return tryDeserialize(node, jacksonTypeRef()) - ?.let { Tool(codeExecution = it, _json = json) } - ?.takeIf { it.isValid() } ?: Tool(_json = json) - } - "url_context" -> { - return tryDeserialize(node, jacksonTypeRef()) - ?.let { Tool(urlContext = it, _json = json) } - ?.takeIf { it.isValid() } ?: Tool(_json = json) - } - "computer_use" -> { - return tryDeserialize(node, jacksonTypeRef())?.let { - Tool(computerUse = it, _json = json) - } ?: Tool(_json = json) - } - "mcp_server" -> { - return tryDeserialize(node, jacksonTypeRef())?.let { - Tool(mcpServer = it, _json = json) - } ?: Tool(_json = json) - } - "google_search" -> { - return tryDeserialize(node, jacksonTypeRef())?.let { - Tool(googleSearch = it, _json = json) - } ?: Tool(_json = json) - } - "file_search" -> { - return tryDeserialize(node, jacksonTypeRef())?.let { - Tool(fileSearch = it, _json = json) - } ?: Tool(_json = json) - } - "google_maps" -> { - return tryDeserialize(node, jacksonTypeRef())?.let { - Tool(googleMaps = it, _json = json) - } ?: Tool(_json = json) - } - "retrieval" -> { - return tryDeserialize(node, jacksonTypeRef())?.let { - Tool(retrieval = it, _json = json) - } ?: Tool(_json = json) - } - } - - return Tool(_json = json) - } - } - - internal class Serializer : BaseSerializer(Tool::class) { - - override fun serialize( - value: Tool, - generator: JsonGenerator, - provider: SerializerProvider, - ) { - when { - value.function != null -> generator.writeObject(value.function) - value.codeExecution != null -> generator.writeObject(value.codeExecution) - value.urlContext != null -> generator.writeObject(value.urlContext) - value.computerUse != null -> generator.writeObject(value.computerUse) - value.mcpServer != null -> generator.writeObject(value.mcpServer) - value.googleSearch != null -> generator.writeObject(value.googleSearch) - value.fileSearch != null -> generator.writeObject(value.fileSearch) - value.googleMaps != null -> generator.writeObject(value.googleMaps) - value.retrieval != null -> generator.writeObject(value.retrieval) - value._json != null -> generator.writeObject(value._json) - else -> throw IllegalStateException("Invalid Tool") - } - } - } - - /** A tool that can be used by the model to interact with the computer. */ - class ComputerUse - @JsonCreator(mode = JsonCreator.Mode.DISABLED) - private constructor( - private val type: JsonValue, - private val environment: JsonField, - private val excludedPredefinedFunctions: JsonField>, - private val additionalProperties: MutableMap, - ) { - - @JsonCreator - private constructor( - @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), - @JsonProperty("environment") - @ExcludeMissing - environment: JsonField = JsonMissing.of(), - @JsonProperty("excluded_predefined_functions") - @ExcludeMissing - excludedPredefinedFunctions: JsonField> = JsonMissing.of(), - ) : this(type, environment, excludedPredefinedFunctions, mutableMapOf()) - - /** - * Expected to always return the following: - * ```java - * JsonValue.from("computer_use") - * ``` - * - * However, this method can be useful for debugging and logging (e.g. if the server - * responded with an unexpected value). - */ - @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type - - /** - * The environment being operated. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type - * (e.g. if the server responded with an unexpected value). - */ - fun environment(): Optional = environment.getOptional("environment") - - /** - * The list of predefined functions that are excluded from the model call. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type - * (e.g. if the server responded with an unexpected value). - */ - fun excludedPredefinedFunctions(): Optional> = - excludedPredefinedFunctions.getOptional("excluded_predefined_functions") - - /** - * Returns the raw JSON value of [environment]. - * - * Unlike [environment], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("environment") - @ExcludeMissing - fun _environment(): JsonField = environment - - /** - * Returns the raw JSON value of [excludedPredefinedFunctions]. - * - * Unlike [excludedPredefinedFunctions], this method doesn't throw if the JSON field has an - * unexpected type. - */ - @JsonProperty("excluded_predefined_functions") - @ExcludeMissing - fun _excludedPredefinedFunctions(): JsonField> = excludedPredefinedFunctions - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [ComputerUse]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [ComputerUse]. */ - class Builder internal constructor() { - - private var type: JsonValue = JsonValue.from("computer_use") - private var environment: JsonField = JsonMissing.of() - private var excludedPredefinedFunctions: JsonField>? = null - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(computerUse: ComputerUse) = apply { - type = computerUse.type - environment = computerUse.environment - excludedPredefinedFunctions = - computerUse.excludedPredefinedFunctions.map { it.toMutableList() } - additionalProperties = computerUse.additionalProperties.toMutableMap() - } - - /** - * Sets the field to an arbitrary JSON value. - * - * It is usually unnecessary to call this method because the field defaults to the - * following: - * ```java - * JsonValue.from("computer_use") - * ``` - * - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun type(type: JsonValue) = apply { this.type = type } - - /** The environment being operated. */ - fun environment(environment: Environment) = environment(JsonField.of(environment)) - - /** - * Sets [Builder.environment] to an arbitrary JSON value. - * - * You should usually call [Builder.environment] with a well-typed [Environment] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun environment(environment: JsonField) = apply { - this.environment = environment - } - - /** The list of predefined functions that are excluded from the model call. */ - fun excludedPredefinedFunctions(excludedPredefinedFunctions: List) = - excludedPredefinedFunctions(JsonField.of(excludedPredefinedFunctions)) - - /** - * Sets [Builder.excludedPredefinedFunctions] to an arbitrary JSON value. - * - * You should usually call [Builder.excludedPredefinedFunctions] with a well-typed - * `List` value instead. This method is primarily for setting the field to an - * undocumented or not yet supported value. - */ - fun excludedPredefinedFunctions(excludedPredefinedFunctions: JsonField>) = - apply { - this.excludedPredefinedFunctions = - excludedPredefinedFunctions.map { it.toMutableList() } - } - - /** - * Adds a single [String] to [excludedPredefinedFunctions]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addExcludedPredefinedFunction(excludedPredefinedFunction: String) = apply { - excludedPredefinedFunctions = - (excludedPredefinedFunctions ?: JsonField.of(mutableListOf())).also { - checkKnown("excludedPredefinedFunctions", it) - .add(excludedPredefinedFunction) - } - } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [ComputerUse]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): ComputerUse = - ComputerUse( - type, - environment, - (excludedPredefinedFunctions ?: JsonMissing.of()).map { it.toImmutable() }, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): ComputerUse = apply { - if (validated) { - return@apply - } - - _type().let { - if (it != JsonValue.from("computer_use")) { - throw GeminiNextGenApiInvalidDataException("'type' is invalid, received $it") - } - } - environment().ifPresent { it.validate() } - excludedPredefinedFunctions() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - type.let { if (it == JsonValue.from("computer_use")) 1 else 0 } + - (environment.asKnown().getOrNull()?.validity() ?: 0) + - (excludedPredefinedFunctions.asKnown().getOrNull()?.size ?: 0) - - /** The environment being operated. */ - class Environment @JsonCreator private constructor(private val value: JsonField) : - Enum { - - /** - * Returns this class instance's raw value. - * - * This is usually only useful if this instance was deserialized from data that doesn't - * match any known member, and you want to know that value. For example, if the SDK is - * on an older version than the API, then the API may respond with new members that the - * SDK is unaware of. - */ - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - companion object { - - @JvmField val BROWSER = of("browser") - - @JvmStatic fun of(value: String) = Environment(JsonField.of(value)) - } - - /** An enum containing [Environment]'s known values. */ - enum class Known { - BROWSER - } - - /** - * An enum containing [Environment]'s known values, as well as an [_UNKNOWN] member. - * - * An instance of [Environment] can contain an unknown value in a couple of cases: - * - It was deserialized from data that doesn't match any known member. For example, if - * the SDK is on an older version than the API, then the API may respond with new - * members that the SDK is unaware of. - * - It was constructed with an arbitrary value using the [of] method. - */ - enum class Value { - BROWSER, - /** - * An enum member indicating that [Environment] was instantiated with an unknown - * value. - */ - _UNKNOWN, - } - - /** - * Returns an enum member corresponding to this class instance's value, or - * [Value._UNKNOWN] if the class was instantiated with an unknown value. - * - * Use the [known] method instead if you're certain the value is always known or if you - * want to throw for the unknown case. - */ - fun value(): Value = - when (this) { - BROWSER -> Value.BROWSER - else -> Value._UNKNOWN - } - - /** - * Returns an enum member corresponding to this class instance's value. - * - * Use the [value] method instead if you're uncertain the value is always known and - * don't want to throw for the unknown case. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value is a not - * a known member. - */ - fun known(): Known = - when (this) { - BROWSER -> Known.BROWSER - else -> - throw GeminiNextGenApiInvalidDataException("Unknown Environment: $value") - } - - /** - * Returns this class instance's primitive wire representation. - * - * This differs from the [toString] method because that method is primarily for - * debugging and generally doesn't throw. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value does not - * have the expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - GeminiNextGenApiInvalidDataException("Value is not a String") - } - - private var validated: Boolean = false - - fun validate(): Environment = apply { - if (validated) { - return@apply - } - - known() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Environment && value == other.value - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is ComputerUse && - type == other.type && - environment == other.environment && - excludedPredefinedFunctions == other.excludedPredefinedFunctions && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { - Objects.hash(type, environment, excludedPredefinedFunctions, additionalProperties) - } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "ComputerUse{type=$type, environment=$environment, excludedPredefinedFunctions=$excludedPredefinedFunctions, additionalProperties=$additionalProperties}" - } - - /** A MCPServer is a server that can be called by the model to perform actions. */ - class McpServer - @JsonCreator(mode = JsonCreator.Mode.DISABLED) - private constructor( - private val type: JsonValue, - private val allowedTools: JsonField>, - private val headers: JsonField, - private val name: JsonField, - private val url: JsonField, - private val additionalProperties: MutableMap, - ) { - - @JsonCreator - private constructor( - @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), - @JsonProperty("allowed_tools") - @ExcludeMissing - allowedTools: JsonField> = JsonMissing.of(), - @JsonProperty("headers") @ExcludeMissing headers: JsonField = JsonMissing.of(), - @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), - @JsonProperty("url") @ExcludeMissing url: JsonField = JsonMissing.of(), - ) : this(type, allowedTools, headers, name, url, mutableMapOf()) - - /** - * Expected to always return the following: - * ```java - * JsonValue.from("mcp_server") - * ``` - * - * However, this method can be useful for debugging and logging (e.g. if the server - * responded with an unexpected value). - */ - @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type - - /** - * The allowed tools. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type - * (e.g. if the server responded with an unexpected value). - */ - fun allowedTools(): Optional> = allowedTools.getOptional("allowed_tools") - - /** - * Optional: Fields for authentication headers, timeouts, etc., if needed. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type - * (e.g. if the server responded with an unexpected value). - */ - fun headers(): Optional = headers.getOptional("headers") - - /** - * The name of the MCPServer. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type - * (e.g. if the server responded with an unexpected value). - */ - fun name(): Optional = name.getOptional("name") - - /** - * The full URL for the MCPServer endpoint. Example: "https://api.example.com/mcp" - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type - * (e.g. if the server responded with an unexpected value). - */ - fun url(): Optional = url.getOptional("url") - - /** - * Returns the raw JSON value of [allowedTools]. - * - * Unlike [allowedTools], this method doesn't throw if the JSON field has an unexpected - * type. - */ - @JsonProperty("allowed_tools") - @ExcludeMissing - fun _allowedTools(): JsonField> = allowedTools - - /** - * Returns the raw JSON value of [headers]. - * - * Unlike [headers], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("headers") @ExcludeMissing fun _headers(): JsonField = headers - - /** - * Returns the raw JSON value of [name]. - * - * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name - - /** - * Returns the raw JSON value of [url]. - * - * Unlike [url], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("url") @ExcludeMissing fun _url(): JsonField = url - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [McpServer]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [McpServer]. */ - class Builder internal constructor() { - - private var type: JsonValue = JsonValue.from("mcp_server") - private var allowedTools: JsonField>? = null - private var headers: JsonField = JsonMissing.of() - private var name: JsonField = JsonMissing.of() - private var url: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(mcpServer: McpServer) = apply { - type = mcpServer.type - allowedTools = mcpServer.allowedTools.map { it.toMutableList() } - headers = mcpServer.headers - name = mcpServer.name - url = mcpServer.url - additionalProperties = mcpServer.additionalProperties.toMutableMap() - } - - /** - * Sets the field to an arbitrary JSON value. - * - * It is usually unnecessary to call this method because the field defaults to the - * following: - * ```java - * JsonValue.from("mcp_server") - * ``` - * - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun type(type: JsonValue) = apply { this.type = type } - - /** The allowed tools. */ - fun allowedTools(allowedTools: List) = - allowedTools(JsonField.of(allowedTools)) - - /** - * Sets [Builder.allowedTools] to an arbitrary JSON value. - * - * You should usually call [Builder.allowedTools] with a well-typed `List` - * value instead. This method is primarily for setting the field to an undocumented or - * not yet supported value. - */ - fun allowedTools(allowedTools: JsonField>) = apply { - this.allowedTools = allowedTools.map { it.toMutableList() } - } - - /** - * Adds a single [AllowedTools] to [allowedTools]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addAllowedTool(allowedTool: AllowedTools) = apply { - allowedTools = - (allowedTools ?: JsonField.of(mutableListOf())).also { - checkKnown("allowedTools", it).add(allowedTool) - } - } - - /** Optional: Fields for authentication headers, timeouts, etc., if needed. */ - fun headers(headers: Headers) = headers(JsonField.of(headers)) - - /** - * Sets [Builder.headers] to an arbitrary JSON value. - * - * You should usually call [Builder.headers] with a well-typed [Headers] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun headers(headers: JsonField) = apply { this.headers = headers } - - /** The name of the MCPServer. */ - fun name(name: String) = name(JsonField.of(name)) - - /** - * Sets [Builder.name] to an arbitrary JSON value. - * - * You should usually call [Builder.name] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun name(name: JsonField) = apply { this.name = name } - - /** The full URL for the MCPServer endpoint. Example: "https://api.example.com/mcp" */ - fun url(url: String) = url(JsonField.of(url)) - - /** - * Sets [Builder.url] to an arbitrary JSON value. - * - * You should usually call [Builder.url] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun url(url: JsonField) = apply { this.url = url } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [McpServer]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): McpServer = - McpServer( - type, - (allowedTools ?: JsonMissing.of()).map { it.toImmutable() }, - headers, - name, - url, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): McpServer = apply { - if (validated) { - return@apply - } - - _type().let { - if (it != JsonValue.from("mcp_server")) { - throw GeminiNextGenApiInvalidDataException("'type' is invalid, received $it") - } - } - allowedTools().ifPresent { it.forEach { it.validate() } } - headers().ifPresent { it.validate() } - name() - url() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - type.let { if (it == JsonValue.from("mcp_server")) 1 else 0 } + - (allowedTools.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + - (headers.asKnown().getOrNull()?.validity() ?: 0) + - (if (name.asKnown().isPresent) 1 else 0) + - (if (url.asKnown().isPresent) 1 else 0) - - /** Optional: Fields for authentication headers, timeouts, etc., if needed. */ - class Headers - @JsonCreator - private constructor( - @com.fasterxml.jackson.annotation.JsonValue - private val additionalProperties: Map - ) { - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [Headers]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Headers]. */ - class Builder internal constructor() { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(headers: Headers) = apply { - additionalProperties = headers.additionalProperties.toMutableMap() - } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = - apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { - additionalProperties.remove(key) - } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [Headers]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): Headers = Headers(additionalProperties.toImmutable()) - } - - private var validated: Boolean = false - - fun validate(): Headers = apply { - if (validated) { - return@apply - } - - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Headers && additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - - override fun hashCode(): Int = hashCode - - override fun toString() = "Headers{additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is McpServer && - type == other.type && - allowedTools == other.allowedTools && - headers == other.headers && - name == other.name && - url == other.url && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { - Objects.hash(type, allowedTools, headers, name, url, additionalProperties) - } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "McpServer{type=$type, allowedTools=$allowedTools, headers=$headers, name=$name, url=$url, additionalProperties=$additionalProperties}" - } - - /** A tool that can be used by the model to search Google. */ - class GoogleSearch - @JsonCreator(mode = JsonCreator.Mode.DISABLED) - private constructor( - private val type: JsonValue, - private val searchTypes: JsonField>, - private val additionalProperties: MutableMap, - ) { - - @JsonCreator - private constructor( - @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), - @JsonProperty("search_types") - @ExcludeMissing - searchTypes: JsonField> = JsonMissing.of(), - ) : this(type, searchTypes, mutableMapOf()) - - /** - * Expected to always return the following: - * ```java - * JsonValue.from("google_search") - * ``` - * - * However, this method can be useful for debugging and logging (e.g. if the server - * responded with an unexpected value). - */ - @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type - - /** - * The types of search grounding to enable. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type - * (e.g. if the server responded with an unexpected value). - */ - fun searchTypes(): Optional> = searchTypes.getOptional("search_types") - - /** - * Returns the raw JSON value of [searchTypes]. - * - * Unlike [searchTypes], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("search_types") - @ExcludeMissing - fun _searchTypes(): JsonField> = searchTypes - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [GoogleSearch]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [GoogleSearch]. */ - class Builder internal constructor() { - - private var type: JsonValue = JsonValue.from("google_search") - private var searchTypes: JsonField>? = null - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(googleSearch: GoogleSearch) = apply { - type = googleSearch.type - searchTypes = googleSearch.searchTypes.map { it.toMutableList() } - additionalProperties = googleSearch.additionalProperties.toMutableMap() - } - - /** - * Sets the field to an arbitrary JSON value. - * - * It is usually unnecessary to call this method because the field defaults to the - * following: - * ```java - * JsonValue.from("google_search") - * ``` - * - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun type(type: JsonValue) = apply { this.type = type } - - /** The types of search grounding to enable. */ - fun searchTypes(searchTypes: List) = searchTypes(JsonField.of(searchTypes)) - - /** - * Sets [Builder.searchTypes] to an arbitrary JSON value. - * - * You should usually call [Builder.searchTypes] with a well-typed `List` - * value instead. This method is primarily for setting the field to an undocumented or - * not yet supported value. - */ - fun searchTypes(searchTypes: JsonField>) = apply { - this.searchTypes = searchTypes.map { it.toMutableList() } - } - - /** - * Adds a single [SearchType] to [searchTypes]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addSearchType(searchType: SearchType) = apply { - searchTypes = - (searchTypes ?: JsonField.of(mutableListOf())).also { - checkKnown("searchTypes", it).add(searchType) - } - } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [GoogleSearch]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): GoogleSearch = - GoogleSearch( - type, - (searchTypes ?: JsonMissing.of()).map { it.toImmutable() }, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): GoogleSearch = apply { - if (validated) { - return@apply - } - - _type().let { - if (it != JsonValue.from("google_search")) { - throw GeminiNextGenApiInvalidDataException("'type' is invalid, received $it") - } - } - searchTypes().ifPresent { it.forEach { it.validate() } } - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - type.let { if (it == JsonValue.from("google_search")) 1 else 0 } + - (searchTypes.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) - - class SearchType @JsonCreator private constructor(private val value: JsonField) : - Enum { - - /** - * Returns this class instance's raw value. - * - * This is usually only useful if this instance was deserialized from data that doesn't - * match any known member, and you want to know that value. For example, if the SDK is - * on an older version than the API, then the API may respond with new members that the - * SDK is unaware of. - */ - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - companion object { - - @JvmField val WEB_SEARCH = of("web_search") - - @JvmField val IMAGE_SEARCH = of("image_search") - - @JvmField val ENTERPRISE_WEB_SEARCH = of("enterprise_web_search") - - @JvmStatic fun of(value: String) = SearchType(JsonField.of(value)) - } - - /** An enum containing [SearchType]'s known values. */ - enum class Known { - WEB_SEARCH, - IMAGE_SEARCH, - ENTERPRISE_WEB_SEARCH, - } - - /** - * An enum containing [SearchType]'s known values, as well as an [_UNKNOWN] member. - * - * An instance of [SearchType] can contain an unknown value in a couple of cases: - * - It was deserialized from data that doesn't match any known member. For example, if - * the SDK is on an older version than the API, then the API may respond with new - * members that the SDK is unaware of. - * - It was constructed with an arbitrary value using the [of] method. - */ - enum class Value { - WEB_SEARCH, - IMAGE_SEARCH, - ENTERPRISE_WEB_SEARCH, - /** - * An enum member indicating that [SearchType] was instantiated with an unknown - * value. - */ - _UNKNOWN, - } - - /** - * Returns an enum member corresponding to this class instance's value, or - * [Value._UNKNOWN] if the class was instantiated with an unknown value. - * - * Use the [known] method instead if you're certain the value is always known or if you - * want to throw for the unknown case. - */ - fun value(): Value = - when (this) { - WEB_SEARCH -> Value.WEB_SEARCH - IMAGE_SEARCH -> Value.IMAGE_SEARCH - ENTERPRISE_WEB_SEARCH -> Value.ENTERPRISE_WEB_SEARCH - else -> Value._UNKNOWN - } - - /** - * Returns an enum member corresponding to this class instance's value. - * - * Use the [value] method instead if you're uncertain the value is always known and - * don't want to throw for the unknown case. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value is a not - * a known member. - */ - fun known(): Known = - when (this) { - WEB_SEARCH -> Known.WEB_SEARCH - IMAGE_SEARCH -> Known.IMAGE_SEARCH - ENTERPRISE_WEB_SEARCH -> Known.ENTERPRISE_WEB_SEARCH - else -> throw GeminiNextGenApiInvalidDataException("Unknown SearchType: $value") - } - - /** - * Returns this class instance's primitive wire representation. - * - * This differs from the [toString] method because that method is primarily for - * debugging and generally doesn't throw. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value does not - * have the expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - GeminiNextGenApiInvalidDataException("Value is not a String") - } - - private var validated: Boolean = false - - fun validate(): SearchType = apply { - if (validated) { - return@apply - } - - known() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is SearchType && value == other.value - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is GoogleSearch && - type == other.type && - searchTypes == other.searchTypes && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { Objects.hash(type, searchTypes, additionalProperties) } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "GoogleSearch{type=$type, searchTypes=$searchTypes, additionalProperties=$additionalProperties}" - } - - /** A tool that can be used by the model to search files. */ - class FileSearch - @JsonCreator(mode = JsonCreator.Mode.DISABLED) - private constructor( - private val type: JsonValue, - private val fileSearchStoreNames: JsonField>, - private val metadataFilter: JsonField, - private val topK: JsonField, - private val additionalProperties: MutableMap, - ) { - - @JsonCreator - private constructor( - @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), - @JsonProperty("file_search_store_names") - @ExcludeMissing - fileSearchStoreNames: JsonField> = JsonMissing.of(), - @JsonProperty("metadata_filter") - @ExcludeMissing - metadataFilter: JsonField = JsonMissing.of(), - @JsonProperty("top_k") @ExcludeMissing topK: JsonField = JsonMissing.of(), - ) : this(type, fileSearchStoreNames, metadataFilter, topK, mutableMapOf()) - - /** - * Expected to always return the following: - * ```java - * JsonValue.from("file_search") - * ``` - * - * However, this method can be useful for debugging and logging (e.g. if the server - * responded with an unexpected value). - */ - @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type - - /** - * The file search store names to search. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type - * (e.g. if the server responded with an unexpected value). - */ - fun fileSearchStoreNames(): Optional> = - fileSearchStoreNames.getOptional("file_search_store_names") - - /** - * Metadata filter to apply to the semantic retrieval documents and chunks. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type - * (e.g. if the server responded with an unexpected value). - */ - fun metadataFilter(): Optional = metadataFilter.getOptional("metadata_filter") - - /** - * The number of semantic retrieval chunks to retrieve. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type - * (e.g. if the server responded with an unexpected value). - */ - fun topK(): Optional = topK.getOptional("top_k") - - /** - * Returns the raw JSON value of [fileSearchStoreNames]. - * - * Unlike [fileSearchStoreNames], this method doesn't throw if the JSON field has an - * unexpected type. - */ - @JsonProperty("file_search_store_names") - @ExcludeMissing - fun _fileSearchStoreNames(): JsonField> = fileSearchStoreNames - - /** - * Returns the raw JSON value of [metadataFilter]. - * - * Unlike [metadataFilter], this method doesn't throw if the JSON field has an unexpected - * type. - */ - @JsonProperty("metadata_filter") - @ExcludeMissing - fun _metadataFilter(): JsonField = metadataFilter - - /** - * Returns the raw JSON value of [topK]. - * - * Unlike [topK], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("top_k") @ExcludeMissing fun _topK(): JsonField = topK - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [FileSearch]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [FileSearch]. */ - class Builder internal constructor() { - - private var type: JsonValue = JsonValue.from("file_search") - private var fileSearchStoreNames: JsonField>? = null - private var metadataFilter: JsonField = JsonMissing.of() - private var topK: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(fileSearch: FileSearch) = apply { - type = fileSearch.type - fileSearchStoreNames = fileSearch.fileSearchStoreNames.map { it.toMutableList() } - metadataFilter = fileSearch.metadataFilter - topK = fileSearch.topK - additionalProperties = fileSearch.additionalProperties.toMutableMap() - } - - /** - * Sets the field to an arbitrary JSON value. - * - * It is usually unnecessary to call this method because the field defaults to the - * following: - * ```java - * JsonValue.from("file_search") - * ``` - * - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun type(type: JsonValue) = apply { this.type = type } - - /** The file search store names to search. */ - fun fileSearchStoreNames(fileSearchStoreNames: List) = - fileSearchStoreNames(JsonField.of(fileSearchStoreNames)) - - /** - * Sets [Builder.fileSearchStoreNames] to an arbitrary JSON value. - * - * You should usually call [Builder.fileSearchStoreNames] with a well-typed - * `List` value instead. This method is primarily for setting the field to an - * undocumented or not yet supported value. - */ - fun fileSearchStoreNames(fileSearchStoreNames: JsonField>) = apply { - this.fileSearchStoreNames = fileSearchStoreNames.map { it.toMutableList() } - } - - /** - * Adds a single [String] to [fileSearchStoreNames]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addFileSearchStoreName(fileSearchStoreName: String) = apply { - fileSearchStoreNames = - (fileSearchStoreNames ?: JsonField.of(mutableListOf())).also { - checkKnown("fileSearchStoreNames", it).add(fileSearchStoreName) - } - } - - /** Metadata filter to apply to the semantic retrieval documents and chunks. */ - fun metadataFilter(metadataFilter: String) = - metadataFilter(JsonField.of(metadataFilter)) - - /** - * Sets [Builder.metadataFilter] to an arbitrary JSON value. - * - * You should usually call [Builder.metadataFilter] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun metadataFilter(metadataFilter: JsonField) = apply { - this.metadataFilter = metadataFilter - } - - /** The number of semantic retrieval chunks to retrieve. */ - fun topK(topK: Int) = topK(JsonField.of(topK)) - - /** - * Sets [Builder.topK] to an arbitrary JSON value. - * - * You should usually call [Builder.topK] with a well-typed [Int] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun topK(topK: JsonField) = apply { this.topK = topK } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [FileSearch]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): FileSearch = - FileSearch( - type, - (fileSearchStoreNames ?: JsonMissing.of()).map { it.toImmutable() }, - metadataFilter, - topK, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): FileSearch = apply { - if (validated) { - return@apply - } - - _type().let { - if (it != JsonValue.from("file_search")) { - throw GeminiNextGenApiInvalidDataException("'type' is invalid, received $it") - } - } - fileSearchStoreNames() - metadataFilter() - topK() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - type.let { if (it == JsonValue.from("file_search")) 1 else 0 } + - (fileSearchStoreNames.asKnown().getOrNull()?.size ?: 0) + - (if (metadataFilter.asKnown().isPresent) 1 else 0) + - (if (topK.asKnown().isPresent) 1 else 0) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is FileSearch && - type == other.type && - fileSearchStoreNames == other.fileSearchStoreNames && - metadataFilter == other.metadataFilter && - topK == other.topK && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { - Objects.hash(type, fileSearchStoreNames, metadataFilter, topK, additionalProperties) - } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "FileSearch{type=$type, fileSearchStoreNames=$fileSearchStoreNames, metadataFilter=$metadataFilter, topK=$topK, additionalProperties=$additionalProperties}" - } - - /** A tool that can be used by the model to call Google Maps. */ - class GoogleMaps - @JsonCreator(mode = JsonCreator.Mode.DISABLED) - private constructor( - private val type: JsonValue, - private val enableWidget: JsonField, - private val latitude: JsonField, - private val longitude: JsonField, - private val additionalProperties: MutableMap, - ) { - - @JsonCreator - private constructor( - @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), - @JsonProperty("enable_widget") - @ExcludeMissing - enableWidget: JsonField = JsonMissing.of(), - @JsonProperty("latitude") - @ExcludeMissing - latitude: JsonField = JsonMissing.of(), - @JsonProperty("longitude") - @ExcludeMissing - longitude: JsonField = JsonMissing.of(), - ) : this(type, enableWidget, latitude, longitude, mutableMapOf()) - - /** - * Expected to always return the following: - * ```java - * JsonValue.from("google_maps") - * ``` - * - * However, this method can be useful for debugging and logging (e.g. if the server - * responded with an unexpected value). - */ - @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type - - /** - * Whether to return a widget context token in the tool call result of the response. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type - * (e.g. if the server responded with an unexpected value). - */ - fun enableWidget(): Optional = enableWidget.getOptional("enable_widget") - - /** - * The latitude of the user's location. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type - * (e.g. if the server responded with an unexpected value). - */ - fun latitude(): Optional = latitude.getOptional("latitude") - - /** - * The longitude of the user's location. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type - * (e.g. if the server responded with an unexpected value). - */ - fun longitude(): Optional = longitude.getOptional("longitude") - - /** - * Returns the raw JSON value of [enableWidget]. - * - * Unlike [enableWidget], this method doesn't throw if the JSON field has an unexpected - * type. - */ - @JsonProperty("enable_widget") - @ExcludeMissing - fun _enableWidget(): JsonField = enableWidget - - /** - * Returns the raw JSON value of [latitude]. - * - * Unlike [latitude], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("latitude") @ExcludeMissing fun _latitude(): JsonField = latitude - - /** - * Returns the raw JSON value of [longitude]. - * - * Unlike [longitude], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("longitude") @ExcludeMissing fun _longitude(): JsonField = longitude - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [GoogleMaps]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [GoogleMaps]. */ - class Builder internal constructor() { - - private var type: JsonValue = JsonValue.from("google_maps") - private var enableWidget: JsonField = JsonMissing.of() - private var latitude: JsonField = JsonMissing.of() - private var longitude: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(googleMaps: GoogleMaps) = apply { - type = googleMaps.type - enableWidget = googleMaps.enableWidget - latitude = googleMaps.latitude - longitude = googleMaps.longitude - additionalProperties = googleMaps.additionalProperties.toMutableMap() - } - - /** - * Sets the field to an arbitrary JSON value. - * - * It is usually unnecessary to call this method because the field defaults to the - * following: - * ```java - * JsonValue.from("google_maps") - * ``` - * - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun type(type: JsonValue) = apply { this.type = type } - - /** Whether to return a widget context token in the tool call result of the response. */ - fun enableWidget(enableWidget: Boolean) = enableWidget(JsonField.of(enableWidget)) - - /** - * Sets [Builder.enableWidget] to an arbitrary JSON value. - * - * You should usually call [Builder.enableWidget] with a well-typed [Boolean] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun enableWidget(enableWidget: JsonField) = apply { - this.enableWidget = enableWidget - } - - /** The latitude of the user's location. */ - fun latitude(latitude: Double) = latitude(JsonField.of(latitude)) - - /** - * Sets [Builder.latitude] to an arbitrary JSON value. - * - * You should usually call [Builder.latitude] with a well-typed [Double] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun latitude(latitude: JsonField) = apply { this.latitude = latitude } - - /** The longitude of the user's location. */ - fun longitude(longitude: Double) = longitude(JsonField.of(longitude)) - - /** - * Sets [Builder.longitude] to an arbitrary JSON value. - * - * You should usually call [Builder.longitude] with a well-typed [Double] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun longitude(longitude: JsonField) = apply { this.longitude = longitude } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [GoogleMaps]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): GoogleMaps = - GoogleMaps( - type, - enableWidget, - latitude, - longitude, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): GoogleMaps = apply { - if (validated) { - return@apply - } - - _type().let { - if (it != JsonValue.from("google_maps")) { - throw GeminiNextGenApiInvalidDataException("'type' is invalid, received $it") - } - } - enableWidget() - latitude() - longitude() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - type.let { if (it == JsonValue.from("google_maps")) 1 else 0 } + - (if (enableWidget.asKnown().isPresent) 1 else 0) + - (if (latitude.asKnown().isPresent) 1 else 0) + - (if (longitude.asKnown().isPresent) 1 else 0) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is GoogleMaps && - type == other.type && - enableWidget == other.enableWidget && - latitude == other.latitude && - longitude == other.longitude && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { - Objects.hash(type, enableWidget, latitude, longitude, additionalProperties) - } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "GoogleMaps{type=$type, enableWidget=$enableWidget, latitude=$latitude, longitude=$longitude, additionalProperties=$additionalProperties}" - } - - /** A tool that can be used by the model to retrieve files. */ - class Retrieval - @JsonCreator(mode = JsonCreator.Mode.DISABLED) - private constructor( - private val type: JsonValue, - private val retrievalTypes: JsonField>, - private val vertexAiSearchConfig: JsonField, - private val additionalProperties: MutableMap, - ) { - - @JsonCreator - private constructor( - @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), - @JsonProperty("retrieval_types") - @ExcludeMissing - retrievalTypes: JsonField> = JsonMissing.of(), - @JsonProperty("vertex_ai_search_config") - @ExcludeMissing - vertexAiSearchConfig: JsonField = JsonMissing.of(), - ) : this(type, retrievalTypes, vertexAiSearchConfig, mutableMapOf()) - - /** - * Expected to always return the following: - * ```java - * JsonValue.from("retrieval") - * ``` - * - * However, this method can be useful for debugging and logging (e.g. if the server - * responded with an unexpected value). - */ - @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type - - /** - * The types of file retrieval to enable. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type - * (e.g. if the server responded with an unexpected value). - */ - fun retrievalTypes(): Optional> = - retrievalTypes.getOptional("retrieval_types") - - /** - * Used to specify configuration for VertexAISearch. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type - * (e.g. if the server responded with an unexpected value). - */ - fun vertexAiSearchConfig(): Optional = - vertexAiSearchConfig.getOptional("vertex_ai_search_config") - - /** - * Returns the raw JSON value of [retrievalTypes]. - * - * Unlike [retrievalTypes], this method doesn't throw if the JSON field has an unexpected - * type. - */ - @JsonProperty("retrieval_types") - @ExcludeMissing - fun _retrievalTypes(): JsonField> = retrievalTypes - - /** - * Returns the raw JSON value of [vertexAiSearchConfig]. - * - * Unlike [vertexAiSearchConfig], this method doesn't throw if the JSON field has an - * unexpected type. - */ - @JsonProperty("vertex_ai_search_config") - @ExcludeMissing - fun _vertexAiSearchConfig(): JsonField = vertexAiSearchConfig - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [Retrieval]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Retrieval]. */ - class Builder internal constructor() { - - private var type: JsonValue = JsonValue.from("retrieval") - private var retrievalTypes: JsonField>? = null - private var vertexAiSearchConfig: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(retrieval: Retrieval) = apply { - type = retrieval.type - retrievalTypes = retrieval.retrievalTypes.map { it.toMutableList() } - vertexAiSearchConfig = retrieval.vertexAiSearchConfig - additionalProperties = retrieval.additionalProperties.toMutableMap() - } - - /** - * Sets the field to an arbitrary JSON value. - * - * It is usually unnecessary to call this method because the field defaults to the - * following: - * ```java - * JsonValue.from("retrieval") - * ``` - * - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun type(type: JsonValue) = apply { this.type = type } - - /** The types of file retrieval to enable. */ - fun retrievalTypes(retrievalTypes: List) = - retrievalTypes(JsonField.of(retrievalTypes)) - - /** - * Sets [Builder.retrievalTypes] to an arbitrary JSON value. - * - * You should usually call [Builder.retrievalTypes] with a well-typed - * `List` value instead. This method is primarily for setting the field - * to an undocumented or not yet supported value. - */ - fun retrievalTypes(retrievalTypes: JsonField>) = apply { - this.retrievalTypes = retrievalTypes.map { it.toMutableList() } - } - - /** - * Adds a single [RetrievalType] to [retrievalTypes]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addRetrievalType(retrievalType: RetrievalType) = apply { - retrievalTypes = - (retrievalTypes ?: JsonField.of(mutableListOf())).also { - checkKnown("retrievalTypes", it).add(retrievalType) - } - } - - /** Used to specify configuration for VertexAISearch. */ - fun vertexAiSearchConfig(vertexAiSearchConfig: VertexAiSearchConfig) = - vertexAiSearchConfig(JsonField.of(vertexAiSearchConfig)) - - /** - * Sets [Builder.vertexAiSearchConfig] to an arbitrary JSON value. - * - * You should usually call [Builder.vertexAiSearchConfig] with a well-typed - * [VertexAiSearchConfig] value instead. This method is primarily for setting the field - * to an undocumented or not yet supported value. - */ - fun vertexAiSearchConfig(vertexAiSearchConfig: JsonField) = - apply { - this.vertexAiSearchConfig = vertexAiSearchConfig - } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [Retrieval]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): Retrieval = - Retrieval( - type, - (retrievalTypes ?: JsonMissing.of()).map { it.toImmutable() }, - vertexAiSearchConfig, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): Retrieval = apply { - if (validated) { - return@apply - } - - _type().let { - if (it != JsonValue.from("retrieval")) { - throw GeminiNextGenApiInvalidDataException("'type' is invalid, received $it") - } - } - retrievalTypes().ifPresent { it.forEach { it.validate() } } - vertexAiSearchConfig().ifPresent { it.validate() } - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - type.let { if (it == JsonValue.from("retrieval")) 1 else 0 } + - (retrievalTypes.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + - (vertexAiSearchConfig.asKnown().getOrNull()?.validity() ?: 0) - - class RetrievalType @JsonCreator private constructor(private val value: JsonField) : - Enum { - - /** - * Returns this class instance's raw value. - * - * This is usually only useful if this instance was deserialized from data that doesn't - * match any known member, and you want to know that value. For example, if the SDK is - * on an older version than the API, then the API may respond with new members that the - * SDK is unaware of. - */ - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - companion object { - - @JvmField val VERTEX_AI_SEARCH = of("vertex_ai_search") - - @JvmStatic fun of(value: String) = RetrievalType(JsonField.of(value)) - } - - /** An enum containing [RetrievalType]'s known values. */ - enum class Known { - VERTEX_AI_SEARCH - } - - /** - * An enum containing [RetrievalType]'s known values, as well as an [_UNKNOWN] member. - * - * An instance of [RetrievalType] can contain an unknown value in a couple of cases: - * - It was deserialized from data that doesn't match any known member. For example, if - * the SDK is on an older version than the API, then the API may respond with new - * members that the SDK is unaware of. - * - It was constructed with an arbitrary value using the [of] method. - */ - enum class Value { - VERTEX_AI_SEARCH, - /** - * An enum member indicating that [RetrievalType] was instantiated with an unknown - * value. - */ - _UNKNOWN, - } - - /** - * Returns an enum member corresponding to this class instance's value, or - * [Value._UNKNOWN] if the class was instantiated with an unknown value. - * - * Use the [known] method instead if you're certain the value is always known or if you - * want to throw for the unknown case. - */ - fun value(): Value = - when (this) { - VERTEX_AI_SEARCH -> Value.VERTEX_AI_SEARCH - else -> Value._UNKNOWN - } - - /** - * Returns an enum member corresponding to this class instance's value. - * - * Use the [value] method instead if you're uncertain the value is always known and - * don't want to throw for the unknown case. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value is a not - * a known member. - */ - fun known(): Known = - when (this) { - VERTEX_AI_SEARCH -> Known.VERTEX_AI_SEARCH - else -> - throw GeminiNextGenApiInvalidDataException("Unknown RetrievalType: $value") - } - - /** - * Returns this class instance's primitive wire representation. - * - * This differs from the [toString] method because that method is primarily for - * debugging and generally doesn't throw. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value does not - * have the expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - GeminiNextGenApiInvalidDataException("Value is not a String") - } - - private var validated: Boolean = false - - fun validate(): RetrievalType = apply { - if (validated) { - return@apply - } - - known() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is RetrievalType && value == other.value - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - /** Used to specify configuration for VertexAISearch. */ - class VertexAiSearchConfig - @JsonCreator(mode = JsonCreator.Mode.DISABLED) - private constructor( - private val datastores: JsonField>, - private val engine: JsonField, - private val additionalProperties: MutableMap, - ) { - - @JsonCreator - private constructor( - @JsonProperty("datastores") - @ExcludeMissing - datastores: JsonField> = JsonMissing.of(), - @JsonProperty("engine") @ExcludeMissing engine: JsonField = JsonMissing.of(), - ) : this(datastores, engine, mutableMapOf()) - - /** - * Optional. Used to specify Vertex AI Search datastores. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type - * (e.g. if the server responded with an unexpected value). - */ - fun datastores(): Optional> = datastores.getOptional("datastores") - - /** - * Optional. Used to specify Vertex AI Search engine. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type - * (e.g. if the server responded with an unexpected value). - */ - fun engine(): Optional = engine.getOptional("engine") - - /** - * Returns the raw JSON value of [datastores]. - * - * Unlike [datastores], this method doesn't throw if the JSON field has an unexpected - * type. - */ - @JsonProperty("datastores") - @ExcludeMissing - fun _datastores(): JsonField> = datastores - - /** - * Returns the raw JSON value of [engine]. - * - * Unlike [engine], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("engine") @ExcludeMissing fun _engine(): JsonField = engine - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [VertexAiSearchConfig]. - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [VertexAiSearchConfig]. */ - class Builder internal constructor() { - - private var datastores: JsonField>? = null - private var engine: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(vertexAiSearchConfig: VertexAiSearchConfig) = apply { - datastores = vertexAiSearchConfig.datastores.map { it.toMutableList() } - engine = vertexAiSearchConfig.engine - additionalProperties = vertexAiSearchConfig.additionalProperties.toMutableMap() - } - - /** Optional. Used to specify Vertex AI Search datastores. */ - fun datastores(datastores: List) = datastores(JsonField.of(datastores)) - - /** - * Sets [Builder.datastores] to an arbitrary JSON value. - * - * You should usually call [Builder.datastores] with a well-typed `List` - * value instead. This method is primarily for setting the field to an undocumented - * or not yet supported value. - */ - fun datastores(datastores: JsonField>) = apply { - this.datastores = datastores.map { it.toMutableList() } - } - - /** - * Adds a single [String] to [datastores]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addDatastore(datastore: String) = apply { - datastores = - (datastores ?: JsonField.of(mutableListOf())).also { - checkKnown("datastores", it).add(datastore) - } - } - - /** Optional. Used to specify Vertex AI Search engine. */ - fun engine(engine: String) = engine(JsonField.of(engine)) - - /** - * Sets [Builder.engine] to an arbitrary JSON value. - * - * You should usually call [Builder.engine] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not - * yet supported value. - */ - fun engine(engine: JsonField) = apply { this.engine = engine } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = - apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { - additionalProperties.remove(key) - } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [VertexAiSearchConfig]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): VertexAiSearchConfig = - VertexAiSearchConfig( - (datastores ?: JsonMissing.of()).map { it.toImmutable() }, - engine, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): VertexAiSearchConfig = apply { - if (validated) { - return@apply - } - - datastores() - engine() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - (datastores.asKnown().getOrNull()?.size ?: 0) + - (if (engine.asKnown().isPresent) 1 else 0) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is VertexAiSearchConfig && - datastores == other.datastores && - engine == other.engine && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { - Objects.hash(datastores, engine, additionalProperties) - } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "VertexAiSearchConfig{datastores=$datastores, engine=$engine, additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Retrieval && - type == other.type && - retrievalTypes == other.retrievalTypes && - vertexAiSearchConfig == other.vertexAiSearchConfig && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { - Objects.hash(type, retrievalTypes, vertexAiSearchConfig, additionalProperties) - } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Retrieval{type=$type, retrievalTypes=$retrievalTypes, vertexAiSearchConfig=$vertexAiSearchConfig, additionalProperties=$additionalProperties}" - } -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/ToolChoiceConfig.kt b/src/main/java/com/google/genai/interactions/models/interactions/ToolChoiceConfig.kt deleted file mode 100644 index 528d6690686..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/ToolChoiceConfig.kt +++ /dev/null @@ -1,182 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import com.google.genai.interactions.core.ExcludeMissing -import com.google.genai.interactions.core.JsonField -import com.google.genai.interactions.core.JsonMissing -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.util.Collections -import java.util.Objects -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -/** The tool choice configuration containing allowed tools. */ -class ToolChoiceConfig -@JsonCreator(mode = JsonCreator.Mode.DISABLED) -private constructor( - private val allowedTools: JsonField, - private val additionalProperties: MutableMap, -) { - - @JsonCreator - private constructor( - @JsonProperty("allowed_tools") - @ExcludeMissing - allowedTools: JsonField = JsonMissing.of() - ) : this(allowedTools, mutableMapOf()) - - /** - * The allowed tools. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun allowedTools(): Optional = allowedTools.getOptional("allowed_tools") - - /** - * Returns the raw JSON value of [allowedTools]. - * - * Unlike [allowedTools], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("allowed_tools") - @ExcludeMissing - fun _allowedTools(): JsonField = allowedTools - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [ToolChoiceConfig]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [ToolChoiceConfig]. */ - class Builder internal constructor() { - - private var allowedTools: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(toolChoiceConfig: ToolChoiceConfig) = apply { - allowedTools = toolChoiceConfig.allowedTools - additionalProperties = toolChoiceConfig.additionalProperties.toMutableMap() - } - - /** The allowed tools. */ - fun allowedTools(allowedTools: AllowedTools) = allowedTools(JsonField.of(allowedTools)) - - /** - * Sets [Builder.allowedTools] to an arbitrary JSON value. - * - * You should usually call [Builder.allowedTools] with a well-typed [AllowedTools] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun allowedTools(allowedTools: JsonField) = apply { - this.allowedTools = allowedTools - } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [ToolChoiceConfig]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): ToolChoiceConfig = - ToolChoiceConfig(allowedTools, additionalProperties.toMutableMap()) - } - - private var validated: Boolean = false - - fun validate(): ToolChoiceConfig = apply { - if (validated) { - return@apply - } - - allowedTools().ifPresent { it.validate() } - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = (allowedTools.asKnown().getOrNull()?.validity() ?: 0) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is ToolChoiceConfig && - allowedTools == other.allowedTools && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { Objects.hash(allowedTools, additionalProperties) } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "ToolChoiceConfig{allowedTools=$allowedTools, additionalProperties=$additionalProperties}" -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/ToolChoiceType.kt b/src/main/java/com/google/genai/interactions/models/interactions/ToolChoiceType.kt deleted file mode 100644 index 5e7d4d41a7d..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/ToolChoiceType.kt +++ /dev/null @@ -1,163 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.annotation.JsonCreator -import com.google.genai.interactions.core.Enum -import com.google.genai.interactions.core.JsonField -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException - -class ToolChoiceType @JsonCreator private constructor(private val value: JsonField) : Enum { - - /** - * Returns this class instance's raw value. - * - * This is usually only useful if this instance was deserialized from data that doesn't match - * any known member, and you want to know that value. For example, if the SDK is on an older - * version than the API, then the API may respond with new members that the SDK is unaware of. - */ - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - companion object { - - @JvmField val AUTO = of("auto") - - @JvmField val ANY = of("any") - - @JvmField val NONE = of("none") - - @JvmField val VALIDATED = of("validated") - - @JvmStatic fun of(value: String) = ToolChoiceType(JsonField.of(value)) - } - - /** An enum containing [ToolChoiceType]'s known values. */ - enum class Known { - AUTO, - ANY, - NONE, - VALIDATED, - } - - /** - * An enum containing [ToolChoiceType]'s known values, as well as an [_UNKNOWN] member. - * - * An instance of [ToolChoiceType] can contain an unknown value in a couple of cases: - * - It was deserialized from data that doesn't match any known member. For example, if the SDK - * is on an older version than the API, then the API may respond with new members that the SDK - * is unaware of. - * - It was constructed with an arbitrary value using the [of] method. - */ - enum class Value { - AUTO, - ANY, - NONE, - VALIDATED, - /** - * An enum member indicating that [ToolChoiceType] was instantiated with an unknown value. - */ - _UNKNOWN, - } - - /** - * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] if - * the class was instantiated with an unknown value. - * - * Use the [known] method instead if you're certain the value is always known or if you want to - * throw for the unknown case. - */ - fun value(): Value = - when (this) { - AUTO -> Value.AUTO - ANY -> Value.ANY - NONE -> Value.NONE - VALIDATED -> Value.VALIDATED - else -> Value._UNKNOWN - } - - /** - * Returns an enum member corresponding to this class instance's value. - * - * Use the [value] method instead if you're uncertain the value is always known and don't want - * to throw for the unknown case. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value is a not a known - * member. - */ - fun known(): Known = - when (this) { - AUTO -> Known.AUTO - ANY -> Known.ANY - NONE -> Known.NONE - VALIDATED -> Known.VALIDATED - else -> throw GeminiNextGenApiInvalidDataException("Unknown ToolChoiceType: $value") - } - - /** - * Returns this class instance's primitive wire representation. - * - * This differs from the [toString] method because that method is primarily for debugging and - * generally doesn't throw. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value does not have the - * expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - GeminiNextGenApiInvalidDataException("Value is not a String") - } - - private var validated: Boolean = false - - fun validate(): ToolChoiceType = apply { - if (validated) { - return@apply - } - - known() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is ToolChoiceType && value == other.value - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/UrlCitation.kt b/src/main/java/com/google/genai/interactions/models/interactions/UrlCitation.kt deleted file mode 100644 index feb5f29271d..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/UrlCitation.kt +++ /dev/null @@ -1,318 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import com.google.genai.interactions.core.ExcludeMissing -import com.google.genai.interactions.core.JsonField -import com.google.genai.interactions.core.JsonMissing -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.util.Collections -import java.util.Objects -import java.util.Optional - -/** A URL citation annotation. */ -class UrlCitation -@JsonCreator(mode = JsonCreator.Mode.DISABLED) -private constructor( - private val type: JsonValue, - private val endIndex: JsonField, - private val startIndex: JsonField, - private val title: JsonField, - private val url: JsonField, - private val additionalProperties: MutableMap, -) { - - @JsonCreator - private constructor( - @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), - @JsonProperty("end_index") @ExcludeMissing endIndex: JsonField = JsonMissing.of(), - @JsonProperty("start_index") @ExcludeMissing startIndex: JsonField = JsonMissing.of(), - @JsonProperty("title") @ExcludeMissing title: JsonField = JsonMissing.of(), - @JsonProperty("url") @ExcludeMissing url: JsonField = JsonMissing.of(), - ) : this(type, endIndex, startIndex, title, url, mutableMapOf()) - - /** - * Expected to always return the following: - * ```java - * JsonValue.from("url_citation") - * ``` - * - * However, this method can be useful for debugging and logging (e.g. if the server responded - * with an unexpected value). - */ - @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type - - /** - * End of the attributed segment, exclusive. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun endIndex(): Optional = endIndex.getOptional("end_index") - - /** - * Start of segment of the response that is attributed to this source. - * - * Index indicates the start of the segment, measured in bytes. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun startIndex(): Optional = startIndex.getOptional("start_index") - - /** - * The title of the URL. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun title(): Optional = title.getOptional("title") - - /** - * The URL. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun url(): Optional = url.getOptional("url") - - /** - * Returns the raw JSON value of [endIndex]. - * - * Unlike [endIndex], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("end_index") @ExcludeMissing fun _endIndex(): JsonField = endIndex - - /** - * Returns the raw JSON value of [startIndex]. - * - * Unlike [startIndex], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("start_index") @ExcludeMissing fun _startIndex(): JsonField = startIndex - - /** - * Returns the raw JSON value of [title]. - * - * Unlike [title], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("title") @ExcludeMissing fun _title(): JsonField = title - - /** - * Returns the raw JSON value of [url]. - * - * Unlike [url], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("url") @ExcludeMissing fun _url(): JsonField = url - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [UrlCitation]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [UrlCitation]. */ - class Builder internal constructor() { - - private var type: JsonValue = JsonValue.from("url_citation") - private var endIndex: JsonField = JsonMissing.of() - private var startIndex: JsonField = JsonMissing.of() - private var title: JsonField = JsonMissing.of() - private var url: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(urlCitation: UrlCitation) = apply { - type = urlCitation.type - endIndex = urlCitation.endIndex - startIndex = urlCitation.startIndex - title = urlCitation.title - url = urlCitation.url - additionalProperties = urlCitation.additionalProperties.toMutableMap() - } - - /** - * Sets the field to an arbitrary JSON value. - * - * It is usually unnecessary to call this method because the field defaults to the - * following: - * ```java - * JsonValue.from("url_citation") - * ``` - * - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun type(type: JsonValue) = apply { this.type = type } - - /** End of the attributed segment, exclusive. */ - fun endIndex(endIndex: Int) = endIndex(JsonField.of(endIndex)) - - /** - * Sets [Builder.endIndex] to an arbitrary JSON value. - * - * You should usually call [Builder.endIndex] with a well-typed [Int] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun endIndex(endIndex: JsonField) = apply { this.endIndex = endIndex } - - /** - * Start of segment of the response that is attributed to this source. - * - * Index indicates the start of the segment, measured in bytes. - */ - fun startIndex(startIndex: Int) = startIndex(JsonField.of(startIndex)) - - /** - * Sets [Builder.startIndex] to an arbitrary JSON value. - * - * You should usually call [Builder.startIndex] with a well-typed [Int] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun startIndex(startIndex: JsonField) = apply { this.startIndex = startIndex } - - /** The title of the URL. */ - fun title(title: String) = title(JsonField.of(title)) - - /** - * Sets [Builder.title] to an arbitrary JSON value. - * - * You should usually call [Builder.title] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun title(title: JsonField) = apply { this.title = title } - - /** The URL. */ - fun url(url: String) = url(JsonField.of(url)) - - /** - * Sets [Builder.url] to an arbitrary JSON value. - * - * You should usually call [Builder.url] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun url(url: JsonField) = apply { this.url = url } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [UrlCitation]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): UrlCitation = - UrlCitation(type, endIndex, startIndex, title, url, additionalProperties.toMutableMap()) - } - - private var validated: Boolean = false - - fun validate(): UrlCitation = apply { - if (validated) { - return@apply - } - - _type().let { - if (it != JsonValue.from("url_citation")) { - throw GeminiNextGenApiInvalidDataException("'type' is invalid, received $it") - } - } - endIndex() - startIndex() - title() - url() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - type.let { if (it == JsonValue.from("url_citation")) 1 else 0 } + - (if (endIndex.asKnown().isPresent) 1 else 0) + - (if (startIndex.asKnown().isPresent) 1 else 0) + - (if (title.asKnown().isPresent) 1 else 0) + - (if (url.asKnown().isPresent) 1 else 0) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is UrlCitation && - type == other.type && - endIndex == other.endIndex && - startIndex == other.startIndex && - title == other.title && - url == other.url && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { - Objects.hash(type, endIndex, startIndex, title, url, additionalProperties) - } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "UrlCitation{type=$type, endIndex=$endIndex, startIndex=$startIndex, title=$title, url=$url, additionalProperties=$additionalProperties}" -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/UrlContextCallArguments.kt b/src/main/java/com/google/genai/interactions/models/interactions/UrlContextCallArguments.kt deleted file mode 100644 index aab7bc8f310..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/UrlContextCallArguments.kt +++ /dev/null @@ -1,191 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import com.google.genai.interactions.core.ExcludeMissing -import com.google.genai.interactions.core.JsonField -import com.google.genai.interactions.core.JsonMissing -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.core.checkKnown -import com.google.genai.interactions.core.toImmutable -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.util.Collections -import java.util.Objects -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -/** The arguments to pass to the URL context. */ -class UrlContextCallArguments -@JsonCreator(mode = JsonCreator.Mode.DISABLED) -private constructor( - private val urls: JsonField>, - private val additionalProperties: MutableMap, -) { - - @JsonCreator - private constructor( - @JsonProperty("urls") @ExcludeMissing urls: JsonField> = JsonMissing.of() - ) : this(urls, mutableMapOf()) - - /** - * The URLs to fetch. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun urls(): Optional> = urls.getOptional("urls") - - /** - * Returns the raw JSON value of [urls]. - * - * Unlike [urls], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("urls") @ExcludeMissing fun _urls(): JsonField> = urls - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [UrlContextCallArguments]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [UrlContextCallArguments]. */ - class Builder internal constructor() { - - private var urls: JsonField>? = null - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(urlContextCallArguments: UrlContextCallArguments) = apply { - urls = urlContextCallArguments.urls.map { it.toMutableList() } - additionalProperties = urlContextCallArguments.additionalProperties.toMutableMap() - } - - /** The URLs to fetch. */ - fun urls(urls: List) = urls(JsonField.of(urls)) - - /** - * Sets [Builder.urls] to an arbitrary JSON value. - * - * You should usually call [Builder.urls] with a well-typed `List` value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun urls(urls: JsonField>) = apply { - this.urls = urls.map { it.toMutableList() } - } - - /** - * Adds a single [String] to [urls]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addUrl(url: String) = apply { - urls = (urls ?: JsonField.of(mutableListOf())).also { checkKnown("urls", it).add(url) } - } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [UrlContextCallArguments]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): UrlContextCallArguments = - UrlContextCallArguments( - (urls ?: JsonMissing.of()).map { it.toImmutable() }, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): UrlContextCallArguments = apply { - if (validated) { - return@apply - } - - urls() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic internal fun validity(): Int = (urls.asKnown().getOrNull()?.size ?: 0) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is UrlContextCallArguments && - urls == other.urls && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { Objects.hash(urls, additionalProperties) } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "UrlContextCallArguments{urls=$urls, additionalProperties=$additionalProperties}" -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/UrlContextCallStep.kt b/src/main/java/com/google/genai/interactions/models/interactions/UrlContextCallStep.kt deleted file mode 100644 index 36821c5befa..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/UrlContextCallStep.kt +++ /dev/null @@ -1,467 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import com.google.genai.interactions.core.ExcludeMissing -import com.google.genai.interactions.core.JsonField -import com.google.genai.interactions.core.JsonMissing -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.core.checkKnown -import com.google.genai.interactions.core.checkRequired -import com.google.genai.interactions.core.toImmutable -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.util.Collections -import java.util.Objects -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -/** URL context call step. */ -class UrlContextCallStep -@JsonCreator(mode = JsonCreator.Mode.DISABLED) -private constructor( - private val id: JsonField, - private val arguments: JsonField, - private val type: JsonValue, - private val signature: JsonField, - private val additionalProperties: MutableMap, -) { - - @JsonCreator - private constructor( - @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), - @JsonProperty("arguments") - @ExcludeMissing - arguments: JsonField = JsonMissing.of(), - @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), - @JsonProperty("signature") @ExcludeMissing signature: JsonField = JsonMissing.of(), - ) : this(id, arguments, type, signature, mutableMapOf()) - - /** - * Required. A unique ID for this specific tool call. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). - */ - fun id(): String = id.getRequired("id") - - /** - * Required. The arguments to pass to the URL context. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). - */ - fun arguments(): Arguments = arguments.getRequired("arguments") - - /** - * Expected to always return the following: - * ```java - * JsonValue.from("url_context_call") - * ``` - * - * However, this method can be useful for debugging and logging (e.g. if the server responded - * with an unexpected value). - */ - @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type - - /** - * A signature hash for backend validation. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun signature(): Optional = signature.getOptional("signature") - - /** - * Returns the raw JSON value of [id]. - * - * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id - - /** - * Returns the raw JSON value of [arguments]. - * - * Unlike [arguments], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("arguments") @ExcludeMissing fun _arguments(): JsonField = arguments - - /** - * Returns the raw JSON value of [signature]. - * - * Unlike [signature], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("signature") @ExcludeMissing fun _signature(): JsonField = signature - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [UrlContextCallStep]. - * - * The following fields are required: - * ```java - * .id() - * .arguments() - * ``` - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [UrlContextCallStep]. */ - class Builder internal constructor() { - - private var id: JsonField? = null - private var arguments: JsonField? = null - private var type: JsonValue = JsonValue.from("url_context_call") - private var signature: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(urlContextCallStep: UrlContextCallStep) = apply { - id = urlContextCallStep.id - arguments = urlContextCallStep.arguments - type = urlContextCallStep.type - signature = urlContextCallStep.signature - additionalProperties = urlContextCallStep.additionalProperties.toMutableMap() - } - - /** Required. A unique ID for this specific tool call. */ - fun id(id: String) = id(JsonField.of(id)) - - /** - * Sets [Builder.id] to an arbitrary JSON value. - * - * You should usually call [Builder.id] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun id(id: JsonField) = apply { this.id = id } - - /** Required. The arguments to pass to the URL context. */ - fun arguments(arguments: Arguments) = arguments(JsonField.of(arguments)) - - /** - * Sets [Builder.arguments] to an arbitrary JSON value. - * - * You should usually call [Builder.arguments] with a well-typed [Arguments] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun arguments(arguments: JsonField) = apply { this.arguments = arguments } - - /** - * Sets the field to an arbitrary JSON value. - * - * It is usually unnecessary to call this method because the field defaults to the - * following: - * ```java - * JsonValue.from("url_context_call") - * ``` - * - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun type(type: JsonValue) = apply { this.type = type } - - /** A signature hash for backend validation. */ - fun signature(signature: String) = signature(JsonField.of(signature)) - - /** - * Sets [Builder.signature] to an arbitrary JSON value. - * - * You should usually call [Builder.signature] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun signature(signature: JsonField) = apply { this.signature = signature } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [UrlContextCallStep]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .id() - * .arguments() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): UrlContextCallStep = - UrlContextCallStep( - checkRequired("id", id), - checkRequired("arguments", arguments), - type, - signature, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): UrlContextCallStep = apply { - if (validated) { - return@apply - } - - id() - arguments().validate() - _type().let { - if (it != JsonValue.from("url_context_call")) { - throw GeminiNextGenApiInvalidDataException("'type' is invalid, received $it") - } - } - signature() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - (if (id.asKnown().isPresent) 1 else 0) + - (arguments.asKnown().getOrNull()?.validity() ?: 0) + - type.let { if (it == JsonValue.from("url_context_call")) 1 else 0 } + - (if (signature.asKnown().isPresent) 1 else 0) - - /** Required. The arguments to pass to the URL context. */ - class Arguments - @JsonCreator(mode = JsonCreator.Mode.DISABLED) - private constructor( - private val urls: JsonField>, - private val additionalProperties: MutableMap, - ) { - - @JsonCreator - private constructor( - @JsonProperty("urls") @ExcludeMissing urls: JsonField> = JsonMissing.of() - ) : this(urls, mutableMapOf()) - - /** - * The URLs to fetch. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type - * (e.g. if the server responded with an unexpected value). - */ - fun urls(): Optional> = urls.getOptional("urls") - - /** - * Returns the raw JSON value of [urls]. - * - * Unlike [urls], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("urls") @ExcludeMissing fun _urls(): JsonField> = urls - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [Arguments]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Arguments]. */ - class Builder internal constructor() { - - private var urls: JsonField>? = null - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(arguments: Arguments) = apply { - urls = arguments.urls.map { it.toMutableList() } - additionalProperties = arguments.additionalProperties.toMutableMap() - } - - /** The URLs to fetch. */ - fun urls(urls: List) = urls(JsonField.of(urls)) - - /** - * Sets [Builder.urls] to an arbitrary JSON value. - * - * You should usually call [Builder.urls] with a well-typed `List` value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun urls(urls: JsonField>) = apply { - this.urls = urls.map { it.toMutableList() } - } - - /** - * Adds a single [String] to [urls]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addUrl(url: String) = apply { - urls = - (urls ?: JsonField.of(mutableListOf())).also { checkKnown("urls", it).add(url) } - } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [Arguments]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): Arguments = - Arguments( - (urls ?: JsonMissing.of()).map { it.toImmutable() }, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): Arguments = apply { - if (validated) { - return@apply - } - - urls() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic internal fun validity(): Int = (urls.asKnown().getOrNull()?.size ?: 0) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Arguments && - urls == other.urls && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { Objects.hash(urls, additionalProperties) } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Arguments{urls=$urls, additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is UrlContextCallStep && - id == other.id && - arguments == other.arguments && - type == other.type && - signature == other.signature && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { - Objects.hash(id, arguments, type, signature, additionalProperties) - } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "UrlContextCallStep{id=$id, arguments=$arguments, type=$type, signature=$signature, additionalProperties=$additionalProperties}" -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/UrlContextResult.kt b/src/main/java/com/google/genai/interactions/models/interactions/UrlContextResult.kt deleted file mode 100644 index 4525af08997..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/UrlContextResult.kt +++ /dev/null @@ -1,349 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import com.google.genai.interactions.core.Enum -import com.google.genai.interactions.core.ExcludeMissing -import com.google.genai.interactions.core.JsonField -import com.google.genai.interactions.core.JsonMissing -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.util.Collections -import java.util.Objects -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -/** The result of the URL context. */ -class UrlContextResult -@JsonCreator(mode = JsonCreator.Mode.DISABLED) -private constructor( - private val status: JsonField, - private val url: JsonField, - private val additionalProperties: MutableMap, -) { - - @JsonCreator - private constructor( - @JsonProperty("status") @ExcludeMissing status: JsonField = JsonMissing.of(), - @JsonProperty("url") @ExcludeMissing url: JsonField = JsonMissing.of(), - ) : this(status, url, mutableMapOf()) - - /** - * The status of the URL retrieval. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun status(): Optional = status.getOptional("status") - - /** - * The URL that was fetched. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun url(): Optional = url.getOptional("url") - - /** - * Returns the raw JSON value of [status]. - * - * Unlike [status], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("status") @ExcludeMissing fun _status(): JsonField = status - - /** - * Returns the raw JSON value of [url]. - * - * Unlike [url], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("url") @ExcludeMissing fun _url(): JsonField = url - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [UrlContextResult]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [UrlContextResult]. */ - class Builder internal constructor() { - - private var status: JsonField = JsonMissing.of() - private var url: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(urlContextResult: UrlContextResult) = apply { - status = urlContextResult.status - url = urlContextResult.url - additionalProperties = urlContextResult.additionalProperties.toMutableMap() - } - - /** The status of the URL retrieval. */ - fun status(status: Status) = status(JsonField.of(status)) - - /** - * Sets [Builder.status] to an arbitrary JSON value. - * - * You should usually call [Builder.status] with a well-typed [Status] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun status(status: JsonField) = apply { this.status = status } - - /** The URL that was fetched. */ - fun url(url: String) = url(JsonField.of(url)) - - /** - * Sets [Builder.url] to an arbitrary JSON value. - * - * You should usually call [Builder.url] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun url(url: JsonField) = apply { this.url = url } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [UrlContextResult]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): UrlContextResult = - UrlContextResult(status, url, additionalProperties.toMutableMap()) - } - - private var validated: Boolean = false - - fun validate(): UrlContextResult = apply { - if (validated) { - return@apply - } - - status().ifPresent { it.validate() } - url() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - (status.asKnown().getOrNull()?.validity() ?: 0) + (if (url.asKnown().isPresent) 1 else 0) - - /** The status of the URL retrieval. */ - class Status @JsonCreator private constructor(private val value: JsonField) : Enum { - - /** - * Returns this class instance's raw value. - * - * This is usually only useful if this instance was deserialized from data that doesn't - * match any known member, and you want to know that value. For example, if the SDK is on an - * older version than the API, then the API may respond with new members that the SDK is - * unaware of. - */ - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - companion object { - - @JvmField val SUCCESS = of("success") - - @JvmField val ERROR = of("error") - - @JvmField val PAYWALL = of("paywall") - - @JvmField val UNSAFE = of("unsafe") - - @JvmStatic fun of(value: String) = Status(JsonField.of(value)) - } - - /** An enum containing [Status]'s known values. */ - enum class Known { - SUCCESS, - ERROR, - PAYWALL, - UNSAFE, - } - - /** - * An enum containing [Status]'s known values, as well as an [_UNKNOWN] member. - * - * An instance of [Status] can contain an unknown value in a couple of cases: - * - It was deserialized from data that doesn't match any known member. For example, if the - * SDK is on an older version than the API, then the API may respond with new members that - * the SDK is unaware of. - * - It was constructed with an arbitrary value using the [of] method. - */ - enum class Value { - SUCCESS, - ERROR, - PAYWALL, - UNSAFE, - /** An enum member indicating that [Status] was instantiated with an unknown value. */ - _UNKNOWN, - } - - /** - * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] - * if the class was instantiated with an unknown value. - * - * Use the [known] method instead if you're certain the value is always known or if you want - * to throw for the unknown case. - */ - fun value(): Value = - when (this) { - SUCCESS -> Value.SUCCESS - ERROR -> Value.ERROR - PAYWALL -> Value.PAYWALL - UNSAFE -> Value.UNSAFE - else -> Value._UNKNOWN - } - - /** - * Returns an enum member corresponding to this class instance's value. - * - * Use the [value] method instead if you're uncertain the value is always known and don't - * want to throw for the unknown case. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value is a not a - * known member. - */ - fun known(): Known = - when (this) { - SUCCESS -> Known.SUCCESS - ERROR -> Known.ERROR - PAYWALL -> Known.PAYWALL - UNSAFE -> Known.UNSAFE - else -> throw GeminiNextGenApiInvalidDataException("Unknown Status: $value") - } - - /** - * Returns this class instance's primitive wire representation. - * - * This differs from the [toString] method because that method is primarily for debugging - * and generally doesn't throw. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value does not have - * the expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - GeminiNextGenApiInvalidDataException("Value is not a String") - } - - private var validated: Boolean = false - - fun validate(): Status = apply { - if (validated) { - return@apply - } - - known() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Status && value == other.value - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is UrlContextResult && - status == other.status && - url == other.url && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { Objects.hash(status, url, additionalProperties) } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "UrlContextResult{status=$status, url=$url, additionalProperties=$additionalProperties}" -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/UrlContextResultDelta.kt b/src/main/java/com/google/genai/interactions/models/interactions/UrlContextResultDelta.kt deleted file mode 100644 index ac6684daf6d..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/UrlContextResultDelta.kt +++ /dev/null @@ -1,316 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import com.google.genai.interactions.core.ExcludeMissing -import com.google.genai.interactions.core.JsonField -import com.google.genai.interactions.core.JsonMissing -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.core.checkKnown -import com.google.genai.interactions.core.checkRequired -import com.google.genai.interactions.core.toImmutable -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.util.Collections -import java.util.Objects -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -class UrlContextResultDelta -@JsonCreator(mode = JsonCreator.Mode.DISABLED) -private constructor( - private val result: JsonField>, - private val type: JsonValue, - private val isError: JsonField, - private val signature: JsonField, - private val additionalProperties: MutableMap, -) { - - @JsonCreator - private constructor( - @JsonProperty("result") - @ExcludeMissing - result: JsonField> = JsonMissing.of(), - @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), - @JsonProperty("is_error") @ExcludeMissing isError: JsonField = JsonMissing.of(), - @JsonProperty("signature") @ExcludeMissing signature: JsonField = JsonMissing.of(), - ) : this(result, type, isError, signature, mutableMapOf()) - - /** - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). - */ - fun result(): List = result.getRequired("result") - - /** - * Expected to always return the following: - * ```java - * JsonValue.from("url_context_result") - * ``` - * - * However, this method can be useful for debugging and logging (e.g. if the server responded - * with an unexpected value). - */ - @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type - - /** - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun isError(): Optional = isError.getOptional("is_error") - - /** - * A signature hash for backend validation. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun signature(): Optional = signature.getOptional("signature") - - /** - * Returns the raw JSON value of [result]. - * - * Unlike [result], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("result") - @ExcludeMissing - fun _result(): JsonField> = result - - /** - * Returns the raw JSON value of [isError]. - * - * Unlike [isError], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("is_error") @ExcludeMissing fun _isError(): JsonField = isError - - /** - * Returns the raw JSON value of [signature]. - * - * Unlike [signature], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("signature") @ExcludeMissing fun _signature(): JsonField = signature - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [UrlContextResultDelta]. - * - * The following fields are required: - * ```java - * .result() - * ``` - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [UrlContextResultDelta]. */ - class Builder internal constructor() { - - private var result: JsonField>? = null - private var type: JsonValue = JsonValue.from("url_context_result") - private var isError: JsonField = JsonMissing.of() - private var signature: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(urlContextResultDelta: UrlContextResultDelta) = apply { - result = urlContextResultDelta.result.map { it.toMutableList() } - type = urlContextResultDelta.type - isError = urlContextResultDelta.isError - signature = urlContextResultDelta.signature - additionalProperties = urlContextResultDelta.additionalProperties.toMutableMap() - } - - fun result(result: List) = result(JsonField.of(result)) - - /** - * Sets [Builder.result] to an arbitrary JSON value. - * - * You should usually call [Builder.result] with a well-typed `List` value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun result(result: JsonField>) = apply { - this.result = result.map { it.toMutableList() } - } - - /** - * Adds a single [UrlContextResult] to [Builder.result]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addResult(result: UrlContextResult) = apply { - this.result = - (this.result ?: JsonField.of(mutableListOf())).also { - checkKnown("result", it).add(result) - } - } - - /** - * Sets the field to an arbitrary JSON value. - * - * It is usually unnecessary to call this method because the field defaults to the - * following: - * ```java - * JsonValue.from("url_context_result") - * ``` - * - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun type(type: JsonValue) = apply { this.type = type } - - fun isError(isError: Boolean) = isError(JsonField.of(isError)) - - /** - * Sets [Builder.isError] to an arbitrary JSON value. - * - * You should usually call [Builder.isError] with a well-typed [Boolean] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun isError(isError: JsonField) = apply { this.isError = isError } - - /** A signature hash for backend validation. */ - fun signature(signature: String) = signature(JsonField.of(signature)) - - /** - * Sets [Builder.signature] to an arbitrary JSON value. - * - * You should usually call [Builder.signature] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun signature(signature: JsonField) = apply { this.signature = signature } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [UrlContextResultDelta]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .result() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): UrlContextResultDelta = - UrlContextResultDelta( - checkRequired("result", result).map { it.toImmutable() }, - type, - isError, - signature, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): UrlContextResultDelta = apply { - if (validated) { - return@apply - } - - result().forEach { it.validate() } - _type().let { - if (it != JsonValue.from("url_context_result")) { - throw GeminiNextGenApiInvalidDataException("'type' is invalid, received $it") - } - } - isError() - signature() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - (result.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + - type.let { if (it == JsonValue.from("url_context_result")) 1 else 0 } + - (if (isError.asKnown().isPresent) 1 else 0) + - (if (signature.asKnown().isPresent) 1 else 0) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is UrlContextResultDelta && - result == other.result && - type == other.type && - isError == other.isError && - signature == other.signature && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { - Objects.hash(result, type, isError, signature, additionalProperties) - } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "UrlContextResultDelta{result=$result, type=$type, isError=$isError, signature=$signature, additionalProperties=$additionalProperties}" -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/UrlContextResultStep.kt b/src/main/java/com/google/genai/interactions/models/interactions/UrlContextResultStep.kt deleted file mode 100644 index 3d256839bf2..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/UrlContextResultStep.kt +++ /dev/null @@ -1,676 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import com.google.genai.interactions.core.Enum -import com.google.genai.interactions.core.ExcludeMissing -import com.google.genai.interactions.core.JsonField -import com.google.genai.interactions.core.JsonMissing -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.core.checkKnown -import com.google.genai.interactions.core.checkRequired -import com.google.genai.interactions.core.toImmutable -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.util.Collections -import java.util.Objects -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -/** URL context result step. */ -class UrlContextResultStep -@JsonCreator(mode = JsonCreator.Mode.DISABLED) -private constructor( - private val callId: JsonField, - private val result: JsonField>, - private val type: JsonValue, - private val isError: JsonField, - private val signature: JsonField, - private val additionalProperties: MutableMap, -) { - - @JsonCreator - private constructor( - @JsonProperty("call_id") @ExcludeMissing callId: JsonField = JsonMissing.of(), - @JsonProperty("result") @ExcludeMissing result: JsonField> = JsonMissing.of(), - @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), - @JsonProperty("is_error") @ExcludeMissing isError: JsonField = JsonMissing.of(), - @JsonProperty("signature") @ExcludeMissing signature: JsonField = JsonMissing.of(), - ) : this(callId, result, type, isError, signature, mutableMapOf()) - - /** - * Required. ID to match the ID from the function call block. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). - */ - fun callId(): String = callId.getRequired("call_id") - - /** - * Required. The results of the URL context. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). - */ - fun result(): List = result.getRequired("result") - - /** - * Expected to always return the following: - * ```java - * JsonValue.from("url_context_result") - * ``` - * - * However, this method can be useful for debugging and logging (e.g. if the server responded - * with an unexpected value). - */ - @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type - - /** - * Whether the URL context resulted in an error. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun isError(): Optional = isError.getOptional("is_error") - - /** - * A signature hash for backend validation. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun signature(): Optional = signature.getOptional("signature") - - /** - * Returns the raw JSON value of [callId]. - * - * Unlike [callId], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("call_id") @ExcludeMissing fun _callId(): JsonField = callId - - /** - * Returns the raw JSON value of [result]. - * - * Unlike [result], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("result") @ExcludeMissing fun _result(): JsonField> = result - - /** - * Returns the raw JSON value of [isError]. - * - * Unlike [isError], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("is_error") @ExcludeMissing fun _isError(): JsonField = isError - - /** - * Returns the raw JSON value of [signature]. - * - * Unlike [signature], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("signature") @ExcludeMissing fun _signature(): JsonField = signature - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [UrlContextResultStep]. - * - * The following fields are required: - * ```java - * .callId() - * .result() - * ``` - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [UrlContextResultStep]. */ - class Builder internal constructor() { - - private var callId: JsonField? = null - private var result: JsonField>? = null - private var type: JsonValue = JsonValue.from("url_context_result") - private var isError: JsonField = JsonMissing.of() - private var signature: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(urlContextResultStep: UrlContextResultStep) = apply { - callId = urlContextResultStep.callId - result = urlContextResultStep.result.map { it.toMutableList() } - type = urlContextResultStep.type - isError = urlContextResultStep.isError - signature = urlContextResultStep.signature - additionalProperties = urlContextResultStep.additionalProperties.toMutableMap() - } - - /** Required. ID to match the ID from the function call block. */ - fun callId(callId: String) = callId(JsonField.of(callId)) - - /** - * Sets [Builder.callId] to an arbitrary JSON value. - * - * You should usually call [Builder.callId] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun callId(callId: JsonField) = apply { this.callId = callId } - - /** Required. The results of the URL context. */ - fun result(result: List) = result(JsonField.of(result)) - - /** - * Sets [Builder.result] to an arbitrary JSON value. - * - * You should usually call [Builder.result] with a well-typed `List` value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun result(result: JsonField>) = apply { - this.result = result.map { it.toMutableList() } - } - - /** - * Adds a single [Result] to [Builder.result]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addResult(result: Result) = apply { - this.result = - (this.result ?: JsonField.of(mutableListOf())).also { - checkKnown("result", it).add(result) - } - } - - /** - * Sets the field to an arbitrary JSON value. - * - * It is usually unnecessary to call this method because the field defaults to the - * following: - * ```java - * JsonValue.from("url_context_result") - * ``` - * - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun type(type: JsonValue) = apply { this.type = type } - - /** Whether the URL context resulted in an error. */ - fun isError(isError: Boolean) = isError(JsonField.of(isError)) - - /** - * Sets [Builder.isError] to an arbitrary JSON value. - * - * You should usually call [Builder.isError] with a well-typed [Boolean] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun isError(isError: JsonField) = apply { this.isError = isError } - - /** A signature hash for backend validation. */ - fun signature(signature: String) = signature(JsonField.of(signature)) - - /** - * Sets [Builder.signature] to an arbitrary JSON value. - * - * You should usually call [Builder.signature] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun signature(signature: JsonField) = apply { this.signature = signature } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [UrlContextResultStep]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .callId() - * .result() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): UrlContextResultStep = - UrlContextResultStep( - checkRequired("callId", callId), - checkRequired("result", result).map { it.toImmutable() }, - type, - isError, - signature, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): UrlContextResultStep = apply { - if (validated) { - return@apply - } - - callId() - result().forEach { it.validate() } - _type().let { - if (it != JsonValue.from("url_context_result")) { - throw GeminiNextGenApiInvalidDataException("'type' is invalid, received $it") - } - } - isError() - signature() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - (if (callId.asKnown().isPresent) 1 else 0) + - (result.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + - type.let { if (it == JsonValue.from("url_context_result")) 1 else 0 } + - (if (isError.asKnown().isPresent) 1 else 0) + - (if (signature.asKnown().isPresent) 1 else 0) - - /** The result of the URL context. */ - class Result - @JsonCreator(mode = JsonCreator.Mode.DISABLED) - private constructor( - private val status: JsonField, - private val url: JsonField, - private val additionalProperties: MutableMap, - ) { - - @JsonCreator - private constructor( - @JsonProperty("status") @ExcludeMissing status: JsonField = JsonMissing.of(), - @JsonProperty("url") @ExcludeMissing url: JsonField = JsonMissing.of(), - ) : this(status, url, mutableMapOf()) - - /** - * The status of the URL retrieval. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type - * (e.g. if the server responded with an unexpected value). - */ - fun status(): Optional = status.getOptional("status") - - /** - * The URL that was fetched. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type - * (e.g. if the server responded with an unexpected value). - */ - fun url(): Optional = url.getOptional("url") - - /** - * Returns the raw JSON value of [status]. - * - * Unlike [status], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("status") @ExcludeMissing fun _status(): JsonField = status - - /** - * Returns the raw JSON value of [url]. - * - * Unlike [url], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("url") @ExcludeMissing fun _url(): JsonField = url - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [Result]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Result]. */ - class Builder internal constructor() { - - private var status: JsonField = JsonMissing.of() - private var url: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(result: Result) = apply { - status = result.status - url = result.url - additionalProperties = result.additionalProperties.toMutableMap() - } - - /** The status of the URL retrieval. */ - fun status(status: Status) = status(JsonField.of(status)) - - /** - * Sets [Builder.status] to an arbitrary JSON value. - * - * You should usually call [Builder.status] with a well-typed [Status] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun status(status: JsonField) = apply { this.status = status } - - /** The URL that was fetched. */ - fun url(url: String) = url(JsonField.of(url)) - - /** - * Sets [Builder.url] to an arbitrary JSON value. - * - * You should usually call [Builder.url] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun url(url: JsonField) = apply { this.url = url } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [Result]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): Result = Result(status, url, additionalProperties.toMutableMap()) - } - - private var validated: Boolean = false - - fun validate(): Result = apply { - if (validated) { - return@apply - } - - status().ifPresent { it.validate() } - url() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - (status.asKnown().getOrNull()?.validity() ?: 0) + - (if (url.asKnown().isPresent) 1 else 0) - - /** The status of the URL retrieval. */ - class Status @JsonCreator private constructor(private val value: JsonField) : Enum { - - /** - * Returns this class instance's raw value. - * - * This is usually only useful if this instance was deserialized from data that doesn't - * match any known member, and you want to know that value. For example, if the SDK is - * on an older version than the API, then the API may respond with new members that the - * SDK is unaware of. - */ - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - companion object { - - @JvmField val SUCCESS = of("success") - - @JvmField val ERROR = of("error") - - @JvmField val PAYWALL = of("paywall") - - @JvmField val UNSAFE = of("unsafe") - - @JvmStatic fun of(value: String) = Status(JsonField.of(value)) - } - - /** An enum containing [Status]'s known values. */ - enum class Known { - SUCCESS, - ERROR, - PAYWALL, - UNSAFE, - } - - /** - * An enum containing [Status]'s known values, as well as an [_UNKNOWN] member. - * - * An instance of [Status] can contain an unknown value in a couple of cases: - * - It was deserialized from data that doesn't match any known member. For example, if - * the SDK is on an older version than the API, then the API may respond with new - * members that the SDK is unaware of. - * - It was constructed with an arbitrary value using the [of] method. - */ - enum class Value { - SUCCESS, - ERROR, - PAYWALL, - UNSAFE, - /** - * An enum member indicating that [Status] was instantiated with an unknown value. - */ - _UNKNOWN, - } - - /** - * Returns an enum member corresponding to this class instance's value, or - * [Value._UNKNOWN] if the class was instantiated with an unknown value. - * - * Use the [known] method instead if you're certain the value is always known or if you - * want to throw for the unknown case. - */ - fun value(): Value = - when (this) { - SUCCESS -> Value.SUCCESS - ERROR -> Value.ERROR - PAYWALL -> Value.PAYWALL - UNSAFE -> Value.UNSAFE - else -> Value._UNKNOWN - } - - /** - * Returns an enum member corresponding to this class instance's value. - * - * Use the [value] method instead if you're uncertain the value is always known and - * don't want to throw for the unknown case. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value is a not - * a known member. - */ - fun known(): Known = - when (this) { - SUCCESS -> Known.SUCCESS - ERROR -> Known.ERROR - PAYWALL -> Known.PAYWALL - UNSAFE -> Known.UNSAFE - else -> throw GeminiNextGenApiInvalidDataException("Unknown Status: $value") - } - - /** - * Returns this class instance's primitive wire representation. - * - * This differs from the [toString] method because that method is primarily for - * debugging and generally doesn't throw. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value does not - * have the expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - GeminiNextGenApiInvalidDataException("Value is not a String") - } - - private var validated: Boolean = false - - fun validate(): Status = apply { - if (validated) { - return@apply - } - - known() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Status && value == other.value - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Result && - status == other.status && - url == other.url && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { Objects.hash(status, url, additionalProperties) } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Result{status=$status, url=$url, additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is UrlContextResultStep && - callId == other.callId && - result == other.result && - type == other.type && - isError == other.isError && - signature == other.signature && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { - Objects.hash(callId, result, type, isError, signature, additionalProperties) - } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "UrlContextResultStep{callId=$callId, result=$result, type=$type, isError=$isError, signature=$signature, additionalProperties=$additionalProperties}" -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/Usage.kt b/src/main/java/com/google/genai/interactions/models/interactions/Usage.kt deleted file mode 100644 index 577358d5603..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/Usage.kt +++ /dev/null @@ -1,2360 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import com.google.genai.interactions.core.Enum -import com.google.genai.interactions.core.ExcludeMissing -import com.google.genai.interactions.core.JsonField -import com.google.genai.interactions.core.JsonMissing -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.core.checkKnown -import com.google.genai.interactions.core.toImmutable -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.util.Collections -import java.util.Objects -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -/** Statistics on the interaction request's token usage. */ -class Usage -@JsonCreator(mode = JsonCreator.Mode.DISABLED) -private constructor( - private val cachedTokensByModality: JsonField>, - private val groundingToolCount: JsonField>, - private val inputTokensByModality: JsonField>, - private val outputTokensByModality: JsonField>, - private val toolUseTokensByModality: JsonField>, - private val totalCachedTokens: JsonField, - private val totalInputTokens: JsonField, - private val totalOutputTokens: JsonField, - private val totalThoughtTokens: JsonField, - private val totalTokens: JsonField, - private val totalToolUseTokens: JsonField, - private val additionalProperties: MutableMap, -) { - - @JsonCreator - private constructor( - @JsonProperty("cached_tokens_by_modality") - @ExcludeMissing - cachedTokensByModality: JsonField> = JsonMissing.of(), - @JsonProperty("grounding_tool_count") - @ExcludeMissing - groundingToolCount: JsonField> = JsonMissing.of(), - @JsonProperty("input_tokens_by_modality") - @ExcludeMissing - inputTokensByModality: JsonField> = JsonMissing.of(), - @JsonProperty("output_tokens_by_modality") - @ExcludeMissing - outputTokensByModality: JsonField> = JsonMissing.of(), - @JsonProperty("tool_use_tokens_by_modality") - @ExcludeMissing - toolUseTokensByModality: JsonField> = JsonMissing.of(), - @JsonProperty("total_cached_tokens") - @ExcludeMissing - totalCachedTokens: JsonField = JsonMissing.of(), - @JsonProperty("total_input_tokens") - @ExcludeMissing - totalInputTokens: JsonField = JsonMissing.of(), - @JsonProperty("total_output_tokens") - @ExcludeMissing - totalOutputTokens: JsonField = JsonMissing.of(), - @JsonProperty("total_thought_tokens") - @ExcludeMissing - totalThoughtTokens: JsonField = JsonMissing.of(), - @JsonProperty("total_tokens") - @ExcludeMissing - totalTokens: JsonField = JsonMissing.of(), - @JsonProperty("total_tool_use_tokens") - @ExcludeMissing - totalToolUseTokens: JsonField = JsonMissing.of(), - ) : this( - cachedTokensByModality, - groundingToolCount, - inputTokensByModality, - outputTokensByModality, - toolUseTokensByModality, - totalCachedTokens, - totalInputTokens, - totalOutputTokens, - totalThoughtTokens, - totalTokens, - totalToolUseTokens, - mutableMapOf(), - ) - - /** - * A breakdown of cached token usage by modality. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun cachedTokensByModality(): Optional> = - cachedTokensByModality.getOptional("cached_tokens_by_modality") - - /** - * Grounding tool count. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun groundingToolCount(): Optional> = - groundingToolCount.getOptional("grounding_tool_count") - - /** - * A breakdown of input token usage by modality. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun inputTokensByModality(): Optional> = - inputTokensByModality.getOptional("input_tokens_by_modality") - - /** - * A breakdown of output token usage by modality. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun outputTokensByModality(): Optional> = - outputTokensByModality.getOptional("output_tokens_by_modality") - - /** - * A breakdown of tool-use token usage by modality. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun toolUseTokensByModality(): Optional> = - toolUseTokensByModality.getOptional("tool_use_tokens_by_modality") - - /** - * Number of tokens in the cached part of the prompt (the cached content). - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun totalCachedTokens(): Optional = totalCachedTokens.getOptional("total_cached_tokens") - - /** - * Number of tokens in the prompt (context). - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun totalInputTokens(): Optional = totalInputTokens.getOptional("total_input_tokens") - - /** - * Total number of tokens across all the generated responses. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun totalOutputTokens(): Optional = totalOutputTokens.getOptional("total_output_tokens") - - /** - * Number of tokens of thoughts for thinking models. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun totalThoughtTokens(): Optional = totalThoughtTokens.getOptional("total_thought_tokens") - - /** - * Total token count for the interaction request (prompt + responses + other internal tokens). - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun totalTokens(): Optional = totalTokens.getOptional("total_tokens") - - /** - * Number of tokens present in tool-use prompt(s). - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun totalToolUseTokens(): Optional = - totalToolUseTokens.getOptional("total_tool_use_tokens") - - /** - * Returns the raw JSON value of [cachedTokensByModality]. - * - * Unlike [cachedTokensByModality], this method doesn't throw if the JSON field has an - * unexpected type. - */ - @JsonProperty("cached_tokens_by_modality") - @ExcludeMissing - fun _cachedTokensByModality(): JsonField> = cachedTokensByModality - - /** - * Returns the raw JSON value of [groundingToolCount]. - * - * Unlike [groundingToolCount], this method doesn't throw if the JSON field has an unexpected - * type. - */ - @JsonProperty("grounding_tool_count") - @ExcludeMissing - fun _groundingToolCount(): JsonField> = groundingToolCount - - /** - * Returns the raw JSON value of [inputTokensByModality]. - * - * Unlike [inputTokensByModality], this method doesn't throw if the JSON field has an unexpected - * type. - */ - @JsonProperty("input_tokens_by_modality") - @ExcludeMissing - fun _inputTokensByModality(): JsonField> = inputTokensByModality - - /** - * Returns the raw JSON value of [outputTokensByModality]. - * - * Unlike [outputTokensByModality], this method doesn't throw if the JSON field has an - * unexpected type. - */ - @JsonProperty("output_tokens_by_modality") - @ExcludeMissing - fun _outputTokensByModality(): JsonField> = outputTokensByModality - - /** - * Returns the raw JSON value of [toolUseTokensByModality]. - * - * Unlike [toolUseTokensByModality], this method doesn't throw if the JSON field has an - * unexpected type. - */ - @JsonProperty("tool_use_tokens_by_modality") - @ExcludeMissing - fun _toolUseTokensByModality(): JsonField> = - toolUseTokensByModality - - /** - * Returns the raw JSON value of [totalCachedTokens]. - * - * Unlike [totalCachedTokens], this method doesn't throw if the JSON field has an unexpected - * type. - */ - @JsonProperty("total_cached_tokens") - @ExcludeMissing - fun _totalCachedTokens(): JsonField = totalCachedTokens - - /** - * Returns the raw JSON value of [totalInputTokens]. - * - * Unlike [totalInputTokens], this method doesn't throw if the JSON field has an unexpected - * type. - */ - @JsonProperty("total_input_tokens") - @ExcludeMissing - fun _totalInputTokens(): JsonField = totalInputTokens - - /** - * Returns the raw JSON value of [totalOutputTokens]. - * - * Unlike [totalOutputTokens], this method doesn't throw if the JSON field has an unexpected - * type. - */ - @JsonProperty("total_output_tokens") - @ExcludeMissing - fun _totalOutputTokens(): JsonField = totalOutputTokens - - /** - * Returns the raw JSON value of [totalThoughtTokens]. - * - * Unlike [totalThoughtTokens], this method doesn't throw if the JSON field has an unexpected - * type. - */ - @JsonProperty("total_thought_tokens") - @ExcludeMissing - fun _totalThoughtTokens(): JsonField = totalThoughtTokens - - /** - * Returns the raw JSON value of [totalTokens]. - * - * Unlike [totalTokens], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("total_tokens") @ExcludeMissing fun _totalTokens(): JsonField = totalTokens - - /** - * Returns the raw JSON value of [totalToolUseTokens]. - * - * Unlike [totalToolUseTokens], this method doesn't throw if the JSON field has an unexpected - * type. - */ - @JsonProperty("total_tool_use_tokens") - @ExcludeMissing - fun _totalToolUseTokens(): JsonField = totalToolUseTokens - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [Usage]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Usage]. */ - class Builder internal constructor() { - - private var cachedTokensByModality: JsonField>? = null - private var groundingToolCount: JsonField>? = null - private var inputTokensByModality: JsonField>? = null - private var outputTokensByModality: JsonField>? = null - private var toolUseTokensByModality: JsonField>? = null - private var totalCachedTokens: JsonField = JsonMissing.of() - private var totalInputTokens: JsonField = JsonMissing.of() - private var totalOutputTokens: JsonField = JsonMissing.of() - private var totalThoughtTokens: JsonField = JsonMissing.of() - private var totalTokens: JsonField = JsonMissing.of() - private var totalToolUseTokens: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(usage: Usage) = apply { - cachedTokensByModality = usage.cachedTokensByModality.map { it.toMutableList() } - groundingToolCount = usage.groundingToolCount.map { it.toMutableList() } - inputTokensByModality = usage.inputTokensByModality.map { it.toMutableList() } - outputTokensByModality = usage.outputTokensByModality.map { it.toMutableList() } - toolUseTokensByModality = usage.toolUseTokensByModality.map { it.toMutableList() } - totalCachedTokens = usage.totalCachedTokens - totalInputTokens = usage.totalInputTokens - totalOutputTokens = usage.totalOutputTokens - totalThoughtTokens = usage.totalThoughtTokens - totalTokens = usage.totalTokens - totalToolUseTokens = usage.totalToolUseTokens - additionalProperties = usage.additionalProperties.toMutableMap() - } - - /** A breakdown of cached token usage by modality. */ - fun cachedTokensByModality(cachedTokensByModality: List) = - cachedTokensByModality(JsonField.of(cachedTokensByModality)) - - /** - * Sets [Builder.cachedTokensByModality] to an arbitrary JSON value. - * - * You should usually call [Builder.cachedTokensByModality] with a well-typed - * `List` value instead. This method is primarily for setting the - * field to an undocumented or not yet supported value. - */ - fun cachedTokensByModality( - cachedTokensByModality: JsonField> - ) = apply { - this.cachedTokensByModality = cachedTokensByModality.map { it.toMutableList() } - } - - /** - * Adds a single [CachedTokensByModality] to [Builder.cachedTokensByModality]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addCachedTokensByModality(cachedTokensByModality: CachedTokensByModality) = apply { - this.cachedTokensByModality = - (this.cachedTokensByModality ?: JsonField.of(mutableListOf())).also { - checkKnown("cachedTokensByModality", it).add(cachedTokensByModality) - } - } - - /** Grounding tool count. */ - fun groundingToolCount(groundingToolCount: List) = - groundingToolCount(JsonField.of(groundingToolCount)) - - /** - * Sets [Builder.groundingToolCount] to an arbitrary JSON value. - * - * You should usually call [Builder.groundingToolCount] with a well-typed - * `List` value instead. This method is primarily for setting the field - * to an undocumented or not yet supported value. - */ - fun groundingToolCount(groundingToolCount: JsonField>) = apply { - this.groundingToolCount = groundingToolCount.map { it.toMutableList() } - } - - /** - * Adds a single [GroundingToolCount] to [Builder.groundingToolCount]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addGroundingToolCount(groundingToolCount: GroundingToolCount) = apply { - this.groundingToolCount = - (this.groundingToolCount ?: JsonField.of(mutableListOf())).also { - checkKnown("groundingToolCount", it).add(groundingToolCount) - } - } - - /** A breakdown of input token usage by modality. */ - fun inputTokensByModality(inputTokensByModality: List) = - inputTokensByModality(JsonField.of(inputTokensByModality)) - - /** - * Sets [Builder.inputTokensByModality] to an arbitrary JSON value. - * - * You should usually call [Builder.inputTokensByModality] with a well-typed - * `List` value instead. This method is primarily for setting the - * field to an undocumented or not yet supported value. - */ - fun inputTokensByModality(inputTokensByModality: JsonField>) = - apply { - this.inputTokensByModality = inputTokensByModality.map { it.toMutableList() } - } - - /** - * Adds a single [InputTokensByModality] to [Builder.inputTokensByModality]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addInputTokensByModality(inputTokensByModality: InputTokensByModality) = apply { - this.inputTokensByModality = - (this.inputTokensByModality ?: JsonField.of(mutableListOf())).also { - checkKnown("inputTokensByModality", it).add(inputTokensByModality) - } - } - - /** A breakdown of output token usage by modality. */ - fun outputTokensByModality(outputTokensByModality: List) = - outputTokensByModality(JsonField.of(outputTokensByModality)) - - /** - * Sets [Builder.outputTokensByModality] to an arbitrary JSON value. - * - * You should usually call [Builder.outputTokensByModality] with a well-typed - * `List` value instead. This method is primarily for setting the - * field to an undocumented or not yet supported value. - */ - fun outputTokensByModality( - outputTokensByModality: JsonField> - ) = apply { - this.outputTokensByModality = outputTokensByModality.map { it.toMutableList() } - } - - /** - * Adds a single [OutputTokensByModality] to [Builder.outputTokensByModality]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addOutputTokensByModality(outputTokensByModality: OutputTokensByModality) = apply { - this.outputTokensByModality = - (this.outputTokensByModality ?: JsonField.of(mutableListOf())).also { - checkKnown("outputTokensByModality", it).add(outputTokensByModality) - } - } - - /** A breakdown of tool-use token usage by modality. */ - fun toolUseTokensByModality(toolUseTokensByModality: List) = - toolUseTokensByModality(JsonField.of(toolUseTokensByModality)) - - /** - * Sets [Builder.toolUseTokensByModality] to an arbitrary JSON value. - * - * You should usually call [Builder.toolUseTokensByModality] with a well-typed - * `List` value instead. This method is primarily for setting the - * field to an undocumented or not yet supported value. - */ - fun toolUseTokensByModality( - toolUseTokensByModality: JsonField> - ) = apply { - this.toolUseTokensByModality = toolUseTokensByModality.map { it.toMutableList() } - } - - /** - * Adds a single [ToolUseTokensByModality] to [Builder.toolUseTokensByModality]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addToolUseTokensByModality(toolUseTokensByModality: ToolUseTokensByModality) = apply { - this.toolUseTokensByModality = - (this.toolUseTokensByModality ?: JsonField.of(mutableListOf())).also { - checkKnown("toolUseTokensByModality", it).add(toolUseTokensByModality) - } - } - - /** Number of tokens in the cached part of the prompt (the cached content). */ - fun totalCachedTokens(totalCachedTokens: Int) = - totalCachedTokens(JsonField.of(totalCachedTokens)) - - /** - * Sets [Builder.totalCachedTokens] to an arbitrary JSON value. - * - * You should usually call [Builder.totalCachedTokens] with a well-typed [Int] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun totalCachedTokens(totalCachedTokens: JsonField) = apply { - this.totalCachedTokens = totalCachedTokens - } - - /** Number of tokens in the prompt (context). */ - fun totalInputTokens(totalInputTokens: Int) = - totalInputTokens(JsonField.of(totalInputTokens)) - - /** - * Sets [Builder.totalInputTokens] to an arbitrary JSON value. - * - * You should usually call [Builder.totalInputTokens] with a well-typed [Int] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun totalInputTokens(totalInputTokens: JsonField) = apply { - this.totalInputTokens = totalInputTokens - } - - /** Total number of tokens across all the generated responses. */ - fun totalOutputTokens(totalOutputTokens: Int) = - totalOutputTokens(JsonField.of(totalOutputTokens)) - - /** - * Sets [Builder.totalOutputTokens] to an arbitrary JSON value. - * - * You should usually call [Builder.totalOutputTokens] with a well-typed [Int] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun totalOutputTokens(totalOutputTokens: JsonField) = apply { - this.totalOutputTokens = totalOutputTokens - } - - /** Number of tokens of thoughts for thinking models. */ - fun totalThoughtTokens(totalThoughtTokens: Int) = - totalThoughtTokens(JsonField.of(totalThoughtTokens)) - - /** - * Sets [Builder.totalThoughtTokens] to an arbitrary JSON value. - * - * You should usually call [Builder.totalThoughtTokens] with a well-typed [Int] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun totalThoughtTokens(totalThoughtTokens: JsonField) = apply { - this.totalThoughtTokens = totalThoughtTokens - } - - /** - * Total token count for the interaction request (prompt + responses + other internal - * tokens). - */ - fun totalTokens(totalTokens: Int) = totalTokens(JsonField.of(totalTokens)) - - /** - * Sets [Builder.totalTokens] to an arbitrary JSON value. - * - * You should usually call [Builder.totalTokens] with a well-typed [Int] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun totalTokens(totalTokens: JsonField) = apply { this.totalTokens = totalTokens } - - /** Number of tokens present in tool-use prompt(s). */ - fun totalToolUseTokens(totalToolUseTokens: Int) = - totalToolUseTokens(JsonField.of(totalToolUseTokens)) - - /** - * Sets [Builder.totalToolUseTokens] to an arbitrary JSON value. - * - * You should usually call [Builder.totalToolUseTokens] with a well-typed [Int] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun totalToolUseTokens(totalToolUseTokens: JsonField) = apply { - this.totalToolUseTokens = totalToolUseTokens - } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [Usage]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): Usage = - Usage( - (cachedTokensByModality ?: JsonMissing.of()).map { it.toImmutable() }, - (groundingToolCount ?: JsonMissing.of()).map { it.toImmutable() }, - (inputTokensByModality ?: JsonMissing.of()).map { it.toImmutable() }, - (outputTokensByModality ?: JsonMissing.of()).map { it.toImmutable() }, - (toolUseTokensByModality ?: JsonMissing.of()).map { it.toImmutable() }, - totalCachedTokens, - totalInputTokens, - totalOutputTokens, - totalThoughtTokens, - totalTokens, - totalToolUseTokens, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): Usage = apply { - if (validated) { - return@apply - } - - cachedTokensByModality().ifPresent { it.forEach { it.validate() } } - groundingToolCount().ifPresent { it.forEach { it.validate() } } - inputTokensByModality().ifPresent { it.forEach { it.validate() } } - outputTokensByModality().ifPresent { it.forEach { it.validate() } } - toolUseTokensByModality().ifPresent { it.forEach { it.validate() } } - totalCachedTokens() - totalInputTokens() - totalOutputTokens() - totalThoughtTokens() - totalTokens() - totalToolUseTokens() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - (cachedTokensByModality.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + - (groundingToolCount.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + - (inputTokensByModality.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + - (outputTokensByModality.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + - (toolUseTokensByModality.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + - (if (totalCachedTokens.asKnown().isPresent) 1 else 0) + - (if (totalInputTokens.asKnown().isPresent) 1 else 0) + - (if (totalOutputTokens.asKnown().isPresent) 1 else 0) + - (if (totalThoughtTokens.asKnown().isPresent) 1 else 0) + - (if (totalTokens.asKnown().isPresent) 1 else 0) + - (if (totalToolUseTokens.asKnown().isPresent) 1 else 0) - - /** The token count for a single response modality. */ - class CachedTokensByModality - @JsonCreator(mode = JsonCreator.Mode.DISABLED) - private constructor( - private val modality: JsonField, - private val tokens: JsonField, - private val additionalProperties: MutableMap, - ) { - - @JsonCreator - private constructor( - @JsonProperty("modality") - @ExcludeMissing - modality: JsonField = JsonMissing.of(), - @JsonProperty("tokens") @ExcludeMissing tokens: JsonField = JsonMissing.of(), - ) : this(modality, tokens, mutableMapOf()) - - /** - * The modality associated with the token count. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type - * (e.g. if the server responded with an unexpected value). - */ - fun modality(): Optional = modality.getOptional("modality") - - /** - * Number of tokens for the modality. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type - * (e.g. if the server responded with an unexpected value). - */ - fun tokens(): Optional = tokens.getOptional("tokens") - - /** - * Returns the raw JSON value of [modality]. - * - * Unlike [modality], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("modality") @ExcludeMissing fun _modality(): JsonField = modality - - /** - * Returns the raw JSON value of [tokens]. - * - * Unlike [tokens], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("tokens") @ExcludeMissing fun _tokens(): JsonField = tokens - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [CachedTokensByModality]. - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [CachedTokensByModality]. */ - class Builder internal constructor() { - - private var modality: JsonField = JsonMissing.of() - private var tokens: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(cachedTokensByModality: CachedTokensByModality) = apply { - modality = cachedTokensByModality.modality - tokens = cachedTokensByModality.tokens - additionalProperties = cachedTokensByModality.additionalProperties.toMutableMap() - } - - /** The modality associated with the token count. */ - fun modality(modality: Modality) = modality(JsonField.of(modality)) - - /** - * Sets [Builder.modality] to an arbitrary JSON value. - * - * You should usually call [Builder.modality] with a well-typed [Modality] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun modality(modality: JsonField) = apply { this.modality = modality } - - /** Number of tokens for the modality. */ - fun tokens(tokens: Int) = tokens(JsonField.of(tokens)) - - /** - * Sets [Builder.tokens] to an arbitrary JSON value. - * - * You should usually call [Builder.tokens] with a well-typed [Int] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun tokens(tokens: JsonField) = apply { this.tokens = tokens } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [CachedTokensByModality]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): CachedTokensByModality = - CachedTokensByModality(modality, tokens, additionalProperties.toMutableMap()) - } - - private var validated: Boolean = false - - fun validate(): CachedTokensByModality = apply { - if (validated) { - return@apply - } - - modality().ifPresent { it.validate() } - tokens() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - (modality.asKnown().getOrNull()?.validity() ?: 0) + - (if (tokens.asKnown().isPresent) 1 else 0) - - /** The modality associated with the token count. */ - class Modality @JsonCreator private constructor(private val value: JsonField) : - Enum { - - /** - * Returns this class instance's raw value. - * - * This is usually only useful if this instance was deserialized from data that doesn't - * match any known member, and you want to know that value. For example, if the SDK is - * on an older version than the API, then the API may respond with new members that the - * SDK is unaware of. - */ - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - companion object { - - @JvmField val TEXT = of("text") - - @JvmField val IMAGE = of("image") - - @JvmField val AUDIO = of("audio") - - @JvmField val VIDEO = of("video") - - @JvmField val DOCUMENT = of("document") - - @JvmStatic fun of(value: String) = Modality(JsonField.of(value)) - } - - /** An enum containing [Modality]'s known values. */ - enum class Known { - TEXT, - IMAGE, - AUDIO, - VIDEO, - DOCUMENT, - } - - /** - * An enum containing [Modality]'s known values, as well as an [_UNKNOWN] member. - * - * An instance of [Modality] can contain an unknown value in a couple of cases: - * - It was deserialized from data that doesn't match any known member. For example, if - * the SDK is on an older version than the API, then the API may respond with new - * members that the SDK is unaware of. - * - It was constructed with an arbitrary value using the [of] method. - */ - enum class Value { - TEXT, - IMAGE, - AUDIO, - VIDEO, - DOCUMENT, - /** - * An enum member indicating that [Modality] was instantiated with an unknown value. - */ - _UNKNOWN, - } - - /** - * Returns an enum member corresponding to this class instance's value, or - * [Value._UNKNOWN] if the class was instantiated with an unknown value. - * - * Use the [known] method instead if you're certain the value is always known or if you - * want to throw for the unknown case. - */ - fun value(): Value = - when (this) { - TEXT -> Value.TEXT - IMAGE -> Value.IMAGE - AUDIO -> Value.AUDIO - VIDEO -> Value.VIDEO - DOCUMENT -> Value.DOCUMENT - else -> Value._UNKNOWN - } - - /** - * Returns an enum member corresponding to this class instance's value. - * - * Use the [value] method instead if you're uncertain the value is always known and - * don't want to throw for the unknown case. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value is a not - * a known member. - */ - fun known(): Known = - when (this) { - TEXT -> Known.TEXT - IMAGE -> Known.IMAGE - AUDIO -> Known.AUDIO - VIDEO -> Known.VIDEO - DOCUMENT -> Known.DOCUMENT - else -> throw GeminiNextGenApiInvalidDataException("Unknown Modality: $value") - } - - /** - * Returns this class instance's primitive wire representation. - * - * This differs from the [toString] method because that method is primarily for - * debugging and generally doesn't throw. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value does not - * have the expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - GeminiNextGenApiInvalidDataException("Value is not a String") - } - - private var validated: Boolean = false - - fun validate(): Modality = apply { - if (validated) { - return@apply - } - - known() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Modality && value == other.value - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is CachedTokensByModality && - modality == other.modality && - tokens == other.tokens && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { Objects.hash(modality, tokens, additionalProperties) } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "CachedTokensByModality{modality=$modality, tokens=$tokens, additionalProperties=$additionalProperties}" - } - - /** The number of grounding tool counts. */ - class GroundingToolCount - @JsonCreator(mode = JsonCreator.Mode.DISABLED) - private constructor( - private val count: JsonField, - private val type: JsonField, - private val additionalProperties: MutableMap, - ) { - - @JsonCreator - private constructor( - @JsonProperty("count") @ExcludeMissing count: JsonField = JsonMissing.of(), - @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), - ) : this(count, type, mutableMapOf()) - - /** - * The number of grounding tool counts. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type - * (e.g. if the server responded with an unexpected value). - */ - fun count(): Optional = count.getOptional("count") - - /** - * The grounding tool type associated with the count. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type - * (e.g. if the server responded with an unexpected value). - */ - fun type(): Optional = type.getOptional("type") - - /** - * Returns the raw JSON value of [count]. - * - * Unlike [count], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("count") @ExcludeMissing fun _count(): JsonField = count - - /** - * Returns the raw JSON value of [type]. - * - * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [GroundingToolCount]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [GroundingToolCount]. */ - class Builder internal constructor() { - - private var count: JsonField = JsonMissing.of() - private var type: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(groundingToolCount: GroundingToolCount) = apply { - count = groundingToolCount.count - type = groundingToolCount.type - additionalProperties = groundingToolCount.additionalProperties.toMutableMap() - } - - /** The number of grounding tool counts. */ - fun count(count: Int) = count(JsonField.of(count)) - - /** - * Sets [Builder.count] to an arbitrary JSON value. - * - * You should usually call [Builder.count] with a well-typed [Int] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun count(count: JsonField) = apply { this.count = count } - - /** The grounding tool type associated with the count. */ - fun type(type: Type) = type(JsonField.of(type)) - - /** - * Sets [Builder.type] to an arbitrary JSON value. - * - * You should usually call [Builder.type] with a well-typed [Type] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun type(type: JsonField) = apply { this.type = type } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [GroundingToolCount]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): GroundingToolCount = - GroundingToolCount(count, type, additionalProperties.toMutableMap()) - } - - private var validated: Boolean = false - - fun validate(): GroundingToolCount = apply { - if (validated) { - return@apply - } - - count() - type().ifPresent { it.validate() } - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - (if (count.asKnown().isPresent) 1 else 0) + - (type.asKnown().getOrNull()?.validity() ?: 0) - - /** The grounding tool type associated with the count. */ - class Type @JsonCreator private constructor(private val value: JsonField) : Enum { - - /** - * Returns this class instance's raw value. - * - * This is usually only useful if this instance was deserialized from data that doesn't - * match any known member, and you want to know that value. For example, if the SDK is - * on an older version than the API, then the API may respond with new members that the - * SDK is unaware of. - */ - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - companion object { - - @JvmField val GOOGLE_SEARCH = of("google_search") - - @JvmField val GOOGLE_MAPS = of("google_maps") - - @JvmField val RETRIEVAL = of("retrieval") - - @JvmStatic fun of(value: String) = Type(JsonField.of(value)) - } - - /** An enum containing [Type]'s known values. */ - enum class Known { - GOOGLE_SEARCH, - GOOGLE_MAPS, - RETRIEVAL, - } - - /** - * An enum containing [Type]'s known values, as well as an [_UNKNOWN] member. - * - * An instance of [Type] can contain an unknown value in a couple of cases: - * - It was deserialized from data that doesn't match any known member. For example, if - * the SDK is on an older version than the API, then the API may respond with new - * members that the SDK is unaware of. - * - It was constructed with an arbitrary value using the [of] method. - */ - enum class Value { - GOOGLE_SEARCH, - GOOGLE_MAPS, - RETRIEVAL, - /** An enum member indicating that [Type] was instantiated with an unknown value. */ - _UNKNOWN, - } - - /** - * Returns an enum member corresponding to this class instance's value, or - * [Value._UNKNOWN] if the class was instantiated with an unknown value. - * - * Use the [known] method instead if you're certain the value is always known or if you - * want to throw for the unknown case. - */ - fun value(): Value = - when (this) { - GOOGLE_SEARCH -> Value.GOOGLE_SEARCH - GOOGLE_MAPS -> Value.GOOGLE_MAPS - RETRIEVAL -> Value.RETRIEVAL - else -> Value._UNKNOWN - } - - /** - * Returns an enum member corresponding to this class instance's value. - * - * Use the [value] method instead if you're uncertain the value is always known and - * don't want to throw for the unknown case. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value is a not - * a known member. - */ - fun known(): Known = - when (this) { - GOOGLE_SEARCH -> Known.GOOGLE_SEARCH - GOOGLE_MAPS -> Known.GOOGLE_MAPS - RETRIEVAL -> Known.RETRIEVAL - else -> throw GeminiNextGenApiInvalidDataException("Unknown Type: $value") - } - - /** - * Returns this class instance's primitive wire representation. - * - * This differs from the [toString] method because that method is primarily for - * debugging and generally doesn't throw. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value does not - * have the expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - GeminiNextGenApiInvalidDataException("Value is not a String") - } - - private var validated: Boolean = false - - fun validate(): Type = apply { - if (validated) { - return@apply - } - - known() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Type && value == other.value - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is GroundingToolCount && - count == other.count && - type == other.type && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { Objects.hash(count, type, additionalProperties) } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "GroundingToolCount{count=$count, type=$type, additionalProperties=$additionalProperties}" - } - - /** The token count for a single response modality. */ - class InputTokensByModality - @JsonCreator(mode = JsonCreator.Mode.DISABLED) - private constructor( - private val modality: JsonField, - private val tokens: JsonField, - private val additionalProperties: MutableMap, - ) { - - @JsonCreator - private constructor( - @JsonProperty("modality") - @ExcludeMissing - modality: JsonField = JsonMissing.of(), - @JsonProperty("tokens") @ExcludeMissing tokens: JsonField = JsonMissing.of(), - ) : this(modality, tokens, mutableMapOf()) - - /** - * The modality associated with the token count. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type - * (e.g. if the server responded with an unexpected value). - */ - fun modality(): Optional = modality.getOptional("modality") - - /** - * Number of tokens for the modality. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type - * (e.g. if the server responded with an unexpected value). - */ - fun tokens(): Optional = tokens.getOptional("tokens") - - /** - * Returns the raw JSON value of [modality]. - * - * Unlike [modality], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("modality") @ExcludeMissing fun _modality(): JsonField = modality - - /** - * Returns the raw JSON value of [tokens]. - * - * Unlike [tokens], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("tokens") @ExcludeMissing fun _tokens(): JsonField = tokens - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [InputTokensByModality]. - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [InputTokensByModality]. */ - class Builder internal constructor() { - - private var modality: JsonField = JsonMissing.of() - private var tokens: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(inputTokensByModality: InputTokensByModality) = apply { - modality = inputTokensByModality.modality - tokens = inputTokensByModality.tokens - additionalProperties = inputTokensByModality.additionalProperties.toMutableMap() - } - - /** The modality associated with the token count. */ - fun modality(modality: Modality) = modality(JsonField.of(modality)) - - /** - * Sets [Builder.modality] to an arbitrary JSON value. - * - * You should usually call [Builder.modality] with a well-typed [Modality] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun modality(modality: JsonField) = apply { this.modality = modality } - - /** Number of tokens for the modality. */ - fun tokens(tokens: Int) = tokens(JsonField.of(tokens)) - - /** - * Sets [Builder.tokens] to an arbitrary JSON value. - * - * You should usually call [Builder.tokens] with a well-typed [Int] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun tokens(tokens: JsonField) = apply { this.tokens = tokens } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [InputTokensByModality]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): InputTokensByModality = - InputTokensByModality(modality, tokens, additionalProperties.toMutableMap()) - } - - private var validated: Boolean = false - - fun validate(): InputTokensByModality = apply { - if (validated) { - return@apply - } - - modality().ifPresent { it.validate() } - tokens() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - (modality.asKnown().getOrNull()?.validity() ?: 0) + - (if (tokens.asKnown().isPresent) 1 else 0) - - /** The modality associated with the token count. */ - class Modality @JsonCreator private constructor(private val value: JsonField) : - Enum { - - /** - * Returns this class instance's raw value. - * - * This is usually only useful if this instance was deserialized from data that doesn't - * match any known member, and you want to know that value. For example, if the SDK is - * on an older version than the API, then the API may respond with new members that the - * SDK is unaware of. - */ - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - companion object { - - @JvmField val TEXT = of("text") - - @JvmField val IMAGE = of("image") - - @JvmField val AUDIO = of("audio") - - @JvmField val VIDEO = of("video") - - @JvmField val DOCUMENT = of("document") - - @JvmStatic fun of(value: String) = Modality(JsonField.of(value)) - } - - /** An enum containing [Modality]'s known values. */ - enum class Known { - TEXT, - IMAGE, - AUDIO, - VIDEO, - DOCUMENT, - } - - /** - * An enum containing [Modality]'s known values, as well as an [_UNKNOWN] member. - * - * An instance of [Modality] can contain an unknown value in a couple of cases: - * - It was deserialized from data that doesn't match any known member. For example, if - * the SDK is on an older version than the API, then the API may respond with new - * members that the SDK is unaware of. - * - It was constructed with an arbitrary value using the [of] method. - */ - enum class Value { - TEXT, - IMAGE, - AUDIO, - VIDEO, - DOCUMENT, - /** - * An enum member indicating that [Modality] was instantiated with an unknown value. - */ - _UNKNOWN, - } - - /** - * Returns an enum member corresponding to this class instance's value, or - * [Value._UNKNOWN] if the class was instantiated with an unknown value. - * - * Use the [known] method instead if you're certain the value is always known or if you - * want to throw for the unknown case. - */ - fun value(): Value = - when (this) { - TEXT -> Value.TEXT - IMAGE -> Value.IMAGE - AUDIO -> Value.AUDIO - VIDEO -> Value.VIDEO - DOCUMENT -> Value.DOCUMENT - else -> Value._UNKNOWN - } - - /** - * Returns an enum member corresponding to this class instance's value. - * - * Use the [value] method instead if you're uncertain the value is always known and - * don't want to throw for the unknown case. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value is a not - * a known member. - */ - fun known(): Known = - when (this) { - TEXT -> Known.TEXT - IMAGE -> Known.IMAGE - AUDIO -> Known.AUDIO - VIDEO -> Known.VIDEO - DOCUMENT -> Known.DOCUMENT - else -> throw GeminiNextGenApiInvalidDataException("Unknown Modality: $value") - } - - /** - * Returns this class instance's primitive wire representation. - * - * This differs from the [toString] method because that method is primarily for - * debugging and generally doesn't throw. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value does not - * have the expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - GeminiNextGenApiInvalidDataException("Value is not a String") - } - - private var validated: Boolean = false - - fun validate(): Modality = apply { - if (validated) { - return@apply - } - - known() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Modality && value == other.value - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is InputTokensByModality && - modality == other.modality && - tokens == other.tokens && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { Objects.hash(modality, tokens, additionalProperties) } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "InputTokensByModality{modality=$modality, tokens=$tokens, additionalProperties=$additionalProperties}" - } - - /** The token count for a single response modality. */ - class OutputTokensByModality - @JsonCreator(mode = JsonCreator.Mode.DISABLED) - private constructor( - private val modality: JsonField, - private val tokens: JsonField, - private val additionalProperties: MutableMap, - ) { - - @JsonCreator - private constructor( - @JsonProperty("modality") - @ExcludeMissing - modality: JsonField = JsonMissing.of(), - @JsonProperty("tokens") @ExcludeMissing tokens: JsonField = JsonMissing.of(), - ) : this(modality, tokens, mutableMapOf()) - - /** - * The modality associated with the token count. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type - * (e.g. if the server responded with an unexpected value). - */ - fun modality(): Optional = modality.getOptional("modality") - - /** - * Number of tokens for the modality. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type - * (e.g. if the server responded with an unexpected value). - */ - fun tokens(): Optional = tokens.getOptional("tokens") - - /** - * Returns the raw JSON value of [modality]. - * - * Unlike [modality], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("modality") @ExcludeMissing fun _modality(): JsonField = modality - - /** - * Returns the raw JSON value of [tokens]. - * - * Unlike [tokens], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("tokens") @ExcludeMissing fun _tokens(): JsonField = tokens - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [OutputTokensByModality]. - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [OutputTokensByModality]. */ - class Builder internal constructor() { - - private var modality: JsonField = JsonMissing.of() - private var tokens: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(outputTokensByModality: OutputTokensByModality) = apply { - modality = outputTokensByModality.modality - tokens = outputTokensByModality.tokens - additionalProperties = outputTokensByModality.additionalProperties.toMutableMap() - } - - /** The modality associated with the token count. */ - fun modality(modality: Modality) = modality(JsonField.of(modality)) - - /** - * Sets [Builder.modality] to an arbitrary JSON value. - * - * You should usually call [Builder.modality] with a well-typed [Modality] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun modality(modality: JsonField) = apply { this.modality = modality } - - /** Number of tokens for the modality. */ - fun tokens(tokens: Int) = tokens(JsonField.of(tokens)) - - /** - * Sets [Builder.tokens] to an arbitrary JSON value. - * - * You should usually call [Builder.tokens] with a well-typed [Int] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun tokens(tokens: JsonField) = apply { this.tokens = tokens } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [OutputTokensByModality]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): OutputTokensByModality = - OutputTokensByModality(modality, tokens, additionalProperties.toMutableMap()) - } - - private var validated: Boolean = false - - fun validate(): OutputTokensByModality = apply { - if (validated) { - return@apply - } - - modality().ifPresent { it.validate() } - tokens() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - (modality.asKnown().getOrNull()?.validity() ?: 0) + - (if (tokens.asKnown().isPresent) 1 else 0) - - /** The modality associated with the token count. */ - class Modality @JsonCreator private constructor(private val value: JsonField) : - Enum { - - /** - * Returns this class instance's raw value. - * - * This is usually only useful if this instance was deserialized from data that doesn't - * match any known member, and you want to know that value. For example, if the SDK is - * on an older version than the API, then the API may respond with new members that the - * SDK is unaware of. - */ - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - companion object { - - @JvmField val TEXT = of("text") - - @JvmField val IMAGE = of("image") - - @JvmField val AUDIO = of("audio") - - @JvmField val VIDEO = of("video") - - @JvmField val DOCUMENT = of("document") - - @JvmStatic fun of(value: String) = Modality(JsonField.of(value)) - } - - /** An enum containing [Modality]'s known values. */ - enum class Known { - TEXT, - IMAGE, - AUDIO, - VIDEO, - DOCUMENT, - } - - /** - * An enum containing [Modality]'s known values, as well as an [_UNKNOWN] member. - * - * An instance of [Modality] can contain an unknown value in a couple of cases: - * - It was deserialized from data that doesn't match any known member. For example, if - * the SDK is on an older version than the API, then the API may respond with new - * members that the SDK is unaware of. - * - It was constructed with an arbitrary value using the [of] method. - */ - enum class Value { - TEXT, - IMAGE, - AUDIO, - VIDEO, - DOCUMENT, - /** - * An enum member indicating that [Modality] was instantiated with an unknown value. - */ - _UNKNOWN, - } - - /** - * Returns an enum member corresponding to this class instance's value, or - * [Value._UNKNOWN] if the class was instantiated with an unknown value. - * - * Use the [known] method instead if you're certain the value is always known or if you - * want to throw for the unknown case. - */ - fun value(): Value = - when (this) { - TEXT -> Value.TEXT - IMAGE -> Value.IMAGE - AUDIO -> Value.AUDIO - VIDEO -> Value.VIDEO - DOCUMENT -> Value.DOCUMENT - else -> Value._UNKNOWN - } - - /** - * Returns an enum member corresponding to this class instance's value. - * - * Use the [value] method instead if you're uncertain the value is always known and - * don't want to throw for the unknown case. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value is a not - * a known member. - */ - fun known(): Known = - when (this) { - TEXT -> Known.TEXT - IMAGE -> Known.IMAGE - AUDIO -> Known.AUDIO - VIDEO -> Known.VIDEO - DOCUMENT -> Known.DOCUMENT - else -> throw GeminiNextGenApiInvalidDataException("Unknown Modality: $value") - } - - /** - * Returns this class instance's primitive wire representation. - * - * This differs from the [toString] method because that method is primarily for - * debugging and generally doesn't throw. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value does not - * have the expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - GeminiNextGenApiInvalidDataException("Value is not a String") - } - - private var validated: Boolean = false - - fun validate(): Modality = apply { - if (validated) { - return@apply - } - - known() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Modality && value == other.value - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is OutputTokensByModality && - modality == other.modality && - tokens == other.tokens && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { Objects.hash(modality, tokens, additionalProperties) } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "OutputTokensByModality{modality=$modality, tokens=$tokens, additionalProperties=$additionalProperties}" - } - - /** The token count for a single response modality. */ - class ToolUseTokensByModality - @JsonCreator(mode = JsonCreator.Mode.DISABLED) - private constructor( - private val modality: JsonField, - private val tokens: JsonField, - private val additionalProperties: MutableMap, - ) { - - @JsonCreator - private constructor( - @JsonProperty("modality") - @ExcludeMissing - modality: JsonField = JsonMissing.of(), - @JsonProperty("tokens") @ExcludeMissing tokens: JsonField = JsonMissing.of(), - ) : this(modality, tokens, mutableMapOf()) - - /** - * The modality associated with the token count. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type - * (e.g. if the server responded with an unexpected value). - */ - fun modality(): Optional = modality.getOptional("modality") - - /** - * Number of tokens for the modality. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type - * (e.g. if the server responded with an unexpected value). - */ - fun tokens(): Optional = tokens.getOptional("tokens") - - /** - * Returns the raw JSON value of [modality]. - * - * Unlike [modality], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("modality") @ExcludeMissing fun _modality(): JsonField = modality - - /** - * Returns the raw JSON value of [tokens]. - * - * Unlike [tokens], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("tokens") @ExcludeMissing fun _tokens(): JsonField = tokens - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [ToolUseTokensByModality]. - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [ToolUseTokensByModality]. */ - class Builder internal constructor() { - - private var modality: JsonField = JsonMissing.of() - private var tokens: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(toolUseTokensByModality: ToolUseTokensByModality) = apply { - modality = toolUseTokensByModality.modality - tokens = toolUseTokensByModality.tokens - additionalProperties = toolUseTokensByModality.additionalProperties.toMutableMap() - } - - /** The modality associated with the token count. */ - fun modality(modality: Modality) = modality(JsonField.of(modality)) - - /** - * Sets [Builder.modality] to an arbitrary JSON value. - * - * You should usually call [Builder.modality] with a well-typed [Modality] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun modality(modality: JsonField) = apply { this.modality = modality } - - /** Number of tokens for the modality. */ - fun tokens(tokens: Int) = tokens(JsonField.of(tokens)) - - /** - * Sets [Builder.tokens] to an arbitrary JSON value. - * - * You should usually call [Builder.tokens] with a well-typed [Int] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun tokens(tokens: JsonField) = apply { this.tokens = tokens } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [ToolUseTokensByModality]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): ToolUseTokensByModality = - ToolUseTokensByModality(modality, tokens, additionalProperties.toMutableMap()) - } - - private var validated: Boolean = false - - fun validate(): ToolUseTokensByModality = apply { - if (validated) { - return@apply - } - - modality().ifPresent { it.validate() } - tokens() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - (modality.asKnown().getOrNull()?.validity() ?: 0) + - (if (tokens.asKnown().isPresent) 1 else 0) - - /** The modality associated with the token count. */ - class Modality @JsonCreator private constructor(private val value: JsonField) : - Enum { - - /** - * Returns this class instance's raw value. - * - * This is usually only useful if this instance was deserialized from data that doesn't - * match any known member, and you want to know that value. For example, if the SDK is - * on an older version than the API, then the API may respond with new members that the - * SDK is unaware of. - */ - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - companion object { - - @JvmField val TEXT = of("text") - - @JvmField val IMAGE = of("image") - - @JvmField val AUDIO = of("audio") - - @JvmField val VIDEO = of("video") - - @JvmField val DOCUMENT = of("document") - - @JvmStatic fun of(value: String) = Modality(JsonField.of(value)) - } - - /** An enum containing [Modality]'s known values. */ - enum class Known { - TEXT, - IMAGE, - AUDIO, - VIDEO, - DOCUMENT, - } - - /** - * An enum containing [Modality]'s known values, as well as an [_UNKNOWN] member. - * - * An instance of [Modality] can contain an unknown value in a couple of cases: - * - It was deserialized from data that doesn't match any known member. For example, if - * the SDK is on an older version than the API, then the API may respond with new - * members that the SDK is unaware of. - * - It was constructed with an arbitrary value using the [of] method. - */ - enum class Value { - TEXT, - IMAGE, - AUDIO, - VIDEO, - DOCUMENT, - /** - * An enum member indicating that [Modality] was instantiated with an unknown value. - */ - _UNKNOWN, - } - - /** - * Returns an enum member corresponding to this class instance's value, or - * [Value._UNKNOWN] if the class was instantiated with an unknown value. - * - * Use the [known] method instead if you're certain the value is always known or if you - * want to throw for the unknown case. - */ - fun value(): Value = - when (this) { - TEXT -> Value.TEXT - IMAGE -> Value.IMAGE - AUDIO -> Value.AUDIO - VIDEO -> Value.VIDEO - DOCUMENT -> Value.DOCUMENT - else -> Value._UNKNOWN - } - - /** - * Returns an enum member corresponding to this class instance's value. - * - * Use the [value] method instead if you're uncertain the value is always known and - * don't want to throw for the unknown case. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value is a not - * a known member. - */ - fun known(): Known = - when (this) { - TEXT -> Known.TEXT - IMAGE -> Known.IMAGE - AUDIO -> Known.AUDIO - VIDEO -> Known.VIDEO - DOCUMENT -> Known.DOCUMENT - else -> throw GeminiNextGenApiInvalidDataException("Unknown Modality: $value") - } - - /** - * Returns this class instance's primitive wire representation. - * - * This differs from the [toString] method because that method is primarily for - * debugging and generally doesn't throw. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value does not - * have the expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - GeminiNextGenApiInvalidDataException("Value is not a String") - } - - private var validated: Boolean = false - - fun validate(): Modality = apply { - if (validated) { - return@apply - } - - known() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Modality && value == other.value - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is ToolUseTokensByModality && - modality == other.modality && - tokens == other.tokens && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { Objects.hash(modality, tokens, additionalProperties) } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "ToolUseTokensByModality{modality=$modality, tokens=$tokens, additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Usage && - cachedTokensByModality == other.cachedTokensByModality && - groundingToolCount == other.groundingToolCount && - inputTokensByModality == other.inputTokensByModality && - outputTokensByModality == other.outputTokensByModality && - toolUseTokensByModality == other.toolUseTokensByModality && - totalCachedTokens == other.totalCachedTokens && - totalInputTokens == other.totalInputTokens && - totalOutputTokens == other.totalOutputTokens && - totalThoughtTokens == other.totalThoughtTokens && - totalTokens == other.totalTokens && - totalToolUseTokens == other.totalToolUseTokens && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { - Objects.hash( - cachedTokensByModality, - groundingToolCount, - inputTokensByModality, - outputTokensByModality, - toolUseTokensByModality, - totalCachedTokens, - totalInputTokens, - totalOutputTokens, - totalThoughtTokens, - totalTokens, - totalToolUseTokens, - additionalProperties, - ) - } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Usage{cachedTokensByModality=$cachedTokensByModality, groundingToolCount=$groundingToolCount, inputTokensByModality=$inputTokensByModality, outputTokensByModality=$outputTokensByModality, toolUseTokensByModality=$toolUseTokensByModality, totalCachedTokens=$totalCachedTokens, totalInputTokens=$totalInputTokens, totalOutputTokens=$totalOutputTokens, totalThoughtTokens=$totalThoughtTokens, totalTokens=$totalTokens, totalToolUseTokens=$totalToolUseTokens, additionalProperties=$additionalProperties}" -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/UserInputStep.kt b/src/main/java/com/google/genai/interactions/models/interactions/UserInputStep.kt deleted file mode 100644 index d66052dfa5b..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/UserInputStep.kt +++ /dev/null @@ -1,257 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import com.google.genai.interactions.core.ExcludeMissing -import com.google.genai.interactions.core.JsonField -import com.google.genai.interactions.core.JsonMissing -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.core.checkKnown -import com.google.genai.interactions.core.toImmutable -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.util.Collections -import java.util.Objects -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -/** Input provided by the user. */ -class UserInputStep -@JsonCreator(mode = JsonCreator.Mode.DISABLED) -private constructor( - private val type: JsonValue, - private val content: JsonField>, - private val additionalProperties: MutableMap, -) { - - @JsonCreator - private constructor( - @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), - @JsonProperty("content") - @ExcludeMissing - content: JsonField> = JsonMissing.of(), - ) : this(type, content, mutableMapOf()) - - /** - * Expected to always return the following: - * ```java - * JsonValue.from("user_input") - * ``` - * - * However, this method can be useful for debugging and logging (e.g. if the server responded - * with an unexpected value). - */ - @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type - - /** - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun content(): Optional> = content.getOptional("content") - - /** - * Returns the raw JSON value of [content]. - * - * Unlike [content], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("content") @ExcludeMissing fun _content(): JsonField> = content - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [UserInputStep]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [UserInputStep]. */ - class Builder internal constructor() { - - private var type: JsonValue = JsonValue.from("user_input") - private var content: JsonField>? = null - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(userInputStep: UserInputStep) = apply { - type = userInputStep.type - content = userInputStep.content.map { it.toMutableList() } - additionalProperties = userInputStep.additionalProperties.toMutableMap() - } - - /** - * Sets the field to an arbitrary JSON value. - * - * It is usually unnecessary to call this method because the field defaults to the - * following: - * ```java - * JsonValue.from("user_input") - * ``` - * - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun type(type: JsonValue) = apply { this.type = type } - - fun content(content: List) = content(JsonField.of(content)) - - /** - * Sets [Builder.content] to an arbitrary JSON value. - * - * You should usually call [Builder.content] with a well-typed `List` value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun content(content: JsonField>) = apply { - this.content = content.map { it.toMutableList() } - } - - /** - * Adds a single [Content] to [Builder.content]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addContent(content: Content) = apply { - this.content = - (this.content ?: JsonField.of(mutableListOf())).also { - checkKnown("content", it).add(content) - } - } - - /** Alias for calling [addContent] with `Content.ofText(text)`. */ - fun addContent(text: TextContent) = addContent(Content.ofText(text)) - - /** - * Alias for calling [addContent] with the following: - * ```java - * TextContent.builder() - * .text(text) - * .build() - * ``` - */ - fun addTextContent(text: String) = addContent(TextContent.builder().text(text).build()) - - /** Alias for calling [addContent] with `Content.ofImage(image)`. */ - fun addContent(image: ImageContent) = addContent(Content.ofImage(image)) - - /** Alias for calling [addContent] with `Content.ofAudio(audio)`. */ - fun addContent(audio: AudioContent) = addContent(Content.ofAudio(audio)) - - /** Alias for calling [addContent] with `Content.ofDocument(document)`. */ - fun addContent(document: DocumentContent) = addContent(Content.ofDocument(document)) - - /** Alias for calling [addContent] with `Content.ofVideo(video)`. */ - fun addContent(video: VideoContent) = addContent(Content.ofVideo(video)) - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [UserInputStep]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): UserInputStep = - UserInputStep( - type, - (content ?: JsonMissing.of()).map { it.toImmutable() }, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): UserInputStep = apply { - if (validated) { - return@apply - } - - _type().let { - if (it != JsonValue.from("user_input")) { - throw GeminiNextGenApiInvalidDataException("'type' is invalid, received $it") - } - } - content().ifPresent { it.forEach { it.validate() } } - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - type.let { if (it == JsonValue.from("user_input")) 1 else 0 } + - (content.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is UserInputStep && - type == other.type && - content == other.content && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { Objects.hash(type, content, additionalProperties) } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "UserInputStep{type=$type, content=$content, additionalProperties=$additionalProperties}" -} diff --git a/src/main/java/com/google/genai/interactions/models/interactions/VideoContent.kt b/src/main/java/com/google/genai/interactions/models/interactions/VideoContent.kt deleted file mode 100644 index 6754ad867ab..00000000000 --- a/src/main/java/com/google/genai/interactions/models/interactions/VideoContent.kt +++ /dev/null @@ -1,632 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.models.interactions - -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import com.google.genai.interactions.core.Enum -import com.google.genai.interactions.core.ExcludeMissing -import com.google.genai.interactions.core.JsonField -import com.google.genai.interactions.core.JsonMissing -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.errors.GeminiNextGenApiInvalidDataException -import java.util.Collections -import java.util.Objects -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -/** A video content block. */ -class VideoContent -@JsonCreator(mode = JsonCreator.Mode.DISABLED) -private constructor( - private val type: JsonValue, - private val data: JsonField, - private val mimeType: JsonField, - private val resolution: JsonField, - private val uri: JsonField, - private val additionalProperties: MutableMap, -) { - - @JsonCreator - private constructor( - @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), - @JsonProperty("data") @ExcludeMissing data: JsonField = JsonMissing.of(), - @JsonProperty("mime_type") @ExcludeMissing mimeType: JsonField = JsonMissing.of(), - @JsonProperty("resolution") - @ExcludeMissing - resolution: JsonField = JsonMissing.of(), - @JsonProperty("uri") @ExcludeMissing uri: JsonField = JsonMissing.of(), - ) : this(type, data, mimeType, resolution, uri, mutableMapOf()) - - /** - * Expected to always return the following: - * ```java - * JsonValue.from("video") - * ``` - * - * However, this method can be useful for debugging and logging (e.g. if the server responded - * with an unexpected value). - */ - @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type - - /** - * The video content. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun data(): Optional = data.getOptional("data") - - /** - * The mime type of the video. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun mimeType(): Optional = mimeType.getOptional("mime_type") - - /** - * The resolution of the media. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun resolution(): Optional = resolution.getOptional("resolution") - - /** - * The URI of the video. - * - * @throws GeminiNextGenApiInvalidDataException if the JSON field has an unexpected type (e.g. - * if the server responded with an unexpected value). - */ - fun uri(): Optional = uri.getOptional("uri") - - /** - * Returns the raw JSON value of [data]. - * - * Unlike [data], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("data") @ExcludeMissing fun _data(): JsonField = data - - /** - * Returns the raw JSON value of [mimeType]. - * - * Unlike [mimeType], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("mime_type") @ExcludeMissing fun _mimeType(): JsonField = mimeType - - /** - * Returns the raw JSON value of [resolution]. - * - * Unlike [resolution], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("resolution") - @ExcludeMissing - fun _resolution(): JsonField = resolution - - /** - * Returns the raw JSON value of [uri]. - * - * Unlike [uri], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("uri") @ExcludeMissing fun _uri(): JsonField = uri - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [VideoContent]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [VideoContent]. */ - class Builder internal constructor() { - - private var type: JsonValue = JsonValue.from("video") - private var data: JsonField = JsonMissing.of() - private var mimeType: JsonField = JsonMissing.of() - private var resolution: JsonField = JsonMissing.of() - private var uri: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(videoContent: VideoContent) = apply { - type = videoContent.type - data = videoContent.data - mimeType = videoContent.mimeType - resolution = videoContent.resolution - uri = videoContent.uri - additionalProperties = videoContent.additionalProperties.toMutableMap() - } - - /** - * Sets the field to an arbitrary JSON value. - * - * It is usually unnecessary to call this method because the field defaults to the - * following: - * ```java - * JsonValue.from("video") - * ``` - * - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun type(type: JsonValue) = apply { this.type = type } - - /** The video content. */ - fun data(data: String) = data(JsonField.of(data)) - - /** - * Sets [Builder.data] to an arbitrary JSON value. - * - * You should usually call [Builder.data] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun data(data: JsonField) = apply { this.data = data } - - /** The mime type of the video. */ - fun mimeType(mimeType: MimeType) = mimeType(JsonField.of(mimeType)) - - /** - * Sets [Builder.mimeType] to an arbitrary JSON value. - * - * You should usually call [Builder.mimeType] with a well-typed [MimeType] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun mimeType(mimeType: JsonField) = apply { this.mimeType = mimeType } - - /** The resolution of the media. */ - fun resolution(resolution: Resolution) = resolution(JsonField.of(resolution)) - - /** - * Sets [Builder.resolution] to an arbitrary JSON value. - * - * You should usually call [Builder.resolution] with a well-typed [Resolution] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun resolution(resolution: JsonField) = apply { this.resolution = resolution } - - /** The URI of the video. */ - fun uri(uri: String) = uri(JsonField.of(uri)) - - /** - * Sets [Builder.uri] to an arbitrary JSON value. - * - * You should usually call [Builder.uri] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun uri(uri: JsonField) = apply { this.uri = uri } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [VideoContent]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): VideoContent = - VideoContent(type, data, mimeType, resolution, uri, additionalProperties.toMutableMap()) - } - - private var validated: Boolean = false - - fun validate(): VideoContent = apply { - if (validated) { - return@apply - } - - _type().let { - if (it != JsonValue.from("video")) { - throw GeminiNextGenApiInvalidDataException("'type' is invalid, received $it") - } - } - data() - mimeType().ifPresent { it.validate() } - resolution().ifPresent { it.validate() } - uri() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic - internal fun validity(): Int = - type.let { if (it == JsonValue.from("video")) 1 else 0 } + - (if (data.asKnown().isPresent) 1 else 0) + - (mimeType.asKnown().getOrNull()?.validity() ?: 0) + - (resolution.asKnown().getOrNull()?.validity() ?: 0) + - (if (uri.asKnown().isPresent) 1 else 0) - - /** The mime type of the video. */ - class MimeType @JsonCreator private constructor(private val value: JsonField) : Enum { - - /** - * Returns this class instance's raw value. - * - * This is usually only useful if this instance was deserialized from data that doesn't - * match any known member, and you want to know that value. For example, if the SDK is on an - * older version than the API, then the API may respond with new members that the SDK is - * unaware of. - */ - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - companion object { - - @JvmField val VIDEO_MP4 = of("video/mp4") - - @JvmField val VIDEO_MPEG = of("video/mpeg") - - @JvmField val VIDEO_MPG = of("video/mpg") - - @JvmField val VIDEO_MOV = of("video/mov") - - @JvmField val VIDEO_AVI = of("video/avi") - - @JvmField val VIDEO_X_FLV = of("video/x-flv") - - @JvmField val VIDEO_WEBM = of("video/webm") - - @JvmField val VIDEO_WMV = of("video/wmv") - - @JvmField val VIDEO_3GPP = of("video/3gpp") - - @JvmStatic fun of(value: String) = MimeType(JsonField.of(value)) - } - - /** An enum containing [MimeType]'s known values. */ - enum class Known { - VIDEO_MP4, - VIDEO_MPEG, - VIDEO_MPG, - VIDEO_MOV, - VIDEO_AVI, - VIDEO_X_FLV, - VIDEO_WEBM, - VIDEO_WMV, - VIDEO_3GPP, - } - - /** - * An enum containing [MimeType]'s known values, as well as an [_UNKNOWN] member. - * - * An instance of [MimeType] can contain an unknown value in a couple of cases: - * - It was deserialized from data that doesn't match any known member. For example, if the - * SDK is on an older version than the API, then the API may respond with new members that - * the SDK is unaware of. - * - It was constructed with an arbitrary value using the [of] method. - */ - enum class Value { - VIDEO_MP4, - VIDEO_MPEG, - VIDEO_MPG, - VIDEO_MOV, - VIDEO_AVI, - VIDEO_X_FLV, - VIDEO_WEBM, - VIDEO_WMV, - VIDEO_3GPP, - /** An enum member indicating that [MimeType] was instantiated with an unknown value. */ - _UNKNOWN, - } - - /** - * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] - * if the class was instantiated with an unknown value. - * - * Use the [known] method instead if you're certain the value is always known or if you want - * to throw for the unknown case. - */ - fun value(): Value = - when (this) { - VIDEO_MP4 -> Value.VIDEO_MP4 - VIDEO_MPEG -> Value.VIDEO_MPEG - VIDEO_MPG -> Value.VIDEO_MPG - VIDEO_MOV -> Value.VIDEO_MOV - VIDEO_AVI -> Value.VIDEO_AVI - VIDEO_X_FLV -> Value.VIDEO_X_FLV - VIDEO_WEBM -> Value.VIDEO_WEBM - VIDEO_WMV -> Value.VIDEO_WMV - VIDEO_3GPP -> Value.VIDEO_3GPP - else -> Value._UNKNOWN - } - - /** - * Returns an enum member corresponding to this class instance's value. - * - * Use the [value] method instead if you're uncertain the value is always known and don't - * want to throw for the unknown case. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value is a not a - * known member. - */ - fun known(): Known = - when (this) { - VIDEO_MP4 -> Known.VIDEO_MP4 - VIDEO_MPEG -> Known.VIDEO_MPEG - VIDEO_MPG -> Known.VIDEO_MPG - VIDEO_MOV -> Known.VIDEO_MOV - VIDEO_AVI -> Known.VIDEO_AVI - VIDEO_X_FLV -> Known.VIDEO_X_FLV - VIDEO_WEBM -> Known.VIDEO_WEBM - VIDEO_WMV -> Known.VIDEO_WMV - VIDEO_3GPP -> Known.VIDEO_3GPP - else -> throw GeminiNextGenApiInvalidDataException("Unknown MimeType: $value") - } - - /** - * Returns this class instance's primitive wire representation. - * - * This differs from the [toString] method because that method is primarily for debugging - * and generally doesn't throw. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value does not have - * the expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - GeminiNextGenApiInvalidDataException("Value is not a String") - } - - private var validated: Boolean = false - - fun validate(): MimeType = apply { - if (validated) { - return@apply - } - - known() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is MimeType && value == other.value - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - /** The resolution of the media. */ - class Resolution @JsonCreator private constructor(private val value: JsonField) : Enum { - - /** - * Returns this class instance's raw value. - * - * This is usually only useful if this instance was deserialized from data that doesn't - * match any known member, and you want to know that value. For example, if the SDK is on an - * older version than the API, then the API may respond with new members that the SDK is - * unaware of. - */ - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - companion object { - - @JvmField val LOW = of("low") - - @JvmField val MEDIUM = of("medium") - - @JvmField val HIGH = of("high") - - @JvmField val ULTRA_HIGH = of("ultra_high") - - @JvmStatic fun of(value: String) = Resolution(JsonField.of(value)) - } - - /** An enum containing [Resolution]'s known values. */ - enum class Known { - LOW, - MEDIUM, - HIGH, - ULTRA_HIGH, - } - - /** - * An enum containing [Resolution]'s known values, as well as an [_UNKNOWN] member. - * - * An instance of [Resolution] can contain an unknown value in a couple of cases: - * - It was deserialized from data that doesn't match any known member. For example, if the - * SDK is on an older version than the API, then the API may respond with new members that - * the SDK is unaware of. - * - It was constructed with an arbitrary value using the [of] method. - */ - enum class Value { - LOW, - MEDIUM, - HIGH, - ULTRA_HIGH, - /** - * An enum member indicating that [Resolution] was instantiated with an unknown value. - */ - _UNKNOWN, - } - - /** - * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] - * if the class was instantiated with an unknown value. - * - * Use the [known] method instead if you're certain the value is always known or if you want - * to throw for the unknown case. - */ - fun value(): Value = - when (this) { - LOW -> Value.LOW - MEDIUM -> Value.MEDIUM - HIGH -> Value.HIGH - ULTRA_HIGH -> Value.ULTRA_HIGH - else -> Value._UNKNOWN - } - - /** - * Returns an enum member corresponding to this class instance's value. - * - * Use the [value] method instead if you're uncertain the value is always known and don't - * want to throw for the unknown case. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value is a not a - * known member. - */ - fun known(): Known = - when (this) { - LOW -> Known.LOW - MEDIUM -> Known.MEDIUM - HIGH -> Known.HIGH - ULTRA_HIGH -> Known.ULTRA_HIGH - else -> throw GeminiNextGenApiInvalidDataException("Unknown Resolution: $value") - } - - /** - * Returns this class instance's primitive wire representation. - * - * This differs from the [toString] method because that method is primarily for debugging - * and generally doesn't throw. - * - * @throws GeminiNextGenApiInvalidDataException if this class instance's value does not have - * the expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - GeminiNextGenApiInvalidDataException("Value is not a String") - } - - private var validated: Boolean = false - - fun validate(): Resolution = apply { - if (validated) { - return@apply - } - - known() - validated = true - } - - fun isValid(): Boolean = - try { - validate() - true - } catch (e: GeminiNextGenApiInvalidDataException) { - false - } - - /** - * Returns a score indicating how many valid values are contained in this object - * recursively. - * - * Used for best match union deserialization. - */ - @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Resolution && value == other.value - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is VideoContent && - type == other.type && - data == other.data && - mimeType == other.mimeType && - resolution == other.resolution && - uri == other.uri && - additionalProperties == other.additionalProperties - } - - private val hashCode: Int by lazy { - Objects.hash(type, data, mimeType, resolution, uri, additionalProperties) - } - - override fun hashCode(): Int = hashCode - - override fun toString() = - "VideoContent{type=$type, data=$data, mimeType=$mimeType, resolution=$resolution, uri=$uri, additionalProperties=$additionalProperties}" -} diff --git a/src/main/java/com/google/genai/interactions/services/async/InteractionServiceAsync.kt b/src/main/java/com/google/genai/interactions/services/async/InteractionServiceAsync.kt deleted file mode 100644 index 7fd33ea5a11..00000000000 --- a/src/main/java/com/google/genai/interactions/services/async/InteractionServiceAsync.kt +++ /dev/null @@ -1,617 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.services.async - -import com.google.genai.interactions.core.ClientOptions -import com.google.genai.interactions.core.RequestOptions -import com.google.genai.interactions.core.http.AsyncStreamResponse -import com.google.genai.interactions.core.http.HttpResponseFor -import com.google.genai.interactions.core.http.StreamResponse -import com.google.genai.interactions.models.interactions.CreateAgentInteractionParams -import com.google.genai.interactions.models.interactions.CreateModelInteractionParams -import com.google.genai.interactions.models.interactions.Interaction -import com.google.genai.interactions.models.interactions.InteractionCancelParams -import com.google.genai.interactions.models.interactions.InteractionCreateParams -import com.google.genai.interactions.models.interactions.InteractionDeleteParams -import com.google.genai.interactions.models.interactions.InteractionDeleteResponse -import com.google.genai.interactions.models.interactions.InteractionGetParams -import com.google.genai.interactions.models.interactions.InteractionSseEvent -import com.google.errorprone.annotations.MustBeClosed -import java.util.concurrent.CompletableFuture -import java.util.function.Consumer - -interface InteractionServiceAsync { - - /** - * Returns a view of this service that provides access to raw HTTP responses for each method. - */ - fun withRawResponse(): WithRawResponse - - /** - * Returns a view of this service with the given option modifications applied. - * - * The original service is not modified. - */ - fun withOptions(modifier: Consumer): InteractionServiceAsync - - /** Creates a new interaction. */ - fun create(params: InteractionCreateParams): CompletableFuture = - create(params, RequestOptions.none()) - - /** @see create */ - fun create( - params: InteractionCreateParams, - requestOptions: RequestOptions = RequestOptions.none(), - ): CompletableFuture - - /** @see create */ - fun create( - body: InteractionCreateParams.Body, - requestOptions: RequestOptions = RequestOptions.none(), - ): CompletableFuture = - create(InteractionCreateParams.builder().body(body).build(), requestOptions) - - /** @see create */ - fun create(body: InteractionCreateParams.Body): CompletableFuture = - create(body, RequestOptions.none()) - - /** @see create */ - fun create( - createModelInteractionParams: CreateModelInteractionParams, - requestOptions: RequestOptions = RequestOptions.none(), - ): CompletableFuture = - create( - InteractionCreateParams.Body.ofCreateModelInteractionParams( - createModelInteractionParams - ), - requestOptions, - ) - - /** @see create */ - fun create( - createModelInteractionParams: CreateModelInteractionParams - ): CompletableFuture = create(createModelInteractionParams, RequestOptions.none()) - - /** @see create */ - fun create( - createAgentInteractionParams: CreateAgentInteractionParams, - requestOptions: RequestOptions = RequestOptions.none(), - ): CompletableFuture = - create( - InteractionCreateParams.Body.ofCreateAgentInteractionParams( - createAgentInteractionParams - ), - requestOptions, - ) - - /** @see create */ - fun create( - createAgentInteractionParams: CreateAgentInteractionParams - ): CompletableFuture = create(createAgentInteractionParams, RequestOptions.none()) - - /** Creates a new interaction. */ - fun createStreaming(params: InteractionCreateParams): AsyncStreamResponse = - createStreaming(params, RequestOptions.none()) - - /** @see createStreaming */ - fun createStreaming( - params: InteractionCreateParams, - requestOptions: RequestOptions = RequestOptions.none(), - ): AsyncStreamResponse - - /** @see createStreaming */ - fun createStreaming( - body: InteractionCreateParams.Body, - requestOptions: RequestOptions = RequestOptions.none(), - ): AsyncStreamResponse = - createStreaming(InteractionCreateParams.builder().body(body).build(), requestOptions) - - /** @see createStreaming */ - fun createStreaming( - body: InteractionCreateParams.Body - ): AsyncStreamResponse = createStreaming(body, RequestOptions.none()) - - /** @see createStreaming */ - fun createStreaming( - createModelInteractionParams: CreateModelInteractionParams, - requestOptions: RequestOptions = RequestOptions.none(), - ): AsyncStreamResponse = - createStreaming( - InteractionCreateParams.Body.ofCreateModelInteractionParams( - createModelInteractionParams - ), - requestOptions, - ) - - /** @see createStreaming */ - fun createStreaming( - createModelInteractionParams: CreateModelInteractionParams - ): AsyncStreamResponse = - createStreaming(createModelInteractionParams, RequestOptions.none()) - - /** @see createStreaming */ - fun createStreaming( - createAgentInteractionParams: CreateAgentInteractionParams, - requestOptions: RequestOptions = RequestOptions.none(), - ): AsyncStreamResponse = - createStreaming( - InteractionCreateParams.Body.ofCreateAgentInteractionParams( - createAgentInteractionParams - ), - requestOptions, - ) - - /** @see createStreaming */ - fun createStreaming( - createAgentInteractionParams: CreateAgentInteractionParams - ): AsyncStreamResponse = - createStreaming(createAgentInteractionParams, RequestOptions.none()) - - /** Deletes the interaction by id. */ - fun delete(id: String): CompletableFuture = - delete(id, InteractionDeleteParams.none()) - - /** @see delete */ - fun delete( - id: String, - params: InteractionDeleteParams = InteractionDeleteParams.none(), - requestOptions: RequestOptions = RequestOptions.none(), - ): CompletableFuture = - delete(params.toBuilder().id(id).build(), requestOptions) - - /** @see delete */ - fun delete( - id: String, - params: InteractionDeleteParams = InteractionDeleteParams.none(), - ): CompletableFuture = delete(id, params, RequestOptions.none()) - - /** @see delete */ - fun delete( - params: InteractionDeleteParams, - requestOptions: RequestOptions = RequestOptions.none(), - ): CompletableFuture - - /** @see delete */ - fun delete(params: InteractionDeleteParams): CompletableFuture = - delete(params, RequestOptions.none()) - - /** @see delete */ - fun delete( - id: String, - requestOptions: RequestOptions, - ): CompletableFuture = - delete(id, InteractionDeleteParams.none(), requestOptions) - - /** - * Cancels an interaction by id. This only applies to background interactions that are still - * running. - */ - fun cancel(id: String): CompletableFuture = - cancel(id, InteractionCancelParams.none()) - - /** @see cancel */ - fun cancel( - id: String, - params: InteractionCancelParams = InteractionCancelParams.none(), - requestOptions: RequestOptions = RequestOptions.none(), - ): CompletableFuture = cancel(params.toBuilder().id(id).build(), requestOptions) - - /** @see cancel */ - fun cancel( - id: String, - params: InteractionCancelParams = InteractionCancelParams.none(), - ): CompletableFuture = cancel(id, params, RequestOptions.none()) - - /** @see cancel */ - fun cancel( - params: InteractionCancelParams, - requestOptions: RequestOptions = RequestOptions.none(), - ): CompletableFuture - - /** @see cancel */ - fun cancel(params: InteractionCancelParams): CompletableFuture = - cancel(params, RequestOptions.none()) - - /** @see cancel */ - fun cancel(id: String, requestOptions: RequestOptions): CompletableFuture = - cancel(id, InteractionCancelParams.none(), requestOptions) - - /** Retrieves the full details of a single interaction based on its `Interaction.id`. */ - fun get(id: String): CompletableFuture = get(id, InteractionGetParams.none()) - - /** @see get */ - fun get( - id: String, - params: InteractionGetParams = InteractionGetParams.none(), - requestOptions: RequestOptions = RequestOptions.none(), - ): CompletableFuture = get(params.toBuilder().id(id).build(), requestOptions) - - /** @see get */ - fun get( - id: String, - params: InteractionGetParams = InteractionGetParams.none(), - ): CompletableFuture = get(id, params, RequestOptions.none()) - - /** @see get */ - fun get( - params: InteractionGetParams, - requestOptions: RequestOptions = RequestOptions.none(), - ): CompletableFuture - - /** @see get */ - fun get(params: InteractionGetParams): CompletableFuture = - get(params, RequestOptions.none()) - - /** @see get */ - fun get(id: String, requestOptions: RequestOptions): CompletableFuture = - get(id, InteractionGetParams.none(), requestOptions) - - /** Retrieves the full details of a single interaction based on its `Interaction.id`. */ - fun getStreaming(id: String): AsyncStreamResponse = - getStreaming(id, InteractionGetParams.none()) - - /** @see getStreaming */ - fun getStreaming( - id: String, - params: InteractionGetParams = InteractionGetParams.none(), - requestOptions: RequestOptions = RequestOptions.none(), - ): AsyncStreamResponse = - getStreaming(params.toBuilder().id(id).build(), requestOptions) - - /** @see getStreaming */ - fun getStreaming( - id: String, - params: InteractionGetParams = InteractionGetParams.none(), - ): AsyncStreamResponse = getStreaming(id, params, RequestOptions.none()) - - /** @see getStreaming */ - fun getStreaming( - params: InteractionGetParams, - requestOptions: RequestOptions = RequestOptions.none(), - ): AsyncStreamResponse - - /** @see getStreaming */ - fun getStreaming(params: InteractionGetParams): AsyncStreamResponse = - getStreaming(params, RequestOptions.none()) - - /** @see getStreaming */ - fun getStreaming( - id: String, - requestOptions: RequestOptions, - ): AsyncStreamResponse = - getStreaming(id, InteractionGetParams.none(), requestOptions) - - /** - * A view of [InteractionServiceAsync] that provides access to raw HTTP responses for each - * method. - */ - interface WithRawResponse { - - /** - * Returns a view of this service with the given option modifications applied. - * - * The original service is not modified. - */ - fun withOptions( - modifier: Consumer - ): InteractionServiceAsync.WithRawResponse - - /** - * Returns a raw HTTP response for `post /{api_version}/interactions`, but is otherwise the - * same as [InteractionServiceAsync.create]. - */ - fun create( - params: InteractionCreateParams - ): CompletableFuture> = create(params, RequestOptions.none()) - - /** @see create */ - fun create( - params: InteractionCreateParams, - requestOptions: RequestOptions = RequestOptions.none(), - ): CompletableFuture> - - /** @see create */ - fun create( - body: InteractionCreateParams.Body, - requestOptions: RequestOptions = RequestOptions.none(), - ): CompletableFuture> = - create(InteractionCreateParams.builder().body(body).build(), requestOptions) - - /** @see create */ - fun create( - body: InteractionCreateParams.Body - ): CompletableFuture> = create(body, RequestOptions.none()) - - /** @see create */ - fun create( - createModelInteractionParams: CreateModelInteractionParams, - requestOptions: RequestOptions = RequestOptions.none(), - ): CompletableFuture> = - create( - InteractionCreateParams.Body.ofCreateModelInteractionParams( - createModelInteractionParams - ), - requestOptions, - ) - - /** @see create */ - fun create( - createModelInteractionParams: CreateModelInteractionParams - ): CompletableFuture> = - create(createModelInteractionParams, RequestOptions.none()) - - /** @see create */ - fun create( - createAgentInteractionParams: CreateAgentInteractionParams, - requestOptions: RequestOptions = RequestOptions.none(), - ): CompletableFuture> = - create( - InteractionCreateParams.Body.ofCreateAgentInteractionParams( - createAgentInteractionParams - ), - requestOptions, - ) - - /** @see create */ - fun create( - createAgentInteractionParams: CreateAgentInteractionParams - ): CompletableFuture> = - create(createAgentInteractionParams, RequestOptions.none()) - - /** - * Returns a raw HTTP response for `post /{api_version}/interactions`, but is otherwise the - * same as [InteractionServiceAsync.createStreaming]. - */ - @MustBeClosed - fun createStreaming( - params: InteractionCreateParams - ): CompletableFuture>> = - createStreaming(params, RequestOptions.none()) - - /** @see createStreaming */ - @MustBeClosed - fun createStreaming( - params: InteractionCreateParams, - requestOptions: RequestOptions = RequestOptions.none(), - ): CompletableFuture>> - - /** @see createStreaming */ - @MustBeClosed - fun createStreaming( - body: InteractionCreateParams.Body, - requestOptions: RequestOptions = RequestOptions.none(), - ): CompletableFuture>> = - createStreaming(InteractionCreateParams.builder().body(body).build(), requestOptions) - - /** @see createStreaming */ - @MustBeClosed - fun createStreaming( - body: InteractionCreateParams.Body - ): CompletableFuture>> = - createStreaming(body, RequestOptions.none()) - - /** @see createStreaming */ - @MustBeClosed - fun createStreaming( - createModelInteractionParams: CreateModelInteractionParams, - requestOptions: RequestOptions = RequestOptions.none(), - ): CompletableFuture>> = - createStreaming( - InteractionCreateParams.Body.ofCreateModelInteractionParams( - createModelInteractionParams - ), - requestOptions, - ) - - /** @see createStreaming */ - @MustBeClosed - fun createStreaming( - createModelInteractionParams: CreateModelInteractionParams - ): CompletableFuture>> = - createStreaming(createModelInteractionParams, RequestOptions.none()) - - /** @see createStreaming */ - @MustBeClosed - fun createStreaming( - createAgentInteractionParams: CreateAgentInteractionParams, - requestOptions: RequestOptions = RequestOptions.none(), - ): CompletableFuture>> = - createStreaming( - InteractionCreateParams.Body.ofCreateAgentInteractionParams( - createAgentInteractionParams - ), - requestOptions, - ) - - /** @see createStreaming */ - @MustBeClosed - fun createStreaming( - createAgentInteractionParams: CreateAgentInteractionParams - ): CompletableFuture>> = - createStreaming(createAgentInteractionParams, RequestOptions.none()) - - /** - * Returns a raw HTTP response for `delete /{api_version}/interactions/{id}`, but is - * otherwise the same as [InteractionServiceAsync.delete]. - */ - fun delete(id: String): CompletableFuture> = - delete(id, InteractionDeleteParams.none()) - - /** @see delete */ - fun delete( - id: String, - params: InteractionDeleteParams = InteractionDeleteParams.none(), - requestOptions: RequestOptions = RequestOptions.none(), - ): CompletableFuture> = - delete(params.toBuilder().id(id).build(), requestOptions) - - /** @see delete */ - fun delete( - id: String, - params: InteractionDeleteParams = InteractionDeleteParams.none(), - ): CompletableFuture> = - delete(id, params, RequestOptions.none()) - - /** @see delete */ - fun delete( - params: InteractionDeleteParams, - requestOptions: RequestOptions = RequestOptions.none(), - ): CompletableFuture> - - /** @see delete */ - fun delete( - params: InteractionDeleteParams - ): CompletableFuture> = - delete(params, RequestOptions.none()) - - /** @see delete */ - fun delete( - id: String, - requestOptions: RequestOptions, - ): CompletableFuture> = - delete(id, InteractionDeleteParams.none(), requestOptions) - - /** - * Returns a raw HTTP response for `post /{api_version}/interactions/{id}/cancel`, but is - * otherwise the same as [InteractionServiceAsync.cancel]. - */ - fun cancel(id: String): CompletableFuture> = - cancel(id, InteractionCancelParams.none()) - - /** @see cancel */ - fun cancel( - id: String, - params: InteractionCancelParams = InteractionCancelParams.none(), - requestOptions: RequestOptions = RequestOptions.none(), - ): CompletableFuture> = - cancel(params.toBuilder().id(id).build(), requestOptions) - - /** @see cancel */ - fun cancel( - id: String, - params: InteractionCancelParams = InteractionCancelParams.none(), - ): CompletableFuture> = - cancel(id, params, RequestOptions.none()) - - /** @see cancel */ - fun cancel( - params: InteractionCancelParams, - requestOptions: RequestOptions = RequestOptions.none(), - ): CompletableFuture> - - /** @see cancel */ - fun cancel( - params: InteractionCancelParams - ): CompletableFuture> = cancel(params, RequestOptions.none()) - - /** @see cancel */ - fun cancel( - id: String, - requestOptions: RequestOptions, - ): CompletableFuture> = - cancel(id, InteractionCancelParams.none(), requestOptions) - - /** - * Returns a raw HTTP response for `get /{api_version}/interactions/{id}`, but is otherwise - * the same as [InteractionServiceAsync.get]. - */ - fun get(id: String): CompletableFuture> = - get(id, InteractionGetParams.none()) - - /** @see get */ - fun get( - id: String, - params: InteractionGetParams = InteractionGetParams.none(), - requestOptions: RequestOptions = RequestOptions.none(), - ): CompletableFuture> = - get(params.toBuilder().id(id).build(), requestOptions) - - /** @see get */ - fun get( - id: String, - params: InteractionGetParams = InteractionGetParams.none(), - ): CompletableFuture> = get(id, params, RequestOptions.none()) - - /** @see get */ - fun get( - params: InteractionGetParams, - requestOptions: RequestOptions = RequestOptions.none(), - ): CompletableFuture> - - /** @see get */ - fun get(params: InteractionGetParams): CompletableFuture> = - get(params, RequestOptions.none()) - - /** @see get */ - fun get( - id: String, - requestOptions: RequestOptions, - ): CompletableFuture> = - get(id, InteractionGetParams.none(), requestOptions) - - /** - * Returns a raw HTTP response for `get /{api_version}/interactions/{id}`, but is otherwise - * the same as [InteractionServiceAsync.getStreaming]. - */ - @MustBeClosed - fun getStreaming( - id: String - ): CompletableFuture>> = - getStreaming(id, InteractionGetParams.none()) - - /** @see getStreaming */ - @MustBeClosed - fun getStreaming( - id: String, - params: InteractionGetParams = InteractionGetParams.none(), - requestOptions: RequestOptions = RequestOptions.none(), - ): CompletableFuture>> = - getStreaming(params.toBuilder().id(id).build(), requestOptions) - - /** @see getStreaming */ - @MustBeClosed - fun getStreaming( - id: String, - params: InteractionGetParams = InteractionGetParams.none(), - ): CompletableFuture>> = - getStreaming(id, params, RequestOptions.none()) - - /** @see getStreaming */ - @MustBeClosed - fun getStreaming( - params: InteractionGetParams, - requestOptions: RequestOptions = RequestOptions.none(), - ): CompletableFuture>> - - /** @see getStreaming */ - @MustBeClosed - fun getStreaming( - params: InteractionGetParams - ): CompletableFuture>> = - getStreaming(params, RequestOptions.none()) - - /** @see getStreaming */ - @MustBeClosed - fun getStreaming( - id: String, - requestOptions: RequestOptions, - ): CompletableFuture>> = - getStreaming(id, InteractionGetParams.none(), requestOptions) - } -} diff --git a/src/main/java/com/google/genai/interactions/services/async/InteractionServiceAsyncImpl.kt b/src/main/java/com/google/genai/interactions/services/async/InteractionServiceAsyncImpl.kt deleted file mode 100644 index 131a5692e79..00000000000 --- a/src/main/java/com/google/genai/interactions/services/async/InteractionServiceAsyncImpl.kt +++ /dev/null @@ -1,396 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.services.async - -import com.google.genai.interactions.core.ClientOptions -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.core.RequestOptions -import com.google.genai.interactions.core.checkRequired -import com.google.genai.interactions.core.handlers.errorBodyHandler -import com.google.genai.interactions.core.handlers.errorHandler -import com.google.genai.interactions.core.handlers.jsonHandler -import com.google.genai.interactions.core.handlers.mapJson -import com.google.genai.interactions.core.handlers.sseHandler -import com.google.genai.interactions.core.http.AsyncStreamResponse -import com.google.genai.interactions.core.http.HttpMethod -import com.google.genai.interactions.core.http.HttpRequest -import com.google.genai.interactions.core.http.HttpResponse -import com.google.genai.interactions.core.http.HttpResponse.Handler -import com.google.genai.interactions.core.http.HttpResponseFor -import com.google.genai.interactions.core.http.StreamResponse -import com.google.genai.interactions.core.http.json -import com.google.genai.interactions.core.http.map -import com.google.genai.interactions.core.http.parseable -import com.google.genai.interactions.core.http.toAsync -import com.google.genai.interactions.core.prepareAsync -import com.google.genai.interactions.models.interactions.CreateAgentInteractionParams -import com.google.genai.interactions.models.interactions.CreateModelInteractionParams -import com.google.genai.interactions.models.interactions.Interaction -import com.google.genai.interactions.models.interactions.InteractionCancelParams -import com.google.genai.interactions.models.interactions.InteractionCreateParams -import com.google.genai.interactions.models.interactions.InteractionDeleteParams -import com.google.genai.interactions.models.interactions.InteractionDeleteResponse -import com.google.genai.interactions.models.interactions.InteractionGetParams -import com.google.genai.interactions.models.interactions.InteractionSseEvent -import java.util.concurrent.CompletableFuture -import java.util.function.Consumer -import kotlin.jvm.optionals.getOrNull - -class InteractionServiceAsyncImpl constructor(private val clientOptions: ClientOptions) : - InteractionServiceAsync { - - private val withRawResponse: InteractionServiceAsync.WithRawResponse by lazy { - WithRawResponseImpl(clientOptions) - } - - override fun withRawResponse(): InteractionServiceAsync.WithRawResponse = withRawResponse - - override fun withOptions(modifier: Consumer): InteractionServiceAsync = - InteractionServiceAsyncImpl(clientOptions.toBuilder().apply(modifier::accept).build()) - - override fun create( - params: InteractionCreateParams, - requestOptions: RequestOptions, - ): CompletableFuture = - // post /{api_version}/interactions - withRawResponse().create(params, requestOptions).thenApply { it.parse() } - - override fun createStreaming( - params: InteractionCreateParams, - requestOptions: RequestOptions, - ): AsyncStreamResponse = - // post /{api_version}/interactions - withRawResponse() - .createStreaming(params, requestOptions) - .thenApply { it.parse() } - .toAsync(clientOptions.streamHandlerExecutor) - - override fun delete( - params: InteractionDeleteParams, - requestOptions: RequestOptions, - ): CompletableFuture = - // delete /{api_version}/interactions/{id} - withRawResponse().delete(params, requestOptions).thenApply { it.parse() } - - override fun cancel( - params: InteractionCancelParams, - requestOptions: RequestOptions, - ): CompletableFuture = - // post /{api_version}/interactions/{id}/cancel - withRawResponse().cancel(params, requestOptions).thenApply { it.parse() } - - override fun get( - params: InteractionGetParams, - requestOptions: RequestOptions, - ): CompletableFuture = - // get /{api_version}/interactions/{id} - withRawResponse().get(params, requestOptions).thenApply { it.parse() } - - override fun getStreaming( - params: InteractionGetParams, - requestOptions: RequestOptions, - ): AsyncStreamResponse = - // get /{api_version}/interactions/{id} - withRawResponse() - .getStreaming(params, requestOptions) - .thenApply { it.parse() } - .toAsync(clientOptions.streamHandlerExecutor) - - class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : - InteractionServiceAsync.WithRawResponse { - - private val errorHandler: Handler = - errorHandler(errorBodyHandler(clientOptions.jsonMapper)) - - override fun withOptions( - modifier: Consumer - ): InteractionServiceAsync.WithRawResponse = - InteractionServiceAsyncImpl.WithRawResponseImpl( - clientOptions.toBuilder().apply(modifier::accept).build() - ) - - private val createHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - - override fun create( - params: InteractionCreateParams, - requestOptions: RequestOptions, - ): CompletableFuture> { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .baseUrl(clientOptions.baseUrl()) - .addPathSegments( - params._pathParam(0).ifBlank { clientOptions.apiVersion }, - "interactions", - ) - .body(json(clientOptions.jsonMapper, params._body())) - .build() - .prepareAsync(clientOptions, params) - val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - errorHandler.handle(response).parseable { - response - .use { createHandler.handle(it) } - .also { - if (requestOptions.responseValidation!!) { - it.validate() - } - } - } - } - } - - private val createStreamingHandler: Handler> = - sseHandler(clientOptions.jsonMapper).mapJson() - - override fun createStreaming( - params: InteractionCreateParams, - requestOptions: RequestOptions, - ): CompletableFuture>> { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .baseUrl(clientOptions.baseUrl()) - .addPathSegments( - params._pathParam(0).ifBlank { clientOptions.apiVersion }, - "interactions", - ) - .putHeader("Accept", "text/event-stream") - .body( - json( - clientOptions.jsonMapper, - params - ._body() - .accept( - object : - InteractionCreateParams.Body.Visitor< - InteractionCreateParams.Body - > { - override fun visitCreateModelInteractionParams( - createModelInteractionParams: - CreateModelInteractionParams - ) = - InteractionCreateParams.Body - .ofCreateModelInteractionParams( - createModelInteractionParams - .toBuilder() - .putAdditionalProperty( - "stream", - JsonValue.from(true), - ) - .build() - ) - - override fun visitCreateAgentInteractionParams( - createAgentInteractionParams: - CreateAgentInteractionParams - ) = - InteractionCreateParams.Body - .ofCreateAgentInteractionParams( - createAgentInteractionParams - .toBuilder() - .putAdditionalProperty( - "stream", - JsonValue.from(true), - ) - .build() - ) - } - ), - ) - ) - .build() - .prepareAsync(clientOptions, params) - val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - errorHandler.handle(response).parseable { - response - .let { createStreamingHandler.handle(it) } - .let { streamResponse -> - if (requestOptions.responseValidation!!) { - streamResponse.map { it.validate() } - } else { - streamResponse - } - } - } - } - } - - private val deleteHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - - override fun delete( - params: InteractionDeleteParams, - requestOptions: RequestOptions, - ): CompletableFuture> { - // We check here instead of in the params builder because this can be specified - // positionally or in the params class. - checkRequired("id", params.id().getOrNull()) - val request = - HttpRequest.builder() - .method(HttpMethod.DELETE) - .baseUrl(clientOptions.baseUrl()) - .addPathSegments( - params._pathParam(0).ifBlank { clientOptions.apiVersion }, - "interactions", - params._pathParam(1), - ) - .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } - .build() - .prepareAsync(clientOptions, params) - val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - errorHandler.handle(response).parseable { - response - .use { deleteHandler.handle(it) } - .also { - if (requestOptions.responseValidation!!) { - it.validate() - } - } - } - } - } - - private val cancelHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - - override fun cancel( - params: InteractionCancelParams, - requestOptions: RequestOptions, - ): CompletableFuture> { - // We check here instead of in the params builder because this can be specified - // positionally or in the params class. - checkRequired("id", params.id().getOrNull()) - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .baseUrl(clientOptions.baseUrl()) - .addPathSegments( - params._pathParam(0).ifBlank { clientOptions.apiVersion }, - "interactions", - params._pathParam(1), - "cancel", - ) - .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } - .build() - .prepareAsync(clientOptions, params) - val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - errorHandler.handle(response).parseable { - response - .use { cancelHandler.handle(it) } - .also { - if (requestOptions.responseValidation!!) { - it.validate() - } - } - } - } - } - - private val getHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - - override fun get( - params: InteractionGetParams, - requestOptions: RequestOptions, - ): CompletableFuture> { - // We check here instead of in the params builder because this can be specified - // positionally or in the params class. - checkRequired("id", params.id().getOrNull()) - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .baseUrl(clientOptions.baseUrl()) - .addPathSegments( - params._pathParam(0).ifBlank { clientOptions.apiVersion }, - "interactions", - params._pathParam(1), - ) - .build() - .prepareAsync(clientOptions, params) - val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - errorHandler.handle(response).parseable { - response - .use { getHandler.handle(it) } - .also { - if (requestOptions.responseValidation!!) { - it.validate() - } - } - } - } - } - - private val getStreamingHandler: Handler> = - sseHandler(clientOptions.jsonMapper).mapJson() - - override fun getStreaming( - params: InteractionGetParams, - requestOptions: RequestOptions, - ): CompletableFuture>> { - // We check here instead of in the params builder because this can be specified - // positionally or in the params class. - checkRequired("id", params.id().getOrNull()) - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .baseUrl(clientOptions.baseUrl()) - .addPathSegments( - params._pathParam(0).ifBlank { clientOptions.apiVersion }, - "interactions", - params._pathParam(1), - ) - .putQueryParam("stream", "true") - .putHeader("Accept", "text/event-stream") - .build() - .prepareAsync(clientOptions, params) - val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - errorHandler.handle(response).parseable { - response - .let { getStreamingHandler.handle(it) } - .let { streamResponse -> - if (requestOptions.responseValidation!!) { - streamResponse.map { it.validate() } - } else { - streamResponse - } - } - } - } - } - } -} diff --git a/src/main/java/com/google/genai/interactions/services/blocking/InteractionService.kt b/src/main/java/com/google/genai/interactions/services/blocking/InteractionService.kt deleted file mode 100644 index 7b9246a8901..00000000000 --- a/src/main/java/com/google/genai/interactions/services/blocking/InteractionService.kt +++ /dev/null @@ -1,621 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.services.blocking - -import com.google.genai.interactions.core.ClientOptions -import com.google.genai.interactions.core.RequestOptions -import com.google.genai.interactions.core.http.HttpResponseFor -import com.google.genai.interactions.core.http.StreamResponse -import com.google.genai.interactions.models.interactions.CreateAgentInteractionParams -import com.google.genai.interactions.models.interactions.CreateModelInteractionParams -import com.google.genai.interactions.models.interactions.Interaction -import com.google.genai.interactions.models.interactions.InteractionCancelParams -import com.google.genai.interactions.models.interactions.InteractionCreateParams -import com.google.genai.interactions.models.interactions.InteractionDeleteParams -import com.google.genai.interactions.models.interactions.InteractionDeleteResponse -import com.google.genai.interactions.models.interactions.InteractionGetParams -import com.google.genai.interactions.models.interactions.InteractionSseEvent -import com.google.errorprone.annotations.MustBeClosed -import java.util.function.Consumer - -interface InteractionService { - - /** - * Returns a view of this service that provides access to raw HTTP responses for each method. - */ - fun withRawResponse(): WithRawResponse - - /** - * Returns a view of this service with the given option modifications applied. - * - * The original service is not modified. - */ - fun withOptions(modifier: Consumer): InteractionService - - /** Creates a new interaction. */ - fun create(params: InteractionCreateParams): Interaction = create(params, RequestOptions.none()) - - /** @see create */ - fun create( - params: InteractionCreateParams, - requestOptions: RequestOptions = RequestOptions.none(), - ): Interaction - - /** @see create */ - fun create( - body: InteractionCreateParams.Body, - requestOptions: RequestOptions = RequestOptions.none(), - ): Interaction = create(InteractionCreateParams.builder().body(body).build(), requestOptions) - - /** @see create */ - fun create(body: InteractionCreateParams.Body): Interaction = - create(body, RequestOptions.none()) - - /** @see create */ - fun create( - createModelInteractionParams: CreateModelInteractionParams, - requestOptions: RequestOptions = RequestOptions.none(), - ): Interaction = - create( - InteractionCreateParams.Body.ofCreateModelInteractionParams( - createModelInteractionParams - ), - requestOptions, - ) - - /** @see create */ - fun create(createModelInteractionParams: CreateModelInteractionParams): Interaction = - create(createModelInteractionParams, RequestOptions.none()) - - /** @see create */ - fun create( - createAgentInteractionParams: CreateAgentInteractionParams, - requestOptions: RequestOptions = RequestOptions.none(), - ): Interaction = - create( - InteractionCreateParams.Body.ofCreateAgentInteractionParams( - createAgentInteractionParams - ), - requestOptions, - ) - - /** @see create */ - fun create(createAgentInteractionParams: CreateAgentInteractionParams): Interaction = - create(createAgentInteractionParams, RequestOptions.none()) - - /** Creates a new interaction. */ - @MustBeClosed - fun createStreaming(params: InteractionCreateParams): StreamResponse = - createStreaming(params, RequestOptions.none()) - - /** @see createStreaming */ - @MustBeClosed - fun createStreaming( - params: InteractionCreateParams, - requestOptions: RequestOptions = RequestOptions.none(), - ): StreamResponse - - /** @see createStreaming */ - @MustBeClosed - fun createStreaming( - body: InteractionCreateParams.Body, - requestOptions: RequestOptions = RequestOptions.none(), - ): StreamResponse = - createStreaming(InteractionCreateParams.builder().body(body).build(), requestOptions) - - /** @see createStreaming */ - @MustBeClosed - fun createStreaming(body: InteractionCreateParams.Body): StreamResponse = - createStreaming(body, RequestOptions.none()) - - /** @see createStreaming */ - @MustBeClosed - fun createStreaming( - createModelInteractionParams: CreateModelInteractionParams, - requestOptions: RequestOptions = RequestOptions.none(), - ): StreamResponse = - createStreaming( - InteractionCreateParams.Body.ofCreateModelInteractionParams( - createModelInteractionParams - ), - requestOptions, - ) - - /** @see createStreaming */ - @MustBeClosed - fun createStreaming( - createModelInteractionParams: CreateModelInteractionParams - ): StreamResponse = - createStreaming(createModelInteractionParams, RequestOptions.none()) - - /** @see createStreaming */ - @MustBeClosed - fun createStreaming( - createAgentInteractionParams: CreateAgentInteractionParams, - requestOptions: RequestOptions = RequestOptions.none(), - ): StreamResponse = - createStreaming( - InteractionCreateParams.Body.ofCreateAgentInteractionParams( - createAgentInteractionParams - ), - requestOptions, - ) - - /** @see createStreaming */ - @MustBeClosed - fun createStreaming( - createAgentInteractionParams: CreateAgentInteractionParams - ): StreamResponse = - createStreaming(createAgentInteractionParams, RequestOptions.none()) - - /** Deletes the interaction by id. */ - fun delete(id: String): InteractionDeleteResponse = delete(id, InteractionDeleteParams.none()) - - /** @see delete */ - fun delete( - id: String, - params: InteractionDeleteParams = InteractionDeleteParams.none(), - requestOptions: RequestOptions = RequestOptions.none(), - ): InteractionDeleteResponse = delete(params.toBuilder().id(id).build(), requestOptions) - - /** @see delete */ - fun delete( - id: String, - params: InteractionDeleteParams = InteractionDeleteParams.none(), - ): InteractionDeleteResponse = delete(id, params, RequestOptions.none()) - - /** @see delete */ - fun delete( - params: InteractionDeleteParams, - requestOptions: RequestOptions = RequestOptions.none(), - ): InteractionDeleteResponse - - /** @see delete */ - fun delete(params: InteractionDeleteParams): InteractionDeleteResponse = - delete(params, RequestOptions.none()) - - /** @see delete */ - fun delete(id: String, requestOptions: RequestOptions): InteractionDeleteResponse = - delete(id, InteractionDeleteParams.none(), requestOptions) - - /** - * Cancels an interaction by id. This only applies to background interactions that are still - * running. - */ - fun cancel(id: String): Interaction = cancel(id, InteractionCancelParams.none()) - - /** @see cancel */ - fun cancel( - id: String, - params: InteractionCancelParams = InteractionCancelParams.none(), - requestOptions: RequestOptions = RequestOptions.none(), - ): Interaction = cancel(params.toBuilder().id(id).build(), requestOptions) - - /** @see cancel */ - fun cancel( - id: String, - params: InteractionCancelParams = InteractionCancelParams.none(), - ): Interaction = cancel(id, params, RequestOptions.none()) - - /** @see cancel */ - fun cancel( - params: InteractionCancelParams, - requestOptions: RequestOptions = RequestOptions.none(), - ): Interaction - - /** @see cancel */ - fun cancel(params: InteractionCancelParams): Interaction = cancel(params, RequestOptions.none()) - - /** @see cancel */ - fun cancel(id: String, requestOptions: RequestOptions): Interaction = - cancel(id, InteractionCancelParams.none(), requestOptions) - - /** Retrieves the full details of a single interaction based on its `Interaction.id`. */ - fun get(id: String): Interaction = get(id, InteractionGetParams.none()) - - /** @see get */ - fun get( - id: String, - params: InteractionGetParams = InteractionGetParams.none(), - requestOptions: RequestOptions = RequestOptions.none(), - ): Interaction = get(params.toBuilder().id(id).build(), requestOptions) - - /** @see get */ - fun get(id: String, params: InteractionGetParams = InteractionGetParams.none()): Interaction = - get(id, params, RequestOptions.none()) - - /** @see get */ - fun get( - params: InteractionGetParams, - requestOptions: RequestOptions = RequestOptions.none(), - ): Interaction - - /** @see get */ - fun get(params: InteractionGetParams): Interaction = get(params, RequestOptions.none()) - - /** @see get */ - fun get(id: String, requestOptions: RequestOptions): Interaction = - get(id, InteractionGetParams.none(), requestOptions) - - /** Retrieves the full details of a single interaction based on its `Interaction.id`. */ - @MustBeClosed - fun getStreaming(id: String): StreamResponse = - getStreaming(id, InteractionGetParams.none()) - - /** @see getStreaming */ - @MustBeClosed - fun getStreaming( - id: String, - params: InteractionGetParams = InteractionGetParams.none(), - requestOptions: RequestOptions = RequestOptions.none(), - ): StreamResponse = - getStreaming(params.toBuilder().id(id).build(), requestOptions) - - /** @see getStreaming */ - @MustBeClosed - fun getStreaming( - id: String, - params: InteractionGetParams = InteractionGetParams.none(), - ): StreamResponse = getStreaming(id, params, RequestOptions.none()) - - /** @see getStreaming */ - @MustBeClosed - fun getStreaming( - params: InteractionGetParams, - requestOptions: RequestOptions = RequestOptions.none(), - ): StreamResponse - - /** @see getStreaming */ - @MustBeClosed - fun getStreaming(params: InteractionGetParams): StreamResponse = - getStreaming(params, RequestOptions.none()) - - /** @see getStreaming */ - @MustBeClosed - fun getStreaming( - id: String, - requestOptions: RequestOptions, - ): StreamResponse = - getStreaming(id, InteractionGetParams.none(), requestOptions) - - /** - * A view of [InteractionService] that provides access to raw HTTP responses for each method. - */ - interface WithRawResponse { - - /** - * Returns a view of this service with the given option modifications applied. - * - * The original service is not modified. - */ - fun withOptions( - modifier: Consumer - ): InteractionService.WithRawResponse - - /** - * Returns a raw HTTP response for `post /{api_version}/interactions`, but is otherwise the - * same as [InteractionService.create]. - */ - @MustBeClosed - fun create(params: InteractionCreateParams): HttpResponseFor = - create(params, RequestOptions.none()) - - /** @see create */ - @MustBeClosed - fun create( - params: InteractionCreateParams, - requestOptions: RequestOptions = RequestOptions.none(), - ): HttpResponseFor - - /** @see create */ - @MustBeClosed - fun create( - body: InteractionCreateParams.Body, - requestOptions: RequestOptions = RequestOptions.none(), - ): HttpResponseFor = - create(InteractionCreateParams.builder().body(body).build(), requestOptions) - - /** @see create */ - @MustBeClosed - fun create(body: InteractionCreateParams.Body): HttpResponseFor = - create(body, RequestOptions.none()) - - /** @see create */ - @MustBeClosed - fun create( - createModelInteractionParams: CreateModelInteractionParams, - requestOptions: RequestOptions = RequestOptions.none(), - ): HttpResponseFor = - create( - InteractionCreateParams.Body.ofCreateModelInteractionParams( - createModelInteractionParams - ), - requestOptions, - ) - - /** @see create */ - @MustBeClosed - fun create( - createModelInteractionParams: CreateModelInteractionParams - ): HttpResponseFor = - create(createModelInteractionParams, RequestOptions.none()) - - /** @see create */ - @MustBeClosed - fun create( - createAgentInteractionParams: CreateAgentInteractionParams, - requestOptions: RequestOptions = RequestOptions.none(), - ): HttpResponseFor = - create( - InteractionCreateParams.Body.ofCreateAgentInteractionParams( - createAgentInteractionParams - ), - requestOptions, - ) - - /** @see create */ - @MustBeClosed - fun create( - createAgentInteractionParams: CreateAgentInteractionParams - ): HttpResponseFor = - create(createAgentInteractionParams, RequestOptions.none()) - - /** - * Returns a raw HTTP response for `post /{api_version}/interactions`, but is otherwise the - * same as [InteractionService.createStreaming]. - */ - @MustBeClosed - fun createStreaming( - params: InteractionCreateParams - ): HttpResponseFor> = - createStreaming(params, RequestOptions.none()) - - /** @see createStreaming */ - @MustBeClosed - fun createStreaming( - params: InteractionCreateParams, - requestOptions: RequestOptions = RequestOptions.none(), - ): HttpResponseFor> - - /** @see createStreaming */ - @MustBeClosed - fun createStreaming( - body: InteractionCreateParams.Body, - requestOptions: RequestOptions = RequestOptions.none(), - ): HttpResponseFor> = - createStreaming(InteractionCreateParams.builder().body(body).build(), requestOptions) - - /** @see createStreaming */ - @MustBeClosed - fun createStreaming( - body: InteractionCreateParams.Body - ): HttpResponseFor> = - createStreaming(body, RequestOptions.none()) - - /** @see createStreaming */ - @MustBeClosed - fun createStreaming( - createModelInteractionParams: CreateModelInteractionParams, - requestOptions: RequestOptions = RequestOptions.none(), - ): HttpResponseFor> = - createStreaming( - InteractionCreateParams.Body.ofCreateModelInteractionParams( - createModelInteractionParams - ), - requestOptions, - ) - - /** @see createStreaming */ - @MustBeClosed - fun createStreaming( - createModelInteractionParams: CreateModelInteractionParams - ): HttpResponseFor> = - createStreaming(createModelInteractionParams, RequestOptions.none()) - - /** @see createStreaming */ - @MustBeClosed - fun createStreaming( - createAgentInteractionParams: CreateAgentInteractionParams, - requestOptions: RequestOptions = RequestOptions.none(), - ): HttpResponseFor> = - createStreaming( - InteractionCreateParams.Body.ofCreateAgentInteractionParams( - createAgentInteractionParams - ), - requestOptions, - ) - - /** @see createStreaming */ - @MustBeClosed - fun createStreaming( - createAgentInteractionParams: CreateAgentInteractionParams - ): HttpResponseFor> = - createStreaming(createAgentInteractionParams, RequestOptions.none()) - - /** - * Returns a raw HTTP response for `delete /{api_version}/interactions/{id}`, but is - * otherwise the same as [InteractionService.delete]. - */ - @MustBeClosed - fun delete(id: String): HttpResponseFor = - delete(id, InteractionDeleteParams.none()) - - /** @see delete */ - @MustBeClosed - fun delete( - id: String, - params: InteractionDeleteParams = InteractionDeleteParams.none(), - requestOptions: RequestOptions = RequestOptions.none(), - ): HttpResponseFor = - delete(params.toBuilder().id(id).build(), requestOptions) - - /** @see delete */ - @MustBeClosed - fun delete( - id: String, - params: InteractionDeleteParams = InteractionDeleteParams.none(), - ): HttpResponseFor = delete(id, params, RequestOptions.none()) - - /** @see delete */ - @MustBeClosed - fun delete( - params: InteractionDeleteParams, - requestOptions: RequestOptions = RequestOptions.none(), - ): HttpResponseFor - - /** @see delete */ - @MustBeClosed - fun delete(params: InteractionDeleteParams): HttpResponseFor = - delete(params, RequestOptions.none()) - - /** @see delete */ - @MustBeClosed - fun delete( - id: String, - requestOptions: RequestOptions, - ): HttpResponseFor = - delete(id, InteractionDeleteParams.none(), requestOptions) - - /** - * Returns a raw HTTP response for `post /{api_version}/interactions/{id}/cancel`, but is - * otherwise the same as [InteractionService.cancel]. - */ - @MustBeClosed - fun cancel(id: String): HttpResponseFor = - cancel(id, InteractionCancelParams.none()) - - /** @see cancel */ - @MustBeClosed - fun cancel( - id: String, - params: InteractionCancelParams = InteractionCancelParams.none(), - requestOptions: RequestOptions = RequestOptions.none(), - ): HttpResponseFor = cancel(params.toBuilder().id(id).build(), requestOptions) - - /** @see cancel */ - @MustBeClosed - fun cancel( - id: String, - params: InteractionCancelParams = InteractionCancelParams.none(), - ): HttpResponseFor = cancel(id, params, RequestOptions.none()) - - /** @see cancel */ - @MustBeClosed - fun cancel( - params: InteractionCancelParams, - requestOptions: RequestOptions = RequestOptions.none(), - ): HttpResponseFor - - /** @see cancel */ - @MustBeClosed - fun cancel(params: InteractionCancelParams): HttpResponseFor = - cancel(params, RequestOptions.none()) - - /** @see cancel */ - @MustBeClosed - fun cancel(id: String, requestOptions: RequestOptions): HttpResponseFor = - cancel(id, InteractionCancelParams.none(), requestOptions) - - /** - * Returns a raw HTTP response for `get /{api_version}/interactions/{id}`, but is otherwise - * the same as [InteractionService.get]. - */ - @MustBeClosed - fun get(id: String): HttpResponseFor = get(id, InteractionGetParams.none()) - - /** @see get */ - @MustBeClosed - fun get( - id: String, - params: InteractionGetParams = InteractionGetParams.none(), - requestOptions: RequestOptions = RequestOptions.none(), - ): HttpResponseFor = get(params.toBuilder().id(id).build(), requestOptions) - - /** @see get */ - @MustBeClosed - fun get( - id: String, - params: InteractionGetParams = InteractionGetParams.none(), - ): HttpResponseFor = get(id, params, RequestOptions.none()) - - /** @see get */ - @MustBeClosed - fun get( - params: InteractionGetParams, - requestOptions: RequestOptions = RequestOptions.none(), - ): HttpResponseFor - - /** @see get */ - @MustBeClosed - fun get(params: InteractionGetParams): HttpResponseFor = - get(params, RequestOptions.none()) - - /** @see get */ - @MustBeClosed - fun get(id: String, requestOptions: RequestOptions): HttpResponseFor = - get(id, InteractionGetParams.none(), requestOptions) - - /** - * Returns a raw HTTP response for `get /{api_version}/interactions/{id}`, but is otherwise - * the same as [InteractionService.getStreaming]. - */ - @MustBeClosed - fun getStreaming(id: String): HttpResponseFor> = - getStreaming(id, InteractionGetParams.none()) - - /** @see getStreaming */ - @MustBeClosed - fun getStreaming( - id: String, - params: InteractionGetParams = InteractionGetParams.none(), - requestOptions: RequestOptions = RequestOptions.none(), - ): HttpResponseFor> = - getStreaming(params.toBuilder().id(id).build(), requestOptions) - - /** @see getStreaming */ - @MustBeClosed - fun getStreaming( - id: String, - params: InteractionGetParams = InteractionGetParams.none(), - ): HttpResponseFor> = - getStreaming(id, params, RequestOptions.none()) - - /** @see getStreaming */ - @MustBeClosed - fun getStreaming( - params: InteractionGetParams, - requestOptions: RequestOptions = RequestOptions.none(), - ): HttpResponseFor> - - /** @see getStreaming */ - @MustBeClosed - fun getStreaming( - params: InteractionGetParams - ): HttpResponseFor> = - getStreaming(params, RequestOptions.none()) - - /** @see getStreaming */ - @MustBeClosed - fun getStreaming( - id: String, - requestOptions: RequestOptions, - ): HttpResponseFor> = - getStreaming(id, InteractionGetParams.none(), requestOptions) - } -} diff --git a/src/main/java/com/google/genai/interactions/services/blocking/InteractionServiceImpl.kt b/src/main/java/com/google/genai/interactions/services/blocking/InteractionServiceImpl.kt deleted file mode 100644 index 7a08c1cdfad..00000000000 --- a/src/main/java/com/google/genai/interactions/services/blocking/InteractionServiceImpl.kt +++ /dev/null @@ -1,366 +0,0 @@ -/* -* 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 -* -* http://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. -*/ - -// File generated from our OpenAPI spec by Stainless. - -package com.google.genai.interactions.services.blocking - -import com.google.genai.interactions.core.ClientOptions -import com.google.genai.interactions.core.JsonValue -import com.google.genai.interactions.core.RequestOptions -import com.google.genai.interactions.core.checkRequired -import com.google.genai.interactions.core.handlers.errorBodyHandler -import com.google.genai.interactions.core.handlers.errorHandler -import com.google.genai.interactions.core.handlers.jsonHandler -import com.google.genai.interactions.core.handlers.mapJson -import com.google.genai.interactions.core.handlers.sseHandler -import com.google.genai.interactions.core.http.HttpMethod -import com.google.genai.interactions.core.http.HttpRequest -import com.google.genai.interactions.core.http.HttpResponse -import com.google.genai.interactions.core.http.HttpResponse.Handler -import com.google.genai.interactions.core.http.HttpResponseFor -import com.google.genai.interactions.core.http.StreamResponse -import com.google.genai.interactions.core.http.json -import com.google.genai.interactions.core.http.map -import com.google.genai.interactions.core.http.parseable -import com.google.genai.interactions.core.prepare -import com.google.genai.interactions.models.interactions.CreateAgentInteractionParams -import com.google.genai.interactions.models.interactions.CreateModelInteractionParams -import com.google.genai.interactions.models.interactions.Interaction -import com.google.genai.interactions.models.interactions.InteractionCancelParams -import com.google.genai.interactions.models.interactions.InteractionCreateParams -import com.google.genai.interactions.models.interactions.InteractionDeleteParams -import com.google.genai.interactions.models.interactions.InteractionDeleteResponse -import com.google.genai.interactions.models.interactions.InteractionGetParams -import com.google.genai.interactions.models.interactions.InteractionSseEvent -import java.util.function.Consumer -import kotlin.jvm.optionals.getOrNull - -class InteractionServiceImpl constructor(private val clientOptions: ClientOptions) : - InteractionService { - - private val withRawResponse: InteractionService.WithRawResponse by lazy { - WithRawResponseImpl(clientOptions) - } - - override fun withRawResponse(): InteractionService.WithRawResponse = withRawResponse - - override fun withOptions(modifier: Consumer): InteractionService = - InteractionServiceImpl(clientOptions.toBuilder().apply(modifier::accept).build()) - - override fun create( - params: InteractionCreateParams, - requestOptions: RequestOptions, - ): Interaction = - // post /{api_version}/interactions - withRawResponse().create(params, requestOptions).parse() - - override fun createStreaming( - params: InteractionCreateParams, - requestOptions: RequestOptions, - ): StreamResponse = - // post /{api_version}/interactions - withRawResponse().createStreaming(params, requestOptions).parse() - - override fun delete( - params: InteractionDeleteParams, - requestOptions: RequestOptions, - ): InteractionDeleteResponse = - // delete /{api_version}/interactions/{id} - withRawResponse().delete(params, requestOptions).parse() - - override fun cancel( - params: InteractionCancelParams, - requestOptions: RequestOptions, - ): Interaction = - // post /{api_version}/interactions/{id}/cancel - withRawResponse().cancel(params, requestOptions).parse() - - override fun get(params: InteractionGetParams, requestOptions: RequestOptions): Interaction = - // get /{api_version}/interactions/{id} - withRawResponse().get(params, requestOptions).parse() - - override fun getStreaming( - params: InteractionGetParams, - requestOptions: RequestOptions, - ): StreamResponse = - // get /{api_version}/interactions/{id} - withRawResponse().getStreaming(params, requestOptions).parse() - - class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : - InteractionService.WithRawResponse { - - private val errorHandler: Handler = - errorHandler(errorBodyHandler(clientOptions.jsonMapper)) - - override fun withOptions( - modifier: Consumer - ): InteractionService.WithRawResponse = - InteractionServiceImpl.WithRawResponseImpl( - clientOptions.toBuilder().apply(modifier::accept).build() - ) - - private val createHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - - override fun create( - params: InteractionCreateParams, - requestOptions: RequestOptions, - ): HttpResponseFor { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .baseUrl(clientOptions.baseUrl()) - .addPathSegments( - params._pathParam(0).ifBlank { clientOptions.apiVersion }, - "interactions", - ) - .body(json(clientOptions.jsonMapper, params._body())) - .build() - .prepare(clientOptions, params) - val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) - val response = clientOptions.httpClient.execute(request, requestOptions) - return errorHandler.handle(response).parseable { - response - .use { createHandler.handle(it) } - .also { - if (requestOptions.responseValidation!!) { - it.validate() - } - } - } - } - - private val createStreamingHandler: Handler> = - sseHandler(clientOptions.jsonMapper).mapJson() - - override fun createStreaming( - params: InteractionCreateParams, - requestOptions: RequestOptions, - ): HttpResponseFor> { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .baseUrl(clientOptions.baseUrl()) - .addPathSegments( - params._pathParam(0).ifBlank { clientOptions.apiVersion }, - "interactions", - ) - .putHeader("Accept", "text/event-stream") - .body( - json( - clientOptions.jsonMapper, - params - ._body() - .accept( - object : - InteractionCreateParams.Body.Visitor< - InteractionCreateParams.Body - > { - override fun visitCreateModelInteractionParams( - createModelInteractionParams: - CreateModelInteractionParams - ) = - InteractionCreateParams.Body - .ofCreateModelInteractionParams( - createModelInteractionParams - .toBuilder() - .putAdditionalProperty( - "stream", - JsonValue.from(true), - ) - .build() - ) - - override fun visitCreateAgentInteractionParams( - createAgentInteractionParams: - CreateAgentInteractionParams - ) = - InteractionCreateParams.Body - .ofCreateAgentInteractionParams( - createAgentInteractionParams - .toBuilder() - .putAdditionalProperty( - "stream", - JsonValue.from(true), - ) - .build() - ) - } - ), - ) - ) - .build() - .prepare(clientOptions, params) - val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) - val response = clientOptions.httpClient.execute(request, requestOptions) - return errorHandler.handle(response).parseable { - response - .let { createStreamingHandler.handle(it) } - .let { streamResponse -> - if (requestOptions.responseValidation!!) { - streamResponse.map { it.validate() } - } else { - streamResponse - } - } - } - } - - private val deleteHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - - override fun delete( - params: InteractionDeleteParams, - requestOptions: RequestOptions, - ): HttpResponseFor { - // We check here instead of in the params builder because this can be specified - // positionally or in the params class. - checkRequired("id", params.id().getOrNull()) - val request = - HttpRequest.builder() - .method(HttpMethod.DELETE) - .baseUrl(clientOptions.baseUrl()) - .addPathSegments( - params._pathParam(0).ifBlank { clientOptions.apiVersion }, - "interactions", - params._pathParam(1), - ) - .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } - .build() - .prepare(clientOptions, params) - val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) - val response = clientOptions.httpClient.execute(request, requestOptions) - return errorHandler.handle(response).parseable { - response - .use { deleteHandler.handle(it) } - .also { - if (requestOptions.responseValidation!!) { - it.validate() - } - } - } - } - - private val cancelHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - - override fun cancel( - params: InteractionCancelParams, - requestOptions: RequestOptions, - ): HttpResponseFor { - // We check here instead of in the params builder because this can be specified - // positionally or in the params class. - checkRequired("id", params.id().getOrNull()) - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .baseUrl(clientOptions.baseUrl()) - .addPathSegments( - params._pathParam(0).ifBlank { clientOptions.apiVersion }, - "interactions", - params._pathParam(1), - "cancel", - ) - .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } - .build() - .prepare(clientOptions, params) - val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) - val response = clientOptions.httpClient.execute(request, requestOptions) - return errorHandler.handle(response).parseable { - response - .use { cancelHandler.handle(it) } - .also { - if (requestOptions.responseValidation!!) { - it.validate() - } - } - } - } - - private val getHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - - override fun get( - params: InteractionGetParams, - requestOptions: RequestOptions, - ): HttpResponseFor { - // We check here instead of in the params builder because this can be specified - // positionally or in the params class. - checkRequired("id", params.id().getOrNull()) - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .baseUrl(clientOptions.baseUrl()) - .addPathSegments( - params._pathParam(0).ifBlank { clientOptions.apiVersion }, - "interactions", - params._pathParam(1), - ) - .build() - .prepare(clientOptions, params) - val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) - val response = clientOptions.httpClient.execute(request, requestOptions) - return errorHandler.handle(response).parseable { - response - .use { getHandler.handle(it) } - .also { - if (requestOptions.responseValidation!!) { - it.validate() - } - } - } - } - - private val getStreamingHandler: Handler> = - sseHandler(clientOptions.jsonMapper).mapJson() - - override fun getStreaming( - params: InteractionGetParams, - requestOptions: RequestOptions, - ): HttpResponseFor> { - // We check here instead of in the params builder because this can be specified - // positionally or in the params class. - checkRequired("id", params.id().getOrNull()) - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .baseUrl(clientOptions.baseUrl()) - .addPathSegments( - params._pathParam(0).ifBlank { clientOptions.apiVersion }, - "interactions", - params._pathParam(1), - ) - .putQueryParam("stream", "true") - .putHeader("Accept", "text/event-stream") - .build() - .prepare(clientOptions, params) - val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) - val response = clientOptions.httpClient.execute(request, requestOptions) - return errorHandler.handle(response).parseable { - response - .let { getStreamingHandler.handle(it) } - .let { streamResponse -> - if (requestOptions.responseValidation!!) { - streamResponse.map { it.validate() } - } else { - streamResponse - } - } - } - } - } -} diff --git a/src/test/java/com/google/genai/GoogleCredentialsHttpClientTest.java b/src/test/java/com/google/genai/GoogleCredentialsHttpClientTest.java deleted file mode 100644 index 8240296b2ef..00000000000 --- a/src/test/java/com/google/genai/GoogleCredentialsHttpClientTest.java +++ /dev/null @@ -1,223 +0,0 @@ -/* - * Copyright 2026 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; - -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import com.google.auth.oauth2.AccessToken; -import com.google.auth.oauth2.GoogleCredentials; -import com.google.genai.errors.GenAiIOException; -import com.google.genai.interactions.core.RequestOptions; -import com.google.genai.interactions.core.http.HttpClient; -import com.google.genai.interactions.core.http.HttpMethod; -import com.google.genai.interactions.core.http.HttpRequest; -import com.google.genai.interactions.core.http.HttpResponse; -import java.io.IOException; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.ArgumentCaptor; - -public class GoogleCredentialsHttpClientTest { - - private static final String ACCESS_TOKEN = "test-access-token"; - private static final String QUOTA_PROJECT = "test-quota-project"; - - private HttpClient mockDelegate; - private GoogleCredentials mockCredentials; - private HttpResponse mockResponse; - - @BeforeEach - void setUp() { - mockDelegate = mock(HttpClient.class); - mockCredentials = mock(GoogleCredentials.class); - mockResponse = mock(HttpResponse.class); - - AccessToken accessToken = AccessToken.newBuilder().setTokenValue(ACCESS_TOKEN).build(); - when(mockCredentials.getAccessToken()).thenReturn(accessToken); - } - - private HttpRequest createRequest() { - return HttpRequest.builder() - .method(HttpMethod.POST) - .baseUrl("https://example.com") - .build(); - } - - private HttpRequest createRequestWithHeader(String name, String value) { - return HttpRequest.builder() - .method(HttpMethod.POST) - .baseUrl("https://example.com") - .putHeader(name, value) - .build(); - } - - @Test - void execute_addsAuthorizationHeader() throws IOException { - GoogleCredentialsHttpClient client = new GoogleCredentialsHttpClient(mockDelegate, mockCredentials); - when(mockDelegate.execute(any(HttpRequest.class), any(RequestOptions.class))).thenReturn(mockResponse); - - client.execute(createRequest(), RequestOptions.none()); - - ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(HttpRequest.class); - verify(mockDelegate).execute(requestCaptor.capture(), any(RequestOptions.class)); - verify(mockCredentials).refreshIfExpired(); - HttpRequest capturedRequest = requestCaptor.getValue(); - assertEquals("Bearer " + ACCESS_TOKEN, capturedRequest.headers().values("Authorization").get(0)); - } - - @Test - void execute_withoutRequestOptions_addsAuthorizationHeader() throws IOException { - GoogleCredentialsHttpClient client = new GoogleCredentialsHttpClient(mockDelegate, mockCredentials); - when(mockDelegate.execute(any(HttpRequest.class))).thenReturn(mockResponse); - - client.execute(createRequest()); - - ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(HttpRequest.class); - verify(mockDelegate).execute(requestCaptor.capture()); - verify(mockCredentials).refreshIfExpired(); - HttpRequest capturedRequest = requestCaptor.getValue(); - assertEquals("Bearer " + ACCESS_TOKEN, capturedRequest.headers().values("Authorization").get(0)); - } - - @Test - void execute_withExistingAuthorizationHeader_doesNotModify() throws IOException { - GoogleCredentialsHttpClient client = new GoogleCredentialsHttpClient(mockDelegate, mockCredentials); - when(mockDelegate.execute(any(HttpRequest.class), any(RequestOptions.class))).thenReturn(mockResponse); - - HttpRequest requestWithAuth = createRequestWithHeader("Authorization", "Bearer existing-token"); - client.execute(requestWithAuth, RequestOptions.none()); - - ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(HttpRequest.class); - verify(mockDelegate).execute(requestCaptor.capture(), any(RequestOptions.class)); - HttpRequest capturedRequest = requestCaptor.getValue(); - assertEquals("Bearer existing-token", capturedRequest.headers().values("Authorization").get(0)); - } - - @Test - void execute_withExistingApiKeyHeader_doesNotModify() throws IOException { - GoogleCredentialsHttpClient client = new GoogleCredentialsHttpClient(mockDelegate, mockCredentials); - when(mockDelegate.execute(any(HttpRequest.class), any(RequestOptions.class))).thenReturn(mockResponse); - - HttpRequest requestWithApiKey = createRequestWithHeader("x-goog-api-key", "test-api-key"); - client.execute(requestWithApiKey, RequestOptions.none()); - - ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(HttpRequest.class); - verify(mockDelegate).execute(requestCaptor.capture(), any(RequestOptions.class)); - HttpRequest capturedRequest = requestCaptor.getValue(); - assertEquals("test-api-key", capturedRequest.headers().values("x-goog-api-key").get(0)); - assertTrue(capturedRequest.headers().values("Authorization").isEmpty()); - } - - @Test - void execute_withQuotaProject_addsUserProjectHeader() throws IOException { - GoogleCredentialsHttpClient client = new GoogleCredentialsHttpClient(mockDelegate, mockCredentials); - when(mockDelegate.execute(any(HttpRequest.class), any(RequestOptions.class))).thenReturn(mockResponse); - when(mockCredentials.getQuotaProjectId()).thenReturn(QUOTA_PROJECT); - - client.execute(createRequest(), RequestOptions.none()); - - ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(HttpRequest.class); - verify(mockDelegate).execute(requestCaptor.capture(), any(RequestOptions.class)); - HttpRequest capturedRequest = requestCaptor.getValue(); - assertEquals("Bearer " + ACCESS_TOKEN, capturedRequest.headers().values("Authorization").get(0)); - assertEquals(QUOTA_PROJECT, capturedRequest.headers().values("x-goog-user-project").get(0)); - } - - @Test - void execute_withExistingUserProjectHeader_doesNotOverride() throws IOException { - GoogleCredentialsHttpClient client = new GoogleCredentialsHttpClient(mockDelegate, mockCredentials); - when(mockDelegate.execute(any(HttpRequest.class), any(RequestOptions.class))).thenReturn(mockResponse); - when(mockCredentials.getQuotaProjectId()).thenReturn(QUOTA_PROJECT); - - HttpRequest requestWithProject = createRequestWithHeader("x-goog-user-project", "existing-project"); - client.execute(requestWithProject, RequestOptions.none()); - - ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(HttpRequest.class); - verify(mockDelegate).execute(requestCaptor.capture(), any(RequestOptions.class)); - HttpRequest capturedRequest = requestCaptor.getValue(); - assertEquals("existing-project", capturedRequest.headers().values("x-goog-user-project").get(0)); - } - - @Test - void execute_whenRefreshFails_throwsGenAiIOException() throws IOException { - GoogleCredentialsHttpClient client = new GoogleCredentialsHttpClient(mockDelegate, mockCredentials); - doThrow(new IOException("Refresh failed")).when(mockCredentials).refreshIfExpired(); - - GenAiIOException exception = assertThrows(GenAiIOException.class, - () -> client.execute(createRequest(), RequestOptions.none())); - - assertEquals("Failed to refresh credentials.", exception.getMessage()); - assertInstanceOf(IOException.class, exception.getCause()); - } - - @Test - void executeAsync_addsAuthorizationHeader() throws Exception { - GoogleCredentialsHttpClient client = new GoogleCredentialsHttpClient(mockDelegate, mockCredentials); - when(mockDelegate.executeAsync(any(HttpRequest.class), any(RequestOptions.class))) - .thenReturn(CompletableFuture.completedFuture(mockResponse)); - - client.executeAsync(createRequest(), RequestOptions.none()).get(); - - ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(HttpRequest.class); - verify(mockDelegate).executeAsync(requestCaptor.capture(), any(RequestOptions.class)); - HttpRequest capturedRequest = requestCaptor.getValue(); - assertEquals("Bearer " + ACCESS_TOKEN, capturedRequest.headers().values("Authorization").get(0)); - } - - @Test - void executeAsync_withoutRequestOptions_addsAuthorizationHeader() throws Exception { - GoogleCredentialsHttpClient client = new GoogleCredentialsHttpClient(mockDelegate, mockCredentials); - when(mockDelegate.executeAsync(any(HttpRequest.class))) - .thenReturn(CompletableFuture.completedFuture(mockResponse)); - - client.executeAsync(createRequest()).get(); - - ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(HttpRequest.class); - verify(mockDelegate).executeAsync(requestCaptor.capture()); - HttpRequest capturedRequest = requestCaptor.getValue(); - assertEquals("Bearer " + ACCESS_TOKEN, capturedRequest.headers().values("Authorization").get(0)); - } - - @Test - void executeAsync_whenRefreshFails_completesExceptionally() throws IOException { - GoogleCredentialsHttpClient client = new GoogleCredentialsHttpClient(mockDelegate, mockCredentials); - doThrow(new IOException("Refresh failed")).when(mockCredentials).refreshIfExpired(); - - CompletableFuture future = client.executeAsync(createRequest(), RequestOptions.none()); - - ExecutionException exception = assertThrows(ExecutionException.class, future::get); - assertInstanceOf(GenAiIOException.class, exception.getCause()); - assertEquals("Failed to refresh credentials.", exception.getCause().getMessage()); - } - - @Test - void close_delegatesToWrappedClient() { - GoogleCredentialsHttpClient client = new GoogleCredentialsHttpClient(mockDelegate, mockCredentials); - - client.close(); - - verify(mockDelegate).close(); - } -} - diff --git a/src/test/java/com/google/genai/HttpApiClientTest.java b/src/test/java/com/google/genai/HttpApiClientTest.java index baa45871b5c..8ca839655e0 100644 --- a/src/test/java/com/google/genai/HttpApiClientTest.java +++ b/src/test/java/com/google/genai/HttpApiClientTest.java @@ -44,7 +44,6 @@ import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Dispatcher; @@ -1733,8 +1732,5 @@ public void testCloseClient() { assertTrue(client.httpClient().dispatcher().executorService().isShutdown()); assertEquals(0, client.httpClient().connectionPool().connectionCount()); - if (client.interactionsClientOptions.streamHandlerExecutor() instanceof ExecutorService) { - assertTrue(((ExecutorService) client.interactionsClientOptions.streamHandlerExecutor()).isShutdown()); - } } } diff --git a/src/test/java/com/google/genai/PrepareRequestTest.kt b/src/test/java/com/google/genai/PrepareRequestTest.kt deleted file mode 100644 index 65501c8b6f8..00000000000 --- a/src/test/java/com/google/genai/PrepareRequestTest.kt +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright 2026 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 - -import com.google.genai.interactions.core.ClientOptions -import com.google.genai.interactions.core.Params -import com.google.genai.interactions.core.VertexInfo -import com.google.genai.interactions.core.http.Headers -import com.google.genai.interactions.core.http.HttpClient -import com.google.genai.interactions.core.http.HttpMethod -import com.google.genai.interactions.core.http.HttpRequest -import com.google.genai.interactions.core.http.QueryParams -import com.google.genai.interactions.core.prepare -import org.junit.jupiter.api.Assertions.assertEquals -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test -import org.mockito.Mockito.mock - -class PrepareRequestTest { - - private lateinit var mockHttpClient: HttpClient - - @BeforeEach - fun setUp() { - mockHttpClient = mock(HttpClient::class.java) - } - - private fun createClientOptions(vertexInfo: VertexInfo? = null): ClientOptions = - ClientOptions.builder() - .httpClient(mockHttpClient) - .vertexInfo(vertexInfo) - .build() - - private fun createRequest(pathSegments: List): HttpRequest = - HttpRequest.builder() - .method(HttpMethod.POST) - .baseUrl("https://example.com") - .pathSegments(pathSegments) - .build() - - private fun createEmptyParams(): Params = object : Params { - override fun _headers(): Headers = Headers.builder().build() - override fun _queryParams(): QueryParams = QueryParams.builder().build() - } - - @Test - fun `prepare transforms path segments when vertexInfo is present`() { - val vertexInfo = VertexInfo("my-project", "us-central1") - val clientOptions = createClientOptions(vertexInfo) - val request = createRequest(listOf("v1beta", "interactions")) - - val preparedRequest = request.prepare(clientOptions, createEmptyParams()) - - assertEquals( - listOf("v1beta", "projects", "my-project", "locations", "us-central1", "interactions"), - preparedRequest.pathSegments - ) - } - - @Test - fun `prepare does not transform path segments when vertexInfo is null`() { - val clientOptions = createClientOptions(vertexInfo = null) - val request = createRequest(listOf("v1beta", "interactions")) - - val preparedRequest = request.prepare(clientOptions, createEmptyParams()) - - assertEquals( - listOf("v1beta", "interactions"), - preparedRequest.pathSegments - ) - } -} -