diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml new file mode 100644 index 00000000000..5fdcb436f99 --- /dev/null +++ b/.github/workflows/stale.yml @@ -0,0 +1,33 @@ +# This workflow warns and then closes issues that have had no activity for a specified amount of time. +name: Mark and close stale issues + +on: + schedule: + # Scheduled to run at 1:30 UTC everyday + - cron: '30 1 * * *' + +jobs: + stale: + + runs-on: ubuntu-latest + permissions: + issues: write + + steps: + - uses: actions/stale@v5 + with: + repo-token: ${{ secrets.GITHUB_TOKEN }} + days-before-issue-stale: 7 + days-before-issue-close: 2 + stale-issue-label: "status:stale" + close-issue-reason: not_planned + any-of-labels: "status:awaiting user response" + remove-stale-when-updated: true + labels-to-remove-when-unstale: 'status:awaiting user response,status:stale' + stale-issue-message: > + This issue has been marked as stale because it has been open for 7 days with no activity. It will be closed in 2 days if no further activity occurs. + close-issue-message: > + This issue was closed because it has been inactive for 9 days. + Please post a new issue if you need further assistance. Thanks! + # Label that can be assigned to issues to exclude them from being marked as stale + exempt-issue-labels: 'override-stale' diff --git a/.github/workflows/unit-tests.yml b/.github/workflows/unit-tests.yml index 72e3eec72d4..d2fd993b39c 100644 --- a/.github/workflows/unit-tests.yml +++ b/.github/workflows/unit-tests.yml @@ -14,7 +14,8 @@ jobs: strategy: matrix: java: [8, 11, 17, 21] - testgroup: ['**/*'] + # Only run unit tests. + testgroup: ["**/*Test"] fail-fast: false name: unit-test (${{matrix.java}}) steps: @@ -25,4 +26,4 @@ jobs: java-version: ${{matrix.java}} cache: 'maven' - name: Java Unit Tests - run: mvn clean test -Dtest=${{matrix.testgroup}} \ No newline at end of file + run: mvn clean test -Dtest=${{matrix.testgroup}} -Djacoco.skip=true \ No newline at end of file diff --git a/.release-please-manifest.json b/.release-please-manifest.json index eb4e0dba726..0c0c0c35760 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.10.0" + ".": "1.25.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index a770a7362d1..1a5d8a27fcb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,213 @@ # Changelog +## [1.25.0](https://github.com/googleapis/java-genai/compare/v1.24.0...v1.25.0) (2025-10-29) + + +### Features + +* Add safety_filter_level and person_generation for Imagen upscaling ([09a8075](https://github.com/googleapis/java-genai/commit/09a80754b202fdf903039341f5266f62d9b879cb)) +* Add support for preference optimization tuning in the SDK. ([5d4123c](https://github.com/googleapis/java-genai/commit/5d4123c0391d443e94bb1e81524ccae8779462d7)) +* Added Operations.get which is a generic method which will handle all Operation types. ([c1dc32f](https://github.com/googleapis/java-genai/commit/c1dc32f84d0e4d14a16345dcb404c8b2bef05338)) +* Pass file name to the backend when uploading with a file path ([081a9a6](https://github.com/googleapis/java-genai/commit/081a9a6a67d1ba542edb1d1330dfa56579204a43)) +* support default global location when not using api key with vertexai backend ([f9028a7](https://github.com/googleapis/java-genai/commit/f9028a71d4e736a8dc97daa54e6e4275b5016abd)) +* Support retries in API requests ([3d5de00](https://github.com/googleapis/java-genai/commit/3d5de000277eb0da172d6b19795c6f2d4b88c213)) + + +### Documentation + +* Add docstring for classes and fields that are not supported in Gemini or Vertex API ([7a03dac](https://github.com/googleapis/java-genai/commit/7a03dac0a4e3388f98be199765794fcf511bfe83)) +* Add docstring for enum classes that are not supported in Gemini or Vertex API ([830a12f](https://github.com/googleapis/java-genai/commit/830a12f3dcbb8beb1dd5ff3ff82f6b19ebb2af93)) +* Add documentation for the retry behavior ([4fbcf51](https://github.com/googleapis/java-genai/commit/4fbcf514321fdc2cbee1393fc6babe33fd0e5e74)) + +## [1.24.0](https://github.com/googleapis/java-genai/compare/v1.23.0...v1.24.0) (2025-10-22) + + +### Features + +* Add enable_enhanced_civic_answers in GenerationConfig ([684a2c5](https://github.com/googleapis/java-genai/commit/684a2c5b582fa4ca13cb9cfe819ef759778101b0)) +* support createEmbeddings in Batches.java ([8947f6f](https://github.com/googleapis/java-genai/commit/8947f6fc20fbdd90a7d17071dee1bd2e5bea0c3e)) +* support jailbreak in HarmCategory and BlockedReason ([3dab40b](https://github.com/googleapis/java-genai/commit/3dab40bc367168ed48d8d1acfb278f5bc6edb83f)) + + +### Bug Fixes + +* Make async methods in Batches module truly non-blocking ([f2ae75a](https://github.com/googleapis/java-genai/commit/f2ae75ac364702f483c376e458a120d1ffa93b17)) +* Make async methods in Caches, Tuning, and Operations modules truly non-blocking ([db56239](https://github.com/googleapis/java-genai/commit/db56239bbebbfe3cb95e00d2d3eac253b76f22fe)) +* Make async methods in Models module truly non-blocking ([c205d01](https://github.com/googleapis/java-genai/commit/c205d0172ca40e01f7d8de17a3bc9d38eeb5fc21)) + +## [1.23.0](https://github.com/googleapis/java-genai/compare/v1.22.0...v1.23.0) (2025-10-15) + + +### Features + +* Support video extension for Veo on Gemini Developer API ([b398509](https://github.com/googleapis/java-genai/commit/b398509697a3e9aa27bad5e804382c5a4db333ab)) + +## [1.22.0](https://github.com/googleapis/java-genai/compare/v1.21.0...v1.22.0) (2025-10-10) + + +### Features + +* Enable Google Maps tool for Genai. ([a4baf3c](https://github.com/googleapis/java-genai/commit/a4baf3c610ddcb1ed36c1501fcb2248b5a6bd610)) +* Support enableWidget feature in GoogleMaps ([aefbd5c](https://github.com/googleapis/java-genai/commit/aefbd5c1519f453cd2fe158a2765c195a9454322)) +* Support Gemini batch inline request's metadata and add test coverage to safety setting ([17033b3](https://github.com/googleapis/java-genai/commit/17033b38a93d6952b29699f5a4c79ed9dd862976)) + +## [1.21.0](https://github.com/googleapis/java-genai/compare/v1.20.0...v1.21.0) (2025-10-08) + + +### Features + +* Add `NO_IMAGE` enum value to `FinishReason` ([6b00c0b](https://github.com/googleapis/java-genai/commit/6b00c0b7dc8c85fcefc5aac643c3588048317614)) +* Add labels field to Imagen configs ([e69cf68](https://github.com/googleapis/java-genai/commit/e69cf68583ca581f1a7fad89b04292036433cdb4)) +* Add thinking_config for live ([274c21d](https://github.com/googleapis/java-genai/commit/274c21d34310e630b9b4ad296b4c8314a4249d0c)) +* Add utility methods for creating `FunctionResponsePart` and creating FunctionResponse `Part` with `FunctionResponseParts` ([af16a4c](https://github.com/googleapis/java-genai/commit/af16a4c994e0cc4e6fbc2cdbda825246df9aa253)) +* Enable Ingredients to Video and Advanced Controls for Veo on Gemini Developer API (Early Access Program) ([4c42e65](https://github.com/googleapis/java-genai/commit/4c42e6527a7fe43c0b534e381d65b5d9650e8709)) + + +### Bug Fixes + +* Ensure Live server message are properly converted ([206dc88](https://github.com/googleapis/java-genai/commit/206dc88e3b220a875f784a507fc9470bc411de36)) + +## [1.20.0](https://github.com/googleapis/java-genai/compare/v1.19.0...v1.20.0) (2025-10-01) + + +### Features + +* Add `ImageConfig` to `GenerateContentConfig` ([6fb5eba](https://github.com/googleapis/java-genai/commit/6fb5eba0e916ada8f300dd5ad333f269e9044ea3)) + +## [1.19.0](https://github.com/googleapis/java-genai/compare/v1.18.0...v1.19.0) (2025-09-30) + + +### Features + +* expose session id in Live API ([b6d5389](https://github.com/googleapis/java-genai/commit/b6d5389899bd1443d5c508776dfe5909eb1d7400)) +* rename ComputerUse tool (early access) ([4bbba2b](https://github.com/googleapis/java-genai/commit/4bbba2b53eedec0b28a5d98d7fc193683c565f50)) + +## [1.18.0](https://github.com/googleapis/java-genai/compare/v1.17.0...v1.18.0) (2025-09-25) + + +### Features + +* Add FunctionResponsePart & ToolComputerUse.excludedPredefinedFunctions ([1a24bed](https://github.com/googleapis/java-genai/commit/1a24bedc752851236b0a7239a7dba7090e4ac4e8)) +* Support Imagen 4 Ingredients on Vertex ([b5eed8d](https://github.com/googleapis/java-genai/commit/b5eed8d1323a3d37b53c1d8c5c5557392ce7ed44)) + + +### Bug Fixes + +* Expose `JOB_STATE_RUNNING` and `JOB_STATE_EXPIRED` for Gemini Batches states ([c5b4fdf](https://github.com/googleapis/java-genai/commit/c5b4fdf58b9d0d74efdd2c7e740bed8b6b661c99)) +* initialization of `pre_tuned_model_checkpoint_id` from tuning config. ([c293633](https://github.com/googleapis/java-genai/commit/c293633a8fe298668f030ba3b257347a8fd0eedf)) +* Make async generateContent and generateContentStream truly non-blocking ([5cb18fd](https://github.com/googleapis/java-genai/commit/5cb18fd4f07f9b1f21efb82fe961e473325f6257)) +* only run unit tests in github action ([9b2861b](https://github.com/googleapis/java-genai/commit/9b2861bb79d50c10c152aa010bedf0bc48a04ad8)) + +## [1.17.0](https://github.com/googleapis/java-genai/compare/v1.16.0...v1.17.0) (2025-09-16) + + +### Features + +* Add 'turn_complete_reason' and 'waiting_for_input' fields. ([5bc4873](https://github.com/googleapis/java-genai/commit/5bc48732fd9281162942b158de34173343d7b179)) +* Add `VideoGenerationMaskMode` enum for Veo 2 Editing ([e5c8277](https://github.com/googleapis/java-genai/commit/e5c82778586dfee4ed7d04a9eabb2a4d8eac6185)) +* Add labels to create tuning job config ([695e17a](https://github.com/googleapis/java-genai/commit/695e17a7b1adebbccb1651d30b768d27f81c3977)) +* generate the function_call class's converters ([38703c7](https://github.com/googleapis/java-genai/commit/38703c726606cbe1b6f5f5f4eb809310b0df94a8)) +* java local tokenizer ([d774185](https://github.com/googleapis/java-genai/commit/d7741856cafd3b8e05803f7b452335fbc4ce8977)) +* Support Veo 2 Editing on Vertex ([d401d3c](https://github.com/googleapis/java-genai/commit/d401d3cf6a5f9ef3d2a76a548eed9d218169170e)) + + +### Bug Fixes + +* Enable `id` field in `FunctionCall` for Vertex AI. ([3773fe7](https://github.com/googleapis/java-genai/commit/3773fe75007b9ce83692de0031853f0f607bff3e)) +* update Live API audio example with better interruption handling ([cad8df9](https://github.com/googleapis/java-genai/commit/cad8df9c4edaf0806a641869fef6379ed05f0189)) + +## [1.16.0](https://github.com/googleapis/java-genai/compare/v1.15.0...v1.16.0) (2025-09-02) + + +### Features + +* Add resolution field for Gemini Developer API Veo 3 generation ([eec410c](https://github.com/googleapis/java-genai/commit/eec410c5b68de471e9a824e61f0efb819841dfe6)) +* add the response body for generateContent ([a011580](https://github.com/googleapis/java-genai/commit/a0115804e438bac120d5155c91ece53c79ada677)) + + +### Documentation + +* Refactor/update docstrings for Imagen and Veo ([2470101](https://github.com/googleapis/java-genai/commit/24701018feb91d147bf1817b04752e2595bf40ab)) + +## [1.15.0](https://github.com/googleapis/java-genai/compare/v1.14.0...v1.15.0) (2025-08-27) + + +### Features + +* add `sdkHttpResponse.headers` to *Delete responses. ([4be038d](https://github.com/googleapis/java-genai/commit/4be038de86c782d103d21258db51055f35e5af21)) +* Add output_gcs_uri to Imagen upscale_image ([7649467](https://github.com/googleapis/java-genai/commit/76494678d3937229778c5063b4f4ff340f977bba)) +* add the response body for generateContent ([6e28ab4](https://github.com/googleapis/java-genai/commit/6e28ab4236565be61fb11e79ca9f2f31a2013598)) +* add the response body for generateContent ([b2a5b3f](https://github.com/googleapis/java-genai/commit/b2a5b3f5a6ef7a8bb4d011980d90ffdc3c745603)) +* Add VALIDATED mode into FunctionCallingConfigMode ([4bb8680](https://github.com/googleapis/java-genai/commit/4bb868046199d3249f75ede213ef7d77e0b7783f)) +* Add VideoGenerationReferenceType enum for generate_videos ([df9d910](https://github.com/googleapis/java-genai/commit/df9d910537ec7de6188f777801b4d50e84cd91e7)) +* Support GenerateVideosSource for Veo GenerateVideos ([c26af63](https://github.com/googleapis/java-genai/commit/c26af6396002cf21c0ed272290d44b09b6a41840)) +* support tunings.cancel in the genai SDK for Python, Java, JS, and Go ([9982251](https://github.com/googleapis/java-genai/commit/9982251d2dd80d3151aefb4462d9e4864d8e064e)) + + +### Documentation + +* Refactor model IDs into a Constants class ([dacd787](https://github.com/googleapis/java-genai/commit/dacd7875d41f810e50f2655e5d0e62f031197e61)) + +## [1.14.0](https://github.com/googleapis/java-genai/compare/v1.13.0...v1.14.0) (2025-08-22) + + +### Features + +* Add add_watermark field for recontext_image (Virtual Try-On, Product Recontext) ([5aacbc0](https://github.com/googleapis/java-genai/commit/5aacbc06435fb36fffde0c3641b3077493f13577)) + + +### Bug Fixes + +* Fix the bug that files.create doesn't return the upload URL correctly ([eb40c5f](https://github.com/googleapis/java-genai/commit/eb40c5f7f255b46a7a820da044e210127c7aac18)) + + +### Documentation + +* update TokensInfo docstring ([48eba7f](https://github.com/googleapis/java-genai/commit/48eba7fcb369537ca4266ec61107e016f7c242ed)) + +## [1.13.0](https://github.com/googleapis/java-genai/compare/v1.12.0...v1.13.0) (2025-08-18) + + +### Features + +* expose JsonSerializable.stringToJsonNode to help user better use *JsonSchema fields. ([35d783b](https://github.com/googleapis/java-genai/commit/35d783b5d1655b6f0d52afefa633c608f39d4e01)) +* Return response headers for all methods (except streaming methods) ([7e8b71b](https://github.com/googleapis/java-genai/commit/7e8b71b0769362a728e2bf9b93738563113a4edc)) +* Support Imagen image segmentation on Vertex ([e2a561b](https://github.com/googleapis/java-genai/commit/e2a561b11b53f3a7cc30aacb4a0dcf6a26e01645)) +* Support Veo 2 Reference Images to Video Generation on Vertex ([2f5580f](https://github.com/googleapis/java-genai/commit/2f5580fd1e78d6e8e4f371f291dacf98c7c617ef)) + +## [1.12.0](https://github.com/googleapis/java-genai/compare/v1.11.0...v1.12.0) (2025-08-13) + + +### Features + +* enable continuous fine-tuning on a pre-tuned model in the SDK. ([e49d350](https://github.com/googleapis/java-genai/commit/e49d3509355f717d391a88b6ff1a6f4f6d83fddc)) +* support document name in grounding metadata ([8273922](https://github.com/googleapis/java-genai/commit/8273922ebfbce4ffafa8993bcc6928b47b5ff821)) +* Support exclude_domains in Google Search and Enterprise Web Search ([e975d28](https://github.com/googleapis/java-genai/commit/e975d284f78e0c9a3cd2199d304b4739bad36fe1)) + +## [1.11.0](https://github.com/googleapis/java-genai/compare/v1.10.0...v1.11.0) (2025-08-06) + + +### Features + +* Add image_size field for Gemini Developer API Imagen 4 generation ([c50c755](https://github.com/googleapis/java-genai/commit/c50c755c08efbed5a62e1006890b1d0bd9956702)) +* enable responseId for Gemini Developer API ([4912ff4](https://github.com/googleapis/java-genai/commit/4912ff421d6d3bc40edd70a939f71f5f33f58597)) +* support extraBody in HttpOptions class ([036bac8](https://github.com/googleapis/java-genai/commit/036bac89fda15022ec4d9c5c73ba81ad0a6cc9be)) +* Support image recontext on Vertex ([e7de8c8](https://github.com/googleapis/java-genai/commit/e7de8c83bbd2e7e37c2198c3501e2d5bee58c0a2)) +* Support new enum types for UrlRetrievalStatus ([cb27222](https://github.com/googleapis/java-genai/commit/cb27222a7f7cdf442a7d6b61496709f7cf084a91)) +* support response headers in Go for all methods. ([222b41e](https://github.com/googleapis/java-genai/commit/222b41e196afc13775cc22292a58567d7b4859fa)) + + +### Bug Fixes + +* Remove duplicate JavaTimeModule in JsonSerializable ([a7dbd4c](https://github.com/googleapis/java-genai/commit/a7dbd4c527456f20aa5d154bde14f74f6e66d174)) + + +### Documentation + +* Add Imagen and Veo to README ([cc0a0aa](https://github.com/googleapis/java-genai/commit/cc0a0aa28cae618acf617ab92819df78d80afea5)) +* Add latest models features in README ([a2eccaf](https://github.com/googleapis/java-genai/commit/a2eccafae5c6c9b82341a148b572bf9bc80f241b)) +* mark Client as thread safe and Chat as not thread safe ([be3e50e](https://github.com/googleapis/java-genai/commit/be3e50e4217780329c0636fd7f8a1b743e7f9597)) + ## [1.10.0](https://github.com/googleapis/java-genai/compare/v1.9.0...v1.10.0) (2025-07-23) diff --git a/README.md b/README.md index dbaa7e1a39a..b69e93492d3 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ If you're using Maven, add the following to your dependencies: com.google.genai google-genai - 1.10.0 + 1.25.0 ``` @@ -161,6 +161,30 @@ per-request basis, providing maximum flexibility for diverse API call settings. See [this example](https://github.com/googleapis/java-genai/blob/main/examples/src/main/java/com/google/genai/examples/RequestLevelHttpOptions.java) for more details. +### HttpRetryOptions + +[HttpRetryOptions](https://github.com/googleapis/java-genai/blob/main/src/main/java/com/google/genai/types/HttpRetryOptions.java) +allows you to configure the automatic retry behavior for failed API calls. You +can customize key settings like: + + * Total number of attempts. + * Which HTTP status codes should trigger a retry (e.g., 429 for rate limits). + * Backoff strategy, including the initial delay and maximum delay between retries. + +```java +HttpOptions httpOptions = HttpOptions.builder() + .retryOptions( + HttpRetryOptions.builder() + .attempts(3) + .httpStatusCodes(408, 429)) + .build(); +``` + +Since HttpRetryOptions is part of HttpOptions, it supports being set at the +client level (as shown) or on a per-request basis. Note that Providing +`HttpRetryOptions` for a specific request will completely override any default +retry settings configured on the client. + ### ClientOptions [ClientOptions](https://github.com/googleapis/java-genai/blob/main/src/main/java/com/google/genai/types/ClientOptions.java) enables you to customize the behavior of the HTTP client. It currently supports @@ -178,11 +202,11 @@ Client client = Client.builder() ``` ### Interact with models -The Gen AI Java SDK allows you to access the service programmatically. +The Google Gen AI Java SDK allows you to access the service programmatically. The following code snippets are some basic usages of model inferencing. #### Generate Content -Use `generateContent` method for the most basic text generation. +Use `generateContent` method for the most basic content generation. ##### with text input @@ -199,10 +223,17 @@ public class GenerateContentWithTextInput { Client client = new Client(); GenerateContentResponse response = - client.models.generateContent("gemini-2.0-flash-001", "What is your name?", null); + client.models.generateContent("gemini-2.5-flash", "What is your name?", null); // Gets the text string from the response by the quick accessor method `text()`. System.out.println("Unary response: " + response.text()); + + // Gets the http headers from the response. + response + .sdkHttpResponse() + .ifPresent( + httpResponse -> + System.out.println("Response headers: " + httpResponse.headers().orElse(null))); } } ``` @@ -232,7 +263,68 @@ public class GenerateContentWithImageInput { Part.fromUri("gs://path/to/image.jpg", "image/jpeg")); GenerateContentResponse response = - client.models.generateContent("gemini-2.0-flash-001", content, null); + client.models.generateContent("gemini-2.5-flash", content, null); + + System.out.println("Response: " + response.text()); + } +} +``` + +##### Generate Content with extra configs +To set configurations like System Instructions and Safety Settings, you can pass +a `GenerateContentConfig` to the `GenerateContent` method. + +```java +package ; + +import com.google.common.collect.ImmutableList; +import com.google.genai.Client; +import com.google.genai.types.Content; +import com.google.genai.types.GenerateContentConfig; +import com.google.genai.types.GenerateContentResponse; +import com.google.genai.types.GoogleSearch; +import com.google.genai.types.HarmBlockThreshold; +import com.google.genai.types.HarmCategory; +import com.google.genai.types.Part; +import com.google.genai.types.SafetySetting; +import com.google.genai.types.ThinkingConfig; +import com.google.genai.types.Tool; + +public class GenerateContentWithConfigs { + public static void main(String[] args) { + Client client = new Client(); + + // Sets the safety settings in the config. + ImmutableList safetySettings = + ImmutableList.of( + SafetySetting.builder() + .category(HarmCategory.Known.HARM_CATEGORY_HATE_SPEECH) + .threshold(HarmBlockThreshold.Known.BLOCK_ONLY_HIGH) + .build(), + SafetySetting.builder() + .category(HarmCategory.Known.HARM_CATEGORY_DANGEROUS_CONTENT) + .threshold(HarmBlockThreshold.Known.BLOCK_LOW_AND_ABOVE) + .build()); + + // Sets the system instruction in the config. + Content systemInstruction = Content.fromParts(Part.fromText("You are a history teacher.")); + + // Sets the Google Search tool in the config. + Tool googleSearchTool = Tool.builder().googleSearch(GoogleSearch.builder()).build(); + + GenerateContentConfig config = + GenerateContentConfig.builder() + // Sets the thinking budget to 0 to disable thinking mode + .thinkingConfig(ThinkingConfig.builder().thinkingBudget(0)) + .candidateCount(1) + .maxOutputTokens(1024) + .safetySettings(safetySettings) + .systemInstruction(systemInstruction) + .tools(googleSearchTool) + .build(); + + GenerateContentResponse response = + client.models.generateContent("gemini-2.5-flash", "Tell me the history of LLM", config); System.out.println("Response: " + response.text()); } @@ -281,20 +373,20 @@ public class GenerateContentWithFunctionCall { public static void main(String[] args) throws NoSuchMethodException { Client client = new Client(); + // Load the method as a reflected Method object so that it can be + // automatically executed on the client side. Method method = GenerateContentWithFunctionCall.class.getMethod( "getCurrentWeather", String.class, String.class); GenerateContentConfig config = GenerateContentConfig.builder() - .tools( - ImmutableList.of( - Tool.builder().functions(ImmutableList.of(method)).build())) + .tools(Tool.builder().functions(method)) .build(); GenerateContentResponse response = client.models.generateContent( - "gemini-2.0-flash-001", + "gemini-2.5-flash", "What is the weather in Vancouver?", config); @@ -306,7 +398,7 @@ public class GenerateContentWithFunctionCall { } ``` -#### Stream Generated Content +##### Stream Generated Content To get a streamed response, you can use the `generateContentStream` method: ```java @@ -318,13 +410,11 @@ import com.google.genai.types.GenerateContentResponse; public class StreamGeneration { public static void main(String[] args) { - // 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().vertexAI(true).build(); + Client client = new Client(); ResponseStream responseStream = client.models.generateContentStream( - "gemini-2.0-flash-001", "Tell me a story in 300 words.", null); + "gemini-2.5-flash", "Tell me a story in 300 words.", null); System.out.println("Streaming response: "); for (GenerateContentResponse res : responseStream) { @@ -338,7 +428,7 @@ public class StreamGeneration { } ``` -#### Async Generate Content +##### Async Generate Content To get a response asynchronously, you can use the `generateContent` method from the `client.async.models` namespace. @@ -351,12 +441,11 @@ import java.util.concurrent.CompletableFuture; public class GenerateContentAsync { public static void main(String[] args) { - // Instantiates the client using Gemini API, and sets the API key in the builder. - Client client = Client.builder().apiKey("your-api-key").build(); + Client client = new Client(); CompletableFuture responseFuture = client.async.models.generateContent( - "gemini-2.0-flash-001", "Introduce Google AI Studio.", null); + "gemini-2.5-flash", "Introduce Google AI Studio.", null); responseFuture .thenAccept( @@ -368,65 +457,7 @@ public class GenerateContentAsync { } ``` -#### Generate Content with extra configs -To set configurations like System Instructions and Safety Settings, you can pass -a `GenerateContentConfig` to the `GenerateContent` method. - -```java -package ; - -import com.google.common.collect.ImmutableList; -import com.google.genai.Client; -import com.google.genai.types.Content; -import com.google.genai.types.GenerateContentConfig; -import com.google.genai.types.GenerateContentResponse; -import com.google.genai.types.GoogleSearch; -import com.google.genai.types.HarmBlockThreshold; -import com.google.genai.types.HarmCategory; -import com.google.genai.types.Part; -import com.google.genai.types.SafetySetting; -import com.google.genai.types.Tool; - -public class GenerateContentWithConfigs { - public static void main(String[] args) { - Client client = new Client(); - - // Sets the safety settings in the config. - ImmutableList safetySettings = - ImmutableList.of( - SafetySetting.builder() - .category(HarmCategory.Known.HARM_CATEGORY_HATE_SPEECH) - .threshold(HarmBlockThreshold.Known.BLOCK_ONLY_HIGH) - .build(), - SafetySetting.builder() - .category(HarmCategory.Known.HARM_CATEGORY_DANGEROUS_CONTENT) - .threshold(HarmBlockThreshold.Known.BLOCK_LOW_AND_ABOVE) - .build()); - - // Sets the system instruction in the config. - Content systemInstruction = Content.fromParts(Part.fromText("You are a history teacher.")); - - // Sets the Google Search tool in the config. - Tool googleSearchTool = Tool.builder().googleSearch(GoogleSearch.builder().build()).build(); - - GenerateContentConfig config = - GenerateContentConfig.builder() - .candidateCount(1) - .maxOutputTokens(1024) - .safetySettings(safetySettings) - .systemInstruction(systemInstruction) - .tools(ImmutableList.of(googleSearchTool)) - .build(); - - GenerateContentResponse response = - client.models.generateContent("gemini-2.0-flash-001", "Tell me the history of LLM", config); - - System.out.println("Response: " + response.text()); - } -} -``` - -#### Generate Content with JSON response schema +##### Generate Content with JSON response schema To get a response in JSON by passing in a response schema to the `GenerateContent` API. @@ -445,6 +476,7 @@ public class GenerateContentWithSchema { public static void main(String[] args) { Client client = new Client(); + // Define the schema for the response, in Json format. ImmutableMap schema = ImmutableMap.of( "type", "object", "properties", ImmutableMap.of( @@ -457,6 +489,7 @@ public class GenerateContentWithSchema { "required", ImmutableList.of("recipe_name", "ingredients") ); + // Set the response schema in GenerateContentConfig GenerateContentConfig config = GenerateContentConfig.builder() .responseMimeType("application/json") @@ -465,13 +498,349 @@ public class GenerateContentWithSchema { .build(); GenerateContentResponse response = - client.models.generateContent("gemini-2.0-flash-001", "Tell me your name", config); + client.models.generateContent("gemini-2.5-flash", "Tell me your name", config); System.out.println("Response: " + response.text()); } } ``` +#### Count Tokens and Compute Tokens + +The `countTokens` method allows you to calculate the number of tokens your +prompt will use before sending it to the model, helping you manage costs and +stay within the context window. + +```java +package ; + +import com.google.genai.Client; +import com.google.genai.types.CountTokensResponse; + +public class CountTokens { + public static void main(String[] args) { + Client client = new Client(); + + CountTokensResponse response = + client.models.countTokens("gemini-2.5-flash", "What is your name?", null); + + System.out.println("Count tokens response: " + response); + } +} +``` + +The `computeTokens` method returns the Tokens Info that contains tokens and +token IDs given your prompt. This method is only supported in Vertex AI. + +```java +package ; + +import com.google.genai.Client; +import com.google.genai.types.ComputeTokensResponse; + +public class ComputeTokens { + public static void main(String[] args) { + Client client = Client.builder().vertexAI(true).build(); + + ComputeTokensResponse response = + client.models.computeTokens("gemini-2.5-flash", "What is your name?", null); + + System.out.println("Compute tokens response: " + response); + } +} +``` + +#### Embed Content + +The `embedContent` method allows you to generate embeddings for words, phrases, +sentences, and code. Note that only text embedding is supported in this method. + +```java +package ; + +import com.google.genai.Client; +import com.google.genai.types.EmbedContentResponse; + +public class EmbedContent { + public static void main(String[] args) { + Client client = new Client(); + + EmbedContentResponse response = + client.models.embedContent("gemini-embedding-001", "why is the sky blue?", null); + + System.out.println("Embedding response: " + response); + } +} +``` + +### Imagen + +Imagen is a text-to-image GenAI service. + +#### Generate Images + +The `generateImages` method helps you create high-quality, unique images given a +text prompt. + +```java +package ; + +import com.google.genai.Client; +import com.google.genai.types.GenerateImagesConfig; +import com.google.genai.types.GenerateImagesResponse; +import com.google.genai.types.Image; + +public class GenerateImages { + public static void main(String[] args) { + Client client = new Client(); + + GenerateImagesConfig config = + GenerateImagesConfig.builder() + .numberOfImages(1) + .outputMimeType("image/jpeg") + .includeSafetyAttributes(true) + .build(); + + GenerateImagesResponse response = + client.models.generateImages( + "imagen-3.0-generate-002", "Robot holding a red skateboard", config); + + response.generatedImages().ifPresent( + images -> { + System.out.println("Generated " + images.size() + " images."); + Image image = images.get(0).image().orElse(null); + // Do something with the image. + } + ); + } +} +``` + +#### Upscale Image + +The `upscaleImage` method allows you to upscale an image. This feature is only +supported in Vertex AI. + +```java +package ; + +import com.google.genai.Client; +import com.google.genai.types.Image; +import com.google.genai.types.UpscaleImageConfig; +import com.google.genai.types.UpscaleImageResponse; + +public class UpscaleImage { + public static void main(String[] args) { + Client client = Client.builder().vertexAI(true).build(); + + Image image = Image.fromFile("path/to/your/image"); + + UpscaleImageConfig config = + UpscaleImageConfig.builder() + .outputMimeType("image/jpeg") + .enhanceInputImage(true) + .imagePreservationFactor(0.6f) + .build(); + + UpscaleImageResponse response = + client.models.upscaleImage("imagen-3.0-generate-002", image, "x2", config); + + response.generatedImages().ifPresent( + images -> { + Image upscaledImage = images.get(0).image().orElse(null); + // Do something with the upscaled image. + } + ); + } +} +``` + +#### Edit Image + +The `editImage` method lets you edit an image. You can input reference images +(ex. mask reference for inpainting, or style reference for style transfer) in +addition to a text prompt to guide the editing. + +This feature uses a different model than `generateImages` and `upscaleImage`. It +is only supported in Vertex AI. + +```java +package ; + +import com.google.genai.Client; +import com.google.genai.types.EditImageConfig; +import com.google.genai.types.EditImageResponse; +import com.google.genai.types.EditMode; +import com.google.genai.types.Image; +import com.google.genai.types.MaskReferenceConfig; +import com.google.genai.types.MaskReferenceImage; +import com.google.genai.types.MaskReferenceMode; +import com.google.genai.types.RawReferenceImage; +import com.google.genai.types.ReferenceImage; +import java.util.ArrayList; + +public class EditImage { + public static void main(String[] args) { + Client client = Client.builder().vertexAI(true).build(); + + Image image = Image.fromFile("path/to/your/image"); + + // Edit image with a mask. + EditImageConfig config = + EditImageConfig.builder() + .editMode(EditMode.Known.EDIT_MODE_INPAINT_INSERTION) + .numberOfImages(1) + .outputMimeType("image/jpeg") + .build(); + + ArrayList referenceImages = new ArrayList<>(); + RawReferenceImage rawReferenceImage = + RawReferenceImage.builder().referenceImage(image).referenceId(1).build(); + referenceImages.add(rawReferenceImage); + + MaskReferenceImage maskReferenceImage = + MaskReferenceImage.builder() + .referenceId(2) + .config( + MaskReferenceConfig.builder() + .maskMode(MaskReferenceMode.Known.MASK_MODE_BACKGROUND) + .maskDilation(0.0f)) + .build(); + referenceImages.add(maskReferenceImage); + + EditImageResponse response = + client.models.editImage( + "imagen-3.0-capability-001", "Sunlight and clear sky", referenceImages, config); + + response.generatedImages().ifPresent( + images -> { + Image editedImage = images.get(0).image().orElse(null); + // Do something with the edited image. + } + ); + } +} +``` + +### Veo + +Veo is a video generation GenAI service. + +#### Generate Videos (Text to Video) + +```java +package ; + +import com.google.genai.Client; +import com.google.genai.types.GenerateVideosConfig; +import com.google.genai.types.GenerateVideosOperation; +import com.google.genai.types.Video; + +public class GenerateVideosWithText { + public static void main(String[] args) { + Client client = new Client(); + + GenerateVideosConfig config = + GenerateVideosConfig.builder() + .numberOfVideos(1) + .enhancePrompt(true) + .durationSeconds(5) + .build(); + + // generateVideos returns an operation + GenerateVideosOperation operation = + client.models.generateVideos( + "veo-2.0-generate-001", "A neon hologram of a cat driving at top speed", null, config); + + // When the operation hasn't been finished, operation.done() is empty + while (!operation.done().isPresent()) { + try { + System.out.println("Waiting for operation to complete..."); + Thread.sleep(10000); + // Sleep for 10 seconds and check the operation again + operation = client.operations.getVideosOperation(operation, null); + } catch (InterruptedException e) { + System.out.println("Thread was interrupted while sleeping."); + Thread.currentThread().interrupt(); + } + } + + operation.response().ifPresent( + response -> { + response.generatedVideos().ifPresent( + videos -> { + System.out.println("Generated " + videos.size() + " videos."); + Video video = videos.get(0).video().orElse(null); + // Do something with the generated video + } + ); + } + ); + } +} +``` + +#### Generate Videos (Image to Video) + +```java +package ; + +import com.google.genai.Client; +import com.google.genai.types.GenerateVideosConfig; +import com.google.genai.types.GenerateVideosOperation; +import com.google.genai.types.Image; +import com.google.genai.types.Video; + +public class GenerateVideosWithImage { + public static void main(String[] args) { + Client client = new Client(); + + Image image = Image.fromFile("path/to/your/image"); + + GenerateVideosConfig config = + GenerateVideosConfig.builder() + .numberOfVideos(1) + .enhancePrompt(true) + .durationSeconds(5) + .build(); + + // generateVideos returns an operation + GenerateVideosOperation operation = + client.models.generateVideos( + "veo-2.0-generate-001", + "Night sky", + image, + config); + + // When the operation hasn't been finished, operation.done() is empty + while (!operation.done().isPresent()) { + try { + System.out.println("Waiting for operation to complete..."); + Thread.sleep(10000); + // Sleep for 10 seconds and check the operation again + operation = client.operations.getVideosOperation(operation, null); + } catch (InterruptedException e) { + System.out.println("Thread was interrupted while sleeping."); + Thread.currentThread().interrupt(); + } + } + + operation.response().ifPresent( + response -> { + response.generatedVideos().ifPresent( + videos -> { + System.out.println("Generated " + videos.size() + " videos."); + Video video = videos.get(0).video().orElse(null); + // Do something with the generated video + } + ); + } + ); + } +} +``` + + ## Versioning This library follows [Semantic Versioning](http://semver.org/). diff --git a/examples/pom.xml b/examples/pom.xml index aa3685b77c3..38ee1a3ecfc 100644 --- a/examples/pom.xml +++ b/examples/pom.xml @@ -5,7 +5,7 @@ com.google.genai.examples google-genai-examples - 1.11.0-SNAPSHOT + 1.26.0-SNAPSHOT google-genai-examples @@ -13,7 +13,7 @@ 1.8 1.8 - 1.11.0-SNAPSHOT + 1.26.0-SNAPSHOT diff --git a/examples/src/main/java/com/google/genai/examples/BatchInlinedRequests.java b/examples/src/main/java/com/google/genai/examples/BatchInlinedRequests.java new file mode 100644 index 00000000000..7e2eee4f361 --- /dev/null +++ b/examples/src/main/java/com/google/genai/examples/BatchInlinedRequests.java @@ -0,0 +1,112 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +/** + * Usage: + * + *

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 + * + *

mvn exec:java -Dexec.mainClass="com.google.genai.examples.BatchInlinedRequests" + * -Dexec.args="YOUR_MODEL_ID" + */ +package com.google.genai.examples; + +import com.google.common.collect.ImmutableList; +import com.google.genai.Client; +import com.google.genai.types.BatchJob; +import com.google.genai.types.BatchJobSource; +import com.google.genai.types.Content; +import com.google.genai.types.CreateBatchJobConfig; +import com.google.genai.types.GenerateContentConfig; +import com.google.genai.types.InlinedRequest; +import com.google.genai.types.Part; + +/** An example of creating a batch job with inlined requests. */ +public final class BatchInlinedRequests { + + 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". + Client client = new Client(); + + if (client.vertexAI()) { + System.out.println("Inlined requests are not supported for Vertex AI backend."); + return; + } else { + System.out.println("Calling GeminiAPI Backend..."); + } + + InlinedRequest request1 = + InlinedRequest.builder() + .contents(Content.builder().parts(Part.fromText("Tell me a one-sentence joke."))) + .config( + GenerateContentConfig.builder() + .systemInstruction( + Content.builder() + .parts( + Part.fromText( + "You are a funny comedian. Always respond with humor and" + + " wit."))) + .temperature(0.5f)) + .build(); + + InlinedRequest request2 = + InlinedRequest.builder() + .contents(Content.builder().parts(Part.fromText("Why is the sky blue?"))) + .config( + GenerateContentConfig.builder() + .systemInstruction( + Content.builder() + .parts( + Part.fromText( + "You are a helpful science teacher. Explain complex concepts in" + + " simple terms."))) + .temperature(0.5f)) + .build(); + + BatchJobSource batchJobSource = + BatchJobSource.builder().inlinedRequests(ImmutableList.of(request1, request2)).build(); + + CreateBatchJobConfig config = + CreateBatchJobConfig.builder().displayName("inlined-requests-job-1").build(); + + BatchJob batchJob = + client.batches.create(Constants.GEMINI_MODEL_NAME, batchJobSource, config); + + System.out.println("Created batch job: " + batchJob.name().get()); + } +} diff --git a/examples/src/main/java/com/google/genai/examples/BatchManagement.java b/examples/src/main/java/com/google/genai/examples/BatchManagement.java index d0050df6712..f200a1ee6d6 100644 --- a/examples/src/main/java/com/google/genai/examples/BatchManagement.java +++ b/examples/src/main/java/com/google/genai/examples/BatchManagement.java @@ -56,6 +56,12 @@ public final class BatchManagement { public static void main(String[] args) { + final String modelId; + if (args.length != 0) { + modelId = args[0]; + } else { + modelId = Constants.GEMINI_MODEL_NAME; + } // 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 @@ -68,10 +74,6 @@ public static void main(String[] args) { Client client = new Client(); if (client.vertexAI()) { - String modelId = "gemini-1.5-flash-002"; - if (args.length != 0) { - modelId = args[0]; - } System.out.println("Using Vertex AI"); // Create a batch job. BatchJobSource batchJobSource = @@ -97,10 +99,6 @@ public static void main(String[] args) { System.out.println("Cancelled batch job: " + batchJob1.name().get()); } else { System.out.println("Using Gemini Developer API"); - String modelId = "gemini-2.0-flash"; - if (args.length != 0) { - modelId = args[0]; - } // Create a batch job. BatchJobSource batchJobSource = BatchJobSource.builder() diff --git a/examples/src/main/java/com/google/genai/examples/BatchManagementAsync.java b/examples/src/main/java/com/google/genai/examples/BatchManagementAsync.java index c1fcca542c5..df00b9b3d15 100644 --- a/examples/src/main/java/com/google/genai/examples/BatchManagementAsync.java +++ b/examples/src/main/java/com/google/genai/examples/BatchManagementAsync.java @@ -58,6 +58,12 @@ public final class BatchManagementAsync { public static void main(String[] args) { + final String modelId; + if (args.length != 0) { + modelId = args[0]; + } else { + modelId = Constants.GEMINI_MODEL_NAME; + } // 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 @@ -70,10 +76,6 @@ public static void main(String[] args) { Client client = new Client(); if (client.vertexAI()) { - String modelId = "gemini-1.5-flash-002"; - if (args.length != 0) { - modelId = args[0]; - } System.out.println("Using Vertex AI"); // Create a batch job. BatchJobSource batchJobSource = @@ -123,10 +125,6 @@ public static void main(String[] args) { System.out.println("All batch job operations completed."); } else { System.out.println("Using Gemini Developer API"); - String modelId = "gemini-2.0-flash"; - if (args.length != 0) { - modelId = args[0]; - } // Create a batch job. BatchJobSource batchJobSource = BatchJobSource.builder() diff --git a/examples/src/main/java/com/google/genai/examples/CachedContentOperations.java b/examples/src/main/java/com/google/genai/examples/CachedContentOperations.java index bcd6d30b997..ad37e1ffe31 100644 --- a/examples/src/main/java/com/google/genai/examples/CachedContentOperations.java +++ b/examples/src/main/java/com/google/genai/examples/CachedContentOperations.java @@ -50,7 +50,6 @@ import com.google.genai.types.ListCachedContentsConfig; import com.google.genai.types.Part; import com.google.genai.types.UpdateCachedContentConfig; - import java.io.IOException; import java.io.InputStream; import java.net.URL; @@ -63,9 +62,11 @@ public final class CachedContentOperations { public static void main(String[] args) { - String modelId = "gemini-2.0-flash-001"; + final String modelId; if (args.length != 0) { modelId = args[0]; + } else { + modelId = Constants.GEMINI_MODEL_NAME; } // Instantiate the client. The client by default uses the Gemini Developer API. It gets the API diff --git a/examples/src/main/java/com/google/genai/examples/CachedContentOperationsAsync.java b/examples/src/main/java/com/google/genai/examples/CachedContentOperationsAsync.java index 223c927a64a..62f16eda543 100644 --- a/examples/src/main/java/com/google/genai/examples/CachedContentOperationsAsync.java +++ b/examples/src/main/java/com/google/genai/examples/CachedContentOperationsAsync.java @@ -66,11 +66,11 @@ public final class CachedContentOperationsAsync { public static void main(String[] args) { - String modelId; + final String modelId; if (args.length != 0) { modelId = args[0]; } else { - modelId = "gemini-2.0-flash-001"; + modelId = Constants.GEMINI_MODEL_NAME; } // Instantiate the client. The client by default uses the Gemini Developer API. It gets the API diff --git a/examples/src/main/java/com/google/genai/examples/ChatWithFunctionCall.java b/examples/src/main/java/com/google/genai/examples/ChatWithFunctionCall.java index 584a4c1e76a..618d6acb360 100644 --- a/examples/src/main/java/com/google/genai/examples/ChatWithFunctionCall.java +++ b/examples/src/main/java/com/google/genai/examples/ChatWithFunctionCall.java @@ -60,9 +60,11 @@ public static Integer divideTwoIntegers(int numerator, int denominator) { } public static void main(String[] args) throws NoSuchMethodException { - String modelId = "gemini-2.0-flash-001"; + final String modelId; if (args.length != 0) { modelId = args[0]; + } else { + modelId = Constants.GEMINI_MODEL_NAME; } // Instantiate the client. The client by default uses the Gemini Developer API. It gets the API diff --git a/examples/src/main/java/com/google/genai/examples/ChatWithHistory.java b/examples/src/main/java/com/google/genai/examples/ChatWithHistory.java index 83a2b4b8af0..f79b0a38db6 100644 --- a/examples/src/main/java/com/google/genai/examples/ChatWithHistory.java +++ b/examples/src/main/java/com/google/genai/examples/ChatWithHistory.java @@ -49,9 +49,11 @@ /** An example of using the Unified Gen AI Java SDK to create a chat session with history. */ public final class ChatWithHistory { public static void main(String[] args) { - String modelId = "gemini-2.0-flash-001"; + final String modelId; if (args.length != 0) { modelId = args[0]; + } else { + modelId = Constants.GEMINI_MODEL_NAME; } // Instantiate the client. The client by default uses the Gemini Developer API. It gets the API diff --git a/examples/src/main/java/com/google/genai/examples/ChatWithHistoryAsync.java b/examples/src/main/java/com/google/genai/examples/ChatWithHistoryAsync.java index aa9da312e55..24c5b17a71a 100644 --- a/examples/src/main/java/com/google/genai/examples/ChatWithHistoryAsync.java +++ b/examples/src/main/java/com/google/genai/examples/ChatWithHistoryAsync.java @@ -50,9 +50,11 @@ /** An example of using the Unified Gen AI Java SDK to create an async chat session with history. */ public final class ChatWithHistoryAsync { public static void main(String[] args) { - String modelId = "gemini-2.0-flash-001"; + final String modelId; if (args.length != 0) { modelId = args[0]; + } else { + modelId = Constants.GEMINI_MODEL_NAME; } // Instantiate the client. The client by default uses the Gemini Developer API. It gets the API diff --git a/examples/src/main/java/com/google/genai/examples/ChatWithHistoryAsyncStreaming.java b/examples/src/main/java/com/google/genai/examples/ChatWithHistoryAsyncStreaming.java index 89112f774fb..427c3840b80 100644 --- a/examples/src/main/java/com/google/genai/examples/ChatWithHistoryAsyncStreaming.java +++ b/examples/src/main/java/com/google/genai/examples/ChatWithHistoryAsyncStreaming.java @@ -54,9 +54,11 @@ */ public final class ChatWithHistoryAsyncStreaming { public static void main(String[] args) { - String modelId = "gemini-2.0-flash-001"; + final String modelId; if (args.length != 0) { modelId = args[0]; + } else { + modelId = Constants.GEMINI_MODEL_NAME; } // Instantiate the client. The client by default uses the Gemini Developer API. It gets the API diff --git a/examples/src/main/java/com/google/genai/examples/ChatWithHistoryStreaming.java b/examples/src/main/java/com/google/genai/examples/ChatWithHistoryStreaming.java index c7c69e7c40b..54b9be2f62f 100644 --- a/examples/src/main/java/com/google/genai/examples/ChatWithHistoryStreaming.java +++ b/examples/src/main/java/com/google/genai/examples/ChatWithHistoryStreaming.java @@ -52,9 +52,11 @@ */ public final class ChatWithHistoryStreaming { public static void main(String[] args) { - String modelId = "gemini-2.0-flash-001"; + final String modelId; if (args.length != 0) { modelId = args[0]; + } else { + modelId = Constants.GEMINI_MODEL_NAME; } // Instantiate the client. The client by default uses the Gemini Developer API. It gets the API diff --git a/examples/src/main/java/com/google/genai/examples/ComputeTokens.java b/examples/src/main/java/com/google/genai/examples/ComputeTokens.java index 38b2d373026..e819816b19e 100644 --- a/examples/src/main/java/com/google/genai/examples/ComputeTokens.java +++ b/examples/src/main/java/com/google/genai/examples/ComputeTokens.java @@ -46,9 +46,11 @@ /** An example of using the Unified Gen AI Java SDK to compute tokens for simple text input. */ public final class ComputeTokens { public static void main(String[] args) { - String modelId = "gemini-2.0-flash-001"; + final String modelId; if (args.length != 0) { modelId = args[0]; + } else { + modelId = Constants.GEMINI_MODEL_NAME; } // Instantiate the client. The client by default uses the Gemini Developer API. It gets the API @@ -64,7 +66,8 @@ public static void main(String[] args) { if (client.vertexAI()) { System.out.println("Using Vertex AI"); } else { - System.out.println("Using Gemini Developer API"); + System.out.println("Gemini Developer API is not supported for this example."); + System.exit(0); } ComputeTokensResponse response = diff --git a/examples/src/main/java/com/google/genai/examples/Constants.java b/examples/src/main/java/com/google/genai/examples/Constants.java new file mode 100644 index 00000000000..ff7d0cc67a4 --- /dev/null +++ b/examples/src/main/java/com/google/genai/examples/Constants.java @@ -0,0 +1,63 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.genai.examples; + +/** A final class to hold constants shared across all examples. */ +public final class Constants { + + private Constants() {} + + /** The name of the generative model to be used in the examples. */ + public static final String GEMINI_MODEL_NAME = "gemini-2.5-flash"; + + /** The name of the live model to be used in the examples. */ + public static final String GEMINI_LIVE_MODEL_NAME = "gemini-live-2.5-flash"; + + /** The name of the preview live model to be used in the examples. */ + public static final String GEMINI_LIVE_MODEL_NAME_PREVIEW = "gemini-live-2.5-flash-preview"; + + /** The name of the image generation model to be used in the examples. */ + public static final String GEMINI_IMAGE_GENERATION_MODEL_NAME = + "gemini-2.0-flash-preview-image-generation"; + + /** The name of the Imagen generate model to be used in the examples. */ + public static final String IMAGEN_GENERATE_MODEL_NAME = "imagen-4.0-generate-001"; + + /** The name of the Imagen model to be used for image editing in the examples. */ + public static final String IMAGEN_CAPABILITY_MODEL_NAME = "imagen-3.0-capability-001"; + + /** The name of the Imagen ingredients model to be used in the examples. */ + public static final String IMAGEN_INGREDIENTS_MODEL_NAME = "imagen-4.0-ingredients-preview"; + + /** The name of the Imagen product recontext model to be used in the examples. */ + public static final String IMAGEN_RECONTEXT_MODEL_NAME = "imagen-product-recontext-preview-06-30"; + + /** The name of the Virtual try-on model to be used in the examples. */ + public static final String VIRTUAL_TRY_ON_MODEL_NAME = "virtual-try-on-preview-08-04"; + + /** The name of the segment image model to be used in the examples. */ + public static final String SEGMENT_IMAGE_MODEL_NAME = "image-segmentation-001"; + + /** The name of the Veo model to be used in the examples. */ + public static final String VEO_MODEL_NAME = "veo-2.0-generate-001"; + + /** The name of the embedding model to be used in the examples. */ + public static final String EMBEDDING_MODEL_NAME = "text-embedding-004"; + + /** The file path to be used in the files operations examples. */ + public static final String UPLOAD_FILE_PATH = "./resources/test.txt"; +} diff --git a/examples/src/main/java/com/google/genai/examples/CountTokens.java b/examples/src/main/java/com/google/genai/examples/CountTokens.java index 5a6cfa28bb5..1e80883700c 100644 --- a/examples/src/main/java/com/google/genai/examples/CountTokens.java +++ b/examples/src/main/java/com/google/genai/examples/CountTokens.java @@ -46,9 +46,11 @@ /** An example of using the Unified Gen AI Java SDK to count tokens for simple text input. */ public final class CountTokens { public static void main(String[] args) { - String modelId = "gemini-2.0-flash-001"; + final String modelId; if (args.length != 0) { modelId = args[0]; + } else { + modelId = Constants.GEMINI_MODEL_NAME; } // Instantiate the client. The client by default uses the Gemini Developer API. It gets the API diff --git a/examples/src/main/java/com/google/genai/examples/CountTokensWithConfigs.java b/examples/src/main/java/com/google/genai/examples/CountTokensWithConfigs.java index 770dbcbcbcd..1ac426d41c3 100644 --- a/examples/src/main/java/com/google/genai/examples/CountTokensWithConfigs.java +++ b/examples/src/main/java/com/google/genai/examples/CountTokensWithConfigs.java @@ -54,9 +54,11 @@ */ public final class CountTokensWithConfigs { public static void main(String[] args) { - String modelId = "gemini-2.0-flash-001"; + final String modelId; if (args.length != 0) { modelId = args[0]; + } else { + modelId = Constants.GEMINI_MODEL_NAME; } // Instantiate the client. The client by default uses the Gemini Developer API. It gets the API @@ -72,7 +74,10 @@ public static void main(String[] args) { if (client.vertexAI()) { System.out.println("Using Vertex AI"); } else { - System.out.println("Using Gemini Developer API"); + System.out.println( + "Gemini Developer API is not supported for this example since system instruction is not" + + " supported."); + System.exit(0); } // Sets the system instruction in the config. diff --git a/examples/src/main/java/com/google/genai/examples/EditImageAsync.java b/examples/src/main/java/com/google/genai/examples/EditImageAsync.java index c1d9a0f6168..0761645158d 100644 --- a/examples/src/main/java/com/google/genai/examples/EditImageAsync.java +++ b/examples/src/main/java/com/google/genai/examples/EditImageAsync.java @@ -56,9 +56,11 @@ /** An example of using the Unified Gen AI Java SDK to edit an image asynchronously. */ public final class EditImageAsync { public static void main(String[] args) { - String modelId = "imagen-3.0-capability-001"; + final String modelId; if (args.length != 0) { modelId = args[0]; + } else { + modelId = Constants.IMAGEN_CAPABILITY_MODEL_NAME; } // Instantiate the client. The client by default uses the Gemini Developer API. It gets the API @@ -74,7 +76,8 @@ public static void main(String[] args) { if (client.vertexAI()) { System.out.println("Using Vertex AI"); } else { - System.out.println("Using Gemini Developer API"); + System.out.println("Gemini Developer API is not supported for this example."); + System.exit(0); } // Base image created using generateImages with prompt: diff --git a/examples/src/main/java/com/google/genai/examples/EditImageContentReference.java b/examples/src/main/java/com/google/genai/examples/EditImageContentReference.java new file mode 100644 index 00000000000..2a66cfdc520 --- /dev/null +++ b/examples/src/main/java/com/google/genai/examples/EditImageContentReference.java @@ -0,0 +1,114 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Usage: + * + *

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 + * + *

mvn exec:java -Dexec.mainClass="com.google.genai.examples.EditImageContentReference" + * -Dexec.args="YOUR_MODEL_ID" + */ +package com.google.genai.examples; + +import com.google.genai.Client; +import com.google.genai.types.ContentReferenceImage; +import com.google.genai.types.EditImageConfig; +import com.google.genai.types.EditImageResponse; +import com.google.genai.types.Image; +import com.google.genai.types.ReferenceImage; +import com.google.genai.types.StyleReferenceConfig; +import com.google.genai.types.StyleReferenceImage; +import java.util.ArrayList; + +/** An example of using the Unified Gen AI Java SDK to edit an image (Mask reference). */ +public final class EditImageContentReference { + public static void main(String[] args) { + final String modelId; + if (args.length != 0) { + modelId = args[0]; + } else { + modelId = Constants.IMAGEN_INGREDIENTS_MODEL_NAME; + } + + // 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("Gemini Developer API is not supported for this example."); + System.exit(0); + } + + EditImageConfig editImageConfig = + EditImageConfig.builder().numberOfImages(1).outputMimeType("image/jpeg").build(); + + ArrayList referenceImages = new ArrayList<>(); + Image dogImage = Image.builder().gcsUri("gs://genai-sdk-tests/inputs/images/dog.jpg").build(); + ContentReferenceImage contentReferenceImage = + ContentReferenceImage.builder().referenceImage(dogImage).referenceId(1).build(); + referenceImages.add(contentReferenceImage); + + Image cyberpunkImage = + Image.builder().gcsUri("gs://genai-sdk-tests/inputs/images/cyberpunk.jpg").build(); + StyleReferenceImage styleReferenceImage = + StyleReferenceImage.builder() + .referenceId(2) + .referenceImage(cyberpunkImage) + .config(StyleReferenceConfig.builder().styleDescription("cyberpunk style").build()) + .build(); + referenceImages.add(styleReferenceImage); + + EditImageResponse editImageResponse = + client.models.editImage( + modelId, + "Dog in [1] sleeping on the ground at the bottom of the image with the cyberpunk city" + + " landscape in [2] in the background visible on the side of the mug.", + referenceImages, + editImageConfig); + + Image editedImage = editImageResponse.generatedImages().get().get(0).image().get(); + // Do something with editedImage. + } + + private EditImageContentReference() {} +} diff --git a/examples/src/main/java/com/google/genai/examples/EditImageControlReference.java b/examples/src/main/java/com/google/genai/examples/EditImageControlReference.java index 7955580d4c4..81842b18500 100644 --- a/examples/src/main/java/com/google/genai/examples/EditImageControlReference.java +++ b/examples/src/main/java/com/google/genai/examples/EditImageControlReference.java @@ -55,9 +55,11 @@ /** An example of using the Unified Gen AI Java SDK to edit an image (Control reference). */ public final class EditImageControlReference { public static void main(String[] args) { - String modelId = "imagen-3.0-capability-001"; + final String modelId; if (args.length != 0) { modelId = args[0]; + } else { + modelId = Constants.IMAGEN_CAPABILITY_MODEL_NAME; } // Instantiate the client. The client by default uses the Gemini Developer API. It gets the API @@ -73,7 +75,8 @@ public static void main(String[] args) { if (client.vertexAI()) { System.out.println("Using Vertex AI"); } else { - System.out.println("Using Gemini Developer API"); + System.out.println("Gemini Developer API is not supported for this example."); + System.exit(0); } // Base image created using generateImages with prompt: diff --git a/examples/src/main/java/com/google/genai/examples/EditImageMaskReference.java b/examples/src/main/java/com/google/genai/examples/EditImageMaskReference.java index 3b832a4ff60..e0044276578 100644 --- a/examples/src/main/java/com/google/genai/examples/EditImageMaskReference.java +++ b/examples/src/main/java/com/google/genai/examples/EditImageMaskReference.java @@ -57,9 +57,11 @@ /** An example of using the Unified Gen AI Java SDK to edit an image (Mask reference). */ public final class EditImageMaskReference { public static void main(String[] args) { - String modelId = "imagen-3.0-capability-001"; + final String modelId; if (args.length != 0) { modelId = args[0]; + } else { + modelId = Constants.IMAGEN_CAPABILITY_MODEL_NAME; } // Instantiate the client. The client by default uses the Gemini Developer API. It gets the API @@ -75,7 +77,8 @@ public static void main(String[] args) { if (client.vertexAI()) { System.out.println("Using Vertex AI"); } else { - System.out.println("Using Gemini Developer API"); + System.out.println("Gemini Developer API is not supported for this example."); + System.exit(0); } // Base image created using generateImages with prompt: diff --git a/examples/src/main/java/com/google/genai/examples/EditImageStyleTransfer.java b/examples/src/main/java/com/google/genai/examples/EditImageStyleTransfer.java index 021e5702495..0e69cf8754b 100644 --- a/examples/src/main/java/com/google/genai/examples/EditImageStyleTransfer.java +++ b/examples/src/main/java/com/google/genai/examples/EditImageStyleTransfer.java @@ -54,9 +54,11 @@ /** An example of using the Unified Gen AI Java SDK to edit an image (Style transfer). */ public final class EditImageStyleTransfer { public static void main(String[] args) { - String modelId = "imagen-3.0-capability-001"; + final String modelId; if (args.length != 0) { modelId = args[0]; + } else { + modelId = Constants.IMAGEN_CAPABILITY_MODEL_NAME; } // Instantiate the client. The client by default uses the Gemini Developer API. It gets the API @@ -72,7 +74,8 @@ public static void main(String[] args) { if (client.vertexAI()) { System.out.println("Using Vertex AI"); } else { - System.out.println("Using Gemini Developer API"); + System.out.println("Gemini Developer API is not supported for this example."); + System.exit(0); } // Base image created using generateImages with prompt: diff --git a/examples/src/main/java/com/google/genai/examples/EditImageSubjectReference.java b/examples/src/main/java/com/google/genai/examples/EditImageSubjectReference.java index 897dcc85635..0ba00a64f2f 100644 --- a/examples/src/main/java/com/google/genai/examples/EditImageSubjectReference.java +++ b/examples/src/main/java/com/google/genai/examples/EditImageSubjectReference.java @@ -55,9 +55,11 @@ /** An example of using the Unified Gen AI Java SDK to edit an image (Subject reference). */ public final class EditImageSubjectReference { public static void main(String[] args) { - String modelId = "imagen-3.0-capability-001"; + final String modelId; if (args.length != 0) { modelId = args[0]; + } else { + modelId = Constants.IMAGEN_CAPABILITY_MODEL_NAME; } // Instantiate the client. The client by default uses the Gemini Developer API. It gets the API @@ -73,7 +75,8 @@ public static void main(String[] args) { if (client.vertexAI()) { System.out.println("Using Vertex AI"); } else { - System.out.println("Using Gemini Developer API"); + System.out.println("Gemini Developer API is not supported for this example."); + System.exit(0); } // Base image created using generateImages with prompt: diff --git a/examples/src/main/java/com/google/genai/examples/EmbedContent.java b/examples/src/main/java/com/google/genai/examples/EmbedContent.java index 2886f90929a..77de9bc09aa 100644 --- a/examples/src/main/java/com/google/genai/examples/EmbedContent.java +++ b/examples/src/main/java/com/google/genai/examples/EmbedContent.java @@ -46,9 +46,11 @@ /** An example of using the Unified Gen AI Java SDK to embed content. */ public final class EmbedContent { public static void main(String[] args) { - String modelId = "text-embedding-004"; + final String modelId; if (args.length != 0) { modelId = args[0]; + } else { + modelId = Constants.EMBEDDING_MODEL_NAME; } // Instantiate the client. The client by default uses the Gemini Developer API. It gets the API diff --git a/examples/src/main/java/com/google/genai/examples/EmbedContentAsync.java b/examples/src/main/java/com/google/genai/examples/EmbedContentAsync.java index 538f017c19a..731ec561a06 100644 --- a/examples/src/main/java/com/google/genai/examples/EmbedContentAsync.java +++ b/examples/src/main/java/com/google/genai/examples/EmbedContentAsync.java @@ -47,9 +47,11 @@ /** An example of using the Unified Gen AI Java SDK to embed content asynchronously. */ public final class EmbedContentAsync { public static void main(String[] args) { - String modelId = "text-embedding-004"; + final String modelId; if (args.length != 0) { modelId = args[0]; + } else { + modelId = Constants.EMBEDDING_MODEL_NAME; } // Instantiate the client. The client by default uses the Gemini Developer API. It gets the API diff --git a/examples/src/main/java/com/google/genai/examples/EmbedContentWithConfig.java b/examples/src/main/java/com/google/genai/examples/EmbedContentWithConfig.java index 1ffbd18f123..09770d6512d 100644 --- a/examples/src/main/java/com/google/genai/examples/EmbedContentWithConfig.java +++ b/examples/src/main/java/com/google/genai/examples/EmbedContentWithConfig.java @@ -50,9 +50,11 @@ /** An example of using the Unified Gen AI Java SDK to embed content with extra config. */ public final class EmbedContentWithConfig { public static void main(String[] args) { - String modelId = "text-embedding-004"; + final String modelId; if (args.length != 0) { modelId = args[0]; + } else { + modelId = Constants.EMBEDDING_MODEL_NAME; } // Instantiate the client. The client by default uses the Gemini Developer API. It gets the API diff --git a/examples/src/main/java/com/google/genai/examples/FileOperations.java b/examples/src/main/java/com/google/genai/examples/FileOperations.java index 3dc7eae5771..0a54cb0b1a4 100644 --- a/examples/src/main/java/com/google/genai/examples/FileOperations.java +++ b/examples/src/main/java/com/google/genai/examples/FileOperations.java @@ -38,7 +38,7 @@ *

mvn clean compile * *

mvn exec:java -Dexec.mainClass="com.google.genai.examples.FileOperations" - * -Dexec.args="./resources/test.txt" + * -Dexec.args="path/to/file" */ package com.google.genai.examples; @@ -52,12 +52,12 @@ /** An example of how to use the Files module to upload, retrieve, and delete files. */ public final class FileOperations { public static void main(String[] args) { - - if (args.length == 0) { - System.out.println("Please provide a file path on the -Dexec.args argument."); - return; + final String filePath; + if (args.length != 0) { + filePath = args[0]; + } else { + filePath = Constants.UPLOAD_FILE_PATH; } - String filePath = args[0]; // 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 @@ -70,7 +70,8 @@ public static void main(String[] args) { Client client = new Client(); if (client.vertexAI()) { - System.out.println("Using Vertex AI"); + System.out.println("Vertex AI API is not supported for this example."); + System.exit(0); } else { System.out.println("Using Gemini Developer API"); } diff --git a/examples/src/main/java/com/google/genai/examples/FileOperationsAsync.java b/examples/src/main/java/com/google/genai/examples/FileOperationsAsync.java index 6fc53aba435..f35c7ed057a 100644 --- a/examples/src/main/java/com/google/genai/examples/FileOperationsAsync.java +++ b/examples/src/main/java/com/google/genai/examples/FileOperationsAsync.java @@ -56,12 +56,12 @@ */ public final class FileOperationsAsync { public static void main(String[] args) { - - if (args.length == 0) { - System.out.println("Please provide a file path on the -Dexec.args argument."); - return; + final String filePath; + if (args.length != 0) { + filePath = args[0]; + } else { + filePath = Constants.UPLOAD_FILE_PATH; } - String filePath = args[0]; // 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 @@ -74,7 +74,8 @@ public static void main(String[] args) { Client client = new Client(); if (client.vertexAI()) { - System.out.println("Using Vertex AI"); + System.out.println("Vertex AI API is not supported for this example."); + System.exit(0); } else { System.out.println("Using Gemini Developer API"); } diff --git a/examples/src/main/java/com/google/genai/examples/GenerateContent.java b/examples/src/main/java/com/google/genai/examples/GenerateContent.java index 2fd163e0155..f89c986fd14 100644 --- a/examples/src/main/java/com/google/genai/examples/GenerateContent.java +++ b/examples/src/main/java/com/google/genai/examples/GenerateContent.java @@ -46,9 +46,11 @@ /** An example of using the Unified Gen AI Java SDK to generate content. */ public final class GenerateContent { public static void main(String[] args) { - String modelId = "gemini-2.0-flash-001"; + final String modelId; if (args.length != 0) { modelId = args[0]; + } else { + modelId = Constants.GEMINI_MODEL_NAME; } // Instantiate the client. The client by default uses the Gemini Developer API. It gets the API diff --git a/examples/src/main/java/com/google/genai/examples/GenerateContentAsync.java b/examples/src/main/java/com/google/genai/examples/GenerateContentAsync.java index 7f180d9197e..655c99ce3f8 100644 --- a/examples/src/main/java/com/google/genai/examples/GenerateContentAsync.java +++ b/examples/src/main/java/com/google/genai/examples/GenerateContentAsync.java @@ -47,9 +47,11 @@ /** An example of using the Unified Gen AI Java SDK to generate content asynchronously. */ public final class GenerateContentAsync { public static void main(String[] args) { - String modelId = "gemini-2.0-flash-001"; + final String modelId; if (args.length != 0) { modelId = args[0]; + } else { + modelId = Constants.GEMINI_MODEL_NAME; } // Instantiate the client. The client by default uses the Gemini Developer API. It gets the API diff --git a/examples/src/main/java/com/google/genai/examples/GenerateContentStream.java b/examples/src/main/java/com/google/genai/examples/GenerateContentStream.java index da242a2924a..df8c1ff72c7 100644 --- a/examples/src/main/java/com/google/genai/examples/GenerateContentStream.java +++ b/examples/src/main/java/com/google/genai/examples/GenerateContentStream.java @@ -47,9 +47,11 @@ /** An example of using the Unified GenAI Java SDK to generate stream of content. */ public final class GenerateContentStream { public static void main(String[] args) { - String modelId = "gemini-2.0-flash-001"; + final String modelId; if (args.length != 0) { modelId = args[0]; + } else { + modelId = Constants.GEMINI_MODEL_NAME; } // Instantiate the client. The client by default uses the Gemini Developer API. It gets the API diff --git a/examples/src/main/java/com/google/genai/examples/GenerateContentWithConfigs.java b/examples/src/main/java/com/google/genai/examples/GenerateContentWithConfigs.java index 38833c0de22..770bbeb5751 100644 --- a/examples/src/main/java/com/google/genai/examples/GenerateContentWithConfigs.java +++ b/examples/src/main/java/com/google/genai/examples/GenerateContentWithConfigs.java @@ -57,9 +57,11 @@ /** An example of using the Unified Gen AI Java SDK to generate content with extra configs. */ public final class GenerateContentWithConfigs { public static void main(String[] args) { - String modelId = "gemini-2.0-flash-001"; + final String modelId; if (args.length != 0) { modelId = args[0]; + } else { + modelId = Constants.GEMINI_MODEL_NAME; } // Instantiate the client. The client by default uses the Gemini Developer API. It gets the API diff --git a/examples/src/main/java/com/google/genai/examples/GenerateContentWithFunctionCall.java b/examples/src/main/java/com/google/genai/examples/GenerateContentWithFunctionCall.java index dc6d4b3e7d4..de4514766a4 100644 --- a/examples/src/main/java/com/google/genai/examples/GenerateContentWithFunctionCall.java +++ b/examples/src/main/java/com/google/genai/examples/GenerateContentWithFunctionCall.java @@ -56,14 +56,16 @@ public static String getCurrentWeather(String location, String unit) { } /** A callable function to divide two integers. */ - public static Integer divideTwoIntegers(Integer numerator, Integer denominator) { + public static Integer divideTwoIntegers(int numerator, int denominator) { return numerator / denominator; } public static void main(String[] args) throws NoSuchMethodException { - String modelId = "gemini-2.0-flash-001"; + final String modelId; if (args.length != 0) { modelId = args[0]; + } else { + modelId = Constants.GEMINI_MODEL_NAME; } // Instantiate the client. The client by default uses the Gemini Developer API. It gets the API @@ -82,12 +84,13 @@ public static void main(String[] args) throws NoSuchMethodException { System.out.println("Using Gemini Developer API"); } + // Load the two methods as reflected Method objects so that they can be automatically executed + // on the client side. Method method1 = GenerateContentWithFunctionCall.class.getMethod( "getCurrentWeather", String.class, String.class); Method method2 = - GenerateContentWithFunctionCall.class.getMethod( - "divideTwoIntegers", Integer.class, Integer.class); + GenerateContentWithFunctionCall.class.getMethod("divideTwoIntegers", int.class, int.class); // Add the two methods as callable functions to the list of tools. GenerateContentConfig config = diff --git a/examples/src/main/java/com/google/genai/examples/GenerateContentWithFunctionCallAsync.java b/examples/src/main/java/com/google/genai/examples/GenerateContentWithFunctionCallAsync.java new file mode 100644 index 00000000000..66f87fcfae2 --- /dev/null +++ b/examples/src/main/java/com/google/genai/examples/GenerateContentWithFunctionCallAsync.java @@ -0,0 +1,125 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Usage: + * + *

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 + * + *

mvn exec:java + * -Dexec.mainClass="com.google.genai.examples.GenerateContentWithFunctionCallAsync" + * -Dexec.args="YOUR_MODEL_ID" + */ +package com.google.genai.examples; + +import com.google.genai.Client; +import com.google.genai.types.GenerateContentConfig; +import com.google.genai.types.GenerateContentResponse; +import com.google.genai.types.Tool; +import java.lang.reflect.Method; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; + +/** + * An example of using the Unified Gen AI Java SDK to generate content with (automatic) function + * calling asynchronously. + */ +public final class GenerateContentWithFunctionCallAsync { + /** A callable function to get the weather. */ + public static String getCurrentWeather(String location, String unit) { + return "The weather in " + location + " is " + "very nice."; + } + + /** A callable function to divide two integers. */ + public static Integer divideTwoIntegers(int numerator, int denominator) { + return numerator / denominator; + } + + public static void main(String[] args) throws NoSuchMethodException, InterruptedException { + final String modelId; + if (args.length != 0) { + modelId = args[0]; + } else { + modelId = Constants.GEMINI_MODEL_NAME; + } + + // 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"); + } + + // Load the two methods as reflected Method objects so that they can be automatically executed + // on the client side. + Method method1 = + GenerateContentWithFunctionCall.class.getMethod( + "getCurrentWeather", String.class, String.class); + Method method2 = + GenerateContentWithFunctionCall.class.getMethod("divideTwoIntegers", int.class, int.class); + + // Add the two methods as callable functions to the list of tools. + GenerateContentConfig config = + GenerateContentConfig.builder().tools(Tool.builder().functions(method1, method2)).build(); + + // --- Asynchronous Call --- + CompletableFuture future = + client.async.models.generateContent( + modelId, "What is the weather in Vancouver? And can you divide 10 by 0?", config); + + try { + GenerateContentResponse response = future.get(); + + System.out.println("The response is: " + response.text()); + System.out.println( + "The automatic function calling history is: " + + response.automaticFunctionCallingHistory().get()); + + } catch (ExecutionException e) { + // This shows how to handle errors in the async call. + System.err.println("Error during execution: " + e.getCause()); + } + } + + private GenerateContentWithFunctionCallAsync() {} +} diff --git a/examples/src/main/java/com/google/genai/examples/GenerateContentWithFunctionCallJson.java b/examples/src/main/java/com/google/genai/examples/GenerateContentWithFunctionCallJson.java index a162b920fdf..6dd91f1c7bf 100644 --- a/examples/src/main/java/com/google/genai/examples/GenerateContentWithFunctionCallJson.java +++ b/examples/src/main/java/com/google/genai/examples/GenerateContentWithFunctionCallJson.java @@ -45,19 +45,20 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.genai.Client; +import com.google.genai.types.FunctionDeclaration; import com.google.genai.types.GenerateContentConfig; import com.google.genai.types.GenerateContentResponse; import com.google.genai.types.Tool; -import com.google.genai.types.FunctionDeclaration; - /** An example of using the Unified Gen AI Java SDK to generate content with function calling. */ public final class GenerateContentWithFunctionCallJson { /** A callable function to get the weather. */ public static void main(String[] args) { - String modelId = "gemini-2.0-flash-001"; + final String modelId; if (args.length != 0) { modelId = args[0]; + } else { + modelId = Constants.GEMINI_MODEL_NAME; } // Instantiate the client. The client by default uses the Gemini Developer API. It gets the API @@ -76,28 +77,34 @@ public static void main(String[] args) { System.out.println("Using Gemini Developer API"); } - ImmutableMap schema = + // Define the schema for the function declaration, in Json format. + ImmutableMap parametersSchema = ImmutableMap.of( "type", "object", "properties", ImmutableMap.of("location", ImmutableMap.of("type", "string")), "required", ImmutableList.of("location")); + ImmutableMap responseSchema = + ImmutableMap.of( + "type", "object", + "properties", ImmutableMap.of("weather", ImmutableMap.of("type", "string")), + "required", ImmutableList.of("weather")); + + // Define the tool with the function declaration. Tool toolWithFunctionDeclarations = Tool.builder() .functionDeclarations( - ImmutableList.of( - FunctionDeclaration.builder() - .name("get_weather") - .description("Returns the weather in a given location.") - .parametersJsonSchema(schema) - .build())) + FunctionDeclaration.builder() + .name("get_weather") + .description("Returns the weather in a given location.") + .parametersJsonSchema(parametersSchema) + .responseJsonSchema(responseSchema) + .build()) .build(); - // Add the two methods as callable functions to the list of tools. + // Add the tool to the GenerateContentConfig. GenerateContentConfig config = - GenerateContentConfig.builder() - .tools(ImmutableList.of(toolWithFunctionDeclarations)) - .build(); + GenerateContentConfig.builder().tools(toolWithFunctionDeclarations).build(); GenerateContentResponse response = client.models.generateContent(modelId, "What is the weather in Vancouver?", config); diff --git a/examples/src/main/java/com/google/genai/examples/GenerateContentWithFunctionCallJsonString.java b/examples/src/main/java/com/google/genai/examples/GenerateContentWithFunctionCallJsonString.java new file mode 100644 index 00000000000..774fc540039 --- /dev/null +++ b/examples/src/main/java/com/google/genai/examples/GenerateContentWithFunctionCallJsonString.java @@ -0,0 +1,133 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * 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 + * + *

mvn exec:java -Dexec.mainClass="com.google.genai.examples.GenerateContentWithFunctionCallJsonString" + * -Dexec.args="YOUR_MODEL_ID" + */ +package com.google.genai.examples; + +import com.google.genai.Client; +import com.google.genai.JsonSerializable; +import com.google.genai.types.FunctionDeclaration; +import com.google.genai.types.GenerateContentConfig; +import com.google.genai.types.GenerateContentResponse; +import com.google.genai.types.Tool; + +/** An example of using the Unified Gen AI Java SDK to generate content with function calling. */ +public final class GenerateContentWithFunctionCallJsonString { + /** A callable function to get the weather. */ + public static void main(String[] args) { + final String modelId; + if (args.length != 0) { + modelId = args[0]; + } else { + modelId = Constants.GEMINI_MODEL_NAME; + } + + // 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"); + } + + // Define the schema for the function declaration, in Json format. Note if you have java 15 or + // above, you can use the following string block instead: + // String parametersSchemaString = + // """{ + // "type": "object", + // "properties": { + // "location": { + // "type": "string" + // } + // }, + // "required": [ + // "location" + // ] + // }"""; + // String responseSchemaString = + // """{ + // "type": "object", + // "properties": { + // "weather": { + // "type": "string" + // } + // }, + // "required": [ + // "weather" + // ] + // }"""; + String parametersSchemaString = + "{\"type\":\"object\",\"properties\":{\"location\":{\"type\":\"string\"}},\"required\":[\"location\"]}"; + String responseSchemaString = + "{\"type\":\"object\",\"properties\":{\"weather\":{\"type\":\"string\"}},\"required\":[\"weather\"]}"; + + // Define the tool with the function declaration. + Tool toolWithFunctionDeclarations = + Tool.builder() + .functionDeclarations( + FunctionDeclaration.builder() + .name("get_weather") + .description("Returns the weather in a given location.") + .parametersJsonSchema(JsonSerializable.stringToJsonNode(parametersSchemaString)) + .responseJsonSchema(JsonSerializable.stringToJsonNode(responseSchemaString)) + .build()) + .build(); + + // Add the tool to the GenerateContentConfig. + GenerateContentConfig config = + GenerateContentConfig.builder().tools(toolWithFunctionDeclarations).build(); + + GenerateContentResponse response = + client.models.generateContent(modelId, "What is the weather in Vancouver?", config); + + System.out.println("The response is: " + response.functionCalls()); + } + + private GenerateContentWithFunctionCallJsonString() {} +} diff --git a/examples/src/main/java/com/google/genai/examples/GenerateContentWithHttpOptions.java b/examples/src/main/java/com/google/genai/examples/GenerateContentWithHttpOptions.java new file mode 100644 index 00000000000..b07847e1c3e --- /dev/null +++ b/examples/src/main/java/com/google/genai/examples/GenerateContentWithHttpOptions.java @@ -0,0 +1,84 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Usage: + * + *

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 + * + *

mvn exec:java -Dexec.mainClass="com.google.genai.examples.GenerateContentWithHttpOptions" + * -Dexec.args="YOUR_MODEL_ID" + */ +package com.google.genai.examples; + +import com.google.genai.Client; +import com.google.genai.types.GenerateContentResponse; +import com.google.genai.types.HttpOptions; +import com.google.genai.types.HttpRetryOptions; + +/** An example of setting http options in a GenerateContent request. */ +public final class GenerateContentWithHttpOptions { + public static void main(String[] args) { + final String modelId; + if (args.length != 0) { + modelId = args[0]; + } else { + modelId = Constants.GEMINI_MODEL_NAME; + } + + // Set the client level http options when creating the client. All the API requests will share + // the same http options. + HttpOptions httpOptions = + HttpOptions.builder() + .apiVersion("v1") + .timeout(5000) + .retryOptions(HttpRetryOptions.builder().attempts(3).httpStatusCodes(408, 429, 504)) + .build(); + + Client client = Client.builder().httpOptions(httpOptions).build(); + + if (client.vertexAI()) { + System.out.println("Using Vertex AI"); + } else { + System.out.println("Using Gemini Developer API"); + } + + GenerateContentResponse response = + client.models.generateContent(modelId, "Tell me the history of LLM in 100 words", null); + + System.out.println("Response: " + response.text()); + } + + private GenerateContentWithHttpOptions() {} +} diff --git a/examples/src/main/java/com/google/genai/examples/GenerateContentWithImageInput.java b/examples/src/main/java/com/google/genai/examples/GenerateContentWithImageInput.java index 997737cb60d..316dbb1ccbd 100644 --- a/examples/src/main/java/com/google/genai/examples/GenerateContentWithImageInput.java +++ b/examples/src/main/java/com/google/genai/examples/GenerateContentWithImageInput.java @@ -50,9 +50,11 @@ /** An example of using the Unified Gen AI Java SDK to generate content with image input. */ public final class GenerateContentWithImageInput { public static void main(String[] args) { - String modelId = "gemini-2.0-flash-001"; + final String modelId; if (args.length != 0) { modelId = args[0]; + } else { + modelId = Constants.GEMINI_MODEL_NAME; } // Instantiate the client. The client by default uses the Gemini Developer API. It gets the API @@ -68,9 +70,10 @@ public static void main(String[] args) { if (client.vertexAI()) { System.out.println("Using Vertex AI"); } else { - throw new IllegalArgumentException( + System.out.println( "This example is not supported for Gemini Developer API since the image uri from GCS is" + " only supported in Vertex AI."); + System.exit(0); } Content content = diff --git a/examples/src/main/java/com/google/genai/examples/GenerateContentWithResponseJsonSchema.java b/examples/src/main/java/com/google/genai/examples/GenerateContentWithResponseJsonSchema.java index bd3882be126..b6ec9707d3f 100644 --- a/examples/src/main/java/com/google/genai/examples/GenerateContentWithResponseJsonSchema.java +++ b/examples/src/main/java/com/google/genai/examples/GenerateContentWithResponseJsonSchema.java @@ -37,7 +37,8 @@ * *

mvn clean compile * - *

mvn exec:java -Dexec.mainClass="com.google.genai.examples.GenerateContentWithResponseSchema" + *

mvn exec:java + * -Dexec.mainClass="com.google.genai.examples.GenerateContentWithResponseJsonSchema" * -Dexec.args="YOUR_MODEL_ID" */ package com.google.genai.examples; @@ -54,9 +55,11 @@ */ public final class GenerateContentWithResponseJsonSchema { public static void main(String[] args) { - String modelId = "gemini-2.0-flash-001"; + final String modelId; if (args.length != 0) { modelId = args[0]; + } else { + modelId = Constants.GEMINI_MODEL_NAME; } // Instantiate the client. The client by default uses the Gemini Developer API. It gets the API diff --git a/examples/src/main/java/com/google/genai/examples/GenerateContentWithResponseJsonSchemaString.java b/examples/src/main/java/com/google/genai/examples/GenerateContentWithResponseJsonSchemaString.java new file mode 100644 index 00000000000..8cb4e6a4d5b --- /dev/null +++ b/examples/src/main/java/com/google/genai/examples/GenerateContentWithResponseJsonSchemaString.java @@ -0,0 +1,115 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Usage: + * + *

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 + * + *

mvn exec:java + * -Dexec.mainClass="com.google.genai.examples.GenerateContentWithResponseJsonSchemaString" + * -Dexec.args="YOUR_MODEL_ID" + */ +package com.google.genai.examples; + +import com.google.genai.Client; +import com.google.genai.JsonSerializable; +import com.google.genai.types.GenerateContentConfig; +import com.google.genai.types.GenerateContentResponse; + +/** + * GenerateContentWithResponseJsonSchema generates a content and returns a json object by passing a + * schema. + */ +public final class GenerateContentWithResponseJsonSchemaString { + public static void main(String[] args) { + final String modelId; + if (args.length != 0) { + modelId = args[0]; + } else { + modelId = Constants.GEMINI_MODEL_NAME; + } + + // 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"); + } + // Note if you have java 15 or above, you can use the following string block instead: + // String schema = """{ + // "type": "object", + // "properties": { + // "recipe_name": { + // "type": "string" + // }, + // "ingredients": { + // "type": "array", + // "items": { + // "type": "string" + // } + // } + // }, + // "required": [ + // "recipe_name", + // "ingredients" + // ] + // }"""; + String schema = + "{\"type\":\"object\",\"properties\":{\"recipe_name\":{\"type\":\"string\"},\"ingredients\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}}},\"required\":[\"recipe_name\",\"ingredients\"]}"; + + GenerateContentConfig config = + GenerateContentConfig.builder() + .responseMimeType("application/json") + .candidateCount(1) + .responseJsonSchema(JsonSerializable.stringToJsonNode(schema)) + .build(); + + GenerateContentResponse response = + client.models.generateContent(modelId, "List a few popular cookie recipes.", config); + + System.out.println("Response: " + response.text()); + } + + private GenerateContentWithResponseJsonSchemaString() {} +} diff --git a/examples/src/main/java/com/google/genai/examples/GenerateContentWithResponseModality.java b/examples/src/main/java/com/google/genai/examples/GenerateContentWithResponseModality.java index c6422966202..55c5e1d08c3 100644 --- a/examples/src/main/java/com/google/genai/examples/GenerateContentWithResponseModality.java +++ b/examples/src/main/java/com/google/genai/examples/GenerateContentWithResponseModality.java @@ -49,9 +49,11 @@ /** An example of using the Unified Gen AI Java SDK to generate content with response modality. */ public final class GenerateContentWithResponseModality { public static void main(String[] args) { - String modelId = "gemini-2.0-flash-preview-image-generation"; + final String modelId; if (args.length != 0) { modelId = args[0]; + } else { + modelId = Constants.GEMINI_IMAGE_GENERATION_MODEL_NAME; } // Instantiate the client. The client by default uses the Gemini Developer API. It gets the API diff --git a/examples/src/main/java/com/google/genai/examples/GenerateContentWithResponseSchema.java b/examples/src/main/java/com/google/genai/examples/GenerateContentWithResponseSchema.java index ce9e53e41e4..ea44ba2c6d2 100644 --- a/examples/src/main/java/com/google/genai/examples/GenerateContentWithResponseSchema.java +++ b/examples/src/main/java/com/google/genai/examples/GenerateContentWithResponseSchema.java @@ -55,9 +55,11 @@ */ public final class GenerateContentWithResponseSchema { public static void main(String[] args) { - String modelId = "gemini-2.0-flash-001"; + final String modelId; if (args.length != 0) { modelId = args[0]; + } else { + modelId = Constants.GEMINI_MODEL_NAME; } // Instantiate the client. The client by default uses the Gemini Developer API. It gets the API diff --git a/examples/src/main/java/com/google/genai/examples/GenerateImages.java b/examples/src/main/java/com/google/genai/examples/GenerateImages.java index c146985827e..45ed006c24f 100644 --- a/examples/src/main/java/com/google/genai/examples/GenerateImages.java +++ b/examples/src/main/java/com/google/genai/examples/GenerateImages.java @@ -48,9 +48,11 @@ /** An example of using the Unified Gen AI Java SDK to generate images. */ public final class GenerateImages { public static void main(String[] args) { - String modelId = "imagen-3.0-generate-002"; + final String modelId; if (args.length != 0) { modelId = args[0]; + } else { + modelId = Constants.IMAGEN_GENERATE_MODEL_NAME; } // Instantiate the client. The client by default uses the Gemini Developer API. It gets the API diff --git a/examples/src/main/java/com/google/genai/examples/GenerateImagesAsync.java b/examples/src/main/java/com/google/genai/examples/GenerateImagesAsync.java index b9ceb3bcc43..2556b5e472a 100644 --- a/examples/src/main/java/com/google/genai/examples/GenerateImagesAsync.java +++ b/examples/src/main/java/com/google/genai/examples/GenerateImagesAsync.java @@ -49,9 +49,11 @@ /** An example of using the Unified Gen AI Java SDK to generate images asynchronously. */ public final class GenerateImagesAsync { public static void main(String[] args) { - String modelId = "imagen-3.0-generate-002"; + final String modelId; if (args.length != 0) { modelId = args[0]; + } else { + modelId = Constants.IMAGEN_GENERATE_MODEL_NAME; } // Instantiate the client. The client by default uses the Gemini Developer API. It gets the API diff --git a/examples/src/main/java/com/google/genai/examples/GenerateVideos.java b/examples/src/main/java/com/google/genai/examples/GenerateVideos.java index 690ee862abd..85a793364bf 100644 --- a/examples/src/main/java/com/google/genai/examples/GenerateVideos.java +++ b/examples/src/main/java/com/google/genai/examples/GenerateVideos.java @@ -44,14 +44,17 @@ import com.google.genai.errors.GenAiIOException; import com.google.genai.types.GenerateVideosConfig; import com.google.genai.types.GenerateVideosOperation; +import com.google.genai.types.GenerateVideosSource; import com.google.genai.types.Video; /** An example of using the Unified Gen AI Java SDK to generate videos. */ public final class GenerateVideos { public static void main(String[] args) { - String modelId = "veo-2.0-generate-001"; + final String modelId; if (args.length != 0) { modelId = args[0]; + } else { + modelId = Constants.VEO_MODEL_NAME; } // Instantiate the client. The client by default uses the Gemini Developer API. It gets the API @@ -77,17 +80,19 @@ public static void main(String[] args) { generateVideosConfigBuilder.outputGcsUri("gs://genai-sdk-tests/tmp/videos"); } GenerateVideosConfig generateVideosConfig = generateVideosConfigBuilder.build(); + GenerateVideosSource generateVideosSource = + GenerateVideosSource.builder() + .prompt("A neon hologram of a cat driving at top speed") + .build(); GenerateVideosOperation generateVideosOperation = - client.models.generateVideos( - modelId, "A neon hologram of a cat driving at top speed", null, generateVideosConfig); + client.models.generateVideos(modelId, generateVideosSource, generateVideosConfig); // GenerateVideosOperation.done() is empty if the operation is not done. while (!generateVideosOperation.done().filter(Boolean::booleanValue).isPresent()) { try { Thread.sleep(10000); // Sleep for 10 seconds. - generateVideosOperation = - client.operations.getVideosOperation(generateVideosOperation, null); + generateVideosOperation = client.operations.get(generateVideosOperation, null); System.out.println("Waiting for operation to complete..."); } catch (InterruptedException e) { System.out.println("Thread was interrupted while sleeping."); diff --git a/examples/src/main/java/com/google/genai/examples/GenerateVideosAsync.java b/examples/src/main/java/com/google/genai/examples/GenerateVideosAsync.java index 5f97af5c0d3..29b0a96be49 100644 --- a/examples/src/main/java/com/google/genai/examples/GenerateVideosAsync.java +++ b/examples/src/main/java/com/google/genai/examples/GenerateVideosAsync.java @@ -43,6 +43,7 @@ import com.google.genai.Client; import com.google.genai.types.GenerateVideosConfig; import com.google.genai.types.GenerateVideosOperation; +import com.google.genai.types.GenerateVideosSource; import com.google.genai.types.Video; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; @@ -50,9 +51,11 @@ /** An example of using the Unified Gen AI Java SDK to generate images asynchronously. */ public final class GenerateVideosAsync { public static void main(String[] args) { - String modelId = "veo-2.0-generate-001"; + final String modelId; if (args.length != 0) { modelId = args[0]; + } else { + modelId = Constants.VEO_MODEL_NAME; } // Instantiate the client. The client by default uses the Gemini Developer API. It gets the API @@ -78,10 +81,13 @@ public static void main(String[] args) { generateVideosConfigBuilder.outputGcsUri("gs://genai-sdk-tests/tmp/videos"); } GenerateVideosConfig generateVideosConfig = generateVideosConfigBuilder.build(); + GenerateVideosSource generateVideosSource = + GenerateVideosSource.builder() + .prompt("A neon hologram of a cat driving at top speed") + .build(); CompletableFuture generateVideosOperationFuture = - client.async.models.generateVideos( - modelId, "A neon hologram of a cat driving at top speed", null, generateVideosConfig); + client.async.models.generateVideos(modelId, generateVideosSource, generateVideosConfig); generateVideosOperationFuture .thenAccept( @@ -92,7 +98,7 @@ public static void main(String[] args) { try { Thread.sleep(10000); // Sleep for 10 seconds. try { - operation = client.async.operations.getVideosOperation(operation, null).get(); + operation = client.async.operations.get(operation, null).get(); } catch (ExecutionException e) { throw new RuntimeException(e); } @@ -109,7 +115,7 @@ public static void main(String[] args) { Video generatedVideo = operation.response().get().generatedVideos().get().get(0).video().get(); - // Do something with the video. + System.out.println("Video URL: " + generatedVideo.uri().get()); }) .join(); } diff --git a/examples/src/main/java/com/google/genai/examples/GenerateVideosEditOutpaint.java b/examples/src/main/java/com/google/genai/examples/GenerateVideosEditOutpaint.java new file mode 100644 index 00000000000..3acfafc6e2f --- /dev/null +++ b/examples/src/main/java/com/google/genai/examples/GenerateVideosEditOutpaint.java @@ -0,0 +1,133 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * 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.GenerateVideosEditOutpaint" + * -Dexec.args="YOUR_MODEL_ID" + */ +package com.google.genai.examples; + +import com.google.genai.Client; +import com.google.genai.types.GenerateVideosConfig; +import com.google.genai.types.GenerateVideosOperation; +import com.google.genai.types.GenerateVideosSource; +import com.google.genai.types.Image; +import com.google.genai.types.Video; +import com.google.genai.types.VideoGenerationMask; +import com.google.genai.types.VideoGenerationMaskMode; + +/** An example of using the Unified Gen AI Java SDK to edit a video with outpaint mode. */ +public final class GenerateVideosEditOutpaint { + public static void main(String[] args) { + final String modelId; + if (args.length != 0) { + modelId = args[0]; + } else { + modelId = "veo-2.0-generate-exp"; // Only supported on experimental model currently. + } + + // 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("Gemini Developer API is not supported for this example."); + System.exit(0); + } + + VideoGenerationMask videoGenerationMask = + VideoGenerationMask.builder() + .image( + Image.builder() + .gcsUri("gs://genai-sdk-tests/inputs/videos/video_outpaint_mask.png") + .mimeType("image/png") + .build()) + .maskMode(VideoGenerationMaskMode.Known.OUTPAINT) + .build(); + + GenerateVideosConfig generateVideosConfig = + GenerateVideosConfig.builder() + .numberOfVideos(1) + .outputGcsUri("gs://genai-sdk-tests/tmp/videos") + .aspectRatio("16:9") + .mask(videoGenerationMask) + .build(); + + GenerateVideosSource generateVideosSource = + GenerateVideosSource.builder() + .prompt("A neon hologram of a cat driving at top speed") + .video( + Video.builder() + .uri("gs://genai-sdk-tests/inputs/videos/editing_demo.mp4") + .mimeType("video/mp4") + .build()) + .build(); + + GenerateVideosOperation generateVideosOperation = + client.models.generateVideos(modelId, generateVideosSource, generateVideosConfig); + + // GenerateVideosOperation.done() is empty if the operation is not done. + while (!generateVideosOperation.done().filter(Boolean::booleanValue).isPresent()) { + try { + Thread.sleep(10000); // Sleep for 10 seconds. + generateVideosOperation = + client.operations.getVideosOperation(generateVideosOperation, null); + System.out.println("Waiting for operation to complete..."); + } catch (InterruptedException e) { + System.out.println("Thread was interrupted while sleeping."); + Thread.currentThread().interrupt(); + } + } + System.out.println( + "Generated " + + generateVideosOperation.response().get().generatedVideos().get().size() + + " video(s)."); + + Video generatedVideo = + generateVideosOperation.response().get().generatedVideos().get().get(0).video().get(); + } + + private GenerateVideosEditOutpaint() {} +} diff --git a/examples/src/main/java/com/google/genai/examples/GenerateVideosExtension.java b/examples/src/main/java/com/google/genai/examples/GenerateVideosExtension.java new file mode 100644 index 00000000000..ca1befb012f --- /dev/null +++ b/examples/src/main/java/com/google/genai/examples/GenerateVideosExtension.java @@ -0,0 +1,157 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Usage: + * + *

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.GenerateVideos" + * -Dexec.args="YOUR_MODEL_ID" + */ +package com.google.genai.examples; + +import com.google.genai.Client; +import com.google.genai.errors.GenAiIOException; +import com.google.genai.types.GenerateVideosConfig; +import com.google.genai.types.GenerateVideosOperation; +import com.google.genai.types.GenerateVideosSource; +import com.google.genai.types.Video; + +/** An example of using the Unified Gen AI Java SDK to generate videos. */ +public final class GenerateVideosExtension { + public static void main(String[] args) { + final String modelId; + if (args.length != 0) { + modelId = args[0]; + } else { + modelId = "veo-3-exp"; + } + + // 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("Sample is only available for Gemini Developer API."); + return; + } else { + System.out.println("Using Gemini Developer API"); + } + + // Generate first video. + GenerateVideosConfig generateVideosConfig = + GenerateVideosConfig.builder().numberOfVideos(1).build(); + GenerateVideosSource generateVideosSource = + GenerateVideosSource.builder() + .prompt("A neon hologram of a cat driving at top speed") + .build(); + + GenerateVideosOperation generateVideosOperation1 = + client.models.generateVideos(modelId, generateVideosSource, generateVideosConfig); + + // GenerateVideosOperation.done() is empty if the operation is not done. + while (!generateVideosOperation1.done().filter(Boolean::booleanValue).isPresent()) { + try { + Thread.sleep(10000); // Sleep for 10 seconds. + generateVideosOperation1 = + client.operations.getVideosOperation(generateVideosOperation1, null); + System.out.println("Waiting for operation to complete..."); + } catch (InterruptedException e) { + System.out.println("Thread was interrupted while sleeping."); + Thread.currentThread().interrupt(); + } + } + System.out.println( + "Generated " + + generateVideosOperation1.response().get().generatedVideos().get().size() + + " video(s)."); + + Video generatedVideo1 = + generateVideosOperation1.response().get().generatedVideos().get().get(0).video().get(); + + if (!client.vertexAI()) { + try { + client.files.download(generatedVideo1, "video.mp4", null); + System.out.println("Downloaded video to video.mp4"); + } catch (GenAiIOException e) { + System.out.println("An error occurred while downloading the video: " + e.getMessage()); + } + } + + // Extend the generated video. + GenerateVideosConfig generateVideosConfig2 = + GenerateVideosConfig.builder().numberOfVideos(1).build(); + GenerateVideosSource generateVideosSource2 = + GenerateVideosSource.builder().prompt("Rain").video(generatedVideo1).build(); + + GenerateVideosOperation generateVideosOperation2 = + client.models.generateVideos(modelId, generateVideosSource2, generateVideosConfig2); + + // GenerateVideosOperation.done() is empty if the operation is not done. + while (!generateVideosOperation2.done().filter(Boolean::booleanValue).isPresent()) { + try { + Thread.sleep(10000); // Sleep for 10 seconds. + generateVideosOperation2 = + client.operations.getVideosOperation(generateVideosOperation2, null); + System.out.println("Waiting for operation to complete..."); + } catch (InterruptedException e) { + System.out.println("Thread was interrupted while sleeping."); + Thread.currentThread().interrupt(); + } + } + System.out.println( + "Generated " + + generateVideosOperation2.response().get().generatedVideos().get().size() + + " video(s)."); + + Video generatedVideo2 = + generateVideosOperation2.response().get().generatedVideos().get().get(0).video().get(); + + if (!client.vertexAI()) { + try { + client.files.download(generatedVideo2, "video.mp4", null); + System.out.println("Downloaded extended video to video.mp4"); + } catch (GenAiIOException e) { + System.out.println("An error occurred while downloading the video: " + e.getMessage()); + } + } + } + + private GenerateVideosExtension() {} +} diff --git a/examples/src/main/java/com/google/genai/examples/HttpOptionsExtraBody.java b/examples/src/main/java/com/google/genai/examples/HttpOptionsExtraBody.java new file mode 100644 index 00000000000..c4fecf6ba01 --- /dev/null +++ b/examples/src/main/java/com/google/genai/examples/HttpOptionsExtraBody.java @@ -0,0 +1,105 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Usage: + * + *

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.HttpOptionsExtraBody" + * -Dexec.args="YOUR_MODEL_ID" + */ +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.types.GenerateContentConfig; +import com.google.genai.types.GenerateContentResponse; +import com.google.genai.types.HttpOptions; + +/** + * An example of using HttpOption extraBody to inject additional parameters to http request body. + */ +public final class HttpOptionsExtraBody { + public static void main(String[] args) { + final String modelId; + if (args.length != 0) { + modelId = args[0]; + } else { + modelId = Constants.GEMINI_MODEL_NAME; + } + + // 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"); + } + + GenerateContentResponse response = + client.models.generateContent( + modelId, + "What is your name?", + GenerateContentConfig.builder() + .httpOptions( + HttpOptions.builder() + .extraBody( + ImmutableMap.of( + "systemInstruction", + ImmutableMap.of( + "parts", + ImmutableList.of( + ImmutableMap.of("text", "You are a chatbot."))))) + .build()) + .build()); + + System.out.println( + "GenerateContent prompt token count: " + response.usageMetadata().get().promptTokenCount()); + } + + private HttpOptionsExtraBody() {} +} diff --git a/examples/src/main/java/com/google/genai/examples/LiveAudioConversationAsync.java b/examples/src/main/java/com/google/genai/examples/LiveAudioConversationAsync.java index c127d81125e..e1a6c82e0a9 100644 --- a/examples/src/main/java/com/google/genai/examples/LiveAudioConversationAsync.java +++ b/examples/src/main/java/com/google/genai/examples/LiveAudioConversationAsync.java @@ -50,12 +50,16 @@ import com.google.genai.AsyncSession; import com.google.genai.Client; import com.google.genai.types.Blob; +import com.google.genai.types.AutomaticActivityDetection; +import com.google.genai.types.EndSensitivity; import com.google.genai.types.LiveConnectConfig; import com.google.genai.types.LiveSendRealtimeInputParameters; import com.google.genai.types.LiveServerMessage; import com.google.genai.types.Modality; +import com.google.genai.types.RealtimeInputConfig; import com.google.genai.types.PrebuiltVoiceConfig; import com.google.genai.types.SpeechConfig; +import com.google.genai.types.StartSensitivity; import com.google.genai.types.VoiceConfig; import java.util.Collection; import java.util.Optional; @@ -86,7 +90,6 @@ public final class LiveAudioConversationAsync { // -------------------------- private static volatile boolean running = true; - private static volatile boolean speakerPlaying = false; private static TargetDataLine microphoneLine; private static SourceDataLine speakerLine; private static AsyncSession session; @@ -113,8 +116,7 @@ private static void sendMicrophoneAudio() { while (running && microphoneLine != null && microphoneLine.isOpen()) { bytesRead = microphoneLine.read(buffer, 0, buffer.length); - if (bytesRead > 0 && !speakerPlaying) { - // Create a copy of the buffer with the actual bytes read + if (bytesRead > 0) { byte[] audioChunk = new byte[bytesRead]; System.arraycopy(buffer, 0, audioChunk, 0, bytesRead); @@ -153,14 +155,13 @@ public static void main(String[] args) throws LineUnavailableException { System.out.println("Using Gemini Developer API"); } - String modelId; - if (client.vertexAI()) { - modelId = "gemini-2.0-flash-live-preview-04-09"; - } else { - modelId = "gemini-live-2.5-flash-preview"; - } + final String modelId; if (args.length != 0) { modelId = args[0]; + } else if (client.vertexAI()) { + modelId = Constants.GEMINI_LIVE_MODEL_NAME; + } else { + modelId = Constants.GEMINI_LIVE_MODEL_NAME_PREVIEW; } // --- Audio Line Setup --- @@ -180,6 +181,14 @@ public static void main(String[] args) throws LineUnavailableException { .prebuiltVoiceConfig( PrebuiltVoiceConfig.builder().voiceName(voiceName))) .languageCode("en-US")) + .realtimeInputConfig( + RealtimeInputConfig.builder() + .automaticActivityDetection( + AutomaticActivityDetection.builder() + .startOfSpeechSensitivity(StartSensitivity.Known.START_SENSITIVITY_HIGH) + .endOfSpeechSensitivity(EndSensitivity.Known.END_SENSITIVITY_HIGH) + .prefixPaddingMs(5) + .silenceDurationMs(100))) .build(); // --- Shutdown Hook for Cleanup --- @@ -302,25 +311,35 @@ public static void handleAudioResponse(LiveServerMessage message) { .serverContent() .ifPresent( content -> { + // Handle interruptions from Gemini. + if (content.interrupted().orElse(false)) { + speakerLine.flush(); + return; // Skip processing the rest of this message's audio. + } + + // Handle Model turn completion. if (content.turnComplete().orElse(false)) { - // When interrupted, Gemini sends a turn_complete. - // Stop the speaker if the turn is complete. - if (speakerLine != null && speakerLine.isOpen()) { - speakerLine.flush(); - } - } else { - content.modelTurn().stream() - .flatMap(modelTurn -> modelTurn.parts().stream()) - .flatMap(Collection::stream) - .map(part -> part.inlineData().flatMap(Blob::data)) - .flatMap(Optional::stream) - .forEach( - audioBytes -> { - if (speakerLine != null && speakerLine.isOpen()) { - // Write audio data to the speaker - speakerLine.write(audioBytes, 0, audioBytes.length); - } - }); + // The turn is over, no more audio will be sent for this turn. + return; + } + + // Process audio content for playback. + content.modelTurn().stream() + .flatMap(modelTurn -> modelTurn.parts().stream()) + .flatMap(Collection::stream) + .map(part -> part.inlineData().flatMap(Blob::data)) + .flatMap(Optional::stream) + .forEach( + audioBytes -> { + if (speakerLine != null && speakerLine.isOpen()) { + // Write audio data to the speaker + speakerLine.write(audioBytes, 0, audioBytes.length); + } + }); + + // If this is the last message of a generation, drain the buffer. + if (content.generationComplete().orElse(false)) { + speakerLine.drain(); } }); } diff --git a/examples/src/main/java/com/google/genai/examples/LiveTextContextWindowCompressionAsync.java b/examples/src/main/java/com/google/genai/examples/LiveTextContextWindowCompressionAsync.java index aa4b7e636dd..526e4250a8e 100644 --- a/examples/src/main/java/com/google/genai/examples/LiveTextContextWindowCompressionAsync.java +++ b/examples/src/main/java/com/google/genai/examples/LiveTextContextWindowCompressionAsync.java @@ -77,14 +77,13 @@ public static void main(String[] args) { System.out.println("Using Gemini Developer API"); } - String modelId; - if (client.vertexAI()) { - modelId = "gemini-2.0-flash-live-preview-04-09"; - } else { - modelId = "gemini-live-2.5-flash-preview"; - } + final String modelId; if (args.length != 0) { modelId = args[0]; + } else if (client.vertexAI()) { + modelId = Constants.GEMINI_LIVE_MODEL_NAME; + } else { + modelId = Constants.GEMINI_LIVE_MODEL_NAME_PREVIEW; } // Configures live session and context window compression. diff --git a/examples/src/main/java/com/google/genai/examples/LiveTextConversationAsync.java b/examples/src/main/java/com/google/genai/examples/LiveTextConversationAsync.java index c0cef47f12e..de2f868c277 100644 --- a/examples/src/main/java/com/google/genai/examples/LiveTextConversationAsync.java +++ b/examples/src/main/java/com/google/genai/examples/LiveTextConversationAsync.java @@ -75,14 +75,13 @@ public static void main(String[] args) { System.out.println("Using Gemini Developer API"); } - String modelId; - if (client.vertexAI()) { - modelId = "gemini-2.0-flash-live-preview-04-09"; - } else { - modelId = "gemini-live-2.5-flash-preview"; - } + final String modelId; if (args.length != 0) { modelId = args[0]; + } else if (client.vertexAI()) { + modelId = Constants.GEMINI_LIVE_MODEL_NAME; + } else { + modelId = Constants.GEMINI_LIVE_MODEL_NAME_PREVIEW; } LiveConnectConfig config = diff --git a/examples/src/main/java/com/google/genai/examples/LiveTextConversationResumptionAsync.java b/examples/src/main/java/com/google/genai/examples/LiveTextConversationResumptionAsync.java index ea18e0eeeac..25bbc8cb5a2 100644 --- a/examples/src/main/java/com/google/genai/examples/LiveTextConversationResumptionAsync.java +++ b/examples/src/main/java/com/google/genai/examples/LiveTextConversationResumptionAsync.java @@ -70,11 +70,9 @@ public final class LiveTextConversationResumptionAsync { public static void main(String[] args) { - boolean containsModelId = false; // Get the session handle from the command line, if provided String sessionHandle = null; if (args.length > 1) { - containsModelId = true; if (args[1].startsWith("--session_handle")) { String[] parts = args[1].split("=", 2); if (parts.length == 2) { @@ -95,8 +93,6 @@ public static void main(String[] args) { System.err.println("Usage: mvn ... --session_handle="); System.exit(1); } - } else { - containsModelId = true; } } @@ -116,14 +112,13 @@ public static void main(String[] args) { System.out.println("Using Gemini Developer API"); } - String modelId; - if (client.vertexAI()) { - modelId = "gemini-2.0-flash-live-preview-04-09"; - } else { - modelId = "gemini-live-2.5-flash-preview"; - } - if (containsModelId) { + final String modelId; + if (args.length != 0) { modelId = args[0]; + } else if (client.vertexAI()) { + modelId = Constants.GEMINI_LIVE_MODEL_NAME; + } else { + modelId = Constants.GEMINI_LIVE_MODEL_NAME_PREVIEW; } SessionResumptionConfig.Builder sessionResumptionConfigBuilder = diff --git a/examples/src/main/java/com/google/genai/examples/LiveTextToAudioTranscriptionAsync.java b/examples/src/main/java/com/google/genai/examples/LiveTextToAudioTranscriptionAsync.java index 5690819f880..b6cd68d3989 100644 --- a/examples/src/main/java/com/google/genai/examples/LiveTextToAudioTranscriptionAsync.java +++ b/examples/src/main/java/com/google/genai/examples/LiveTextToAudioTranscriptionAsync.java @@ -80,14 +80,13 @@ public static void main(String[] args) { System.out.println("Using Gemini Developer API"); } - String modelId; - if (client.vertexAI()) { - modelId = "gemini-2.0-flash-live-preview-04-09"; - } else { - modelId = "gemini-live-2.5-flash-preview"; - } + final String modelId; if (args.length != 0) { modelId = args[0]; + } else if (client.vertexAI()) { + modelId = Constants.GEMINI_LIVE_MODEL_NAME; + } else { + modelId = Constants.GEMINI_LIVE_MODEL_NAME_PREVIEW; } // Sets the system instruction in the config. diff --git a/examples/src/main/java/com/google/genai/examples/LiveTextToTextGenerationAsync.java b/examples/src/main/java/com/google/genai/examples/LiveTextToTextGenerationAsync.java index 8e7541e9c04..92c1a11fd0f 100644 --- a/examples/src/main/java/com/google/genai/examples/LiveTextToTextGenerationAsync.java +++ b/examples/src/main/java/com/google/genai/examples/LiveTextToTextGenerationAsync.java @@ -73,14 +73,13 @@ public static void main(String[] args) { System.out.println("Using Gemini Developer API"); } - String modelId; - if (client.vertexAI()) { - modelId = "gemini-2.0-flash-live-preview-04-09"; - } else { - modelId = "gemini-live-2.5-flash-preview"; - } + final String modelId; if (args.length != 0) { modelId = args[0]; + } else if (client.vertexAI()) { + modelId = Constants.GEMINI_LIVE_MODEL_NAME; + } else { + modelId = Constants.GEMINI_LIVE_MODEL_NAME_PREVIEW; } LiveConnectConfig config = @@ -94,6 +93,8 @@ public static void main(String[] args) { .thenCompose( session -> { String inputText = "Write a short poem about a cat."; + System.out.println("Connecting to live session..."); + System.out.println(session.sessionId()); System.out.println("\n**Input**\n" + inputText); return session @@ -133,6 +134,8 @@ public static void printLiveServerMessage( // Check if the server's turn is complete and signal the allDone future if so. if (message.serverContent().flatMap(LiveServerContent::turnComplete).orElse(false)) { + System.out.println("\n**End of turn, full message: **\n"); + System.out.println(message); System.out.println(); allDone.complete(null); } diff --git a/examples/src/main/java/com/google/genai/examples/LocalComputeTokens.java b/examples/src/main/java/com/google/genai/examples/LocalComputeTokens.java new file mode 100644 index 00000000000..d142e31af94 --- /dev/null +++ b/examples/src/main/java/com/google/genai/examples/LocalComputeTokens.java @@ -0,0 +1,35 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Usage: + * + *

1. Compile the java package and run the sample code. + * + *

mvn clean compile exec:java -Dexec.mainClass="com.google.genai.examples.LocalComputeTokens" + */ +package com.google.genai.examples; + +import com.google.genai.LocalTokenizer; + +/** An example of using the Unified Gen AI Java SDK to compute tokens locally. */ +public class LocalComputeTokens { + public static void main(String[] args) { + LocalTokenizer tokenizer = new LocalTokenizer(Constants.GEMINI_MODEL_NAME); + System.out.println( + "Compute tokens for 'Hello world': " + tokenizer.computeTokens("Hello world").toJson()); + } +} diff --git a/examples/src/main/java/com/google/genai/examples/LocalCountTokens.java b/examples/src/main/java/com/google/genai/examples/LocalCountTokens.java new file mode 100644 index 00000000000..9e1c0fc425b --- /dev/null +++ b/examples/src/main/java/com/google/genai/examples/LocalCountTokens.java @@ -0,0 +1,35 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Usage: + * + *

1. Compile the java package and run the sample code. + * + *

mvn clean compile exec:java -Dexec.mainClass="com.google.genai.examples.LocalCountTokens" + */ +package com.google.genai.examples; + +import com.google.genai.LocalTokenizer; + +/** An example of using the Unified Gen AI Java SDK to count tokens locally. */ +public class LocalCountTokens { + public static void main(String[] args) { + LocalTokenizer tokenizer = new LocalTokenizer(Constants.GEMINI_MODEL_NAME); + System.out.println( + "Count for 'Hello world': " + tokenizer.countTokens("Hello world").totalTokens()); + } +} diff --git a/examples/src/main/java/com/google/genai/examples/ModelManagement.java b/examples/src/main/java/com/google/genai/examples/ModelManagement.java index f6652492d88..0c51973a64e 100644 --- a/examples/src/main/java/com/google/genai/examples/ModelManagement.java +++ b/examples/src/main/java/com/google/genai/examples/ModelManagement.java @@ -49,13 +49,13 @@ public final class ModelManagement { public static void main(String[] args) { - if (args.length == 0) { - System.out.println("Please provide a model ID on the -Dexec.args argument."); - return; + final String modelId; + if (args.length != 0) { + modelId = args[0]; + } else { + modelId = Constants.GEMINI_MODEL_NAME; } - String modelId = args[0]; - // 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 diff --git a/examples/src/main/java/com/google/genai/examples/ModelManagementAsync.java b/examples/src/main/java/com/google/genai/examples/ModelManagementAsync.java index 58829301c54..a310cc28d68 100644 --- a/examples/src/main/java/com/google/genai/examples/ModelManagementAsync.java +++ b/examples/src/main/java/com/google/genai/examples/ModelManagementAsync.java @@ -51,13 +51,13 @@ public final class ModelManagementAsync { public static void main(String[] args) { - if (args.length == 0) { - System.out.println("Please provide a model ID on the -Dexec.args argument."); - return; + final String modelId; + if (args.length != 0) { + modelId = args[0]; + } else { + modelId = Constants.GEMINI_MODEL_NAME; } - String modelId = args[0]; - // 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 diff --git a/examples/src/main/java/com/google/genai/examples/RecontextImageAsync.java b/examples/src/main/java/com/google/genai/examples/RecontextImageAsync.java new file mode 100644 index 00000000000..aab3a33b777 --- /dev/null +++ b/examples/src/main/java/com/google/genai/examples/RecontextImageAsync.java @@ -0,0 +1,114 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Usage: + * + *

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 + * + *

mvn exec:java -Dexec.mainClass="com.google.genai.examples.RecontextImageAsync" + * -Dexec.args="YOUR_MODEL_ID" + */ +package com.google.genai.examples; + +import com.google.genai.Client; +import com.google.genai.types.Image; +import com.google.genai.types.ProductImage; +import com.google.genai.types.RecontextImageConfig; +import com.google.genai.types.RecontextImageResponse; +import com.google.genai.types.RecontextImageSource; +import java.util.ArrayList; +import java.util.concurrent.CompletableFuture; + +/** + * An example of using the Unified Gen AI Java SDK to recontextualize an image (product recontext) + * asynchronously. + */ +public final class RecontextImageAsync { + public static void main(String[] args) { + final String modelId; + if (args.length != 0) { + modelId = args[0]; + } else { + modelId = Constants.IMAGEN_RECONTEXT_MODEL_NAME; + } + + // 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("Gemini Developer API is not supported for this example."); + System.exit(0); + } + + Image productImageBackpack = + Image.builder().gcsUri("gs://genai-sdk-tests/inputs/images/backpack1.png").build(); + + RecontextImageConfig recontextImageConfig = + RecontextImageConfig.builder().numberOfImages(1).outputMimeType("image/jpeg").build(); + + ArrayList productImages = new ArrayList<>(); + ProductImage productImage = ProductImage.builder().productImage(productImageBackpack).build(); + productImages.add(productImage); + + RecontextImageSource recontextImageSource = + RecontextImageSource.builder() + .prompt("On a school desk.") + .productImages(productImages) + .build(); + + CompletableFuture recontextImageResponseFuture = + client.async.models.recontextImage(modelId, recontextImageSource, recontextImageConfig); + + recontextImageResponseFuture + .thenAccept( + recontextImageResponse -> { + Image generatedImage = + recontextImageResponse.generatedImages().get().get(0).image().get(); + // Do something with generatedImage. + }) + .join(); + } + + private RecontextImageAsync() {} +} diff --git a/examples/src/main/java/com/google/genai/examples/RecontextImageProductRecontext.java b/examples/src/main/java/com/google/genai/examples/RecontextImageProductRecontext.java new file mode 100644 index 00000000000..5bddb418e12 --- /dev/null +++ b/examples/src/main/java/com/google/genai/examples/RecontextImageProductRecontext.java @@ -0,0 +1,106 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Usage: + * + *

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 + * + *

mvn exec:java -Dexec.mainClass="com.google.genai.examples.RecontextImageProductRecontext" + * -Dexec.args="YOUR_MODEL_ID" + */ +package com.google.genai.examples; + +import com.google.genai.Client; +import com.google.genai.types.Image; +import com.google.genai.types.ProductImage; +import com.google.genai.types.RecontextImageConfig; +import com.google.genai.types.RecontextImageResponse; +import com.google.genai.types.RecontextImageSource; +import java.util.ArrayList; + +/** + * An example of using the Unified Gen AI Java SDK to recontextualize an image (product recontext). + */ +public final class RecontextImageProductRecontext { + public static void main(String[] args) { + final String modelId; + if (args.length != 0) { + modelId = args[0]; + } else { + modelId = Constants.IMAGEN_RECONTEXT_MODEL_NAME; + } + + // 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("Gemini Developer API is not supported for this example."); + System.exit(0); + } + + Image productImageBackpack = + Image.builder().gcsUri("gs://genai-sdk-tests/inputs/images/backpack1.png").build(); + + RecontextImageConfig recontextImageConfig = + RecontextImageConfig.builder().numberOfImages(1).outputMimeType("image/jpeg").build(); + + ArrayList productImages = new ArrayList<>(); + ProductImage productImage = ProductImage.builder().productImage(productImageBackpack).build(); + productImages.add(productImage); + + RecontextImageSource recontextImageSource = + RecontextImageSource.builder() + .prompt("On a school desk.") + .productImages(productImages) + .build(); + + RecontextImageResponse recontextImageResponse = + client.models.recontextImage(modelId, recontextImageSource, recontextImageConfig); + + Image generatedImage = recontextImageResponse.generatedImages().get().get(0).image().get(); + // Do something with generatedImage. + } + + private RecontextImageProductRecontext() {} +} diff --git a/examples/src/main/java/com/google/genai/examples/RecontextImageVirtualTryOn.java b/examples/src/main/java/com/google/genai/examples/RecontextImageVirtualTryOn.java new file mode 100644 index 00000000000..28e12fb1ccc --- /dev/null +++ b/examples/src/main/java/com/google/genai/examples/RecontextImageVirtualTryOn.java @@ -0,0 +1,107 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Usage: + * + *

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 + * + *

mvn exec:java -Dexec.mainClass="com.google.genai.examples.RecontextImageVirtualTryOn" + * -Dexec.args="YOUR_MODEL_ID" + */ +package com.google.genai.examples; + +import com.google.genai.Client; +import com.google.genai.types.Image; +import com.google.genai.types.ProductImage; +import com.google.genai.types.RecontextImageConfig; +import com.google.genai.types.RecontextImageResponse; +import com.google.genai.types.RecontextImageSource; +import java.util.ArrayList; + +/** An example of using the Unified Gen AI Java SDK to recontextualize an image (virtual try-on). */ +public final class RecontextImageVirtualTryOn { + public static void main(String[] args) { + final String modelId; + if (args.length != 0) { + modelId = args[0]; + } else { + modelId = Constants.VIRTUAL_TRY_ON_MODEL_NAME; + } + + // 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("Gemini Developer API is not supported for this example."); + System.exit(0); + } + + Image productImagePants = + Image.builder().gcsUri("gs://genai-sdk-tests/inputs/images/pants.jpg").build(); + + Image personImage = + Image.builder().gcsUri("gs://genai-sdk-tests/inputs/images/man.jpg").build(); + + RecontextImageConfig recontextImageConfig = + RecontextImageConfig.builder().numberOfImages(1).outputMimeType("image/jpeg").build(); + + ArrayList productImages = new ArrayList<>(); + ProductImage productImage = ProductImage.builder().productImage(productImagePants).build(); + productImages.add(productImage); + + RecontextImageSource recontextImageSource = + RecontextImageSource.builder() + .personImage(personImage) + .productImages(productImages) + .build(); + + RecontextImageResponse recontextImageResponse = + client.models.recontextImage(modelId, recontextImageSource, recontextImageConfig); + + Image generatedImage = recontextImageResponse.generatedImages().get().get(0).image().get(); + // Do something with generatedImage. + } + + private RecontextImageVirtualTryOn() {} +} diff --git a/examples/src/main/java/com/google/genai/examples/RequestLevelHttpOptions.java b/examples/src/main/java/com/google/genai/examples/RequestLevelHttpOptions.java index 5ba7dd1e712..d21ecee4850 100644 --- a/examples/src/main/java/com/google/genai/examples/RequestLevelHttpOptions.java +++ b/examples/src/main/java/com/google/genai/examples/RequestLevelHttpOptions.java @@ -47,13 +47,16 @@ import com.google.genai.types.GenerateContentConfig; import com.google.genai.types.GenerateContentResponse; import com.google.genai.types.HttpOptions; +import com.google.genai.types.HttpRetryOptions; /** An example of setting http options at request level. */ public final class RequestLevelHttpOptions { public static void main(String[] args) { - String modelId = "gemini-2.0-flash-001"; + final String modelId; if (args.length != 0) { modelId = args[0]; + } else { + modelId = Constants.GEMINI_MODEL_NAME; } // Instantiate the client. The client by default uses the Gemini Developer API. It gets the API @@ -72,10 +75,13 @@ public static void main(String[] args) { System.out.println("Using Gemini Developer API"); } - // Set a customized header per request config. + // Set a customized header and retry options per request config. GenerateContentConfig config = GenerateContentConfig.builder() - .httpOptions(HttpOptions.builder().headers(ImmutableMap.of("my-header", "my-value"))) + .httpOptions( + HttpOptions.builder() + .headers(ImmutableMap.of("my-header", "my-value")) + .retryOptions(HttpRetryOptions.builder().attempts(3).httpStatusCodes(408, 429))) .build(); GenerateContentResponse response = diff --git a/examples/src/main/java/com/google/genai/examples/SegmentImage.java b/examples/src/main/java/com/google/genai/examples/SegmentImage.java new file mode 100644 index 00000000000..9adcf6f93a3 --- /dev/null +++ b/examples/src/main/java/com/google/genai/examples/SegmentImage.java @@ -0,0 +1,96 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * 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 + * + *

mvn exec:java -Dexec.mainClass="com.google.genai.examples.SegmentImage" + * -Dexec.args="YOUR_MODEL_ID" + */ +package com.google.genai.examples; + +import com.google.genai.Client; +import com.google.genai.types.Image; +import com.google.genai.types.SegmentImageConfig; +import com.google.genai.types.SegmentImageResponse; +import com.google.genai.types.SegmentImageSource; +import com.google.genai.types.SegmentMode; + +/** An example of using the Unified Gen AI Java SDK to segment an image. */ +public final class SegmentImage { + public static void main(String[] args) { + final String modelId; + if (args.length != 0) { + modelId = args[0]; + } else { + modelId = Constants.SEGMENT_IMAGE_MODEL_NAME; + } + + // 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("Gemini Developer API is not supported for this example."); + System.exit(0); + } + + // Base image created using generateImages with prompt: + // "A square, circle, and triangle with a white background" + Image image = Image.fromFile("./resources/shapes.jpg"); + + // Control reference. + SegmentImageConfig segmentImageConfig = + SegmentImageConfig.builder().mode(SegmentMode.Known.FOREGROUND).build(); + + SegmentImageResponse segmentImageResponse = + client.models.segmentImage( + modelId, SegmentImageSource.builder().image(image).build(), segmentImageConfig); + + Image maskImage = segmentImageResponse.generatedMasks().get().get(0).mask().get(); + // Do something with maskImage. + } + + private SegmentImage() {} +} diff --git a/examples/src/main/java/com/google/genai/examples/SegmentImageAsync.java b/examples/src/main/java/com/google/genai/examples/SegmentImageAsync.java new file mode 100644 index 00000000000..32ffead7e76 --- /dev/null +++ b/examples/src/main/java/com/google/genai/examples/SegmentImageAsync.java @@ -0,0 +1,102 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Usage: + * + *

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 + * + *

mvn exec:java -Dexec.mainClass="com.google.genai.examples.SegmentImage" + * -Dexec.args="YOUR_MODEL_ID" + */ +package com.google.genai.examples; + +import com.google.genai.Client; +import com.google.genai.types.Image; +import com.google.genai.types.SegmentImageConfig; +import com.google.genai.types.SegmentImageResponse; +import com.google.genai.types.SegmentImageSource; +import com.google.genai.types.SegmentMode; +import java.util.concurrent.CompletableFuture; + +/** An example of using the Unified Gen AI Java SDK to segment an image asynchronously. */ +public final class SegmentImageAsync { + public static void main(String[] args) { + final String modelId; + if (args.length != 0) { + modelId = args[0]; + } else { + modelId = Constants.SEGMENT_IMAGE_MODEL_NAME; + } + + // 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("Gemini Developer API is not supported for this example."); + System.exit(0); + } + + // Base image created using generateImages with prompt: + // "A square, circle, and triangle with a white background" + Image image = Image.fromFile("./resources/shapes.jpg"); + + // Control reference. + SegmentImageConfig segmentImageConfig = + SegmentImageConfig.builder().mode(SegmentMode.Known.FOREGROUND).build(); + + CompletableFuture segmentImageResponseFuture = + client.async.models.segmentImage( + modelId, SegmentImageSource.builder().image(image).build(), segmentImageConfig); + + segmentImageResponseFuture + .thenAccept( + segmentImageResponse -> { + Image maskImage = segmentImageResponse.generatedMasks().get().get(0).mask().get(); + // Do something with maskImage. + }) + .join(); + } + + private SegmentImageAsync() {} +} diff --git a/examples/src/main/java/com/google/genai/examples/TuningJobs.java b/examples/src/main/java/com/google/genai/examples/TuningJobs.java index 67765fcdde0..05f323a6164 100644 --- a/examples/src/main/java/com/google/genai/examples/TuningJobs.java +++ b/examples/src/main/java/com/google/genai/examples/TuningJobs.java @@ -51,9 +51,11 @@ public final class TuningJobs { public static void main(String[] args) { - String modelId = "gemini-2.0-flash-001"; + final String modelId; if (args.length != 0) { modelId = args[0]; + } else { + modelId = Constants.GEMINI_MODEL_NAME; } // Instantiate the client. The client by default uses the Gemini Developer API. It gets the API diff --git a/examples/src/main/java/com/google/genai/examples/TuningJobsAsync.java b/examples/src/main/java/com/google/genai/examples/TuningJobsAsync.java index b76235894fb..442a062ba2a 100644 --- a/examples/src/main/java/com/google/genai/examples/TuningJobsAsync.java +++ b/examples/src/main/java/com/google/genai/examples/TuningJobsAsync.java @@ -56,9 +56,11 @@ public final class TuningJobsAsync { public static void main(String[] args) { - String modelId = "gemini-2.0-flash-001"; + final String modelId; if (args.length != 0) { modelId = args[0]; + } else { + modelId = Constants.GEMINI_MODEL_NAME; } // Instantiate the client. The client by default uses the Gemini Developer API. It gets the API diff --git a/examples/src/main/java/com/google/genai/examples/UpscaleImage.java b/examples/src/main/java/com/google/genai/examples/UpscaleImage.java index ef726d4c105..a7fa7393561 100644 --- a/examples/src/main/java/com/google/genai/examples/UpscaleImage.java +++ b/examples/src/main/java/com/google/genai/examples/UpscaleImage.java @@ -48,9 +48,11 @@ /** An example of using the Unified Gen AI Java SDK to upscale an image. */ public final class UpscaleImage { public static void main(String[] args) { - String modelId = "imagen-3.0-generate-001"; + final String modelId; if (args.length != 0) { modelId = args[0]; + } else { + modelId = Constants.IMAGEN_CAPABILITY_MODEL_NAME; } // Instantiate the client. The client by default uses the Gemini Developer API. It gets the API @@ -66,7 +68,8 @@ public static void main(String[] args) { if (client.vertexAI()) { System.out.println("Using Vertex AI"); } else { - System.out.println("Using Gemini Developer API"); + System.out.println("Gemini Developer API is not supported for this example."); + System.exit(0); } // Base image created using generateImages with prompt: diff --git a/examples/src/main/java/com/google/genai/examples/UpscaleImageAsync.java b/examples/src/main/java/com/google/genai/examples/UpscaleImageAsync.java index 0f7e136bf3b..df3e099c881 100644 --- a/examples/src/main/java/com/google/genai/examples/UpscaleImageAsync.java +++ b/examples/src/main/java/com/google/genai/examples/UpscaleImageAsync.java @@ -49,9 +49,11 @@ /** An example of using the Unified Gen AI Java SDK to upscale an image asynchronously. */ public final class UpscaleImageAsync { public static void main(String[] args) { - String modelId = "imagen-3.0-generate-001"; + final String modelId; if (args.length != 0) { modelId = args[0]; + } else { + modelId = Constants.IMAGEN_CAPABILITY_MODEL_NAME; } // Instantiate the client. The client by default uses the Gemini Developer API. It gets the API @@ -67,7 +69,8 @@ public static void main(String[] args) { if (client.vertexAI()) { System.out.println("Using Vertex AI"); } else { - System.out.println("Using Gemini Developer API"); + System.out.println("Gemini Developer API is not supported for this example."); + System.exit(0); } // Base image created using generateImages with prompt: diff --git a/pom.xml b/pom.xml index caea5b8c446..b71713b2c2f 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.google.genai google-genai google-genai - 1.11.0-SNAPSHOT + 1.26.0-SNAPSHOT jar Java idiomatic SDK for the Gemini Developer APIs and Vertex AI APIs. @@ -47,6 +47,7 @@ 1.8 1.8 1.33.0 + 3.25.1 2.47.0 4.5.14 1.11.0 @@ -90,11 +91,6 @@ httpclient ${apache.httpcomponents.httpclient.version} - - com.google.auto.value - auto-value - ${auto-value.version} - com.google.auto.value auto-value-annotations @@ -130,6 +126,11 @@ okhttp ${okhttp.version} + + com.google.protobuf + protobuf-java + ${protobuf.version} + org.junit.jupiter @@ -155,12 +156,6 @@ jspecify 1.0.0 - - com.github.tomakehurst - wiremock-jre8 - 2.35.0 - test - org.jetbrains.kotlin @@ -170,6 +165,13 @@ + + + kr.motd.maven + os-maven-plugin + 1.7.1 + + @@ -193,6 +195,9 @@ ${auto-value.version} + + -parameters + @@ -200,20 +205,27 @@ 3.5.2 - - me.fabriciorby - maven-surefire-junit5-tree-reporter - 0.1.0 - + + me.fabriciorby + maven-surefire-junit5-tree-reporter + 0.1.0 + - plain - + plain + maven-jar-plugin - 3.0.2 + 3.3.0 + + + + com.google.genai + + + maven-install-plugin @@ -259,16 +271,6 @@ - - org.apache.maven.plugins - maven-compiler-plugin - 3.14.0 - - - -parameters - - - org.apache.maven.plugins maven-javadoc-plugin @@ -313,6 +315,7 @@ test report + check @@ -321,6 +324,85 @@ com/google/genai/types/AutoValue_*.class + + + PACKAGE + + com.google.genai + + + + INSTRUCTION + COVEREDRATIO + + 0.70 + + + + + PACKAGE + + com.google.genai.errors + + + + INSTRUCTION + COVEREDRATIO + 0.95 + + + + + PACKAGE + + com.google.genai.types + + + + INSTRUCTION + COVEREDRATIO + + 0.40 + + + + + + + + + + org.xolstice.maven.plugins + protobuf-maven-plugin + 0.6.1 + + com.google.protobuf:protoc:${protobuf.version}:exe:${os.detected.classifier} + ${project.basedir}/src/main/proto + + + + + compile + test-compile + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 3.5.0 + + + add-source + generate-sources + + add-source + + + + ${project.build.directory}/generated-sources/protobuf/java + diff --git a/run_shared_tests.sh b/run_shared_tests.sh new file mode 100755 index 00000000000..d84285b67e7 --- /dev/null +++ b/run_shared_tests.sh @@ -0,0 +1,12 @@ +#!/bin/bash + +export GOOGLE_GENAI_CLIENT_MODE=api +export GOOGLE_GENAI_TESTS_SUBDIR=shared +REPLAYS_DIR="$(blaze info workspace 2>/dev/null)/google/cloud/aiplatform/sdk/genai/replays" +export GOOGLE_GENAI_REPLAYS_DIRECTORY="$REPLAYS_DIR" + +echo "Replays directory: $GOOGLE_GENAI_REPLAYS_DIRECTORY" +echo "Client mode: $GOOGLE_GENAI_CLIENT_MODE" +echo "Tests subdirectory: $GOOGLE_GENAI_TESTS_SUBDIR" +echo "Running shared table tests in API mode..." +mvn clean test -Dtest=TableTest -Djacoco.skip=true && mvn clean diff --git a/src/main/java/com/google/genai/ApiClient.java b/src/main/java/com/google/genai/ApiClient.java index 48d5f3c7878..ecd5414c559 100644 --- a/src/main/java/com/google/genai/ApiClient.java +++ b/src/main/java/com/google/genai/ApiClient.java @@ -19,18 +19,22 @@ import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.ImmutableMap.toImmutableMap; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; import com.google.auth.oauth2.GoogleCredentials; import com.google.common.base.Ascii; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; -import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.genai.errors.GenAiIOException; import com.google.genai.types.ClientOptions; import com.google.genai.types.HttpOptions; +import com.google.genai.types.HttpRetryOptions; import java.io.IOException; import java.time.Duration; +import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.concurrent.CompletableFuture; import java.util.logging.Logger; import java.util.stream.Stream; import okhttp3.Dispatcher; @@ -40,12 +44,11 @@ import okhttp3.RequestBody; import org.jspecify.annotations.Nullable; - /** Interface for an API client which issues HTTP requests to the GenAI APIs. */ abstract class ApiClient { // {x-version-update-start:google-genai:released} - private static final String SDK_VERSION = "1.10.0"; + private static final String SDK_VERSION = "1.25.0"; // {x-version-update-end:google-genai:released} private static final Logger logger = Logger.getLogger(ApiClient.class.getName()); @@ -99,7 +102,7 @@ protected ApiClient( this.httpOptions = mergeHttpOptions(customHttpOptions.get()); } - this.httpClient = createHttpClient(httpOptions.timeout(), clientOptions); + this.httpClient = createHttpClient(httpOptions, clientOptions); } ApiClient( @@ -187,14 +190,18 @@ protected ApiClient( apiKeyValue = null; } + if (locationValue == null && apiKeyValue == null) { + locationValue = "global"; + } + this.apiKey = Optional.ofNullable(apiKeyValue); this.project = Optional.ofNullable(projectValue); this.location = Optional.ofNullable(locationValue); // Validate that either project and location or API key is set. - if (!((this.project.isPresent() && this.location.isPresent()) || this.apiKey.isPresent())) { + if (!(this.project.isPresent() || this.apiKey.isPresent())) { throw new IllegalArgumentException( - "For Vertex AI APIs, either project/location or API key must be set."); + "For Vertex AI APIs, either project or API key must be set."); } // Only set credentials if using project/location. @@ -211,18 +218,24 @@ protected ApiClient( this.httpOptions = mergeHttpOptions(customHttpOptions.get()); } this.vertexAI = true; - this.httpClient = createHttpClient(httpOptions.timeout(), clientOptions); + this.httpClient = createHttpClient(httpOptions, clientOptions); } private OkHttpClient createHttpClient( - Optional timeout, Optional clientOptions) { + HttpOptions httpOptions, Optional clientOptions) { OkHttpClient.Builder builder = new OkHttpClient.Builder(); // Remove timeouts by default (OkHttp has a default of 10 seconds) builder.connectTimeout(Duration.ofMillis(0)); builder.readTimeout(Duration.ofMillis(0)); builder.writeTimeout(Duration.ofMillis(0)); - timeout.ifPresent(connectTimeout -> builder.connectTimeout(Duration.ofMillis(connectTimeout))); + httpOptions + .timeout() + .ifPresent(connectTimeout -> builder.connectTimeout(Duration.ofMillis(connectTimeout))); + + HttpRetryOptions retryOptions = + httpOptions.retryOptions().orElse(HttpRetryOptions.builder().build()); + builder.addInterceptor(new RetryInterceptor(retryOptions)); clientOptions.ifPresent( options -> { @@ -236,6 +249,7 @@ private OkHttpClient createHttpClient( } /** Builds a HTTP request given the http method, path, and request json string. */ + @SuppressWarnings("unchecked") protected Request buildRequest( String httpMethod, String path, @@ -280,15 +294,41 @@ protected Request buildRequest( throw new IllegalArgumentException("Unsupported HTTP method: " + capitalizedHttpMethod); } + ObjectMapper objectMapper = new ObjectMapper(); RequestBody body; if (METHODS_WITH_BODY.contains(capitalizedHttpMethod)) { body = RequestBody.create(requestJson, MediaType.parse("application/json")); } else { body = null; } + + if (mergedHttpOptions.extraBody().isPresent() && body != null) { + try { + Map requestBodyMap = objectMapper.readValue(requestJson, Map.class); + mergeMaps(requestBodyMap, mergedHttpOptions.extraBody().get()); + requestJson = objectMapper.writeValueAsString(requestBodyMap); + body = RequestBody.create(requestJson, MediaType.parse("application/json")); + } catch (JsonProcessingException e) { + logger.warning("Failed to merge extraBody into request body: " + e.getMessage()); + // If merging fails, proceed with the original request body + body = RequestBody.create(requestJson, MediaType.parse("application/json")); + } + } else if (mergedHttpOptions.extraBody().isPresent()) { + logger.warning( + "HttpOptions.extraBody is set, but the HTTP method does not support a request body. " + + "The extraBody will be ignored."); + } + Request.Builder requestBuilder = new Request.Builder().url(requestUrl).method(capitalizedHttpMethod, body); + requestHttpOptions.ifPresent( + httpOptions -> { + if (httpOptions.retryOptions().isPresent()) { + requestBuilder.tag(HttpRetryOptions.class, mergedHttpOptions.retryOptions().get()); + } + }); + setHeaders(requestBuilder, mergedHttpOptions); return requestBuilder.build(); } @@ -304,6 +344,12 @@ protected Request buildRequest( RequestBody body = RequestBody.create(requestBytes, MediaType.get("application/octet-stream")); Request.Builder requestBuilder = new Request.Builder().url(url).post(body); + requestHttpOptions.ifPresent( + httpOptions -> { + if (httpOptions.retryOptions().isPresent()) { + requestBuilder.tag(HttpRetryOptions.class, mergedHttpOptions.retryOptions().get()); + } + }); setHeaders(requestBuilder, mergedHttpOptions); return requestBuilder.build(); } else { @@ -341,7 +387,6 @@ private void setHeaders(Request.Builder request, HttpOptions requestHttpOptions) } /** Sends a Http request given the http method, path, and request json string. */ - @CanIgnoreReturnValue public abstract ApiResponse request( String httpMethod, String path, String requestJson, Optional httpOptions); @@ -349,6 +394,20 @@ public abstract ApiResponse request( public abstract ApiResponse request( String httpMethod, String path, byte[] requestBytes, Optional httpOptions); + /** + * Sends an asynchronous Http request given the http method, path, request json string, and http + * options. + */ + public abstract CompletableFuture asyncRequest( + String httpMethod, String path, String requestJson, Optional httpOptions); + + /** + * Sends an asynchronous Http request given the http method, path, request bytes, and http + * options. + */ + public abstract CompletableFuture asyncRequest( + String httpMethod, String path, byte[] requestBytes, Optional httpOptions); + /** Returns the library version. */ static String libraryVersion() { // TODO: Automate revisions to the SDK library version. @@ -382,6 +441,47 @@ OkHttpClient httpClient() { return httpClient; } + /** + * Merges two maps recursively. If a key exists in both maps, the value from `source` overwrites + * the value in `target`. If the value is a list, then update the whole list. A warning is logged + * if the types of the values for the same key are different. + * + * @param target The target map to merge into. + * @param source The source map to merge from. + */ + @SuppressWarnings("unchecked") + private void mergeMaps(Map target, Map source) { + for (Map.Entry entry : source.entrySet()) { + String key = entry.getKey(); + Object sourceValue = entry.getValue(); + + if (target.containsKey(key)) { + Object targetValue = target.get(key); + + if (targetValue instanceof Map && sourceValue instanceof Map) { + // Both values are maps, recursively merge them + mergeMaps((Map) targetValue, (Map) sourceValue); + } else if (targetValue instanceof List && sourceValue instanceof List) { + // Both values are lists, replace the target list with the source list + target.put(key, sourceValue); + } else { + // Values are not both maps or both lists, check if they have the same type + if (targetValue.getClass() != sourceValue.getClass()) { + logger.warning( + String.format( + "Type mismatch for key '%s'. Original type: %s, new type: %s. Overwriting" + + " with the new value.", + key, targetValue.getClass().getName(), sourceValue.getClass().getName())); + } + target.put(key, sourceValue); + } + } else { + // Key does not exist in target, add it + target.put(key, sourceValue); + } + } + } + private Optional> getTimeoutHeader(HttpOptions httpOptionsToApply) { if (httpOptionsToApply.timeout().isPresent()) { int timeoutInSeconds = (int) Math.ceil((double) httpOptionsToApply.timeout().get() / 1000.0); @@ -402,15 +502,13 @@ HttpOptions mergeHttpOptions(HttpOptions httpOptionsToApply) { return this.httpOptions; } HttpOptions.Builder mergedHttpOptionsBuilder = this.httpOptions.toBuilder(); - if (httpOptionsToApply.baseUrl().isPresent()) { - mergedHttpOptionsBuilder.baseUrl(httpOptionsToApply.baseUrl().get()); - } - if (httpOptionsToApply.apiVersion().isPresent()) { - mergedHttpOptionsBuilder.apiVersion(httpOptionsToApply.apiVersion().get()); - } - if (httpOptionsToApply.timeout().isPresent()) { - mergedHttpOptionsBuilder.timeout(httpOptionsToApply.timeout().get()); - } + + httpOptionsToApply.baseUrl().ifPresent(mergedHttpOptionsBuilder::baseUrl); + httpOptionsToApply.apiVersion().ifPresent(mergedHttpOptionsBuilder::apiVersion); + httpOptionsToApply.timeout().ifPresent(mergedHttpOptionsBuilder::timeout); + httpOptionsToApply.extraBody().ifPresent(mergedHttpOptionsBuilder::extraBody); + httpOptionsToApply.retryOptions().ifPresent(mergedHttpOptionsBuilder::retryOptions); + if (httpOptionsToApply.headers().isPresent()) { Stream> headersStream = Stream.concat( @@ -426,6 +524,7 @@ HttpOptions mergeHttpOptions(HttpOptions httpOptionsToApply) { toImmutableMap(Map.Entry::getKey, Map.Entry::getValue, (val1, val2) -> val2)); mergedHttpOptionsBuilder.headers(mergedHeaders); } + return mergedHttpOptionsBuilder.build(); } diff --git a/src/main/java/com/google/genai/AsyncBatches.java b/src/main/java/com/google/genai/AsyncBatches.java index f5f61ba3a62..64e7f9edd4e 100644 --- a/src/main/java/com/google/genai/AsyncBatches.java +++ b/src/main/java/com/google/genai/AsyncBatches.java @@ -20,26 +20,59 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; +import com.google.genai.Common.BuiltRequest; import com.google.genai.errors.GenAiIOException; import com.google.genai.types.BatchJob; import com.google.genai.types.BatchJobSource; import com.google.genai.types.CancelBatchJobConfig; import com.google.genai.types.CreateBatchJobConfig; +import com.google.genai.types.CreateEmbeddingsBatchJobConfig; import com.google.genai.types.DeleteBatchJobConfig; import com.google.genai.types.DeleteResourceJob; +import com.google.genai.types.EmbeddingsBatchJobSource; import com.google.genai.types.GetBatchJobConfig; import com.google.genai.types.ListBatchJobsConfig; +import com.google.genai.types.ListBatchJobsResponse; import java.util.concurrent.CompletableFuture; import java.util.function.Function; /** Async module of {@link Batches} */ public final class AsyncBatches { + Batches batches; + ApiClient apiClient; public AsyncBatches(ApiClient apiClient) { + this.apiClient = apiClient; this.batches = new Batches(apiClient); } + CompletableFuture privateCreate( + String model, BatchJobSource src, CreateBatchJobConfig config) { + BuiltRequest builtRequest = batches.buildRequestForPrivateCreate(model, src, config); + return this.apiClient + .asyncRequest("post", builtRequest.path, builtRequest.body, builtRequest.httpOptions) + .thenApplyAsync( + response -> { + try (ApiResponse res = response) { + return batches.processResponseForPrivateCreate(res, config); + } + }); + } + + CompletableFuture privateCreateEmbeddings( + String model, EmbeddingsBatchJobSource src, CreateEmbeddingsBatchJobConfig config) { + BuiltRequest builtRequest = batches.buildRequestForPrivateCreateEmbeddings(model, src, config); + return this.apiClient + .asyncRequest("post", builtRequest.path, builtRequest.body, builtRequest.httpOptions) + .thenApplyAsync( + response -> { + try (ApiResponse res = response) { + return batches.processResponseForPrivateCreateEmbeddings(res, config); + } + }); + } + /** * Asynchronously gets a batch job resource. * @@ -50,7 +83,15 @@ public AsyncBatches(ApiClient apiClient) { * @return A {@link BatchJob} object that contains the info of the batch job. */ public CompletableFuture get(String name, GetBatchJobConfig config) { - return CompletableFuture.supplyAsync(() -> batches.get(name, config)); + BuiltRequest builtRequest = batches.buildRequestForGet(name, config); + return this.apiClient + .asyncRequest("get", builtRequest.path, builtRequest.body, builtRequest.httpOptions) + .thenApplyAsync( + response -> { + try (ApiResponse res = response) { + return batches.processResponseForGet(res, config); + } + }); } /** @@ -62,7 +103,25 @@ public CompletableFuture get(String name, GetBatchJobConfig config) { * @param config A {@link CancelBatchJobConfig} for configuring the cancel request. */ public CompletableFuture cancel(String name, CancelBatchJobConfig config) { - return CompletableFuture.runAsync(() -> batches.cancel(name, config)); + BuiltRequest builtRequest = batches.buildRequestForCancel(name, config); + return this.apiClient + .asyncRequest("post", builtRequest.path, builtRequest.body, builtRequest.httpOptions) + .thenAccept( + response -> { + try (ApiResponse res = response) {} + }); + } + + CompletableFuture privateList(ListBatchJobsConfig config) { + BuiltRequest builtRequest = batches.buildRequestForPrivateList(config); + return this.apiClient + .asyncRequest("get", builtRequest.path, builtRequest.body, builtRequest.httpOptions) + .thenApplyAsync( + response -> { + try (ApiResponse res = response) { + return batches.processResponseForPrivateList(res, config); + } + }); } /** @@ -74,7 +133,15 @@ public CompletableFuture cancel(String name, CancelBatchJobConfig config) * @param config A {@link DeleteBatchJobConfig} for configuring the delete request. */ public CompletableFuture delete(String name, DeleteBatchJobConfig config) { - return CompletableFuture.supplyAsync(() -> batches.delete(name, config)); + BuiltRequest builtRequest = batches.buildRequestForDelete(name, config); + return this.apiClient + .asyncRequest("delete", builtRequest.path, builtRequest.body, builtRequest.httpOptions) + .thenApplyAsync( + response -> { + try (ApiResponse res = response) { + return batches.processResponseForDelete(res, config); + } + }); } /** @@ -87,7 +154,47 @@ public CompletableFuture delete(String name, DeleteBatchJobCo */ public CompletableFuture create( String model, BatchJobSource src, CreateBatchJobConfig config) { - return CompletableFuture.supplyAsync(() -> batches.create(model, src, config)); + if (this.apiClient.vertexAI()) { + if (src.inlinedRequests().isPresent()) { + throw new GenAiIOException("inlinedRequests is not supported for Vertex AI."); + } + if (src.fileName().isPresent()) { + throw new GenAiIOException("fileName is not supported for Vertex AI."); + } + if (src.gcsUri().isPresent() && src.bigqueryUri().isPresent()) { + throw new GenAiIOException("Only one of gcsUri and bigqueryUri can be set."); + } + if (!src.gcsUri().isPresent() && !src.bigqueryUri().isPresent()) { + throw new GenAiIOException("One of gcsUri and bigqueryUri must be set."); + } + } else { + if (src.fileName().isPresent() && src.inlinedRequests().isPresent()) { + throw new GenAiIOException("Only one of fileName and InlinedRequests can be set."); + } + if (!src.fileName().isPresent() && !src.inlinedRequests().isPresent()) { + throw new GenAiIOException("one of fileName and InlinedRequests must be set."); + } + } + return this.privateCreate(model, src, config); + } + + /** + * Makes an API request to create the batch embeddings job. + * + *

This method is experimental. + * + * @param model the name of the GenAI model to use for generation + * @param src The {@link EmbeddingsBatchJobSource} of the batch job. + * @param config The configuration {@link CreateEmbeddingsBatchJobConfig} for the batch job. + * @return A BatchJob. + */ + public CompletableFuture createEmbeddings( + String model, EmbeddingsBatchJobSource src, CreateEmbeddingsBatchJobConfig config) { + if (this.apiClient.vertexAI()) { + throw new UnsupportedOperationException( + "Vertex AI does not support batches.createEmbeddings."); + } + return this.privateCreateEmbeddings(model, src, config); } /** @@ -107,10 +214,8 @@ public CompletableFuture> list(ListBatchJobsConfig config) "Internal error: Pager expected ListBatchJobsConfig but received " + requestConfig.getClass().getName()); } - return CompletableFuture.supplyAsync( - () -> - JsonSerializable.toJsonNode( - batches.privateList((ListBatchJobsConfig) requestConfig))); + return this.privateList((ListBatchJobsConfig) requestConfig) + .thenApply(JsonSerializable::toJsonNode); }; return CompletableFuture.supplyAsync( () -> diff --git a/src/main/java/com/google/genai/AsyncCaches.java b/src/main/java/com/google/genai/AsyncCaches.java index 575822e8723..6e5449b8f0d 100644 --- a/src/main/java/com/google/genai/AsyncCaches.java +++ b/src/main/java/com/google/genai/AsyncCaches.java @@ -20,6 +20,7 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; +import com.google.genai.Common.BuiltRequest; import com.google.genai.errors.GenAiIOException; import com.google.genai.types.CachedContent; import com.google.genai.types.CreateCachedContentConfig; @@ -27,15 +28,19 @@ import com.google.genai.types.DeleteCachedContentResponse; import com.google.genai.types.GetCachedContentConfig; import com.google.genai.types.ListCachedContentsConfig; +import com.google.genai.types.ListCachedContentsResponse; import com.google.genai.types.UpdateCachedContentConfig; import java.util.concurrent.CompletableFuture; import java.util.function.Function; /** Async module of {@link Caches} */ public final class AsyncCaches { + Caches caches; + ApiClient apiClient; public AsyncCaches(ApiClient apiClient) { + this.apiClient = apiClient; this.caches = new Caches(apiClient); } @@ -47,7 +52,15 @@ public AsyncCaches(ApiClient apiClient) { * @return A {@link CachedContent} object that contains the info of the created resource. */ public CompletableFuture create(String model, CreateCachedContentConfig config) { - return CompletableFuture.supplyAsync(() -> caches.create(model, config)); + BuiltRequest builtRequest = caches.buildRequestForCreate(model, config); + return this.apiClient + .asyncRequest("post", builtRequest.path, builtRequest.body, builtRequest.httpOptions) + .thenApplyAsync( + response -> { + try (ApiResponse res = response) { + return caches.processResponseForCreate(res, config); + } + }); } /** @@ -58,7 +71,15 @@ public CompletableFuture create(String model, CreateCachedContent * @return A {@link CachedContent} object that contains the info of the cached content. */ public CompletableFuture get(String name, GetCachedContentConfig config) { - return CompletableFuture.supplyAsync(() -> caches.get(name, config)); + BuiltRequest builtRequest = caches.buildRequestForGet(name, config); + return this.apiClient + .asyncRequest("get", builtRequest.path, builtRequest.body, builtRequest.httpOptions) + .thenApplyAsync( + response -> { + try (ApiResponse res = response) { + return caches.processResponseForGet(res, config); + } + }); } /** @@ -69,7 +90,15 @@ public CompletableFuture get(String name, GetCachedContentConfig */ public CompletableFuture delete( String name, DeleteCachedContentConfig config) { - return CompletableFuture.supplyAsync(() -> caches.delete(name, config)); + BuiltRequest builtRequest = caches.buildRequestForDelete(name, config); + return this.apiClient + .asyncRequest("delete", builtRequest.path, builtRequest.body, builtRequest.httpOptions) + .thenApplyAsync( + response -> { + try (ApiResponse res = response) { + return caches.processResponseForDelete(res, config); + } + }); } /** @@ -80,7 +109,27 @@ public CompletableFuture delete( * @return A {@link CachedContent} object that contains the info of the updated resource. */ public CompletableFuture update(String name, UpdateCachedContentConfig config) { - return CompletableFuture.supplyAsync(() -> caches.update(name, config)); + BuiltRequest builtRequest = caches.buildRequestForUpdate(name, config); + return this.apiClient + .asyncRequest("patch", builtRequest.path, builtRequest.body, builtRequest.httpOptions) + .thenApplyAsync( + response -> { + try (ApiResponse res = response) { + return caches.processResponseForUpdate(res, config); + } + }); + } + + CompletableFuture privateList(ListCachedContentsConfig config) { + BuiltRequest builtRequest = caches.buildRequestForPrivateList(config); + return this.apiClient + .asyncRequest("get", builtRequest.path, builtRequest.body, builtRequest.httpOptions) + .thenApplyAsync( + response -> { + try (ApiResponse res = response) { + return caches.processResponseForPrivateList(res, config); + } + }); } /** @@ -100,10 +149,8 @@ public CompletableFuture> list(ListCachedContentsConfi "Internal error: Pager expected ListCachedContentsConfig but received " + requestConfig.getClass().getName()); } - return CompletableFuture.supplyAsync( - () -> - JsonSerializable.toJsonNode( - caches.privateList((ListCachedContentsConfig) requestConfig))); + return this.privateList((ListCachedContentsConfig) requestConfig) + .thenApply(JsonSerializable::toJsonNode); }; return CompletableFuture.supplyAsync( () -> diff --git a/src/main/java/com/google/genai/AsyncFiles.java b/src/main/java/com/google/genai/AsyncFiles.java index 4070a1cfcc9..d04a04de63f 100644 --- a/src/main/java/com/google/genai/AsyncFiles.java +++ b/src/main/java/com/google/genai/AsyncFiles.java @@ -20,7 +20,10 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; +import com.google.genai.Common.BuiltRequest; import com.google.genai.errors.GenAiIOException; +import com.google.genai.types.CreateFileConfig; +import com.google.genai.types.CreateFileResponse; import com.google.genai.types.DeleteFileConfig; import com.google.genai.types.DeleteFileResponse; import com.google.genai.types.DownloadFileConfig; @@ -28,6 +31,7 @@ import com.google.genai.types.GeneratedVideo; import com.google.genai.types.GetFileConfig; import com.google.genai.types.ListFilesConfig; +import com.google.genai.types.ListFilesResponse; import com.google.genai.types.UploadFileConfig; import com.google.genai.types.Video; import java.io.InputStream; @@ -36,12 +40,45 @@ /** Async module of {@link Files} */ public final class AsyncFiles { + Files files; + ApiClient apiClient; public AsyncFiles(ApiClient apiClient) { + this.apiClient = apiClient; this.files = new Files(apiClient); } + /** + * Asynchronously lists all files from the service. + * + * @param config - Optional, configuration for the list method. + * @return The ListFilesResponse, the response for the list method. + */ + CompletableFuture privateList(ListFilesConfig config) { + BuiltRequest builtRequest = files.buildRequestForPrivateList(config); + return this.apiClient + .asyncRequest("get", builtRequest.path, builtRequest.body, builtRequest.httpOptions) + .thenApplyAsync( + response -> { + try (ApiResponse res = response) { + return files.processResponseForPrivateList(res, config); + } + }); + } + + CompletableFuture privateCreate(File file, CreateFileConfig config) { + BuiltRequest builtRequest = files.buildRequestForPrivateCreate(file, config); + return this.apiClient + .asyncRequest("post", builtRequest.path, builtRequest.body, builtRequest.httpOptions) + .thenApplyAsync( + response -> { + try (ApiResponse res = response) { + return files.processResponseForPrivateCreate(res, config); + } + }); + } + /** * Asynchronously retrieves the file information from the service. * @@ -50,7 +87,15 @@ public AsyncFiles(ApiClient apiClient) { * @return A File object representing the file. */ public CompletableFuture get(String name, GetFileConfig config) { - return CompletableFuture.supplyAsync(() -> files.get(name, config)); + BuiltRequest builtRequest = files.buildRequestForGet(name, config); + return this.apiClient + .asyncRequest("get", builtRequest.path, builtRequest.body, builtRequest.httpOptions) + .thenApplyAsync( + response -> { + try (ApiResponse res = response) { + return files.processResponseForGet(res, config); + } + }); } /** @@ -61,7 +106,15 @@ public CompletableFuture get(String name, GetFileConfig config) { * @return The DeleteFileResponse, the response for the delete method. */ public CompletableFuture delete(String name, DeleteFileConfig config) { - return CompletableFuture.supplyAsync(() -> files.delete(name, config)); + BuiltRequest builtRequest = files.buildRequestForDelete(name, config); + return this.apiClient + .asyncRequest("delete", builtRequest.path, builtRequest.body, builtRequest.httpOptions) + .thenApplyAsync( + response -> { + try (ApiResponse res = response) { + return files.processResponseForDelete(res, config); + } + }); } /** @@ -178,9 +231,8 @@ public CompletableFuture> list(ListFilesConfig config) { "Internal error: Pager expected ListFilesConfig but received " + requestConfig.getClass().getName()); } - return CompletableFuture.supplyAsync( - () -> - JsonSerializable.toJsonNode(files.privateList((ListFilesConfig) requestConfig))); + return this.privateList((ListFilesConfig) requestConfig) + .thenApply(JsonSerializable::toJsonNode); }; return CompletableFuture.supplyAsync( () -> diff --git a/src/main/java/com/google/genai/AsyncLive.java b/src/main/java/com/google/genai/AsyncLive.java index bb04bd85f0c..d54cf32bbcd 100644 --- a/src/main/java/com/google/genai/AsyncLive.java +++ b/src/main/java/com/google/genai/AsyncLive.java @@ -240,13 +240,36 @@ private void handleIncomingMessage(String message) { if (!sessionFuture.isDone()) { // For the first message, we know it's the setup response. // We just complete the future and don't handle the message. - sessionFuture.complete(new AsyncSession(apiClient, this)); + try { + LiveServerMessage initialResponse = LiveServerMessage.fromJson(message); + if (initialResponse.setupComplete().isPresent()) { + sessionFuture.complete( + new AsyncSession( + apiClient, + this, + initialResponse.setupComplete().get().sessionId().orElse(null))); + } else { + sessionFuture.completeExceptionally( + new GenAiIOException( + "Initial message from WebSocket did not contain setupComplete: " + message)); + } + } catch (RuntimeException e) { + System.err.println("Error deserializing message: " + e.getMessage()); + e.printStackTrace(); + sessionFuture.completeExceptionally(e); + } return; } if (messageCallback != null) { try { - LiveServerMessage serverMessage = LiveServerMessage.fromJson(message); + LiveConverters liveConverters = new LiveConverters(this.apiClient); + JsonNode responseNode = JsonSerializable.stringToJsonNode(message); + if (this.apiClient.vertexAI()) { + responseNode = liveConverters.liveServerMessageFromVertex(responseNode, null); + } + LiveServerMessage serverMessage = + JsonSerializable.fromJsonNode(responseNode, LiveServerMessage.class); messageCallback.accept(serverMessage); } catch (RuntimeException e) { System.err.println("Error deserializing message: " + e.getMessage()); diff --git a/src/main/java/com/google/genai/AsyncModels.java b/src/main/java/com/google/genai/AsyncModels.java index 8502b25b5d3..b70f9e99149 100644 --- a/src/main/java/com/google/genai/AsyncModels.java +++ b/src/main/java/com/google/genai/AsyncModels.java @@ -20,6 +20,9 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import com.google.genai.Common.BuiltRequest; import com.google.genai.errors.GenAiIOException; import com.google.genai.types.ComputeTokensConfig; import com.google.genai.types.ComputeTokensResponse; @@ -38,34 +41,216 @@ import com.google.genai.types.GenerateImagesResponse; import com.google.genai.types.GenerateVideosConfig; import com.google.genai.types.GenerateVideosOperation; +import com.google.genai.types.GenerateVideosSource; import com.google.genai.types.GetModelConfig; import com.google.genai.types.Image; import com.google.genai.types.ListModelsConfig; +import com.google.genai.types.ListModelsResponse; import com.google.genai.types.Model; +import com.google.genai.types.Part; +import com.google.genai.types.RecontextImageConfig; +import com.google.genai.types.RecontextImageResponse; +import com.google.genai.types.RecontextImageSource; import com.google.genai.types.ReferenceImage; +import com.google.genai.types.ReferenceImageAPI; +import com.google.genai.types.SegmentImageConfig; +import com.google.genai.types.SegmentImageResponse; +import com.google.genai.types.SegmentImageSource; import com.google.genai.types.UpdateModelConfig; +import com.google.genai.types.UpscaleImageAPIConfig; import com.google.genai.types.UpscaleImageConfig; import com.google.genai.types.UpscaleImageResponse; import com.google.genai.types.Video; +import java.lang.reflect.Method; +import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.function.Function; +import java.util.logging.Logger; /** Async module of {@link Models} */ public final class AsyncModels { + Models models; + ApiClient apiClient; public AsyncModels(ApiClient apiClient) { + this.apiClient = apiClient; this.models = new Models(apiClient); } + CompletableFuture privateGenerateContent( + String model, List contents, GenerateContentConfig config) { + BuiltRequest builtRequest = + models.buildRequestForPrivateGenerateContent(model, contents, config); + return this.apiClient + .asyncRequest("post", builtRequest.path, builtRequest.body, builtRequest.httpOptions) + .thenApplyAsync( + response -> { + try (ApiResponse res = response) { + return models.processResponseForPrivateGenerateContent(res, config); + } + }); + } + + CompletableFuture> privateGenerateContentStream( + String model, List contents, GenerateContentConfig config) { + BuiltRequest builtRequest = + models.buildRequestForPrivateGenerateContentStream(model, contents, config); + return this.apiClient + .asyncRequest("post", builtRequest.path, builtRequest.body, builtRequest.httpOptions) + .thenApplyAsync( + response -> { + return models.processResponseForPrivateGenerateContentStream(response, config); + }); + } + + CompletableFuture privateEmbedContent( + String model, List contents, EmbedContentConfig config) { + BuiltRequest builtRequest = models.buildRequestForPrivateEmbedContent(model, contents, config); + return this.apiClient + .asyncRequest("post", builtRequest.path, builtRequest.body, builtRequest.httpOptions) + .thenApplyAsync( + response -> { + try (ApiResponse res = response) { + return models.processResponseForPrivateEmbedContent(res, config); + } + }); + } + + /** Asynchronously private method for generating images. */ + CompletableFuture privateGenerateImages( + String model, String prompt, GenerateImagesConfig config) { + BuiltRequest builtRequest = models.buildRequestForPrivateGenerateImages(model, prompt, config); + return this.apiClient + .asyncRequest("post", builtRequest.path, builtRequest.body, builtRequest.httpOptions) + .thenApplyAsync( + response -> { + try (ApiResponse res = response) { + return models.processResponseForPrivateGenerateImages(res, config); + } + }); + } + + /** Asynchronously private method for editing an image. */ + CompletableFuture privateEditImage( + String model, + String prompt, + List referenceImages, + EditImageConfig config) { + BuiltRequest builtRequest = + models.buildRequestForPrivateEditImage(model, prompt, referenceImages, config); + return this.apiClient + .asyncRequest("post", builtRequest.path, builtRequest.body, builtRequest.httpOptions) + .thenApplyAsync( + response -> { + try (ApiResponse res = response) { + return models.processResponseForPrivateEditImage(res, config); + } + }); + } + + /** Asynchronously private method for upscaling an image. */ + CompletableFuture privateUpscaleImage( + String model, Image image, String upscaleFactor, UpscaleImageAPIConfig config) { + BuiltRequest builtRequest = + models.buildRequestForPrivateUpscaleImage(model, image, upscaleFactor, config); + return this.apiClient + .asyncRequest("post", builtRequest.path, builtRequest.body, builtRequest.httpOptions) + .thenApplyAsync( + response -> { + try (ApiResponse res = response) { + return models.processResponseForPrivateUpscaleImage(res, config); + } + }); + } + + /** + * Asynchronously recontextualizes an image. + * + *

There are two types of recontextualization currently supported: 1) Imagen Product Recontext + * - Generate images of products in new scenes and contexts. 2) Virtual Try-On: Generate images of + * persons modeling fashion products. + * + * @param model the name of the GenAI model to use for image recontext + * @param source a {@link com.google.genai.types.RecontextImageSource} An object containing the + * source inputs (prompt, personImage, productImages) for image recontext. prompt is optional + * for product recontext and disallowed for virtual try-on. personImage is required for + * virtual try-on, disallowed for product recontext. productImages is required for both + * product recontext and virtual try-on. Only one product image is supported for virtual + * try-on, and up to 3 product images (different angles of the same product) are supported for + * product recontext. + * @param config a {@link com.google.genai.types.RecontextImageConfig} instance that specifies the + * optional configurations + * @return a {@link com.google.genai.types.RecontextImageResponse} instance that contains the + * generated images. + */ + public CompletableFuture recontextImage( + String model, RecontextImageSource source, RecontextImageConfig config) { + BuiltRequest builtRequest = models.buildRequestForRecontextImage(model, source, config); + return this.apiClient + .asyncRequest("post", builtRequest.path, builtRequest.body, builtRequest.httpOptions) + .thenApplyAsync( + response -> { + try (ApiResponse res = response) { + return models.processResponseForRecontextImage(res, config); + } + }); + } + + /** + * Asynchronously segments an image, creating a mask of a specified area. + * + * @param model the name of the GenAI model to use for image segmentation + * @param source a {@link com.google.genai.types.SegmentImageSource} An object containing the + * source inputs (prompt, image, scribbleImmage) for image segmentation. The prompt is + * required for prompt mode and semantic mode, disallowed for other modes. scribbleImage is + * required for the interactive mode, disallowed for other modes. + * @param config a {@link com.google.genai.types.SegmentImageConfig} instance that specifies the + * optional configurations + * @return a {@link com.google.genai.types.SegmentImageResponse} instance that contains the + * generated mask. + */ + public CompletableFuture segmentImage( + String model, SegmentImageSource source, SegmentImageConfig config) { + BuiltRequest builtRequest = models.buildRequestForSegmentImage(model, source, config); + return this.apiClient + .asyncRequest("post", builtRequest.path, builtRequest.body, builtRequest.httpOptions) + .thenApplyAsync( + response -> { + try (ApiResponse res = response) { + return models.processResponseForSegmentImage(res, config); + } + }); + } + /** * Asynchronously fetches information about a model by name. * * @example ```java Model model = client.models.get("gemini-2.0-flash"); ``` */ public CompletableFuture get(String model, GetModelConfig config) { - return CompletableFuture.supplyAsync(() -> models.get(model, config)); + BuiltRequest builtRequest = models.buildRequestForGet(model, config); + return this.apiClient + .asyncRequest("get", builtRequest.path, builtRequest.body, builtRequest.httpOptions) + .thenApplyAsync( + response -> { + try (ApiResponse res = response) { + return models.processResponseForGet(res, config); + } + }); + } + + CompletableFuture privateList(ListModelsConfig config) { + BuiltRequest builtRequest = models.buildRequestForPrivateList(config); + return this.apiClient + .asyncRequest("get", builtRequest.path, builtRequest.body, builtRequest.httpOptions) + .thenApplyAsync( + response -> { + try (ApiResponse res = response) { + return models.processResponseForPrivateList(res, config); + } + }); } /** @@ -80,7 +265,15 @@ public CompletableFuture get(String model, GetModelConfig config) { * description") .build()); ``` */ public CompletableFuture update(String model, UpdateModelConfig config) { - return CompletableFuture.supplyAsync(() -> models.update(model, config)); + BuiltRequest builtRequest = models.buildRequestForUpdate(model, config); + return this.apiClient + .asyncRequest("patch", builtRequest.path, builtRequest.body, builtRequest.httpOptions) + .thenApplyAsync( + response -> { + try (ApiResponse res = response) { + return models.processResponseForUpdate(res, config); + } + }); } /** @@ -89,7 +282,15 @@ public CompletableFuture update(String model, UpdateModelConfig config) { * @example ```java Model model = client.models.delete("tunedModels/12345"); ``` */ public CompletableFuture delete(String model, DeleteModelConfig config) { - return CompletableFuture.supplyAsync(() -> models.delete(model, config)); + BuiltRequest builtRequest = models.buildRequestForDelete(model, config); + return this.apiClient + .asyncRequest("delete", builtRequest.path, builtRequest.body, builtRequest.httpOptions) + .thenApplyAsync( + response -> { + try (ApiResponse res = response) { + return models.processResponseForDelete(res, config); + } + }); } /** @@ -104,7 +305,15 @@ public CompletableFuture delete(String model, DeleteModelCo */ public CompletableFuture countTokens( String model, List contents, CountTokensConfig config) { - return CompletableFuture.supplyAsync(() -> models.countTokens(model, contents, config)); + BuiltRequest builtRequest = models.buildRequestForCountTokens(model, contents, config); + return this.apiClient + .asyncRequest("post", builtRequest.path, builtRequest.body, builtRequest.httpOptions) + .thenApplyAsync( + response -> { + try (ApiResponse res = response) { + return models.processResponseForCountTokens(res, config); + } + }); } /** @@ -119,9 +328,39 @@ public CompletableFuture countTokens( */ public CompletableFuture computeTokens( String model, List contents, ComputeTokensConfig config) { - return CompletableFuture.supplyAsync(() -> models.computeTokens(model, contents, config)); + BuiltRequest builtRequest = models.buildRequestForComputeTokens(model, contents, config); + return this.apiClient + .asyncRequest("post", builtRequest.path, builtRequest.body, builtRequest.httpOptions) + .thenApplyAsync( + response -> { + try (ApiResponse res = response) { + return models.processResponseForComputeTokens(res, config); + } + }); + } + + /** Asynchronously private method for generating videos. */ + CompletableFuture privateGenerateVideos( + String model, + String prompt, + Image image, + Video video, + GenerateVideosSource source, + GenerateVideosConfig config) { + BuiltRequest builtRequest = + models.buildRequestForPrivateGenerateVideos(model, prompt, image, video, source, config); + return this.apiClient + .asyncRequest("post", builtRequest.path, builtRequest.body, builtRequest.httpOptions) + .thenApplyAsync( + response -> { + try (ApiResponse res = response) { + return models.processResponseForPrivateGenerateVideos(res, config); + } + }); } + private static final Logger logger = Logger.getLogger(AsyncModels.class.getName()); + /** * Asynchronously counts tokens given a GenAI model and a text string. * @@ -134,7 +373,7 @@ public CompletableFuture computeTokens( */ public CompletableFuture countTokens( String model, String text, CountTokensConfig config) { - return CompletableFuture.supplyAsync(() -> models.countTokens(model, text, config)); + return countTokens(model, Transformers.tContents(text), config); } /** @@ -149,7 +388,80 @@ public CompletableFuture countTokens( */ public CompletableFuture computeTokens( String model, String text, ComputeTokensConfig config) { - return CompletableFuture.supplyAsync(() -> models.computeTokens(model, text, config)); + return computeTokens(model, Transformers.tContents(text), config); + } + + /** A private helper class to pass the result of the AFC loop up the async chain. */ + private static class AfcLoopResult { + final GenerateContentResponse response; + final List history; + + AfcLoopResult(GenerateContentResponse response, List history) { + this.response = response; + this.history = history; + } + } + + /** + * Represents a single iteration of the asynchronous AFC loop. This method calls itself + * recursively inside a .thenCompose() block to chain asynchronous calls sequentially. + */ + private CompletableFuture privateGenerateContentLoopAsync( + String model, + List contents, + GenerateContentConfig transformedConfig, + ImmutableMap functionMap, + List automaticFunctionCallingHistory, + int remainingRemoteCalls, + int initialMaxCalls) { + + logger.info( + String.format( + "Automatic function calling remote call %d is done", + (initialMaxCalls - remainingRemoteCalls + 1))); + + return privateGenerateContent(model, contents, transformedConfig) + .thenCompose( + response -> { + if (remainingRemoteCalls - 1 <= 0) { + logger.info("Reached max remote calls for automatic function calling."); + return CompletableFuture.completedFuture( + new AfcLoopResult(response, automaticFunctionCallingHistory)); + } + + if (!response.candidates().isPresent() + || response.candidates().get().isEmpty() + || !response.candidates().get().get(0).content().isPresent() + || !response.candidates().get().get(0).content().get().parts().isPresent() + || response.candidates().get().get(0).content().get().parts().get().isEmpty()) { + return CompletableFuture.completedFuture( + new AfcLoopResult(response, automaticFunctionCallingHistory)); + } + + ImmutableList functionResponseParts = + AfcUtil.getFunctionResponseParts(response, functionMap); + if (functionResponseParts.isEmpty()) { + return CompletableFuture.completedFuture( + new AfcLoopResult(response, automaticFunctionCallingHistory)); + } + + Content functionCallContent = response.candidates().get().get(0).content().get(); + Content functionResponseContent = + Content.builder().role("user").parts(functionResponseParts).build(); + + List newHistory = new ArrayList<>(automaticFunctionCallingHistory); + newHistory.add(functionCallContent); + newHistory.add(functionResponseContent); + + return privateGenerateContentLoopAsync( + model, + newHistory, + transformedConfig, + functionMap, + newHistory, + remainingRemoteCalls - 1, + initialMaxCalls); + }); } /** @@ -164,7 +476,42 @@ public CompletableFuture computeTokens( */ public CompletableFuture generateContent( String model, List contents, GenerateContentConfig config) { - return CompletableFuture.supplyAsync(() -> models.generateContent(model, contents, config)); + GenerateContentConfig transformedConfig = AfcUtil.transformGenerateContentConfig(config); + if (AfcUtil.shouldDisableAfc(transformedConfig)) { + return privateGenerateContent(model, contents, transformedConfig); + } + + ImmutableMap functionMap = AfcUtil.getFunctionMap(config); + if (functionMap.isEmpty()) { + return privateGenerateContent(model, contents, transformedConfig); + } + + int maxRemoteCalls = AfcUtil.getMaxRemoteCallsAfc(transformedConfig); + logger.info( + String.format( + "Automatic function calling is enabled with max remote calls: %d", maxRemoteCalls)); + List automaticFunctionCallingHistory = new ArrayList<>(contents); + + return privateGenerateContentLoopAsync( + model, + contents, + transformedConfig, + functionMap, + automaticFunctionCallingHistory, + maxRemoteCalls, + maxRemoteCalls) + .thenApply( + loopResult -> { + if (AfcUtil.shouldAppendAfcHistory(transformedConfig)) { + ObjectNode responseNode = + JsonSerializable.objectMapper.valueToTree(loopResult.response); + responseNode.set( + "automaticFunctionCallingHistory", + JsonSerializable.objectMapper.valueToTree(loopResult.history)); + return JsonSerializable.fromJsonNode(responseNode, GenerateContentResponse.class); + } + return loopResult.response; + }); } /** @@ -210,8 +557,16 @@ public CompletableFuture generateContent( */ public CompletableFuture> generateContentStream( String model, List contents, GenerateContentConfig config) { - return CompletableFuture.supplyAsync( - () -> models.generateContentStream(model, contents, config)); + GenerateContentConfig transformedConfig = AfcUtil.transformGenerateContentConfig(config); + if (AfcUtil.hasCallableTool(config) && !AfcUtil.shouldDisableAfc(transformedConfig)) { + logger.warning( + "In generateContentStream method, detected that automatic function calling is enabled in" + + " the config.AutomaticFunctionCalling(), and callable tool is present in the" + + " config.tools() list. Automatic function calling is not supported in streaming" + + " methods at the moment, will just return the function call parts from model if" + + " there is any."); + } + return privateGenerateContentStream(model, contents, transformedConfig); } /** @@ -257,7 +612,8 @@ public CompletableFuture> generateConten */ public CompletableFuture generateImages( String model, String prompt, GenerateImagesConfig config) { - return CompletableFuture.supplyAsync(() -> models.generateImages(model, prompt, config)); + return privateGenerateImages(model, prompt, config) + .thenApply(models::postProcessGenerateImagesResponse); } /** @@ -279,9 +635,12 @@ public CompletableFuture generateImages( */ public CompletableFuture editImage( String model, String prompt, List referenceImages, EditImageConfig config) { + List referenceImagesAPI = new ArrayList<>(); + for (ReferenceImage referenceImage : referenceImages) { + referenceImagesAPI.add(referenceImage.toReferenceImageAPI()); + } - return CompletableFuture.supplyAsync( - () -> models.editImage(model, prompt, referenceImages, config)); + return privateEditImage(model, prompt, referenceImagesAPI, config); } /** @@ -297,8 +656,27 @@ public CompletableFuture editImage( */ public CompletableFuture upscaleImage( String model, Image image, String upscaleFactor, UpscaleImageConfig config) { - return CompletableFuture.supplyAsync( - () -> models.upscaleImage(model, image, upscaleFactor, config)); + return privateUpscaleImage( + model, image, upscaleFactor, models.preProcessUpscaleImageConfig(config)); + } + + /** + * Asynchronously generates videos given a GenAI model, and a GenerateVideosSource source. + * + *

This method is experimental. + * + * @param model the name of the GenAI model to use for generating videos + * @param source a {@link com.google.genai.types.GenerateVideosSource} that specifies the inputs + * (prompt, image, and/or video) to generate videos. + * @param config a {@link com.google.genai.types.GenerateVideosConfig} instance that specifies the + * optional configurations + * @return a {@link com.google.genai.types.GenerateVideosOperation} instance that contains the + * generated videos. + */ + public CompletableFuture generateVideos( + String model, GenerateVideosSource source, GenerateVideosConfig config) { + return privateGenerateVideos( + model, null, null, null, models.preProcessGenerateVideosSource(source), config); } /** @@ -319,8 +697,7 @@ public CompletableFuture upscaleImage( */ public CompletableFuture generateVideos( String model, String prompt, Image image, Video video, GenerateVideosConfig config) { - return CompletableFuture.supplyAsync( - () -> models.privateGenerateVideos(model, prompt, image, video, config)); + return privateGenerateVideos(model, prompt, image, models.preProcessVideo(video), null, config); } /** @@ -338,8 +715,7 @@ public CompletableFuture generateVideos( */ public CompletableFuture generateVideos( String model, String prompt, Image image, GenerateVideosConfig config) { - return CompletableFuture.supplyAsync( - () -> models.privateGenerateVideos(model, prompt, image, null, config)); + return generateVideos(model, prompt, image, null, config); } /** @@ -352,7 +728,7 @@ public CompletableFuture generateVideos( */ public CompletableFuture embedContent( String model, String text, EmbedContentConfig config) { - return CompletableFuture.supplyAsync(() -> models.embedContent(model, text, config)); + return embedContent(model, ImmutableList.of(text), config); } /** @@ -365,7 +741,11 @@ public CompletableFuture embedContent( */ public CompletableFuture embedContent( String model, List texts, EmbedContentConfig config) { - return CompletableFuture.supplyAsync(() -> models.embedContent(model, texts, config)); + List contents = new ArrayList<>(); + for (String text : texts) { + contents.add(Content.fromParts(Part.fromText(text))); + } + return privateEmbedContent(model, contents, config); } /** @@ -399,10 +779,8 @@ public CompletableFuture> list(ListModelsConfig config) { "Internal error: Pager expected ListModelsConfig but received " + requestConfig.getClass().getName()); } - return CompletableFuture.supplyAsync( - () -> - JsonSerializable.toJsonNode( - models.privateList((ListModelsConfig) requestConfig))); + return this.privateList((ListModelsConfig) requestConfig) + .thenApply(JsonSerializable::toJsonNode); }; return CompletableFuture.supplyAsync( () -> diff --git a/src/main/java/com/google/genai/AsyncOperations.java b/src/main/java/com/google/genai/AsyncOperations.java index ba2710233b5..e396b9cc7a2 100644 --- a/src/main/java/com/google/genai/AsyncOperations.java +++ b/src/main/java/com/google/genai/AsyncOperations.java @@ -18,18 +18,54 @@ package com.google.genai; +import com.fasterxml.jackson.databind.JsonNode; +import com.google.genai.Common.BuiltRequest; +import com.google.genai.types.FetchPredictOperationConfig; import com.google.genai.types.GenerateVideosOperation; import com.google.genai.types.GetOperationConfig; +import com.google.genai.types.Operation; import java.util.concurrent.CompletableFuture; /** Async module of {@link Operations} */ public final class AsyncOperations { + Operations operations; + ApiClient apiClient; public AsyncOperations(ApiClient apiClient) { + this.apiClient = apiClient; this.operations = new Operations(apiClient); } + CompletableFuture privateGetVideosOperation( + String operationName, GetOperationConfig config) { + BuiltRequest builtRequest = + operations.buildRequestForPrivateGetVideosOperation(operationName, config); + return this.apiClient + .asyncRequest("get", builtRequest.path, builtRequest.body, builtRequest.httpOptions) + .thenApplyAsync( + response -> { + try (ApiResponse res = response) { + return operations.processResponseForPrivateGetVideosOperation(res, config); + } + }); + } + + CompletableFuture privateFetchPredictVideosOperation( + String operationName, String resourceName, FetchPredictOperationConfig config) { + BuiltRequest builtRequest = + operations.buildRequestForPrivateFetchPredictVideosOperation( + operationName, resourceName, config); + return this.apiClient + .asyncRequest("post", builtRequest.path, builtRequest.body, builtRequest.httpOptions) + .thenApplyAsync( + response -> { + try (ApiResponse res = response) { + return operations.processResponseForPrivateFetchPredictVideosOperation(res, config); + } + }); + } + /** * Gets the status of a GenerateVideosOperation. * @@ -39,6 +75,29 @@ public AsyncOperations(ApiClient apiClient) { */ public CompletableFuture getVideosOperation( GenerateVideosOperation operation, GetOperationConfig config) { - return CompletableFuture.supplyAsync(() -> operations.getVideosOperation(operation, config)); + return get(operation, config); + } + + /** + * Gets the status of an Operation. + * + * @param operation An Operation. + * @param config The configuration for getting the operation. + * @return An Operation with the updated status of the operation. + */ + public > CompletableFuture get( + U operation, GetOperationConfig config) { + if (!operation.name().isPresent()) { + throw new IllegalArgumentException("Operation name is required."); + } + + if (this.apiClient.vertexAI()) { + String resourceName = operation.name().get().split("/operations/")[0]; + return this.privateFetchPredictVideosOperation(operation.name().get(), resourceName, null) + .thenApplyAsync(response -> operation.fromApiResponse(response, true)); + } else { + return this.privateGetVideosOperation(operation.name().get(), config) + .thenApplyAsync(response -> operation.fromApiResponse(response, false)); + } } } diff --git a/src/main/java/com/google/genai/AsyncPager.java b/src/main/java/com/google/genai/AsyncPager.java index 997d5526f69..331bceb7d10 100644 --- a/src/main/java/com/google/genai/AsyncPager.java +++ b/src/main/java/com/google/genai/AsyncPager.java @@ -20,6 +20,8 @@ import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.common.collect.ImmutableList; import com.google.genai.errors.GenAiIOException; +import com.google.genai.types.HttpResponse; +import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; import java.util.function.Function; @@ -149,4 +151,12 @@ public CompletableFuture pageSize() { public CompletableFuture size() { return initializationFuture.thenApply(v -> page.size()); } + + /** + * Asynchronously returns an Optional of the {@link HttpResponse} for the current page, which can + * be used to get the http headers. + */ + public CompletableFuture> sdkHttpResponse() { + return initializationFuture.thenApply(v -> Optional.ofNullable(sdkHttpResponse)); + } } diff --git a/src/main/java/com/google/genai/AsyncSession.java b/src/main/java/com/google/genai/AsyncSession.java index 0d84c8763bd..8047efc068c 100644 --- a/src/main/java/com/google/genai/AsyncSession.java +++ b/src/main/java/com/google/genai/AsyncSession.java @@ -39,10 +39,12 @@ public final class AsyncSession { private final ApiClient apiClient; private final AsyncLive.GenAiWebSocketClient websocket; + final String sessionId; - AsyncSession(ApiClient apiClient, AsyncLive.GenAiWebSocketClient websocket) { + AsyncSession(ApiClient apiClient, AsyncLive.GenAiWebSocketClient websocket, String sessionId) { this.apiClient = apiClient; this.websocket = websocket; + this.sessionId = sessionId; } /** @@ -134,4 +136,13 @@ public CompletableFuture close() { websocket.close(); }); } + + /** + * Gets the session ID of the live session. + * + * @return The session ID of the live session. + */ + public String sessionId() { + return sessionId; + } } diff --git a/src/main/java/com/google/genai/AsyncTunings.java b/src/main/java/com/google/genai/AsyncTunings.java index 239a822346e..a8e682841ed 100644 --- a/src/main/java/com/google/genai/AsyncTunings.java +++ b/src/main/java/com/google/genai/AsyncTunings.java @@ -20,11 +20,15 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; +import com.google.genai.Common.BuiltRequest; import com.google.genai.errors.GenAiIOException; +import com.google.genai.types.CancelTuningJobConfig; import com.google.genai.types.CreateTuningJobConfig; import com.google.genai.types.GetTuningJobConfig; import com.google.genai.types.JobState; import com.google.genai.types.ListTuningJobsConfig; +import com.google.genai.types.ListTuningJobsResponse; +import com.google.genai.types.PreTunedModel; import com.google.genai.types.TuningDataset; import com.google.genai.types.TuningJob; import com.google.genai.types.TuningOperation; @@ -33,12 +37,90 @@ /** Async module of {@link Tunings} */ public final class AsyncTunings { + Tunings tunings; + ApiClient apiClient; public AsyncTunings(ApiClient apiClient) { + this.apiClient = apiClient; this.tunings = new Tunings(apiClient); } + CompletableFuture privateGet(String name, GetTuningJobConfig config) { + BuiltRequest builtRequest = tunings.buildRequestForPrivateGet(name, config); + return this.apiClient + .asyncRequest("get", builtRequest.path, builtRequest.body, builtRequest.httpOptions) + .thenApplyAsync( + response -> { + try (ApiResponse res = response) { + return tunings.processResponseForPrivateGet(res, config); + } + }); + } + + CompletableFuture privateList(ListTuningJobsConfig config) { + BuiltRequest builtRequest = tunings.buildRequestForPrivateList(config); + return this.apiClient + .asyncRequest("get", builtRequest.path, builtRequest.body, builtRequest.httpOptions) + .thenApplyAsync( + response -> { + try (ApiResponse res = response) { + return tunings.processResponseForPrivateList(res, config); + } + }); + } + + /** + * Asynchronously cancels a tuning job resource. + * + * @param name The resource name of the tuning job. For Vertex, this is the full resource name. + * For Gemini API, this is `tunedModels/{id}`. + * @param config A {@link CancelTuningJobConfig} for configuring the cancel request. + */ + public CompletableFuture cancel(String name, CancelTuningJobConfig config) { + BuiltRequest builtRequest = tunings.buildRequestForCancel(name, config); + return this.apiClient + .asyncRequest("post", builtRequest.path, builtRequest.body, builtRequest.httpOptions) + .thenAccept( + response -> { + try (ApiResponse res = response) {} + }); + } + + CompletableFuture privateTune( + String baseModel, + PreTunedModel preTunedModel, + TuningDataset trainingDataset, + CreateTuningJobConfig config) { + BuiltRequest builtRequest = + tunings.buildRequestForPrivateTune(baseModel, preTunedModel, trainingDataset, config); + return this.apiClient + .asyncRequest("post", builtRequest.path, builtRequest.body, builtRequest.httpOptions) + .thenApplyAsync( + response -> { + try (ApiResponse res = response) { + return tunings.processResponseForPrivateTune(res, config); + } + }); + } + + CompletableFuture privateTuneMldev( + String baseModel, + PreTunedModel preTunedModel, + TuningDataset trainingDataset, + CreateTuningJobConfig config) { + BuiltRequest builtRequest = + tunings.buildRequestForPrivateTuneMldev(baseModel, preTunedModel, trainingDataset, config); + return this.apiClient + .asyncRequest("post", builtRequest.path, builtRequest.body, builtRequest.httpOptions) + .thenApplyAsync( + response -> { + try (ApiResponse res = response) { + return tunings.processResponseForPrivateTuneMldev(res, config); + } + }); + } + /** * Asynchronously makes an API request to get a tuning job. * @@ -67,10 +149,8 @@ public CompletableFuture> list(ListTuningJobsConfig config "Internal error: Pager expected ListTuningJobsConfig but received " + requestConfig.getClass().getName()); } - return CompletableFuture.supplyAsync( - () -> - JsonSerializable.toJsonNode( - tunings.privateList((ListTuningJobsConfig) requestConfig))); + return this.privateList((ListTuningJobsConfig) requestConfig) + .thenApply(JsonSerializable::toJsonNode); }; return CompletableFuture.supplyAsync( () -> @@ -93,28 +173,33 @@ public CompletableFuture> list(ListTuningJobsConfig config */ public CompletableFuture tune( String baseModel, TuningDataset trainingDataset, CreateTuningJobConfig config) { - return CompletableFuture.supplyAsync( - () -> { - if (tunings.apiClient.vertexAI()) { - return tunings.privateTune(baseModel, trainingDataset, config); - } else { - TuningOperation operation = - tunings.privateTuneMldev(baseModel, trainingDataset, config); - String tunedModelName = ""; - if (operation.metadata().isPresent() - && operation.metadata().get().containsKey("tunedModel")) { - tunedModelName = (String) operation.metadata().get().get("tunedModel"); - } else { - if (!operation.name().isPresent()) { - throw new IllegalArgumentException("Operation name is required."); - } - tunedModelName = operation.name().get().split("/operations/")[0]; - } - return TuningJob.builder() - .name(tunedModelName) - .state(JobState.Known.JOB_STATE_QUEUED) - .build(); - } - }); + + if (tunings.apiClient.vertexAI()) { + if (baseModel.startsWith("projects/")) { + PreTunedModel.Builder preTunedModelBuilder = + PreTunedModel.builder().tunedModelName(baseModel); + if (config != null && config.preTunedModelCheckpointId().isPresent()) { + preTunedModelBuilder.checkpointId(config.preTunedModelCheckpointId().get()); + } + return this.privateTune(null, preTunedModelBuilder.build(), trainingDataset, config); + } else { + return this.privateTune(baseModel, null, trainingDataset, config); + } + } else { + TuningOperation operation = + tunings.privateTuneMldev(baseModel, null, trainingDataset, config); + String tunedModelName = ""; + if (operation.metadata().isPresent() + && operation.metadata().get().containsKey("tunedModel")) { + tunedModelName = (String) operation.metadata().get().get("tunedModel"); + } else { + if (!operation.name().isPresent()) { + throw new IllegalArgumentException("Operation name is required."); + } + tunedModelName = operation.name().get().split("/operations/")[0]; + } + return CompletableFuture.completedFuture( + TuningJob.builder().name(tunedModelName).state(JobState.Known.JOB_STATE_QUEUED).build()); + } } } diff --git a/src/main/java/com/google/genai/BasePager.java b/src/main/java/com/google/genai/BasePager.java index 6cdf197b7cb..610e2de2a95 100644 --- a/src/main/java/com/google/genai/BasePager.java +++ b/src/main/java/com/google/genai/BasePager.java @@ -19,9 +19,11 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.common.collect.ImmutableList; +import com.google.genai.errors.GenAiIOException; import com.google.genai.types.BatchJob; import com.google.genai.types.CachedContent; import com.google.genai.types.File; +import com.google.genai.types.HttpResponse; import com.google.genai.types.ListBatchJobsConfig; import com.google.genai.types.ListCachedContentsConfig; import com.google.genai.types.ListFilesConfig; @@ -78,6 +80,7 @@ public Class requestConfigClass() { protected ImmutableList page; protected int pageSize; protected String nextPageToken; + protected HttpResponse sdkHttpResponse; /** Constructs a BasePager. */ protected BasePager(PagedItem pagedItem, ObjectNode requestConfig) { @@ -108,6 +111,12 @@ protected void initNewPage(JsonNode response) { } this.page = ImmutableList.copyOf(page); } + try { + this.sdkHttpResponse = + JsonSerializable.fromJsonNode(response.get("sdkHttpResponse"), HttpResponse.class); + } catch (GenAiIOException e) { + this.sdkHttpResponse = null; + } // Sets the page size. if (requestConfig.get("pageSize") != null) { diff --git a/src/main/java/com/google/genai/Batches.java b/src/main/java/com/google/genai/Batches.java index d0c5aadf02d..a2ce323ee84 100644 --- a/src/main/java/com/google/genai/Batches.java +++ b/src/main/java/com/google/genai/Batches.java @@ -22,6 +22,8 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; +import com.google.common.collect.ImmutableMap; +import com.google.genai.Common.BuiltRequest; import com.google.genai.errors.GenAiIOException; import com.google.genai.types.BatchJob; import com.google.genai.types.BatchJobSource; @@ -29,18 +31,25 @@ import com.google.genai.types.CancelBatchJobParameters; import com.google.genai.types.CreateBatchJobConfig; import com.google.genai.types.CreateBatchJobParameters; +import com.google.genai.types.CreateEmbeddingsBatchJobConfig; +import com.google.genai.types.CreateEmbeddingsBatchJobParameters; import com.google.genai.types.DeleteBatchJobConfig; import com.google.genai.types.DeleteBatchJobParameters; import com.google.genai.types.DeleteResourceJob; +import com.google.genai.types.EmbeddingsBatchJobSource; import com.google.genai.types.GetBatchJobConfig; import com.google.genai.types.GetBatchJobParameters; import com.google.genai.types.HttpOptions; +import com.google.genai.types.HttpResponse; import com.google.genai.types.ListBatchJobsConfig; import com.google.genai.types.ListBatchJobsParameters; import com.google.genai.types.ListBatchJobsResponse; import java.io.IOException; +import java.util.HashMap; +import java.util.Map; import java.util.Optional; import java.util.function.Function; +import okhttp3.Headers; import okhttp3.ResponseBody; /** @@ -48,6 +57,7 @@ * instantiating a {@link Client}, access methods through `client.batches.methodName(...)` directly. */ public final class Batches { + final ApiClient apiClient; public Batches(ApiClient apiClient) { @@ -55,664 +65,580 @@ public Batches(ApiClient apiClient) { } @ExcludeFromGeneratedCoverageReport - ObjectNode videoMetadataToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode batchJobDestinationFromMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"fps"}) != null) { - Common.setValueByPath( - toObject, new String[] {"fps"}, Common.getValueByPath(fromObject, new String[] {"fps"})); - } - if (Common.getValueByPath(fromObject, new String[] {"endOffset"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"responsesFile"}) != null) { Common.setValueByPath( toObject, - new String[] {"endOffset"}, - Common.getValueByPath(fromObject, new String[] {"endOffset"})); + new String[] {"fileName"}, + Common.getValueByPath(fromObject, new String[] {"responsesFile"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"inlinedResponses", "inlinedResponses"}) + != null) { + ArrayNode keyArray = + (ArrayNode) + Common.getValueByPath( + fromObject, new String[] {"inlinedResponses", "inlinedResponses"}); + ObjectMapper objectMapper = new ObjectMapper(); + ArrayNode result = objectMapper.createArrayNode(); + + for (JsonNode item : keyArray) { + result.add(inlinedResponseFromMldev(JsonSerializable.toJsonNode(item), toObject)); + } + Common.setValueByPath(toObject, new String[] {"inlinedResponses"}, result); } - if (Common.getValueByPath(fromObject, new String[] {"startOffset"}) != null) { + if (Common.getValueByPath( + fromObject, new String[] {"inlinedEmbedContentResponses", "inlinedResponses"}) + != null) { Common.setValueByPath( toObject, - new String[] {"startOffset"}, - Common.getValueByPath(fromObject, new String[] {"startOffset"})); + new String[] {"inlinedEmbedContentResponses"}, + Common.getValueByPath( + fromObject, new String[] {"inlinedEmbedContentResponses", "inlinedResponses"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode blobToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode batchJobDestinationFromVertex(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"displayName"}))) { - throw new IllegalArgumentException("displayName parameter is not supported in Gemini API."); + if (Common.getValueByPath(fromObject, new String[] {"predictionsFormat"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"format"}, + Common.getValueByPath(fromObject, new String[] {"predictionsFormat"})); } - if (Common.getValueByPath(fromObject, new String[] {"data"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"gcsDestination", "outputUriPrefix"}) + != null) { Common.setValueByPath( toObject, - new String[] {"data"}, - Common.getValueByPath(fromObject, new String[] {"data"})); + new String[] {"gcsUri"}, + Common.getValueByPath(fromObject, new String[] {"gcsDestination", "outputUriPrefix"})); } - if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"bigqueryDestination", "outputUri"}) + != null) { Common.setValueByPath( toObject, - new String[] {"mimeType"}, - Common.getValueByPath(fromObject, new String[] {"mimeType"})); + new String[] {"bigqueryUri"}, + Common.getValueByPath(fromObject, new String[] {"bigqueryDestination", "outputUri"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode fileDataToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode batchJobDestinationToVertex(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"displayName"}))) { - throw new IllegalArgumentException("displayName parameter is not supported in Gemini API."); - } - - if (Common.getValueByPath(fromObject, new String[] {"fileUri"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"format"}) != null) { Common.setValueByPath( toObject, - new String[] {"fileUri"}, - Common.getValueByPath(fromObject, new String[] {"fileUri"})); + new String[] {"predictionsFormat"}, + Common.getValueByPath(fromObject, new String[] {"format"})); } - if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"gcsUri"}) != null) { Common.setValueByPath( toObject, - new String[] {"mimeType"}, - Common.getValueByPath(fromObject, new String[] {"mimeType"})); + new String[] {"gcsDestination", "outputUriPrefix"}, + Common.getValueByPath(fromObject, new String[] {"gcsUri"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode partToMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"videoMetadata"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"bigqueryUri"}) != null) { Common.setValueByPath( toObject, - new String[] {"videoMetadata"}, - videoMetadataToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"videoMetadata"})), - toObject)); + new String[] {"bigqueryDestination", "outputUri"}, + Common.getValueByPath(fromObject, new String[] {"bigqueryUri"})); } - if (Common.getValueByPath(fromObject, new String[] {"thought"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"thought"}, - Common.getValueByPath(fromObject, new String[] {"thought"})); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"fileName"}))) { + throw new IllegalArgumentException("fileName parameter is not supported in Vertex AI."); } - if (Common.getValueByPath(fromObject, new String[] {"inlineData"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"inlineData"}, - blobToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"inlineData"})), - toObject)); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"inlinedResponses"}))) { + throw new IllegalArgumentException( + "inlinedResponses parameter is not supported in Vertex AI."); } - if (Common.getValueByPath(fromObject, new String[] {"fileData"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"fileData"}, - fileDataToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"fileData"})), - toObject)); + if (!Common.isZero( + Common.getValueByPath(fromObject, new String[] {"inlinedEmbedContentResponses"}))) { + throw new IllegalArgumentException( + "inlinedEmbedContentResponses parameter is not supported in Vertex AI."); } - if (Common.getValueByPath(fromObject, new String[] {"thoughtSignature"}) != null) { + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode batchJobFromMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { Common.setValueByPath( toObject, - new String[] {"thoughtSignature"}, - Common.getValueByPath(fromObject, new String[] {"thoughtSignature"})); + new String[] {"name"}, + Common.getValueByPath(fromObject, new String[] {"name"})); } - if (Common.getValueByPath(fromObject, new String[] {"codeExecutionResult"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"metadata", "displayName"}) != null) { Common.setValueByPath( toObject, - new String[] {"codeExecutionResult"}, - Common.getValueByPath(fromObject, new String[] {"codeExecutionResult"})); + new String[] {"displayName"}, + Common.getValueByPath(fromObject, new String[] {"metadata", "displayName"})); } - if (Common.getValueByPath(fromObject, new String[] {"executableCode"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"metadata", "state"}) != null) { Common.setValueByPath( toObject, - new String[] {"executableCode"}, - Common.getValueByPath(fromObject, new String[] {"executableCode"})); + new String[] {"state"}, + Transformers.tJobState( + Common.getValueByPath(fromObject, new String[] {"metadata", "state"}))); } - if (Common.getValueByPath(fromObject, new String[] {"functionCall"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"metadata", "createTime"}) != null) { Common.setValueByPath( toObject, - new String[] {"functionCall"}, - Common.getValueByPath(fromObject, new String[] {"functionCall"})); + new String[] {"createTime"}, + Common.getValueByPath(fromObject, new String[] {"metadata", "createTime"})); } - if (Common.getValueByPath(fromObject, new String[] {"functionResponse"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"metadata", "endTime"}) != null) { Common.setValueByPath( toObject, - new String[] {"functionResponse"}, - Common.getValueByPath(fromObject, new String[] {"functionResponse"})); + new String[] {"endTime"}, + Common.getValueByPath(fromObject, new String[] {"metadata", "endTime"})); } - if (Common.getValueByPath(fromObject, new String[] {"text"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"metadata", "updateTime"}) != null) { Common.setValueByPath( toObject, - new String[] {"text"}, - Common.getValueByPath(fromObject, new String[] {"text"})); + new String[] {"updateTime"}, + Common.getValueByPath(fromObject, new String[] {"metadata", "updateTime"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode contentToMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"parts"}) != null) { - ArrayNode keyArray = (ArrayNode) Common.getValueByPath(fromObject, new String[] {"parts"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add(partToMldev(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"parts"}, result); + if (Common.getValueByPath(fromObject, new String[] {"metadata", "model"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"model"}, + Common.getValueByPath(fromObject, new String[] {"metadata", "model"})); } - if (Common.getValueByPath(fromObject, new String[] {"role"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"metadata", "output"}) != null) { Common.setValueByPath( toObject, - new String[] {"role"}, - Common.getValueByPath(fromObject, new String[] {"role"})); + new String[] {"dest"}, + batchJobDestinationFromMldev( + JsonSerializable.toJsonNode( + Transformers.tRecvBatchJobDestination( + Common.getValueByPath(fromObject, new String[] {"metadata", "output"}))), + toObject)); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode schemaToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode batchJobFromVertex(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - if (Common.getValueByPath(fromObject, new String[] {"anyOf"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { Common.setValueByPath( toObject, - new String[] {"anyOf"}, - Common.getValueByPath(fromObject, new String[] {"anyOf"})); + new String[] {"name"}, + Common.getValueByPath(fromObject, new String[] {"name"})); } - if (Common.getValueByPath(fromObject, new String[] {"default"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"displayName"}) != null) { Common.setValueByPath( toObject, - new String[] {"default"}, - Common.getValueByPath(fromObject, new String[] {"default"})); + new String[] {"displayName"}, + Common.getValueByPath(fromObject, new String[] {"displayName"})); } - if (Common.getValueByPath(fromObject, new String[] {"description"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"state"}) != null) { Common.setValueByPath( toObject, - new String[] {"description"}, - Common.getValueByPath(fromObject, new String[] {"description"})); + new String[] {"state"}, + Transformers.tJobState(Common.getValueByPath(fromObject, new String[] {"state"}))); } - if (Common.getValueByPath(fromObject, new String[] {"enum"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"error"}) != null) { Common.setValueByPath( toObject, - new String[] {"enum"}, - Common.getValueByPath(fromObject, new String[] {"enum"})); + new String[] {"error"}, + Common.getValueByPath(fromObject, new String[] {"error"})); } - if (Common.getValueByPath(fromObject, new String[] {"example"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"createTime"}) != null) { Common.setValueByPath( toObject, - new String[] {"example"}, - Common.getValueByPath(fromObject, new String[] {"example"})); + new String[] {"createTime"}, + Common.getValueByPath(fromObject, new String[] {"createTime"})); } - if (Common.getValueByPath(fromObject, new String[] {"format"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"startTime"}) != null) { Common.setValueByPath( toObject, - new String[] {"format"}, - Common.getValueByPath(fromObject, new String[] {"format"})); + new String[] {"startTime"}, + Common.getValueByPath(fromObject, new String[] {"startTime"})); } - if (Common.getValueByPath(fromObject, new String[] {"items"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"endTime"}) != null) { Common.setValueByPath( toObject, - new String[] {"items"}, - Common.getValueByPath(fromObject, new String[] {"items"})); + new String[] {"endTime"}, + Common.getValueByPath(fromObject, new String[] {"endTime"})); } - if (Common.getValueByPath(fromObject, new String[] {"maxItems"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"updateTime"}) != null) { Common.setValueByPath( toObject, - new String[] {"maxItems"}, - Common.getValueByPath(fromObject, new String[] {"maxItems"})); + new String[] {"updateTime"}, + Common.getValueByPath(fromObject, new String[] {"updateTime"})); } - if (Common.getValueByPath(fromObject, new String[] {"maxLength"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { Common.setValueByPath( toObject, - new String[] {"maxLength"}, - Common.getValueByPath(fromObject, new String[] {"maxLength"})); + new String[] {"model"}, + Common.getValueByPath(fromObject, new String[] {"model"})); } - if (Common.getValueByPath(fromObject, new String[] {"maxProperties"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"inputConfig"}) != null) { Common.setValueByPath( toObject, - new String[] {"maxProperties"}, - Common.getValueByPath(fromObject, new String[] {"maxProperties"})); + new String[] {"src"}, + batchJobSourceFromVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"inputConfig"})), + toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"maximum"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"outputConfig"}) != null) { Common.setValueByPath( toObject, - new String[] {"maximum"}, - Common.getValueByPath(fromObject, new String[] {"maximum"})); + new String[] {"dest"}, + batchJobDestinationFromVertex( + JsonSerializable.toJsonNode( + Transformers.tRecvBatchJobDestination( + Common.getValueByPath(fromObject, new String[] {"outputConfig"}))), + toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"minItems"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"minItems"}, - Common.getValueByPath(fromObject, new String[] {"minItems"})); - } + return toObject; + } - if (Common.getValueByPath(fromObject, new String[] {"minLength"}) != null) { + @ExcludeFromGeneratedCoverageReport + ObjectNode batchJobSourceFromVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"instancesFormat"}) != null) { Common.setValueByPath( toObject, - new String[] {"minLength"}, - Common.getValueByPath(fromObject, new String[] {"minLength"})); + new String[] {"format"}, + Common.getValueByPath(fromObject, new String[] {"instancesFormat"})); } - if (Common.getValueByPath(fromObject, new String[] {"minProperties"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"gcsSource", "uris"}) != null) { Common.setValueByPath( toObject, - new String[] {"minProperties"}, - Common.getValueByPath(fromObject, new String[] {"minProperties"})); + new String[] {"gcsUri"}, + Common.getValueByPath(fromObject, new String[] {"gcsSource", "uris"})); } - if (Common.getValueByPath(fromObject, new String[] {"minimum"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"bigquerySource", "inputUri"}) != null) { Common.setValueByPath( toObject, - new String[] {"minimum"}, - Common.getValueByPath(fromObject, new String[] {"minimum"})); + new String[] {"bigqueryUri"}, + Common.getValueByPath(fromObject, new String[] {"bigquerySource", "inputUri"})); } - if (Common.getValueByPath(fromObject, new String[] {"nullable"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"nullable"}, - Common.getValueByPath(fromObject, new String[] {"nullable"})); + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode batchJobSourceToMldev( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"format"}))) { + throw new IllegalArgumentException("format parameter is not supported in Gemini API."); } - if (Common.getValueByPath(fromObject, new String[] {"pattern"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"pattern"}, - Common.getValueByPath(fromObject, new String[] {"pattern"})); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"gcsUri"}))) { + throw new IllegalArgumentException("gcsUri parameter is not supported in Gemini API."); } - if (Common.getValueByPath(fromObject, new String[] {"properties"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"properties"}, - Common.getValueByPath(fromObject, new String[] {"properties"})); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"bigqueryUri"}))) { + throw new IllegalArgumentException("bigqueryUri parameter is not supported in Gemini API."); } - if (Common.getValueByPath(fromObject, new String[] {"propertyOrdering"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"fileName"}) != null) { Common.setValueByPath( toObject, - new String[] {"propertyOrdering"}, - Common.getValueByPath(fromObject, new String[] {"propertyOrdering"})); + new String[] {"fileName"}, + Common.getValueByPath(fromObject, new String[] {"fileName"})); } - if (Common.getValueByPath(fromObject, new String[] {"required"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"required"}, - Common.getValueByPath(fromObject, new String[] {"required"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"title"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"title"}, - Common.getValueByPath(fromObject, new String[] {"title"})); - } + if (Common.getValueByPath(fromObject, new String[] {"inlinedRequests"}) != null) { + ArrayNode keyArray = + (ArrayNode) Common.getValueByPath(fromObject, new String[] {"inlinedRequests"}); + ObjectMapper objectMapper = new ObjectMapper(); + ArrayNode result = objectMapper.createArrayNode(); - if (Common.getValueByPath(fromObject, new String[] {"type"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"type"}, - Common.getValueByPath(fromObject, new String[] {"type"})); + for (JsonNode item : keyArray) { + result.add(inlinedRequestToMldev(apiClient, JsonSerializable.toJsonNode(item), toObject)); + } + Common.setValueByPath(toObject, new String[] {"requests", "requests"}, result); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode safetySettingToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode batchJobSourceToVertex(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"method"}))) { - throw new IllegalArgumentException("method parameter is not supported in Gemini API."); - } - - if (Common.getValueByPath(fromObject, new String[] {"category"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"format"}) != null) { Common.setValueByPath( toObject, - new String[] {"category"}, - Common.getValueByPath(fromObject, new String[] {"category"})); + new String[] {"instancesFormat"}, + Common.getValueByPath(fromObject, new String[] {"format"})); } - if (Common.getValueByPath(fromObject, new String[] {"threshold"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"gcsUri"}) != null) { Common.setValueByPath( toObject, - new String[] {"threshold"}, - Common.getValueByPath(fromObject, new String[] {"threshold"})); + new String[] {"gcsSource", "uris"}, + Common.getValueByPath(fromObject, new String[] {"gcsUri"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode functionDeclarationToMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"behavior"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"bigqueryUri"}) != null) { Common.setValueByPath( toObject, - new String[] {"behavior"}, - Common.getValueByPath(fromObject, new String[] {"behavior"})); + new String[] {"bigquerySource", "inputUri"}, + Common.getValueByPath(fromObject, new String[] {"bigqueryUri"})); } - if (Common.getValueByPath(fromObject, new String[] {"description"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"description"}, - Common.getValueByPath(fromObject, new String[] {"description"})); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"fileName"}))) { + throw new IllegalArgumentException("fileName parameter is not supported in Vertex AI."); } - if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"name"}, - Common.getValueByPath(fromObject, new String[] {"name"})); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"inlinedRequests"}))) { + throw new IllegalArgumentException( + "inlinedRequests parameter is not supported in Vertex AI."); } - if (Common.getValueByPath(fromObject, new String[] {"parameters"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"parameters"}, - Common.getValueByPath(fromObject, new String[] {"parameters"})); - } + return toObject; + } - if (Common.getValueByPath(fromObject, new String[] {"parametersJsonSchema"}) != null) { + @ExcludeFromGeneratedCoverageReport + ObjectNode blobToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"data"}) != null) { Common.setValueByPath( toObject, - new String[] {"parametersJsonSchema"}, - Common.getValueByPath(fromObject, new String[] {"parametersJsonSchema"})); + new String[] {"data"}, + Common.getValueByPath(fromObject, new String[] {"data"})); } - if (Common.getValueByPath(fromObject, new String[] {"response"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"response"}, - Common.getValueByPath(fromObject, new String[] {"response"})); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"displayName"}))) { + throw new IllegalArgumentException("displayName parameter is not supported in Gemini API."); } - if (Common.getValueByPath(fromObject, new String[] {"responseJsonSchema"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { Common.setValueByPath( toObject, - new String[] {"responseJsonSchema"}, - Common.getValueByPath(fromObject, new String[] {"responseJsonSchema"})); + new String[] {"mimeType"}, + Common.getValueByPath(fromObject, new String[] {"mimeType"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode intervalToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode cancelBatchJobParametersToMldev( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"startTime"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"startTime"}, - Common.getValueByPath(fromObject, new String[] {"startTime"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"endTime"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { Common.setValueByPath( toObject, - new String[] {"endTime"}, - Common.getValueByPath(fromObject, new String[] {"endTime"})); + new String[] {"_url", "name"}, + Transformers.tBatchJobName( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"name"}))); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode googleSearchToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode cancelBatchJobParametersToVertex( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"timeRangeFilter"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { Common.setValueByPath( toObject, - new String[] {"timeRangeFilter"}, - intervalToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"timeRangeFilter"})), - toObject)); + new String[] {"_url", "name"}, + Transformers.tBatchJobName( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"name"}))); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode dynamicRetrievalConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode candidateFromMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"mode"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"mode"}, - Common.getValueByPath(fromObject, new String[] {"mode"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"dynamicThreshold"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"content"}) != null) { Common.setValueByPath( toObject, - new String[] {"dynamicThreshold"}, - Common.getValueByPath(fromObject, new String[] {"dynamicThreshold"})); + new String[] {"content"}, + Common.getValueByPath(fromObject, new String[] {"content"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode googleSearchRetrievalToMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"dynamicRetrievalConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"citationMetadata"}) != null) { Common.setValueByPath( toObject, - new String[] {"dynamicRetrievalConfig"}, - dynamicRetrievalConfigToMldev( + new String[] {"citationMetadata"}, + citationMetadataFromMldev( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"dynamicRetrievalConfig"})), + Common.getValueByPath(fromObject, new String[] {"citationMetadata"})), toObject)); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode urlContextToMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode toolToMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"functionDeclarations"}) != null) { - ArrayNode keyArray = - (ArrayNode) Common.getValueByPath(fromObject, new String[] {"functionDeclarations"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add(functionDeclarationToMldev(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"functionDeclarations"}, result); - } - - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"retrieval"}))) { - throw new IllegalArgumentException("retrieval parameter is not supported in Gemini API."); + if (Common.getValueByPath(fromObject, new String[] {"tokenCount"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"tokenCount"}, + Common.getValueByPath(fromObject, new String[] {"tokenCount"})); } - if (Common.getValueByPath(fromObject, new String[] {"googleSearch"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"finishReason"}) != null) { Common.setValueByPath( toObject, - new String[] {"googleSearch"}, - googleSearchToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"googleSearch"})), - toObject)); + new String[] {"finishReason"}, + Common.getValueByPath(fromObject, new String[] {"finishReason"})); } - if (Common.getValueByPath(fromObject, new String[] {"googleSearchRetrieval"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"avgLogprobs"}) != null) { Common.setValueByPath( toObject, - new String[] {"googleSearchRetrieval"}, - googleSearchRetrievalToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"googleSearchRetrieval"})), - toObject)); + new String[] {"avgLogprobs"}, + Common.getValueByPath(fromObject, new String[] {"avgLogprobs"})); } - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"enterpriseWebSearch"}))) { - throw new IllegalArgumentException( - "enterpriseWebSearch parameter is not supported in Gemini API."); + if (Common.getValueByPath(fromObject, new String[] {"groundingMetadata"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"groundingMetadata"}, + Common.getValueByPath(fromObject, new String[] {"groundingMetadata"})); } - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"googleMaps"}))) { - throw new IllegalArgumentException("googleMaps parameter is not supported in Gemini API."); + if (Common.getValueByPath(fromObject, new String[] {"index"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"index"}, + Common.getValueByPath(fromObject, new String[] {"index"})); } - if (Common.getValueByPath(fromObject, new String[] {"urlContext"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"logprobsResult"}) != null) { Common.setValueByPath( toObject, - new String[] {"urlContext"}, - urlContextToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"urlContext"})), - toObject)); + new String[] {"logprobsResult"}, + Common.getValueByPath(fromObject, new String[] {"logprobsResult"})); } - if (Common.getValueByPath(fromObject, new String[] {"codeExecution"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"safetyRatings"}) != null) { Common.setValueByPath( toObject, - new String[] {"codeExecution"}, - Common.getValueByPath(fromObject, new String[] {"codeExecution"})); + new String[] {"safetyRatings"}, + Common.getValueByPath(fromObject, new String[] {"safetyRatings"})); } - if (Common.getValueByPath(fromObject, new String[] {"computerUse"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"urlContextMetadata"}) != null) { Common.setValueByPath( toObject, - new String[] {"computerUse"}, - Common.getValueByPath(fromObject, new String[] {"computerUse"})); + new String[] {"urlContextMetadata"}, + Common.getValueByPath(fromObject, new String[] {"urlContextMetadata"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode functionCallingConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode citationMetadataFromMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"mode"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"mode"}, - Common.getValueByPath(fromObject, new String[] {"mode"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"allowedFunctionNames"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"citationSources"}) != null) { Common.setValueByPath( toObject, - new String[] {"allowedFunctionNames"}, - Common.getValueByPath(fromObject, new String[] {"allowedFunctionNames"})); + new String[] {"citations"}, + Common.getValueByPath(fromObject, new String[] {"citationSources"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode latLngToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode contentToMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"latitude"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"latitude"}, - Common.getValueByPath(fromObject, new String[] {"latitude"})); + if (Common.getValueByPath(fromObject, new String[] {"parts"}) != null) { + ArrayNode keyArray = (ArrayNode) Common.getValueByPath(fromObject, new String[] {"parts"}); + ObjectMapper objectMapper = new ObjectMapper(); + ArrayNode result = objectMapper.createArrayNode(); + + for (JsonNode item : keyArray) { + result.add(partToMldev(JsonSerializable.toJsonNode(item), toObject)); + } + Common.setValueByPath(toObject, new String[] {"parts"}, result); } - if (Common.getValueByPath(fromObject, new String[] {"longitude"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"role"}) != null) { Common.setValueByPath( toObject, - new String[] {"longitude"}, - Common.getValueByPath(fromObject, new String[] {"longitude"})); + new String[] {"role"}, + Common.getValueByPath(fromObject, new String[] {"role"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode retrievalConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode createBatchJobConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"latLng"}) != null) { + + if (Common.getValueByPath(fromObject, new String[] {"displayName"}) != null) { Common.setValueByPath( - toObject, - new String[] {"latLng"}, - latLngToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"latLng"})), - toObject)); + parentObject, + new String[] {"batch", "displayName"}, + Common.getValueByPath(fromObject, new String[] {"displayName"})); } - if (Common.getValueByPath(fromObject, new String[] {"languageCode"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"languageCode"}, - Common.getValueByPath(fromObject, new String[] {"languageCode"})); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"dest"}))) { + throw new IllegalArgumentException("dest parameter is not supported in Gemini API."); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode toolConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode createBatchJobConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"functionCallingConfig"}) != null) { + + if (Common.getValueByPath(fromObject, new String[] {"displayName"}) != null) { Common.setValueByPath( - toObject, - new String[] {"functionCallingConfig"}, - functionCallingConfigToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"functionCallingConfig"})), - toObject)); + parentObject, + new String[] {"displayName"}, + Common.getValueByPath(fromObject, new String[] {"displayName"})); } - if (Common.getValueByPath(fromObject, new String[] {"retrievalConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"dest"}) != null) { Common.setValueByPath( - toObject, - new String[] {"retrievalConfig"}, - retrievalConfigToMldev( + parentObject, + new String[] {"outputConfig"}, + batchJobDestinationToVertex( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"retrievalConfig"})), + Transformers.tBatchJobDestination( + Common.getValueByPath(fromObject, new String[] {"dest"}))), toObject)); } @@ -720,123 +646,325 @@ ObjectNode toolConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { } @ExcludeFromGeneratedCoverageReport - ObjectNode prebuiltVoiceConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode createBatchJobParametersToMldev( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"voiceName"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { Common.setValueByPath( toObject, - new String[] {"voiceName"}, - Common.getValueByPath(fromObject, new String[] {"voiceName"})); - } - + new String[] {"_url", "model"}, + Transformers.tModel( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); + } + + if (Common.getValueByPath(fromObject, new String[] {"src"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"batch", "inputConfig"}, + batchJobSourceToMldev( + apiClient, + JsonSerializable.toJsonNode( + Transformers.tBatchJobSource( + Common.getValueByPath(fromObject, new String[] {"src"}))), + toObject)); + } + + if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + JsonNode unused = + createBatchJobConfigToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"config"})), + toObject); + } + return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode voiceConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode createBatchJobParametersToVertex( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"prebuiltVoiceConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"model"}, + Transformers.tModel( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); + } + + if (Common.getValueByPath(fromObject, new String[] {"src"}) != null) { Common.setValueByPath( toObject, - new String[] {"prebuiltVoiceConfig"}, - prebuiltVoiceConfigToMldev( + new String[] {"inputConfig"}, + batchJobSourceToVertex( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"prebuiltVoiceConfig"})), + Transformers.tBatchJobSource( + Common.getValueByPath(fromObject, new String[] {"src"}))), toObject)); } + if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + JsonNode unused = + createBatchJobConfigToVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"config"})), + toObject); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode createEmbeddingsBatchJobConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + + if (Common.getValueByPath(fromObject, new String[] {"displayName"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"batch", "displayName"}, + Common.getValueByPath(fromObject, new String[] {"displayName"})); + } + return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode speakerVoiceConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode createEmbeddingsBatchJobParametersToMldev( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"speaker"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { Common.setValueByPath( toObject, - new String[] {"speaker"}, - Common.getValueByPath(fromObject, new String[] {"speaker"})); + new String[] {"_url", "model"}, + Transformers.tModel( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); } - if (Common.getValueByPath(fromObject, new String[] {"voiceConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"src"}) != null) { Common.setValueByPath( toObject, - new String[] {"voiceConfig"}, - voiceConfigToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"voiceConfig"})), + new String[] {"batch", "inputConfig"}, + embeddingsBatchJobSourceToMldev( + apiClient, + JsonSerializable.toJsonNode(Common.getValueByPath(fromObject, new String[] {"src"})), toObject)); } + if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + JsonNode unused = + createEmbeddingsBatchJobConfigToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"config"})), + toObject); + } + return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode multiSpeakerVoiceConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode deleteBatchJobParametersToMldev( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"speakerVoiceConfigs"}) != null) { - ArrayNode keyArray = - (ArrayNode) Common.getValueByPath(fromObject, new String[] {"speakerVoiceConfigs"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); + if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"_url", "name"}, + Transformers.tBatchJobName( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"name"}))); + } - for (JsonNode item : keyArray) { - result.add(speakerVoiceConfigToMldev(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"speakerVoiceConfigs"}, result); + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode deleteBatchJobParametersToVertex( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"_url", "name"}, + Transformers.tBatchJobName( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"name"}))); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode speechConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode deleteResourceJobFromMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"voiceConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"}) != null) { Common.setValueByPath( toObject, - new String[] {"voiceConfig"}, - voiceConfigToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"voiceConfig"})), - toObject)); + new String[] {"sdkHttpResponse"}, + Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"name"}, + Common.getValueByPath(fromObject, new String[] {"name"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"done"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"done"}, + Common.getValueByPath(fromObject, new String[] {"done"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"error"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"error"}, + Common.getValueByPath(fromObject, new String[] {"error"})); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode deleteResourceJobFromVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"sdkHttpResponse"}, + Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"name"}, + Common.getValueByPath(fromObject, new String[] {"name"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"done"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"done"}, + Common.getValueByPath(fromObject, new String[] {"done"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"error"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"error"}, + Common.getValueByPath(fromObject, new String[] {"error"})); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode embedContentBatchToMldev( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"contents"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"requests[]", "request", "content"}, + Transformers.tContentsForEmbed( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"contents"}))); } - if (Common.getValueByPath(fromObject, new String[] {"multiSpeakerVoiceConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { Common.setValueByPath( toObject, - new String[] {"multiSpeakerVoiceConfig"}, - multiSpeakerVoiceConfigToMldev( + new String[] {"_self"}, + embedContentConfigToMldev( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"multiSpeakerVoiceConfig"})), + Common.getValueByPath(fromObject, new String[] {"config"})), toObject)); + Common.moveValueByPath(toObject, ImmutableMap.of("requests[].*", "requests[].request.*")); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode embedContentConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + + if (Common.getValueByPath(fromObject, new String[] {"taskType"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"requests[]", "taskType"}, + Common.getValueByPath(fromObject, new String[] {"taskType"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"title"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"requests[]", "title"}, + Common.getValueByPath(fromObject, new String[] {"title"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"outputDimensionality"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"requests[]", "outputDimensionality"}, + Common.getValueByPath(fromObject, new String[] {"outputDimensionality"})); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"mimeType"}))) { + throw new IllegalArgumentException("mimeType parameter is not supported in Gemini API."); } - if (Common.getValueByPath(fromObject, new String[] {"languageCode"}) != null) { + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"autoTruncate"}))) { + throw new IllegalArgumentException("autoTruncate parameter is not supported in Gemini API."); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode embeddingsBatchJobSourceToMldev( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"fileName"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"file_name"}, + Common.getValueByPath(fromObject, new String[] {"fileName"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"inlinedRequests"}) != null) { Common.setValueByPath( toObject, - new String[] {"languageCode"}, - Common.getValueByPath(fromObject, new String[] {"languageCode"})); + new String[] {"requests"}, + embedContentBatchToMldev( + apiClient, + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"inlinedRequests"})), + toObject)); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode thinkingConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode fileDataToMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"includeThoughts"}) != null) { + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"displayName"}))) { + throw new IllegalArgumentException("displayName parameter is not supported in Gemini API."); + } + + if (Common.getValueByPath(fromObject, new String[] {"fileUri"}) != null) { Common.setValueByPath( toObject, - new String[] {"includeThoughts"}, - Common.getValueByPath(fromObject, new String[] {"includeThoughts"})); + new String[] {"fileUri"}, + Common.getValueByPath(fromObject, new String[] {"fileUri"})); } - if (Common.getValueByPath(fromObject, new String[] {"thinkingBudget"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { Common.setValueByPath( toObject, - new String[] {"thinkingBudget"}, - Common.getValueByPath(fromObject, new String[] {"thinkingBudget"})); + new String[] {"mimeType"}, + Common.getValueByPath(fromObject, new String[] {"mimeType"})); } return toObject; @@ -946,11 +1074,7 @@ ObjectNode generateContentConfigToMldev( Common.setValueByPath( toObject, new String[] {"responseSchema"}, - schemaToMldev( - JsonSerializable.toJsonNode( - Transformers.tSchema( - Common.getValueByPath(fromObject, new String[] {"responseSchema"}))), - toObject)); + Transformers.tSchema(Common.getValueByPath(fromObject, new String[] {"responseSchema"}))); } if (Common.getValueByPath(fromObject, new String[] {"responseJsonSchema"}) != null) { @@ -998,10 +1122,7 @@ ObjectNode generateContentConfigToMldev( Common.setValueByPath( parentObject, new String[] {"toolConfig"}, - toolConfigToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"toolConfig"})), - toObject)); + Common.getValueByPath(fromObject, new String[] {"toolConfig"})); } if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"labels"}))) { @@ -1034,11 +1155,8 @@ ObjectNode generateContentConfigToMldev( Common.setValueByPath( toObject, new String[] {"speechConfig"}, - speechConfigToMldev( - JsonSerializable.toJsonNode( - Transformers.tSpeechConfig( - Common.getValueByPath(fromObject, new String[] {"speechConfig"}))), - toObject)); + Transformers.tSpeechConfig( + Common.getValueByPath(fromObject, new String[] {"speechConfig"}))); } if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"audioTimestamp"}))) { @@ -1050,193 +1168,237 @@ ObjectNode generateContentConfigToMldev( Common.setValueByPath( toObject, new String[] {"thinkingConfig"}, - thinkingConfigToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"thinkingConfig"})), - toObject)); + Common.getValueByPath(fromObject, new String[] {"thinkingConfig"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"imageConfig"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"imageConfig"}, + Common.getValueByPath(fromObject, new String[] {"imageConfig"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode inlinedRequestToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { + ObjectNode generateContentResponseFromMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"}) != null) { Common.setValueByPath( toObject, - new String[] {"request", "model"}, - Transformers.tModel( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); + new String[] {"sdkHttpResponse"}, + Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"})); } - if (Common.getValueByPath(fromObject, new String[] {"contents"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"candidates"}) != null) { ArrayNode keyArray = - (ArrayNode) - Transformers.tContents(Common.getValueByPath(fromObject, new String[] {"contents"})); + (ArrayNode) Common.getValueByPath(fromObject, new String[] {"candidates"}); ObjectMapper objectMapper = new ObjectMapper(); ArrayNode result = objectMapper.createArrayNode(); for (JsonNode item : keyArray) { - result.add(contentToMldev(JsonSerializable.toJsonNode(item), toObject)); + result.add(candidateFromMldev(JsonSerializable.toJsonNode(item), toObject)); } - Common.setValueByPath(toObject, new String[] {"request", "contents"}, result); + Common.setValueByPath(toObject, new String[] {"candidates"}, result); } - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"modelVersion"}) != null) { Common.setValueByPath( toObject, - new String[] {"request", "generationConfig"}, - generateContentConfigToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"config"})), - toObject)); + new String[] {"modelVersion"}, + Common.getValueByPath(fromObject, new String[] {"modelVersion"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"promptFeedback"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"promptFeedback"}, + Common.getValueByPath(fromObject, new String[] {"promptFeedback"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"responseId"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"responseId"}, + Common.getValueByPath(fromObject, new String[] {"responseId"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"usageMetadata"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"usageMetadata"}, + Common.getValueByPath(fromObject, new String[] {"usageMetadata"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode batchJobSourceToMldev( + ObjectNode getBatchJobParametersToMldev( ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"format"}))) { - throw new IllegalArgumentException("format parameter is not supported in Gemini API."); - } - - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"gcsUri"}))) { - throw new IllegalArgumentException("gcsUri parameter is not supported in Gemini API."); + if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"_url", "name"}, + Transformers.tBatchJobName( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"name"}))); } - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"bigqueryUri"}))) { - throw new IllegalArgumentException("bigqueryUri parameter is not supported in Gemini API."); - } + return toObject; + } - if (Common.getValueByPath(fromObject, new String[] {"fileName"}) != null) { + @ExcludeFromGeneratedCoverageReport + ObjectNode getBatchJobParametersToVertex( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { Common.setValueByPath( toObject, - new String[] {"fileName"}, - Common.getValueByPath(fromObject, new String[] {"fileName"})); + new String[] {"_url", "name"}, + Transformers.tBatchJobName( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"name"}))); } - if (Common.getValueByPath(fromObject, new String[] {"inlinedRequests"}) != null) { - ArrayNode keyArray = - (ArrayNode) Common.getValueByPath(fromObject, new String[] {"inlinedRequests"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); + return toObject; + } - for (JsonNode item : keyArray) { - result.add(inlinedRequestToMldev(apiClient, JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"requests", "requests"}, result); + @ExcludeFromGeneratedCoverageReport + ObjectNode googleMapsToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"authConfig"}))) { + throw new IllegalArgumentException("authConfig parameter is not supported in Gemini API."); + } + + if (Common.getValueByPath(fromObject, new String[] {"enableWidget"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"enableWidget"}, + Common.getValueByPath(fromObject, new String[] {"enableWidget"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode createBatchJobConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode googleSearchToMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - if (Common.getValueByPath(fromObject, new String[] {"displayName"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"batch", "displayName"}, - Common.getValueByPath(fromObject, new String[] {"displayName"})); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"excludeDomains"}))) { + throw new IllegalArgumentException( + "excludeDomains parameter is not supported in Gemini API."); } - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"dest"}))) { - throw new IllegalArgumentException("dest parameter is not supported in Gemini API."); + if (Common.getValueByPath(fromObject, new String[] {"timeRangeFilter"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"timeRangeFilter"}, + Common.getValueByPath(fromObject, new String[] {"timeRangeFilter"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode createBatchJobParametersToMldev( + ObjectNode inlinedRequestToMldev( ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { Common.setValueByPath( toObject, - new String[] {"_url", "model"}, + new String[] {"request", "model"}, Transformers.tModel( this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); } - if (Common.getValueByPath(fromObject, new String[] {"src"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"contents"}) != null) { + ArrayNode keyArray = + (ArrayNode) + Transformers.tContents(Common.getValueByPath(fromObject, new String[] {"contents"})); + ObjectMapper objectMapper = new ObjectMapper(); + ArrayNode result = objectMapper.createArrayNode(); + + for (JsonNode item : keyArray) { + result.add(contentToMldev(JsonSerializable.toJsonNode(item), toObject)); + } + Common.setValueByPath(toObject, new String[] {"request", "contents"}, result); + } + + if (Common.getValueByPath(fromObject, new String[] {"metadata"}) != null) { Common.setValueByPath( toObject, - new String[] {"batch", "inputConfig"}, - batchJobSourceToMldev( - apiClient, - JsonSerializable.toJsonNode( - Transformers.tBatchJobSource( - Common.getValueByPath(fromObject, new String[] {"src"}))), - toObject)); + new String[] {"metadata"}, + Common.getValueByPath(fromObject, new String[] {"metadata"})); } if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { Common.setValueByPath( toObject, - new String[] {"config"}, - createBatchJobConfigToMldev( + new String[] {"request", "generationConfig"}, + generateContentConfigToMldev( + apiClient, JsonSerializable.toJsonNode( Common.getValueByPath(fromObject, new String[] {"config"})), - toObject)); + (ObjectNode) + Common.getValueByPath( + toObject, + new String[] {"request"}, + (new ObjectMapper()).createObjectNode()))); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode getBatchJobParametersToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { + ObjectNode inlinedResponseFromMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"response"}) != null) { Common.setValueByPath( toObject, - new String[] {"_url", "name"}, - Transformers.tBatchJobName( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"name"}))); + new String[] {"response"}, + generateContentResponseFromMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"response"})), + toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"error"}) != null) { Common.setValueByPath( toObject, - new String[] {"config"}, - Common.getValueByPath(fromObject, new String[] {"config"})); + new String[] {"error"}, + Common.getValueByPath(fromObject, new String[] {"error"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode cancelBatchJobParametersToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { + ObjectNode listBatchJobsConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { + + if (Common.getValueByPath(fromObject, new String[] {"pageSize"}) != null) { Common.setValueByPath( - toObject, - new String[] {"_url", "name"}, - Transformers.tBatchJobName( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"name"}))); + parentObject, + new String[] {"_query", "pageSize"}, + Common.getValueByPath(fromObject, new String[] {"pageSize"})); } - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"pageToken"}) != null) { Common.setValueByPath( - toObject, - new String[] {"config"}, - Common.getValueByPath(fromObject, new String[] {"config"})); + parentObject, + new String[] {"_query", "pageToken"}, + Common.getValueByPath(fromObject, new String[] {"pageToken"})); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"filter"}))) { + throw new IllegalArgumentException("filter parameter is not supported in Gemini API."); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode listBatchJobsConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode listBatchJobsConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); if (Common.getValueByPath(fromObject, new String[] {"pageSize"}) != null) { @@ -1253,8 +1415,11 @@ ObjectNode listBatchJobsConfigToMldev(JsonNode fromObject, ObjectNode parentObje Common.getValueByPath(fromObject, new String[] {"pageToken"})); } - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"filter"}))) { - throw new IllegalArgumentException("filter parameter is not supported in Gemini API."); + if (Common.getValueByPath(fromObject, new String[] {"filter"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"_query", "filter"}, + Common.getValueByPath(fromObject, new String[] {"filter"})); } return toObject; @@ -1264,1077 +1429,273 @@ ObjectNode listBatchJobsConfigToMldev(JsonNode fromObject, ObjectNode parentObje ObjectNode listBatchJobsParametersToMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"config"}, + JsonNode unused = listBatchJobsConfigToMldev( JsonSerializable.toJsonNode( Common.getValueByPath(fromObject, new String[] {"config"})), - toObject)); + toObject); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode deleteBatchJobParametersToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { + ObjectNode listBatchJobsParametersToVertex(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"_url", "name"}, - Transformers.tBatchJobName( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"name"}))); - } - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"config"}, - Common.getValueByPath(fromObject, new String[] {"config"})); + JsonNode unused = + listBatchJobsConfigToVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"config"})), + toObject); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode batchJobSourceToVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode listBatchJobsResponseFromMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"format"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"instancesFormat"}, - Common.getValueByPath(fromObject, new String[] {"format"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"gcsUri"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"}) != null) { Common.setValueByPath( toObject, - new String[] {"gcsSource", "uris"}, - Common.getValueByPath(fromObject, new String[] {"gcsUri"})); + new String[] {"sdkHttpResponse"}, + Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"})); } - if (Common.getValueByPath(fromObject, new String[] {"bigqueryUri"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"nextPageToken"}) != null) { Common.setValueByPath( toObject, - new String[] {"bigquerySource", "inputUri"}, - Common.getValueByPath(fromObject, new String[] {"bigqueryUri"})); + new String[] {"nextPageToken"}, + Common.getValueByPath(fromObject, new String[] {"nextPageToken"})); } - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"fileName"}))) { - throw new IllegalArgumentException("fileName parameter is not supported in Vertex AI."); - } + if (Common.getValueByPath(fromObject, new String[] {"operations"}) != null) { + ArrayNode keyArray = + (ArrayNode) Common.getValueByPath(fromObject, new String[] {"operations"}); + ObjectMapper objectMapper = new ObjectMapper(); + ArrayNode result = objectMapper.createArrayNode(); - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"inlinedRequests"}))) { - throw new IllegalArgumentException( - "inlinedRequests parameter is not supported in Vertex AI."); + for (JsonNode item : keyArray) { + result.add(batchJobFromMldev(JsonSerializable.toJsonNode(item), toObject)); + } + Common.setValueByPath(toObject, new String[] {"batchJobs"}, result); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode batchJobDestinationToVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode listBatchJobsResponseFromVertex(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"format"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"predictionsFormat"}, - Common.getValueByPath(fromObject, new String[] {"format"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"gcsUri"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"}) != null) { Common.setValueByPath( toObject, - new String[] {"gcsDestination", "outputUriPrefix"}, - Common.getValueByPath(fromObject, new String[] {"gcsUri"})); + new String[] {"sdkHttpResponse"}, + Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"})); } - if (Common.getValueByPath(fromObject, new String[] {"bigqueryUri"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"nextPageToken"}) != null) { Common.setValueByPath( toObject, - new String[] {"bigqueryDestination", "outputUri"}, - Common.getValueByPath(fromObject, new String[] {"bigqueryUri"})); + new String[] {"nextPageToken"}, + Common.getValueByPath(fromObject, new String[] {"nextPageToken"})); } - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"fileName"}))) { - throw new IllegalArgumentException("fileName parameter is not supported in Vertex AI."); - } + if (Common.getValueByPath(fromObject, new String[] {"batchPredictionJobs"}) != null) { + ArrayNode keyArray = + (ArrayNode) Common.getValueByPath(fromObject, new String[] {"batchPredictionJobs"}); + ObjectMapper objectMapper = new ObjectMapper(); + ArrayNode result = objectMapper.createArrayNode(); - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"inlinedResponses"}))) { - throw new IllegalArgumentException( - "inlinedResponses parameter is not supported in Vertex AI."); + for (JsonNode item : keyArray) { + result.add(batchJobFromVertex(JsonSerializable.toJsonNode(item), toObject)); + } + Common.setValueByPath(toObject, new String[] {"batchJobs"}, result); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode createBatchJobConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - if (Common.getValueByPath(fromObject, new String[] {"displayName"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"displayName"}, - Common.getValueByPath(fromObject, new String[] {"displayName"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"dest"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"outputConfig"}, - batchJobDestinationToVertex( - JsonSerializable.toJsonNode( - Transformers.tBatchJobDestination( - Common.getValueByPath(fromObject, new String[] {"dest"}))), - toObject)); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode createBatchJobParametersToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"model"}, - Transformers.tModel( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); - } - - if (Common.getValueByPath(fromObject, new String[] {"src"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"inputConfig"}, - batchJobSourceToVertex( - JsonSerializable.toJsonNode( - Transformers.tBatchJobSource( - Common.getValueByPath(fromObject, new String[] {"src"}))), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"config"}, - createBatchJobConfigToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"config"})), - toObject)); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode getBatchJobParametersToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"_url", "name"}, - Transformers.tBatchJobName( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"name"}))); - } - - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"config"}, - Common.getValueByPath(fromObject, new String[] {"config"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode cancelBatchJobParametersToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"_url", "name"}, - Transformers.tBatchJobName( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"name"}))); - } - - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"config"}, - Common.getValueByPath(fromObject, new String[] {"config"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode listBatchJobsConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - if (Common.getValueByPath(fromObject, new String[] {"pageSize"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"_query", "pageSize"}, - Common.getValueByPath(fromObject, new String[] {"pageSize"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"pageToken"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"_query", "pageToken"}, - Common.getValueByPath(fromObject, new String[] {"pageToken"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"filter"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"_query", "filter"}, - Common.getValueByPath(fromObject, new String[] {"filter"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode listBatchJobsParametersToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"config"}, - listBatchJobsConfigToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"config"})), - toObject)); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode deleteBatchJobParametersToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"_url", "name"}, - Transformers.tBatchJobName( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"name"}))); - } - - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"config"}, - Common.getValueByPath(fromObject, new String[] {"config"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode videoMetadataFromMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"fps"}) != null) { - Common.setValueByPath( - toObject, new String[] {"fps"}, Common.getValueByPath(fromObject, new String[] {"fps"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"endOffset"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"endOffset"}, - Common.getValueByPath(fromObject, new String[] {"endOffset"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"startOffset"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"startOffset"}, - Common.getValueByPath(fromObject, new String[] {"startOffset"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode blobFromMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - if (Common.getValueByPath(fromObject, new String[] {"data"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"data"}, - Common.getValueByPath(fromObject, new String[] {"data"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"mimeType"}, - Common.getValueByPath(fromObject, new String[] {"mimeType"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode fileDataFromMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - if (Common.getValueByPath(fromObject, new String[] {"fileUri"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"fileUri"}, - Common.getValueByPath(fromObject, new String[] {"fileUri"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"mimeType"}, - Common.getValueByPath(fromObject, new String[] {"mimeType"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode partFromMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"videoMetadata"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"videoMetadata"}, - videoMetadataFromMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"videoMetadata"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"thought"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"thought"}, - Common.getValueByPath(fromObject, new String[] {"thought"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"inlineData"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"inlineData"}, - blobFromMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"inlineData"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"fileData"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"fileData"}, - fileDataFromMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"fileData"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"thoughtSignature"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"thoughtSignature"}, - Common.getValueByPath(fromObject, new String[] {"thoughtSignature"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"codeExecutionResult"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"codeExecutionResult"}, - Common.getValueByPath(fromObject, new String[] {"codeExecutionResult"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"executableCode"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"executableCode"}, - Common.getValueByPath(fromObject, new String[] {"executableCode"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"functionCall"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"functionCall"}, - Common.getValueByPath(fromObject, new String[] {"functionCall"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"functionResponse"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"functionResponse"}, - Common.getValueByPath(fromObject, new String[] {"functionResponse"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"text"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"text"}, - Common.getValueByPath(fromObject, new String[] {"text"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode contentFromMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"parts"}) != null) { - ArrayNode keyArray = (ArrayNode) Common.getValueByPath(fromObject, new String[] {"parts"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add(partFromMldev(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"parts"}, result); - } - - if (Common.getValueByPath(fromObject, new String[] {"role"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"role"}, - Common.getValueByPath(fromObject, new String[] {"role"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode citationMetadataFromMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"citationSources"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"citations"}, - Common.getValueByPath(fromObject, new String[] {"citationSources"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode urlMetadataFromMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"retrievedUrl"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"retrievedUrl"}, - Common.getValueByPath(fromObject, new String[] {"retrievedUrl"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"urlRetrievalStatus"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"urlRetrievalStatus"}, - Common.getValueByPath(fromObject, new String[] {"urlRetrievalStatus"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode urlContextMetadataFromMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"urlMetadata"}) != null) { - ArrayNode keyArray = - (ArrayNode) Common.getValueByPath(fromObject, new String[] {"urlMetadata"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add(urlMetadataFromMldev(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"urlMetadata"}, result); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode candidateFromMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"content"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"content"}, - contentFromMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"content"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"citationMetadata"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"citationMetadata"}, - citationMetadataFromMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"citationMetadata"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"tokenCount"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"tokenCount"}, - Common.getValueByPath(fromObject, new String[] {"tokenCount"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"finishReason"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"finishReason"}, - Common.getValueByPath(fromObject, new String[] {"finishReason"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"urlContextMetadata"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"urlContextMetadata"}, - urlContextMetadataFromMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"urlContextMetadata"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"avgLogprobs"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"avgLogprobs"}, - Common.getValueByPath(fromObject, new String[] {"avgLogprobs"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"groundingMetadata"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"groundingMetadata"}, - Common.getValueByPath(fromObject, new String[] {"groundingMetadata"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"index"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"index"}, - Common.getValueByPath(fromObject, new String[] {"index"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"logprobsResult"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"logprobsResult"}, - Common.getValueByPath(fromObject, new String[] {"logprobsResult"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"safetyRatings"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"safetyRatings"}, - Common.getValueByPath(fromObject, new String[] {"safetyRatings"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode generateContentResponseFromMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"sdkHttpResponse"}, - Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"candidates"}) != null) { - ArrayNode keyArray = - (ArrayNode) Common.getValueByPath(fromObject, new String[] {"candidates"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add(candidateFromMldev(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"candidates"}, result); - } - - if (Common.getValueByPath(fromObject, new String[] {"modelVersion"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"modelVersion"}, - Common.getValueByPath(fromObject, new String[] {"modelVersion"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"promptFeedback"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"promptFeedback"}, - Common.getValueByPath(fromObject, new String[] {"promptFeedback"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"usageMetadata"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"usageMetadata"}, - Common.getValueByPath(fromObject, new String[] {"usageMetadata"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode jobErrorFromMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"details"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"details"}, - Common.getValueByPath(fromObject, new String[] {"details"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"code"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"code"}, - Common.getValueByPath(fromObject, new String[] {"code"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"message"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"message"}, - Common.getValueByPath(fromObject, new String[] {"message"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode inlinedResponseFromMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"response"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"response"}, - generateContentResponseFromMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"response"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"error"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"error"}, - jobErrorFromMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"error"})), - toObject)); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode batchJobDestinationFromMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - if (Common.getValueByPath(fromObject, new String[] {"responsesFile"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"fileName"}, - Common.getValueByPath(fromObject, new String[] {"responsesFile"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"inlinedResponses", "inlinedResponses"}) - != null) { - ArrayNode keyArray = - (ArrayNode) - Common.getValueByPath( - fromObject, new String[] {"inlinedResponses", "inlinedResponses"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add(inlinedResponseFromMldev(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"inlinedResponses"}, result); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode batchJobFromMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode partToMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"name"}, - Common.getValueByPath(fromObject, new String[] {"name"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"metadata", "displayName"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"displayName"}, - Common.getValueByPath(fromObject, new String[] {"metadata", "displayName"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"metadata", "state"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"state"}, - Transformers.tJobState( - Common.getValueByPath(fromObject, new String[] {"metadata", "state"}))); - } - - if (Common.getValueByPath(fromObject, new String[] {"metadata", "createTime"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"createTime"}, - Common.getValueByPath(fromObject, new String[] {"metadata", "createTime"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"metadata", "endTime"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"functionCall"}) != null) { Common.setValueByPath( toObject, - new String[] {"endTime"}, - Common.getValueByPath(fromObject, new String[] {"metadata", "endTime"})); + new String[] {"functionCall"}, + Common.getValueByPath(fromObject, new String[] {"functionCall"})); } - if (Common.getValueByPath(fromObject, new String[] {"metadata", "updateTime"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"codeExecutionResult"}) != null) { Common.setValueByPath( toObject, - new String[] {"updateTime"}, - Common.getValueByPath(fromObject, new String[] {"metadata", "updateTime"})); + new String[] {"codeExecutionResult"}, + Common.getValueByPath(fromObject, new String[] {"codeExecutionResult"})); } - if (Common.getValueByPath(fromObject, new String[] {"metadata", "model"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"executableCode"}) != null) { Common.setValueByPath( toObject, - new String[] {"model"}, - Common.getValueByPath(fromObject, new String[] {"metadata", "model"})); + new String[] {"executableCode"}, + Common.getValueByPath(fromObject, new String[] {"executableCode"})); } - if (Common.getValueByPath(fromObject, new String[] {"metadata", "output"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"fileData"}) != null) { Common.setValueByPath( toObject, - new String[] {"dest"}, - batchJobDestinationFromMldev( + new String[] {"fileData"}, + fileDataToMldev( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"metadata", "output"})), + Common.getValueByPath(fromObject, new String[] {"fileData"})), toObject)); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode listBatchJobsResponseFromMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - if (Common.getValueByPath(fromObject, new String[] {"nextPageToken"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"nextPageToken"}, - Common.getValueByPath(fromObject, new String[] {"nextPageToken"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"operations"}) != null) { - ArrayNode keyArray = - (ArrayNode) Common.getValueByPath(fromObject, new String[] {"operations"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add(batchJobFromMldev(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"batchJobs"}, result); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode deleteResourceJobFromMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"name"}, - Common.getValueByPath(fromObject, new String[] {"name"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"done"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"functionResponse"}) != null) { Common.setValueByPath( toObject, - new String[] {"done"}, - Common.getValueByPath(fromObject, new String[] {"done"})); + new String[] {"functionResponse"}, + Common.getValueByPath(fromObject, new String[] {"functionResponse"})); } - if (Common.getValueByPath(fromObject, new String[] {"error"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"inlineData"}) != null) { Common.setValueByPath( toObject, - new String[] {"error"}, - jobErrorFromMldev( + new String[] {"inlineData"}, + blobToMldev( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"error"})), + Common.getValueByPath(fromObject, new String[] {"inlineData"})), toObject)); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode jobErrorFromVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"details"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"details"}, - Common.getValueByPath(fromObject, new String[] {"details"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"code"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"code"}, - Common.getValueByPath(fromObject, new String[] {"code"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"message"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"message"}, - Common.getValueByPath(fromObject, new String[] {"message"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode batchJobSourceFromVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"instancesFormat"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"format"}, - Common.getValueByPath(fromObject, new String[] {"instancesFormat"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"gcsSource", "uris"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"gcsUri"}, - Common.getValueByPath(fromObject, new String[] {"gcsSource", "uris"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"bigquerySource", "inputUri"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"text"}) != null) { Common.setValueByPath( toObject, - new String[] {"bigqueryUri"}, - Common.getValueByPath(fromObject, new String[] {"bigquerySource", "inputUri"})); + new String[] {"text"}, + Common.getValueByPath(fromObject, new String[] {"text"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode batchJobDestinationFromVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"predictionsFormat"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"thought"}) != null) { Common.setValueByPath( toObject, - new String[] {"format"}, - Common.getValueByPath(fromObject, new String[] {"predictionsFormat"})); + new String[] {"thought"}, + Common.getValueByPath(fromObject, new String[] {"thought"})); } - if (Common.getValueByPath(fromObject, new String[] {"gcsDestination", "outputUriPrefix"}) - != null) { + if (Common.getValueByPath(fromObject, new String[] {"thoughtSignature"}) != null) { Common.setValueByPath( toObject, - new String[] {"gcsUri"}, - Common.getValueByPath(fromObject, new String[] {"gcsDestination", "outputUriPrefix"})); + new String[] {"thoughtSignature"}, + Common.getValueByPath(fromObject, new String[] {"thoughtSignature"})); } - if (Common.getValueByPath(fromObject, new String[] {"bigqueryDestination", "outputUri"}) - != null) { + if (Common.getValueByPath(fromObject, new String[] {"videoMetadata"}) != null) { Common.setValueByPath( toObject, - new String[] {"bigqueryUri"}, - Common.getValueByPath(fromObject, new String[] {"bigqueryDestination", "outputUri"})); + new String[] {"videoMetadata"}, + Common.getValueByPath(fromObject, new String[] {"videoMetadata"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode batchJobFromVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode safetySettingToMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"name"}, - Common.getValueByPath(fromObject, new String[] {"name"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"displayName"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"displayName"}, - Common.getValueByPath(fromObject, new String[] {"displayName"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"state"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"state"}, - Transformers.tJobState(Common.getValueByPath(fromObject, new String[] {"state"}))); - } - - if (Common.getValueByPath(fromObject, new String[] {"error"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"error"}, - jobErrorFromVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"error"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"createTime"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"createTime"}, - Common.getValueByPath(fromObject, new String[] {"createTime"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"startTime"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"startTime"}, - Common.getValueByPath(fromObject, new String[] {"startTime"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"endTime"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"endTime"}, - Common.getValueByPath(fromObject, new String[] {"endTime"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"updateTime"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"updateTime"}, - Common.getValueByPath(fromObject, new String[] {"updateTime"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"category"}) != null) { Common.setValueByPath( toObject, - new String[] {"model"}, - Common.getValueByPath(fromObject, new String[] {"model"})); + new String[] {"category"}, + Common.getValueByPath(fromObject, new String[] {"category"})); } - if (Common.getValueByPath(fromObject, new String[] {"inputConfig"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"src"}, - batchJobSourceFromVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"inputConfig"})), - toObject)); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"method"}))) { + throw new IllegalArgumentException("method parameter is not supported in Gemini API."); } - if (Common.getValueByPath(fromObject, new String[] {"outputConfig"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"dest"}, - batchJobDestinationFromVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"outputConfig"})), - toObject)); + if (Common.getValueByPath(fromObject, new String[] {"threshold"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"threshold"}, + Common.getValueByPath(fromObject, new String[] {"threshold"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode listBatchJobsResponseFromVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toolToMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - if (Common.getValueByPath(fromObject, new String[] {"nextPageToken"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"functionDeclarations"}) != null) { Common.setValueByPath( toObject, - new String[] {"nextPageToken"}, - Common.getValueByPath(fromObject, new String[] {"nextPageToken"})); + new String[] {"functionDeclarations"}, + Common.getValueByPath(fromObject, new String[] {"functionDeclarations"})); } - if (Common.getValueByPath(fromObject, new String[] {"batchPredictionJobs"}) != null) { - ArrayNode keyArray = - (ArrayNode) Common.getValueByPath(fromObject, new String[] {"batchPredictionJobs"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"retrieval"}))) { + throw new IllegalArgumentException("retrieval parameter is not supported in Gemini API."); + } - for (JsonNode item : keyArray) { - result.add(batchJobFromVertex(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"batchJobs"}, result); + if (Common.getValueByPath(fromObject, new String[] {"googleSearchRetrieval"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"googleSearchRetrieval"}, + Common.getValueByPath(fromObject, new String[] {"googleSearchRetrieval"})); } - return toObject; - } + if (Common.getValueByPath(fromObject, new String[] {"googleMaps"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"googleMaps"}, + googleMapsToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"googleMaps"})), + toObject)); + } - @ExcludeFromGeneratedCoverageReport - ObjectNode deleteResourceJobFromVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"computerUse"}) != null) { Common.setValueByPath( toObject, - new String[] {"name"}, - Common.getValueByPath(fromObject, new String[] {"name"})); + new String[] {"computerUse"}, + Common.getValueByPath(fromObject, new String[] {"computerUse"})); } - if (Common.getValueByPath(fromObject, new String[] {"done"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"codeExecution"}) != null) { Common.setValueByPath( toObject, - new String[] {"done"}, - Common.getValueByPath(fromObject, new String[] {"done"})); + new String[] {"codeExecution"}, + Common.getValueByPath(fromObject, new String[] {"codeExecution"})); } - if (Common.getValueByPath(fromObject, new String[] {"error"}) != null) { + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"enterpriseWebSearch"}))) { + throw new IllegalArgumentException( + "enterpriseWebSearch parameter is not supported in Gemini API."); + } + + if (Common.getValueByPath(fromObject, new String[] {"googleSearch"}) != null) { Common.setValueByPath( toObject, - new String[] {"error"}, - jobErrorFromVertex( + new String[] {"googleSearch"}, + googleSearchToMldev( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"error"})), + Common.getValueByPath(fromObject, new String[] {"googleSearch"})), toObject)); } + if (Common.getValueByPath(fromObject, new String[] {"urlContext"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"urlContext"}, + Common.getValueByPath(fromObject, new String[] {"urlContext"})); + } + return toObject; } - BatchJob privateCreate(String model, BatchJobSource src, CreateBatchJobConfig config) { + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForPrivateCreate( + String model, BatchJobSource src, CreateBatchJobConfig config) { CreateBatchJobParameters.Builder parameterBuilder = CreateBatchJobParameters.builder(); @@ -2371,44 +1732,133 @@ BatchJob privateCreate(String model, BatchJobSource src, CreateBatchJobConfig co } // TODO: Remove the hack that removes config. - body.remove("config"); - Optional requestHttpOptions = Optional.empty(); if (config != null) { requestHttpOptions = config.httpOptions(); } + return new BuiltRequest(path, JsonSerializable.toJsonString(body), requestHttpOptions); + } + + /** A shared processResponse function for both sync and async methods. */ + BatchJob processResponseForPrivateCreate(ApiResponse response, CreateBatchJobConfig config) { + ResponseBody responseBody = response.getBody(); + String responseString; + try { + responseString = responseBody.string(); + } catch (IOException e) { + throw new GenAiIOException("Failed to read HTTP response.", e); + } + + JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); + + if (this.apiClient.vertexAI()) { + responseNode = batchJobFromVertex(responseNode, null); + } + + if (!this.apiClient.vertexAI()) { + responseNode = batchJobFromMldev(responseNode, null); + } + + return JsonSerializable.fromJsonNode(responseNode, BatchJob.class); + } + + BatchJob privateCreate(String model, BatchJobSource src, CreateBatchJobConfig config) { + BuiltRequest builtRequest = buildRequestForPrivateCreate(model, src, config); + try (ApiResponse response = this.apiClient.request( - "post", path, JsonSerializable.toJsonString(body), requestHttpOptions)) { - ResponseBody responseBody = response.getBody(); - String responseString; - try { - responseString = responseBody.string(); - } catch (IOException e) { - throw new GenAiIOException("Failed to read HTTP response.", e); - } + "post", builtRequest.path, builtRequest.body, builtRequest.httpOptions)) { + return processResponseForPrivateCreate(response, config); + } + } + + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForPrivateCreateEmbeddings( + String model, EmbeddingsBatchJobSource src, CreateEmbeddingsBatchJobConfig config) { + + CreateEmbeddingsBatchJobParameters.Builder parameterBuilder = + CreateEmbeddingsBatchJobParameters.builder(); + + if (!Common.isZero(model)) { + parameterBuilder.model(model); + } + if (!Common.isZero(src)) { + parameterBuilder.src(src); + } + if (!Common.isZero(config)) { + parameterBuilder.config(config); + } + JsonNode parameterNode = JsonSerializable.toJsonNode(parameterBuilder.build()); - JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); - if (this.apiClient.vertexAI()) { - responseNode = batchJobFromVertex(responseNode, null); + ObjectNode body; + String path; + if (this.apiClient.vertexAI()) { + throw new UnsupportedOperationException( + "This method is only supported in the Gemini Developer client."); + } else { + body = createEmbeddingsBatchJobParametersToMldev(this.apiClient, parameterNode, null); + if (body.get("_url") != null) { + path = Common.formatMap("{model}:asyncBatchEmbedContent", body.get("_url")); } else { - responseNode = batchJobFromMldev(responseNode, null); + path = "{model}:asyncBatchEmbedContent"; } - return JsonSerializable.fromJsonNode(responseNode, BatchJob.class); } + body.remove("_url"); + + JsonNode queryParams = body.get("_query"); + if (queryParams != null) { + body.remove("_query"); + path = String.format("%s?%s", path, Common.urlEncode((ObjectNode) queryParams)); + } + + // TODO: Remove the hack that removes config. + Optional requestHttpOptions = Optional.empty(); + if (config != null) { + requestHttpOptions = config.httpOptions(); + } + + return new BuiltRequest(path, JsonSerializable.toJsonString(body), requestHttpOptions); } - /** - * Gets a batch job resource. - * - * @param name A fully-qualified BatchJob resource name or ID. Example: - * "projects/.../locations/.../batchPredictionJobs/456" or "456" when project and location are - * initialized in the Vertex AI client. Or "batches/abc" using the Gemini Developer AI client. - * @param config A {@link GetBatchJobConfig} for configuring the get request. - * @return A {@link BatchJob} object that contains the info of the batch job. - */ - public BatchJob get(String name, GetBatchJobConfig config) { + /** A shared processResponse function for both sync and async methods. */ + BatchJob processResponseForPrivateCreateEmbeddings( + ApiResponse response, CreateEmbeddingsBatchJobConfig config) { + ResponseBody responseBody = response.getBody(); + String responseString; + try { + responseString = responseBody.string(); + } catch (IOException e) { + throw new GenAiIOException("Failed to read HTTP response.", e); + } + + JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); + + if (this.apiClient.vertexAI()) { + throw new UnsupportedOperationException( + "This method is only supported in the Gemini Developer client."); + } + + if (!this.apiClient.vertexAI()) { + responseNode = batchJobFromMldev(responseNode, null); + } + + return JsonSerializable.fromJsonNode(responseNode, BatchJob.class); + } + + BatchJob privateCreateEmbeddings( + String model, EmbeddingsBatchJobSource src, CreateEmbeddingsBatchJobConfig config) { + BuiltRequest builtRequest = buildRequestForPrivateCreateEmbeddings(model, src, config); + + try (ApiResponse response = + this.apiClient.request( + "post", builtRequest.path, builtRequest.body, builtRequest.httpOptions)) { + return processResponseForPrivateCreateEmbeddings(response, config); + } + } + + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForGet(String name, GetBatchJobConfig config) { GetBatchJobParameters.Builder parameterBuilder = GetBatchJobParameters.builder(); @@ -2442,43 +1892,58 @@ public BatchJob get(String name, GetBatchJobConfig config) { } // TODO: Remove the hack that removes config. - body.remove("config"); - Optional requestHttpOptions = Optional.empty(); if (config != null) { requestHttpOptions = config.httpOptions(); } - try (ApiResponse response = - this.apiClient.request( - "get", path, JsonSerializable.toJsonString(body), requestHttpOptions)) { - ResponseBody responseBody = response.getBody(); - String responseString; - try { - responseString = responseBody.string(); - } catch (IOException e) { - throw new GenAiIOException("Failed to read HTTP response.", e); - } + return new BuiltRequest(path, JsonSerializable.toJsonString(body), requestHttpOptions); + } - JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); - if (this.apiClient.vertexAI()) { - responseNode = batchJobFromVertex(responseNode, null); - } else { - responseNode = batchJobFromMldev(responseNode, null); - } - return JsonSerializable.fromJsonNode(responseNode, BatchJob.class); + /** A shared processResponse function for both sync and async methods. */ + BatchJob processResponseForGet(ApiResponse response, GetBatchJobConfig config) { + ResponseBody responseBody = response.getBody(); + String responseString; + try { + responseString = responseBody.string(); + } catch (IOException e) { + throw new GenAiIOException("Failed to read HTTP response.", e); + } + + JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); + + if (this.apiClient.vertexAI()) { + responseNode = batchJobFromVertex(responseNode, null); + } + + if (!this.apiClient.vertexAI()) { + responseNode = batchJobFromMldev(responseNode, null); } + + return JsonSerializable.fromJsonNode(responseNode, BatchJob.class); } /** - * Cancels a batch job resource. + * Gets a batch job resource. * * @param name A fully-qualified BatchJob resource name or ID. Example: * "projects/.../locations/.../batchPredictionJobs/456" or "456" when project and location are * initialized in the Vertex AI client. Or "batches/abc" using the Gemini Developer AI client. - * @param config A {@link CancelBatchJobConfig} for configuring the cancel request. + * @param config A {@link GetBatchJobConfig} for configuring the get request. + * @return A {@link BatchJob} object that contains the info of the batch job. */ - public void cancel(String name, CancelBatchJobConfig config) { + public BatchJob get(String name, GetBatchJobConfig config) { + BuiltRequest builtRequest = buildRequestForGet(name, config); + + try (ApiResponse response = + this.apiClient.request( + "get", builtRequest.path, builtRequest.body, builtRequest.httpOptions)) { + return processResponseForGet(response, config); + } + } + + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForCancel(String name, CancelBatchJobConfig config) { CancelBatchJobParameters.Builder parameterBuilder = CancelBatchJobParameters.builder(); @@ -2512,17 +1977,34 @@ public void cancel(String name, CancelBatchJobConfig config) { } // TODO: Remove the hack that removes config. - body.remove("config"); - Optional requestHttpOptions = Optional.empty(); if (config != null) { requestHttpOptions = config.httpOptions(); } - this.apiClient.request("post", path, JsonSerializable.toJsonString(body), requestHttpOptions); + return new BuiltRequest(path, JsonSerializable.toJsonString(body), requestHttpOptions); } - ListBatchJobsResponse privateList(ListBatchJobsConfig config) { + /** + * Cancels a batch job resource. + * + * @param name A fully-qualified BatchJob resource name or ID. Example: + * "projects/.../locations/.../batchPredictionJobs/456" or "456" when project and location are + * initialized in the Vertex AI client. Or "batches/abc" using the Gemini Developer AI client. + * @param config A {@link CancelBatchJobConfig} for configuring the cancel request. + */ + public void cancel(String name, CancelBatchJobConfig config) { + BuiltRequest builtRequest = buildRequestForCancel(name, config); + + try (ApiResponse response = + this.apiClient.request( + "post", builtRequest.path, builtRequest.body, builtRequest.httpOptions)) { + return; + } + } + + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForPrivateList(ListBatchJobsConfig config) { ListBatchJobsParameters.Builder parameterBuilder = ListBatchJobsParameters.builder(); @@ -2553,43 +2035,60 @@ ListBatchJobsResponse privateList(ListBatchJobsConfig config) { } // TODO: Remove the hack that removes config. - body.remove("config"); - Optional requestHttpOptions = Optional.empty(); if (config != null) { requestHttpOptions = config.httpOptions(); } + return new BuiltRequest(path, JsonSerializable.toJsonString(body), requestHttpOptions); + } + + /** A shared processResponse function for both sync and async methods. */ + ListBatchJobsResponse processResponseForPrivateList( + ApiResponse response, ListBatchJobsConfig config) { + ResponseBody responseBody = response.getBody(); + String responseString; + try { + responseString = responseBody.string(); + } catch (IOException e) { + throw new GenAiIOException("Failed to read HTTP response.", e); + } + + JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); + + if (this.apiClient.vertexAI()) { + responseNode = listBatchJobsResponseFromVertex(responseNode, null); + } + + if (!this.apiClient.vertexAI()) { + responseNode = listBatchJobsResponseFromMldev(responseNode, null); + } + + ListBatchJobsResponse sdkResponse = + JsonSerializable.fromJsonNode(responseNode, ListBatchJobsResponse.class); + Headers responseHeaders = response.getHeaders(); + if (responseHeaders == null) { + return sdkResponse; + } + Map headers = new HashMap<>(); + for (String headerName : responseHeaders.names()) { + headers.put(headerName, responseHeaders.get(headerName)); + } + return sdkResponse.toBuilder().sdkHttpResponse(HttpResponse.builder().headers(headers)).build(); + } + + ListBatchJobsResponse privateList(ListBatchJobsConfig config) { + BuiltRequest builtRequest = buildRequestForPrivateList(config); + try (ApiResponse response = this.apiClient.request( - "get", path, JsonSerializable.toJsonString(body), requestHttpOptions)) { - ResponseBody responseBody = response.getBody(); - String responseString; - try { - responseString = responseBody.string(); - } catch (IOException e) { - throw new GenAiIOException("Failed to read HTTP response.", e); - } - - JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); - if (this.apiClient.vertexAI()) { - responseNode = listBatchJobsResponseFromVertex(responseNode, null); - } else { - responseNode = listBatchJobsResponseFromMldev(responseNode, null); - } - return JsonSerializable.fromJsonNode(responseNode, ListBatchJobsResponse.class); + "get", builtRequest.path, builtRequest.body, builtRequest.httpOptions)) { + return processResponseForPrivateList(response, config); } } - /** - * Deletes a batch job resource. - * - * @param name A fully-qualified BatchJob resource name or ID. Example: - * "projects/.../locations/.../batchPredictionJobs/456" or "456" when project and location are - * initialized in the Vertex AI client. Or "batches/abc" using the Gemini Developer AI client. - * @param config A {@link DeleteBatchJobConfig} for configuring the delete request. - */ - public DeleteResourceJob delete(String name, DeleteBatchJobConfig config) { + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForDelete(String name, DeleteBatchJobConfig config) { DeleteBatchJobParameters.Builder parameterBuilder = DeleteBatchJobParameters.builder(); @@ -2623,31 +2122,62 @@ public DeleteResourceJob delete(String name, DeleteBatchJobConfig config) { } // TODO: Remove the hack that removes config. - body.remove("config"); - Optional requestHttpOptions = Optional.empty(); if (config != null) { requestHttpOptions = config.httpOptions(); } + return new BuiltRequest(path, JsonSerializable.toJsonString(body), requestHttpOptions); + } + + /** A shared processResponse function for both sync and async methods. */ + DeleteResourceJob processResponseForDelete(ApiResponse response, DeleteBatchJobConfig config) { + ResponseBody responseBody = response.getBody(); + String responseString; + try { + responseString = responseBody.string(); + } catch (IOException e) { + throw new GenAiIOException("Failed to read HTTP response.", e); + } + + JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); + + if (this.apiClient.vertexAI()) { + responseNode = deleteResourceJobFromVertex(responseNode, null); + } + + if (!this.apiClient.vertexAI()) { + responseNode = deleteResourceJobFromMldev(responseNode, null); + } + + DeleteResourceJob sdkResponse = + JsonSerializable.fromJsonNode(responseNode, DeleteResourceJob.class); + Headers responseHeaders = response.getHeaders(); + if (responseHeaders == null) { + return sdkResponse; + } + Map headers = new HashMap<>(); + for (String headerName : responseHeaders.names()) { + headers.put(headerName, responseHeaders.get(headerName)); + } + return sdkResponse.toBuilder().sdkHttpResponse(HttpResponse.builder().headers(headers)).build(); + } + + /** + * Deletes a batch job resource. + * + * @param name A fully-qualified BatchJob resource name or ID. Example: + * "projects/.../locations/.../batchPredictionJobs/456" or "456" when project and location are + * initialized in the Vertex AI client. Or "batches/abc" using the Gemini Developer AI client. + * @param config A {@link DeleteBatchJobConfig} for configuring the delete request. + */ + public DeleteResourceJob delete(String name, DeleteBatchJobConfig config) { + BuiltRequest builtRequest = buildRequestForDelete(name, config); + try (ApiResponse response = this.apiClient.request( - "delete", path, JsonSerializable.toJsonString(body), requestHttpOptions)) { - ResponseBody responseBody = response.getBody(); - String responseString; - try { - responseString = responseBody.string(); - } catch (IOException e) { - throw new GenAiIOException("Failed to read HTTP response.", e); - } - - JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); - if (this.apiClient.vertexAI()) { - responseNode = deleteResourceJobFromVertex(responseNode, null); - } else { - responseNode = deleteResourceJobFromMldev(responseNode, null); - } - return JsonSerializable.fromJsonNode(responseNode, DeleteResourceJob.class); + "delete", builtRequest.path, builtRequest.body, builtRequest.httpOptions)) { + return processResponseForDelete(response, config); } } @@ -2678,12 +2208,31 @@ public BatchJob create(String model, BatchJobSource src, CreateBatchJobConfig co throw new GenAiIOException("Only one of fileName and InlinedRequests can be set."); } if (!src.fileName().isPresent() && !src.inlinedRequests().isPresent()) { - throw new GenAiIOException("One of fileName and InlinedRequests must be set."); + throw new GenAiIOException("one of fileName and InlinedRequests must be set."); } } return this.privateCreate(model, src, config); } + /** + * Makes an API request to create the batch embeddings job. + * + *

This method is experimental. + * + * @param model the name of the GenAI model to use for generation + * @param src The {@link EmbeddingsBatchJobSource} of the batch job. + * @param config The configuration {@link CreateEmbeddingsBatchJobConfig} for the batch job. + * @return A BatchJob. + */ + public BatchJob createEmbeddings( + String model, EmbeddingsBatchJobSource src, CreateEmbeddingsBatchJobConfig config) { + if (this.apiClient.vertexAI()) { + throw new UnsupportedOperationException( + "Vertex AI does not support batches.createEmbeddings."); + } + return this.privateCreateEmbeddings(model, src, config); + } + /** * Makes an API request to list the available batch jobs. * diff --git a/src/main/java/com/google/genai/Caches.java b/src/main/java/com/google/genai/Caches.java index f7e807b750a..83bddf7ba7a 100644 --- a/src/main/java/com/google/genai/Caches.java +++ b/src/main/java/com/google/genai/Caches.java @@ -22,7 +22,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; -import com.google.common.collect.ImmutableSet; +import com.google.genai.Common.BuiltRequest; import com.google.genai.errors.GenAiIOException; import com.google.genai.types.CachedContent; import com.google.genai.types.CreateCachedContentConfig; @@ -33,14 +33,18 @@ import com.google.genai.types.GetCachedContentConfig; import com.google.genai.types.GetCachedContentParameters; import com.google.genai.types.HttpOptions; +import com.google.genai.types.HttpResponse; import com.google.genai.types.ListCachedContentsConfig; import com.google.genai.types.ListCachedContentsParameters; import com.google.genai.types.ListCachedContentsResponse; import com.google.genai.types.UpdateCachedContentConfig; import com.google.genai.types.UpdateCachedContentParameters; import java.io.IOException; +import java.util.HashMap; +import java.util.Map; import java.util.Optional; import java.util.function.Function; +import okhttp3.Headers; import okhttp3.ResponseBody; /** @@ -48,44 +52,16 @@ * instantiating a {@link Client}, access methods through `client.caches.methodName(...)` directly. */ public final class Caches { + final ApiClient apiClient; public Caches(ApiClient apiClient) { this.apiClient = apiClient; } - @ExcludeFromGeneratedCoverageReport - ObjectNode videoMetadataToMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"fps"}) != null) { - Common.setValueByPath( - toObject, new String[] {"fps"}, Common.getValueByPath(fromObject, new String[] {"fps"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"endOffset"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"endOffset"}, - Common.getValueByPath(fromObject, new String[] {"endOffset"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"startOffset"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"startOffset"}, - Common.getValueByPath(fromObject, new String[] {"startOffset"})); - } - - return toObject; - } - @ExcludeFromGeneratedCoverageReport ObjectNode blobToMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"displayName"}))) { - throw new IllegalArgumentException("displayName parameter is not supported in Gemini API."); - } - if (Common.getValueByPath(fromObject, new String[] {"data"}) != null) { Common.setValueByPath( toObject, @@ -93,6 +69,10 @@ ObjectNode blobToMldev(JsonNode fromObject, ObjectNode parentObject) { Common.getValueByPath(fromObject, new String[] {"data"})); } + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"displayName"}))) { + throw new IllegalArgumentException("displayName parameter is not supported in Gemini API."); + } + if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { Common.setValueByPath( toObject, @@ -104,1675 +84,854 @@ ObjectNode blobToMldev(JsonNode fromObject, ObjectNode parentObject) { } @ExcludeFromGeneratedCoverageReport - ObjectNode fileDataToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode contentToMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"displayName"}))) { - throw new IllegalArgumentException("displayName parameter is not supported in Gemini API."); - } + if (Common.getValueByPath(fromObject, new String[] {"parts"}) != null) { + ArrayNode keyArray = (ArrayNode) Common.getValueByPath(fromObject, new String[] {"parts"}); + ObjectMapper objectMapper = new ObjectMapper(); + ArrayNode result = objectMapper.createArrayNode(); - if (Common.getValueByPath(fromObject, new String[] {"fileUri"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"fileUri"}, - Common.getValueByPath(fromObject, new String[] {"fileUri"})); + for (JsonNode item : keyArray) { + result.add(partToMldev(JsonSerializable.toJsonNode(item), toObject)); + } + Common.setValueByPath(toObject, new String[] {"parts"}, result); } - if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"role"}) != null) { Common.setValueByPath( toObject, - new String[] {"mimeType"}, - Common.getValueByPath(fromObject, new String[] {"mimeType"})); + new String[] {"role"}, + Common.getValueByPath(fromObject, new String[] {"role"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode partToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode createCachedContentConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"videoMetadata"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"videoMetadata"}, - videoMetadataToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"videoMetadata"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"thought"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"thought"}, - Common.getValueByPath(fromObject, new String[] {"thought"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"inlineData"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"inlineData"}, - blobToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"inlineData"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"fileData"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"fileData"}, - fileDataToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"fileData"})), - toObject)); - } - if (Common.getValueByPath(fromObject, new String[] {"thoughtSignature"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"ttl"}) != null) { Common.setValueByPath( - toObject, - new String[] {"thoughtSignature"}, - Common.getValueByPath(fromObject, new String[] {"thoughtSignature"})); + parentObject, + new String[] {"ttl"}, + Common.getValueByPath(fromObject, new String[] {"ttl"})); } - if (Common.getValueByPath(fromObject, new String[] {"codeExecutionResult"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"expireTime"}) != null) { Common.setValueByPath( - toObject, - new String[] {"codeExecutionResult"}, - Common.getValueByPath(fromObject, new String[] {"codeExecutionResult"})); + parentObject, + new String[] {"expireTime"}, + Common.getValueByPath(fromObject, new String[] {"expireTime"})); } - if (Common.getValueByPath(fromObject, new String[] {"executableCode"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"displayName"}) != null) { Common.setValueByPath( - toObject, - new String[] {"executableCode"}, - Common.getValueByPath(fromObject, new String[] {"executableCode"})); + parentObject, + new String[] {"displayName"}, + Common.getValueByPath(fromObject, new String[] {"displayName"})); } - if (Common.getValueByPath(fromObject, new String[] {"functionCall"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"functionCall"}, - Common.getValueByPath(fromObject, new String[] {"functionCall"})); - } + if (Common.getValueByPath(fromObject, new String[] {"contents"}) != null) { + ArrayNode keyArray = + (ArrayNode) + Transformers.tContents(Common.getValueByPath(fromObject, new String[] {"contents"})); + ObjectMapper objectMapper = new ObjectMapper(); + ArrayNode result = objectMapper.createArrayNode(); - if (Common.getValueByPath(fromObject, new String[] {"functionResponse"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"functionResponse"}, - Common.getValueByPath(fromObject, new String[] {"functionResponse"})); + for (JsonNode item : keyArray) { + result.add(contentToMldev(JsonSerializable.toJsonNode(item), toObject)); + } + Common.setValueByPath(parentObject, new String[] {"contents"}, result); } - if (Common.getValueByPath(fromObject, new String[] {"text"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"systemInstruction"}) != null) { Common.setValueByPath( - toObject, - new String[] {"text"}, - Common.getValueByPath(fromObject, new String[] {"text"})); + parentObject, + new String[] {"systemInstruction"}, + contentToMldev( + JsonSerializable.toJsonNode( + Transformers.tContent( + Common.getValueByPath(fromObject, new String[] {"systemInstruction"}))), + toObject)); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode contentToMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"parts"}) != null) { - ArrayNode keyArray = (ArrayNode) Common.getValueByPath(fromObject, new String[] {"parts"}); + if (Common.getValueByPath(fromObject, new String[] {"tools"}) != null) { + ArrayNode keyArray = (ArrayNode) Common.getValueByPath(fromObject, new String[] {"tools"}); ObjectMapper objectMapper = new ObjectMapper(); ArrayNode result = objectMapper.createArrayNode(); for (JsonNode item : keyArray) { - result.add(partToMldev(JsonSerializable.toJsonNode(item), toObject)); + result.add(toolToMldev(JsonSerializable.toJsonNode(item), toObject)); } - Common.setValueByPath(toObject, new String[] {"parts"}, result); + Common.setValueByPath(parentObject, new String[] {"tools"}, result); } - if (Common.getValueByPath(fromObject, new String[] {"role"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"toolConfig"}) != null) { Common.setValueByPath( - toObject, - new String[] {"role"}, - Common.getValueByPath(fromObject, new String[] {"role"})); + parentObject, + new String[] {"toolConfig"}, + Common.getValueByPath(fromObject, new String[] {"toolConfig"})); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"kmsKeyName"}))) { + throw new IllegalArgumentException("kmsKeyName parameter is not supported in Gemini API."); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode functionDeclarationToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode createCachedContentConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"behavior"}) != null) { + + if (Common.getValueByPath(fromObject, new String[] {"ttl"}) != null) { Common.setValueByPath( - toObject, - new String[] {"behavior"}, - Common.getValueByPath(fromObject, new String[] {"behavior"})); + parentObject, + new String[] {"ttl"}, + Common.getValueByPath(fromObject, new String[] {"ttl"})); } - if (Common.getValueByPath(fromObject, new String[] {"description"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"expireTime"}) != null) { Common.setValueByPath( - toObject, - new String[] {"description"}, - Common.getValueByPath(fromObject, new String[] {"description"})); + parentObject, + new String[] {"expireTime"}, + Common.getValueByPath(fromObject, new String[] {"expireTime"})); } - if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"displayName"}) != null) { Common.setValueByPath( - toObject, - new String[] {"name"}, - Common.getValueByPath(fromObject, new String[] {"name"})); + parentObject, + new String[] {"displayName"}, + Common.getValueByPath(fromObject, new String[] {"displayName"})); } - if (Common.getValueByPath(fromObject, new String[] {"parameters"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"contents"}) != null) { Common.setValueByPath( - toObject, - new String[] {"parameters"}, - Common.getValueByPath(fromObject, new String[] {"parameters"})); + parentObject, + new String[] {"contents"}, + Transformers.tContents(Common.getValueByPath(fromObject, new String[] {"contents"}))); } - if (Common.getValueByPath(fromObject, new String[] {"parametersJsonSchema"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"systemInstruction"}) != null) { Common.setValueByPath( - toObject, - new String[] {"parametersJsonSchema"}, - Common.getValueByPath(fromObject, new String[] {"parametersJsonSchema"})); + parentObject, + new String[] {"systemInstruction"}, + Transformers.tContent( + Common.getValueByPath(fromObject, new String[] {"systemInstruction"}))); } - if (Common.getValueByPath(fromObject, new String[] {"response"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"tools"}) != null) { + ArrayNode keyArray = (ArrayNode) Common.getValueByPath(fromObject, new String[] {"tools"}); + ObjectMapper objectMapper = new ObjectMapper(); + ArrayNode result = objectMapper.createArrayNode(); + + for (JsonNode item : keyArray) { + result.add(toolToVertex(JsonSerializable.toJsonNode(item), toObject)); + } + Common.setValueByPath(parentObject, new String[] {"tools"}, result); + } + + if (Common.getValueByPath(fromObject, new String[] {"toolConfig"}) != null) { Common.setValueByPath( - toObject, - new String[] {"response"}, - Common.getValueByPath(fromObject, new String[] {"response"})); + parentObject, + new String[] {"toolConfig"}, + Common.getValueByPath(fromObject, new String[] {"toolConfig"})); } - if (Common.getValueByPath(fromObject, new String[] {"responseJsonSchema"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"kmsKeyName"}) != null) { Common.setValueByPath( - toObject, - new String[] {"responseJsonSchema"}, - Common.getValueByPath(fromObject, new String[] {"responseJsonSchema"})); + parentObject, + new String[] {"encryption_spec", "kmsKeyName"}, + Common.getValueByPath(fromObject, new String[] {"kmsKeyName"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode intervalToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode createCachedContentParametersToMldev( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"startTime"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { Common.setValueByPath( toObject, - new String[] {"startTime"}, - Common.getValueByPath(fromObject, new String[] {"startTime"})); + new String[] {"model"}, + Transformers.tCachesModel( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); } - if (Common.getValueByPath(fromObject, new String[] {"endTime"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"endTime"}, - Common.getValueByPath(fromObject, new String[] {"endTime"})); + if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + JsonNode unused = + createCachedContentConfigToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"config"})), + toObject); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode googleSearchToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode createCachedContentParametersToVertex( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"timeRangeFilter"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { Common.setValueByPath( toObject, - new String[] {"timeRangeFilter"}, - intervalToMldev( + new String[] {"model"}, + Transformers.tCachesModel( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); + } + + if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + JsonNode unused = + createCachedContentConfigToVertex( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"timeRangeFilter"})), - toObject)); + Common.getValueByPath(fromObject, new String[] {"config"})), + toObject); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode dynamicRetrievalConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode deleteCachedContentParametersToMldev( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"mode"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { Common.setValueByPath( toObject, - new String[] {"mode"}, - Common.getValueByPath(fromObject, new String[] {"mode"})); + new String[] {"_url", "name"}, + Transformers.tCachedContentName( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"name"}))); } - if (Common.getValueByPath(fromObject, new String[] {"dynamicThreshold"}) != null) { + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode deleteCachedContentParametersToVertex( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { Common.setValueByPath( toObject, - new String[] {"dynamicThreshold"}, - Common.getValueByPath(fromObject, new String[] {"dynamicThreshold"})); + new String[] {"_url", "name"}, + Transformers.tCachedContentName( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"name"}))); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode googleSearchRetrievalToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode deleteCachedContentResponseFromMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"dynamicRetrievalConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"}) != null) { Common.setValueByPath( toObject, - new String[] {"dynamicRetrievalConfig"}, - dynamicRetrievalConfigToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"dynamicRetrievalConfig"})), - toObject)); + new String[] {"sdkHttpResponse"}, + Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode urlContextToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode deleteCachedContentResponseFromVertex(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"sdkHttpResponse"}, + Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"})); + } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode toolToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode fileDataToMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"functionDeclarations"}) != null) { - ArrayNode keyArray = - (ArrayNode) Common.getValueByPath(fromObject, new String[] {"functionDeclarations"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add(functionDeclarationToMldev(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"functionDeclarations"}, result); - } - - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"retrieval"}))) { - throw new IllegalArgumentException("retrieval parameter is not supported in Gemini API."); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"displayName"}))) { + throw new IllegalArgumentException("displayName parameter is not supported in Gemini API."); } - if (Common.getValueByPath(fromObject, new String[] {"googleSearch"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"fileUri"}) != null) { Common.setValueByPath( toObject, - new String[] {"googleSearch"}, - googleSearchToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"googleSearch"})), - toObject)); + new String[] {"fileUri"}, + Common.getValueByPath(fromObject, new String[] {"fileUri"})); } - if (Common.getValueByPath(fromObject, new String[] {"googleSearchRetrieval"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { Common.setValueByPath( toObject, - new String[] {"googleSearchRetrieval"}, - googleSearchRetrievalToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"googleSearchRetrieval"})), - toObject)); + new String[] {"mimeType"}, + Common.getValueByPath(fromObject, new String[] {"mimeType"})); } - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"enterpriseWebSearch"}))) { - throw new IllegalArgumentException( - "enterpriseWebSearch parameter is not supported in Gemini API."); - } + return toObject; + } - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"googleMaps"}))) { - throw new IllegalArgumentException("googleMaps parameter is not supported in Gemini API."); + @ExcludeFromGeneratedCoverageReport + ObjectNode functionDeclarationToVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"behavior"}))) { + throw new IllegalArgumentException("behavior parameter is not supported in Vertex AI."); } - if (Common.getValueByPath(fromObject, new String[] {"urlContext"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"description"}) != null) { Common.setValueByPath( toObject, - new String[] {"urlContext"}, - urlContextToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"urlContext"})), - toObject)); + new String[] {"description"}, + Common.getValueByPath(fromObject, new String[] {"description"})); } - if (Common.getValueByPath(fromObject, new String[] {"codeExecution"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { Common.setValueByPath( toObject, - new String[] {"codeExecution"}, - Common.getValueByPath(fromObject, new String[] {"codeExecution"})); + new String[] {"name"}, + Common.getValueByPath(fromObject, new String[] {"name"})); } - if (Common.getValueByPath(fromObject, new String[] {"computerUse"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"parameters"}) != null) { Common.setValueByPath( toObject, - new String[] {"computerUse"}, - Common.getValueByPath(fromObject, new String[] {"computerUse"})); + new String[] {"parameters"}, + Common.getValueByPath(fromObject, new String[] {"parameters"})); } - return toObject; - } + if (Common.getValueByPath(fromObject, new String[] {"parametersJsonSchema"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"parametersJsonSchema"}, + Common.getValueByPath(fromObject, new String[] {"parametersJsonSchema"})); + } - @ExcludeFromGeneratedCoverageReport - ObjectNode functionCallingConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"mode"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"response"}) != null) { Common.setValueByPath( toObject, - new String[] {"mode"}, - Common.getValueByPath(fromObject, new String[] {"mode"})); + new String[] {"response"}, + Common.getValueByPath(fromObject, new String[] {"response"})); } - if (Common.getValueByPath(fromObject, new String[] {"allowedFunctionNames"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"responseJsonSchema"}) != null) { Common.setValueByPath( toObject, - new String[] {"allowedFunctionNames"}, - Common.getValueByPath(fromObject, new String[] {"allowedFunctionNames"})); + new String[] {"responseJsonSchema"}, + Common.getValueByPath(fromObject, new String[] {"responseJsonSchema"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode latLngToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode getCachedContentParametersToMldev( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"latitude"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { Common.setValueByPath( toObject, - new String[] {"latitude"}, - Common.getValueByPath(fromObject, new String[] {"latitude"})); + new String[] {"_url", "name"}, + Transformers.tCachedContentName( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"name"}))); } - if (Common.getValueByPath(fromObject, new String[] {"longitude"}) != null) { + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode getCachedContentParametersToVertex( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { Common.setValueByPath( toObject, - new String[] {"longitude"}, - Common.getValueByPath(fromObject, new String[] {"longitude"})); + new String[] {"_url", "name"}, + Transformers.tCachedContentName( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"name"}))); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode retrievalConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode googleMapsToMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"latLng"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"latLng"}, - latLngToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"latLng"})), - toObject)); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"authConfig"}))) { + throw new IllegalArgumentException("authConfig parameter is not supported in Gemini API."); } - if (Common.getValueByPath(fromObject, new String[] {"languageCode"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"enableWidget"}) != null) { Common.setValueByPath( toObject, - new String[] {"languageCode"}, - Common.getValueByPath(fromObject, new String[] {"languageCode"})); + new String[] {"enableWidget"}, + Common.getValueByPath(fromObject, new String[] {"enableWidget"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode toolConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode googleSearchToMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"functionCallingConfig"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"functionCallingConfig"}, - functionCallingConfigToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"functionCallingConfig"})), - toObject)); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"excludeDomains"}))) { + throw new IllegalArgumentException( + "excludeDomains parameter is not supported in Gemini API."); } - if (Common.getValueByPath(fromObject, new String[] {"retrievalConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"timeRangeFilter"}) != null) { Common.setValueByPath( toObject, - new String[] {"retrievalConfig"}, - retrievalConfigToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"retrievalConfig"})), - toObject)); + new String[] {"timeRangeFilter"}, + Common.getValueByPath(fromObject, new String[] {"timeRangeFilter"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode createCachedContentConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode listCachedContentsConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"ttl"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"ttl"}, - Common.getValueByPath(fromObject, new String[] {"ttl"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"expireTime"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"pageSize"}) != null) { Common.setValueByPath( parentObject, - new String[] {"expireTime"}, - Common.getValueByPath(fromObject, new String[] {"expireTime"})); + new String[] {"_query", "pageSize"}, + Common.getValueByPath(fromObject, new String[] {"pageSize"})); } - if (Common.getValueByPath(fromObject, new String[] {"displayName"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"pageToken"}) != null) { Common.setValueByPath( parentObject, - new String[] {"displayName"}, - Common.getValueByPath(fromObject, new String[] {"displayName"})); + new String[] {"_query", "pageToken"}, + Common.getValueByPath(fromObject, new String[] {"pageToken"})); } - if (Common.getValueByPath(fromObject, new String[] {"contents"}) != null) { - ArrayNode keyArray = - (ArrayNode) - Transformers.tContents(Common.getValueByPath(fromObject, new String[] {"contents"})); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); + return toObject; + } - for (JsonNode item : keyArray) { - result.add(contentToMldev(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(parentObject, new String[] {"contents"}, result); - } + @ExcludeFromGeneratedCoverageReport + ObjectNode listCachedContentsConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"systemInstruction"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"pageSize"}) != null) { Common.setValueByPath( parentObject, - new String[] {"systemInstruction"}, - contentToMldev( - JsonSerializable.toJsonNode( - Transformers.tContent( - Common.getValueByPath(fromObject, new String[] {"systemInstruction"}))), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"tools"}) != null) { - ArrayNode keyArray = (ArrayNode) Common.getValueByPath(fromObject, new String[] {"tools"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add(toolToMldev(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(parentObject, new String[] {"tools"}, result); + new String[] {"_query", "pageSize"}, + Common.getValueByPath(fromObject, new String[] {"pageSize"})); } - if (Common.getValueByPath(fromObject, new String[] {"toolConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"pageToken"}) != null) { Common.setValueByPath( parentObject, - new String[] {"toolConfig"}, - toolConfigToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"toolConfig"})), - toObject)); - } - - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"kmsKeyName"}))) { - throw new IllegalArgumentException("kmsKeyName parameter is not supported in Gemini API."); + new String[] {"_query", "pageToken"}, + Common.getValueByPath(fromObject, new String[] {"pageToken"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode createCachedContentParametersToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { + ObjectNode listCachedContentsParametersToMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"model"}, - Transformers.tCachesModel( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); + if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + JsonNode unused = + listCachedContentsConfigToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"config"})), + toObject); } + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode listCachedContentsParametersToVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"config"}, - createCachedContentConfigToMldev( + JsonNode unused = + listCachedContentsConfigToVertex( JsonSerializable.toJsonNode( Common.getValueByPath(fromObject, new String[] {"config"})), - toObject)); + toObject); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode getCachedContentParametersToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { + ObjectNode listCachedContentsResponseFromMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"}) != null) { Common.setValueByPath( toObject, - new String[] {"_url", "name"}, - Transformers.tCachedContentName( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"name"}))); + new String[] {"sdkHttpResponse"}, + Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"})); } - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"nextPageToken"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"nextPageToken"}, + Common.getValueByPath(fromObject, new String[] {"nextPageToken"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"cachedContents"}) != null) { Common.setValueByPath( toObject, - new String[] {"config"}, - Common.getValueByPath(fromObject, new String[] {"config"})); + new String[] {"cachedContents"}, + Common.getValueByPath(fromObject, new String[] {"cachedContents"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode deleteCachedContentParametersToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { + ObjectNode listCachedContentsResponseFromVertex(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"}) != null) { Common.setValueByPath( toObject, - new String[] {"_url", "name"}, - Transformers.tCachedContentName( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"name"}))); + new String[] {"sdkHttpResponse"}, + Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"})); } - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"nextPageToken"}) != null) { Common.setValueByPath( toObject, - new String[] {"config"}, - Common.getValueByPath(fromObject, new String[] {"config"})); + new String[] {"nextPageToken"}, + Common.getValueByPath(fromObject, new String[] {"nextPageToken"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode updateCachedContentConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - if (Common.getValueByPath(fromObject, new String[] {"ttl"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"ttl"}, - Common.getValueByPath(fromObject, new String[] {"ttl"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"expireTime"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"cachedContents"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"expireTime"}, - Common.getValueByPath(fromObject, new String[] {"expireTime"})); + toObject, + new String[] {"cachedContents"}, + Common.getValueByPath(fromObject, new String[] {"cachedContents"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode updateCachedContentParametersToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { + ObjectNode partToMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"functionCall"}) != null) { Common.setValueByPath( toObject, - new String[] {"_url", "name"}, - Transformers.tCachedContentName( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"name"}))); + new String[] {"functionCall"}, + Common.getValueByPath(fromObject, new String[] {"functionCall"})); } - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"codeExecutionResult"}) != null) { Common.setValueByPath( toObject, - new String[] {"config"}, - updateCachedContentConfigToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"config"})), - toObject)); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode listCachedContentsConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - if (Common.getValueByPath(fromObject, new String[] {"pageSize"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"_query", "pageSize"}, - Common.getValueByPath(fromObject, new String[] {"pageSize"})); + new String[] {"codeExecutionResult"}, + Common.getValueByPath(fromObject, new String[] {"codeExecutionResult"})); } - if (Common.getValueByPath(fromObject, new String[] {"pageToken"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"executableCode"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"_query", "pageToken"}, - Common.getValueByPath(fromObject, new String[] {"pageToken"})); + toObject, + new String[] {"executableCode"}, + Common.getValueByPath(fromObject, new String[] {"executableCode"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode listCachedContentsParametersToMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"fileData"}) != null) { Common.setValueByPath( toObject, - new String[] {"config"}, - listCachedContentsConfigToMldev( + new String[] {"fileData"}, + fileDataToMldev( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"config"})), + Common.getValueByPath(fromObject, new String[] {"fileData"})), toObject)); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode videoMetadataToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"fps"}) != null) { - Common.setValueByPath( - toObject, new String[] {"fps"}, Common.getValueByPath(fromObject, new String[] {"fps"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"endOffset"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"endOffset"}, - Common.getValueByPath(fromObject, new String[] {"endOffset"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"startOffset"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"startOffset"}, - Common.getValueByPath(fromObject, new String[] {"startOffset"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode blobToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"displayName"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"functionResponse"}) != null) { Common.setValueByPath( toObject, - new String[] {"displayName"}, - Common.getValueByPath(fromObject, new String[] {"displayName"})); + new String[] {"functionResponse"}, + Common.getValueByPath(fromObject, new String[] {"functionResponse"})); } - if (Common.getValueByPath(fromObject, new String[] {"data"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"inlineData"}) != null) { Common.setValueByPath( toObject, - new String[] {"data"}, - Common.getValueByPath(fromObject, new String[] {"data"})); + new String[] {"inlineData"}, + blobToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"inlineData"})), + toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"text"}) != null) { Common.setValueByPath( toObject, - new String[] {"mimeType"}, - Common.getValueByPath(fromObject, new String[] {"mimeType"})); + new String[] {"text"}, + Common.getValueByPath(fromObject, new String[] {"text"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode fileDataToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"displayName"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"thought"}) != null) { Common.setValueByPath( toObject, - new String[] {"displayName"}, - Common.getValueByPath(fromObject, new String[] {"displayName"})); + new String[] {"thought"}, + Common.getValueByPath(fromObject, new String[] {"thought"})); } - if (Common.getValueByPath(fromObject, new String[] {"fileUri"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"thoughtSignature"}) != null) { Common.setValueByPath( toObject, - new String[] {"fileUri"}, - Common.getValueByPath(fromObject, new String[] {"fileUri"})); + new String[] {"thoughtSignature"}, + Common.getValueByPath(fromObject, new String[] {"thoughtSignature"})); } - if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"videoMetadata"}) != null) { Common.setValueByPath( toObject, - new String[] {"mimeType"}, - Common.getValueByPath(fromObject, new String[] {"mimeType"})); + new String[] {"videoMetadata"}, + Common.getValueByPath(fromObject, new String[] {"videoMetadata"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode partToVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toolToMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"videoMetadata"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"functionDeclarations"}) != null) { Common.setValueByPath( toObject, - new String[] {"videoMetadata"}, - videoMetadataToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"videoMetadata"})), - toObject)); + new String[] {"functionDeclarations"}, + Common.getValueByPath(fromObject, new String[] {"functionDeclarations"})); } - if (Common.getValueByPath(fromObject, new String[] {"thought"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"thought"}, - Common.getValueByPath(fromObject, new String[] {"thought"})); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"retrieval"}))) { + throw new IllegalArgumentException("retrieval parameter is not supported in Gemini API."); } - if (Common.getValueByPath(fromObject, new String[] {"inlineData"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"googleSearchRetrieval"}) != null) { Common.setValueByPath( toObject, - new String[] {"inlineData"}, - blobToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"inlineData"})), - toObject)); + new String[] {"googleSearchRetrieval"}, + Common.getValueByPath(fromObject, new String[] {"googleSearchRetrieval"})); } - if (Common.getValueByPath(fromObject, new String[] {"fileData"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"googleMaps"}) != null) { Common.setValueByPath( toObject, - new String[] {"fileData"}, - fileDataToVertex( + new String[] {"googleMaps"}, + googleMapsToMldev( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"fileData"})), + Common.getValueByPath(fromObject, new String[] {"googleMaps"})), toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"thoughtSignature"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"thoughtSignature"}, - Common.getValueByPath(fromObject, new String[] {"thoughtSignature"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"codeExecutionResult"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"computerUse"}) != null) { Common.setValueByPath( toObject, - new String[] {"codeExecutionResult"}, - Common.getValueByPath(fromObject, new String[] {"codeExecutionResult"})); + new String[] {"computerUse"}, + Common.getValueByPath(fromObject, new String[] {"computerUse"})); } - if (Common.getValueByPath(fromObject, new String[] {"executableCode"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"codeExecution"}) != null) { Common.setValueByPath( toObject, - new String[] {"executableCode"}, - Common.getValueByPath(fromObject, new String[] {"executableCode"})); + new String[] {"codeExecution"}, + Common.getValueByPath(fromObject, new String[] {"codeExecution"})); } - if (Common.getValueByPath(fromObject, new String[] {"functionCall"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"functionCall"}, - Common.getValueByPath(fromObject, new String[] {"functionCall"})); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"enterpriseWebSearch"}))) { + throw new IllegalArgumentException( + "enterpriseWebSearch parameter is not supported in Gemini API."); } - if (Common.getValueByPath(fromObject, new String[] {"functionResponse"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"googleSearch"}) != null) { Common.setValueByPath( toObject, - new String[] {"functionResponse"}, - Common.getValueByPath(fromObject, new String[] {"functionResponse"})); + new String[] {"googleSearch"}, + googleSearchToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"googleSearch"})), + toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"text"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"urlContext"}) != null) { Common.setValueByPath( toObject, - new String[] {"text"}, - Common.getValueByPath(fromObject, new String[] {"text"})); + new String[] {"urlContext"}, + Common.getValueByPath(fromObject, new String[] {"urlContext"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode contentToVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toolToVertex(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"parts"}) != null) { - ArrayNode keyArray = (ArrayNode) Common.getValueByPath(fromObject, new String[] {"parts"}); + if (Common.getValueByPath(fromObject, new String[] {"functionDeclarations"}) != null) { + ArrayNode keyArray = + (ArrayNode) Common.getValueByPath(fromObject, new String[] {"functionDeclarations"}); ObjectMapper objectMapper = new ObjectMapper(); ArrayNode result = objectMapper.createArrayNode(); for (JsonNode item : keyArray) { - result.add(partToVertex(JsonSerializable.toJsonNode(item), toObject)); + result.add(functionDeclarationToVertex(JsonSerializable.toJsonNode(item), toObject)); } - Common.setValueByPath(toObject, new String[] {"parts"}, result); - } - - if (Common.getValueByPath(fromObject, new String[] {"role"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"role"}, - Common.getValueByPath(fromObject, new String[] {"role"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode functionDeclarationToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"behavior"}))) { - throw new IllegalArgumentException("behavior parameter is not supported in Vertex AI."); - } - - if (Common.getValueByPath(fromObject, new String[] {"description"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"description"}, - Common.getValueByPath(fromObject, new String[] {"description"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"name"}, - Common.getValueByPath(fromObject, new String[] {"name"})); + Common.setValueByPath(toObject, new String[] {"functionDeclarations"}, result); } - if (Common.getValueByPath(fromObject, new String[] {"parameters"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"retrieval"}) != null) { Common.setValueByPath( toObject, - new String[] {"parameters"}, - Common.getValueByPath(fromObject, new String[] {"parameters"})); + new String[] {"retrieval"}, + Common.getValueByPath(fromObject, new String[] {"retrieval"})); } - if (Common.getValueByPath(fromObject, new String[] {"parametersJsonSchema"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"googleSearchRetrieval"}) != null) { Common.setValueByPath( toObject, - new String[] {"parametersJsonSchema"}, - Common.getValueByPath(fromObject, new String[] {"parametersJsonSchema"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"response"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"response"}, - Common.getValueByPath(fromObject, new String[] {"response"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"responseJsonSchema"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"responseJsonSchema"}, - Common.getValueByPath(fromObject, new String[] {"responseJsonSchema"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode intervalToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"startTime"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"startTime"}, - Common.getValueByPath(fromObject, new String[] {"startTime"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"endTime"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"endTime"}, - Common.getValueByPath(fromObject, new String[] {"endTime"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode googleSearchToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"timeRangeFilter"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"timeRangeFilter"}, - intervalToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"timeRangeFilter"})), - toObject)); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode dynamicRetrievalConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"mode"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"mode"}, - Common.getValueByPath(fromObject, new String[] {"mode"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"dynamicThreshold"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"dynamicThreshold"}, - Common.getValueByPath(fromObject, new String[] {"dynamicThreshold"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode googleSearchRetrievalToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"dynamicRetrievalConfig"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"dynamicRetrievalConfig"}, - dynamicRetrievalConfigToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"dynamicRetrievalConfig"})), - toObject)); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode enterpriseWebSearchToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode apiKeyConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"apiKeyString"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"apiKeyString"}, - Common.getValueByPath(fromObject, new String[] {"apiKeyString"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode authConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"apiKeyConfig"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"apiKeyConfig"}, - apiKeyConfigToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"apiKeyConfig"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"authType"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"authType"}, - Common.getValueByPath(fromObject, new String[] {"authType"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"googleServiceAccountConfig"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"googleServiceAccountConfig"}, - Common.getValueByPath(fromObject, new String[] {"googleServiceAccountConfig"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"httpBasicAuthConfig"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"httpBasicAuthConfig"}, - Common.getValueByPath(fromObject, new String[] {"httpBasicAuthConfig"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"oauthConfig"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"oauthConfig"}, - Common.getValueByPath(fromObject, new String[] {"oauthConfig"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"oidcConfig"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"oidcConfig"}, - Common.getValueByPath(fromObject, new String[] {"oidcConfig"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode googleMapsToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"authConfig"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"authConfig"}, - authConfigToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"authConfig"})), - toObject)); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode urlContextToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode toolToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"functionDeclarations"}) != null) { - ArrayNode keyArray = - (ArrayNode) Common.getValueByPath(fromObject, new String[] {"functionDeclarations"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add(functionDeclarationToVertex(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"functionDeclarations"}, result); - } - - if (Common.getValueByPath(fromObject, new String[] {"retrieval"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"retrieval"}, - Common.getValueByPath(fromObject, new String[] {"retrieval"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"googleSearch"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"googleSearch"}, - googleSearchToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"googleSearch"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"googleSearchRetrieval"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"googleSearchRetrieval"}, - googleSearchRetrievalToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"googleSearchRetrieval"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"enterpriseWebSearch"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"enterpriseWebSearch"}, - enterpriseWebSearchToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"enterpriseWebSearch"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"googleMaps"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"googleMaps"}, - googleMapsToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"googleMaps"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"urlContext"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"urlContext"}, - urlContextToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"urlContext"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"codeExecution"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"codeExecution"}, - Common.getValueByPath(fromObject, new String[] {"codeExecution"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"computerUse"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"computerUse"}, - Common.getValueByPath(fromObject, new String[] {"computerUse"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode functionCallingConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"mode"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"mode"}, - Common.getValueByPath(fromObject, new String[] {"mode"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"allowedFunctionNames"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"allowedFunctionNames"}, - Common.getValueByPath(fromObject, new String[] {"allowedFunctionNames"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode latLngToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"latitude"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"latitude"}, - Common.getValueByPath(fromObject, new String[] {"latitude"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"longitude"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"longitude"}, - Common.getValueByPath(fromObject, new String[] {"longitude"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode retrievalConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"latLng"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"latLng"}, - latLngToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"latLng"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"languageCode"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"languageCode"}, - Common.getValueByPath(fromObject, new String[] {"languageCode"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode toolConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"functionCallingConfig"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"functionCallingConfig"}, - functionCallingConfigToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"functionCallingConfig"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"retrievalConfig"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"retrievalConfig"}, - retrievalConfigToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"retrievalConfig"})), - toObject)); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode createCachedContentConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - if (Common.getValueByPath(fromObject, new String[] {"ttl"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"ttl"}, - Common.getValueByPath(fromObject, new String[] {"ttl"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"expireTime"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"expireTime"}, - Common.getValueByPath(fromObject, new String[] {"expireTime"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"displayName"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"displayName"}, - Common.getValueByPath(fromObject, new String[] {"displayName"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"contents"}) != null) { - ArrayNode keyArray = - (ArrayNode) - Transformers.tContents(Common.getValueByPath(fromObject, new String[] {"contents"})); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add(contentToVertex(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(parentObject, new String[] {"contents"}, result); - } - - if (Common.getValueByPath(fromObject, new String[] {"systemInstruction"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"systemInstruction"}, - contentToVertex( - JsonSerializable.toJsonNode( - Transformers.tContent( - Common.getValueByPath(fromObject, new String[] {"systemInstruction"}))), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"tools"}) != null) { - ArrayNode keyArray = (ArrayNode) Common.getValueByPath(fromObject, new String[] {"tools"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add(toolToVertex(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(parentObject, new String[] {"tools"}, result); - } - - if (Common.getValueByPath(fromObject, new String[] {"toolConfig"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"toolConfig"}, - toolConfigToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"toolConfig"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"kmsKeyName"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"encryption_spec", "kmsKeyName"}, - Common.getValueByPath(fromObject, new String[] {"kmsKeyName"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode createCachedContentParametersToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"model"}, - Transformers.tCachesModel( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); - } - - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"config"}, - createCachedContentConfigToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"config"})), - toObject)); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode getCachedContentParametersToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"_url", "name"}, - Transformers.tCachedContentName( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"name"}))); - } - - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"config"}, - Common.getValueByPath(fromObject, new String[] {"config"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode deleteCachedContentParametersToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"_url", "name"}, - Transformers.tCachedContentName( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"name"}))); - } - - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"config"}, - Common.getValueByPath(fromObject, new String[] {"config"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode updateCachedContentConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - if (Common.getValueByPath(fromObject, new String[] {"ttl"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"ttl"}, - Common.getValueByPath(fromObject, new String[] {"ttl"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"expireTime"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"expireTime"}, - Common.getValueByPath(fromObject, new String[] {"expireTime"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode updateCachedContentParametersToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"_url", "name"}, - Transformers.tCachedContentName( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"name"}))); - } - - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"config"}, - updateCachedContentConfigToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"config"})), - toObject)); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode listCachedContentsConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - if (Common.getValueByPath(fromObject, new String[] {"pageSize"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"_query", "pageSize"}, - Common.getValueByPath(fromObject, new String[] {"pageSize"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"pageToken"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"_query", "pageToken"}, - Common.getValueByPath(fromObject, new String[] {"pageToken"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode listCachedContentsParametersToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"config"}, - listCachedContentsConfigToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"config"})), - toObject)); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - void behaviorVertexEnumValidate(Object enumValue) { - ImmutableSet invalidEnumValues = - ImmutableSet.of("UNSPECIFIED", "BLOCKING", "NON_BLOCKING"); - if (invalidEnumValues.contains(enumValue.toString().replace("\"", ""))) { - throw new IllegalArgumentException( - String.format("%s enum value is not supported in Vertex AI.", enumValue)); - } - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode cachedContentFromMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"name"}, - Common.getValueByPath(fromObject, new String[] {"name"})); + new String[] {"googleSearchRetrieval"}, + Common.getValueByPath(fromObject, new String[] {"googleSearchRetrieval"})); } - if (Common.getValueByPath(fromObject, new String[] {"displayName"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"googleMaps"}) != null) { Common.setValueByPath( toObject, - new String[] {"displayName"}, - Common.getValueByPath(fromObject, new String[] {"displayName"})); + new String[] {"googleMaps"}, + Common.getValueByPath(fromObject, new String[] {"googleMaps"})); } - if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"computerUse"}) != null) { Common.setValueByPath( toObject, - new String[] {"model"}, - Common.getValueByPath(fromObject, new String[] {"model"})); + new String[] {"computerUse"}, + Common.getValueByPath(fromObject, new String[] {"computerUse"})); } - if (Common.getValueByPath(fromObject, new String[] {"createTime"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"codeExecution"}) != null) { Common.setValueByPath( toObject, - new String[] {"createTime"}, - Common.getValueByPath(fromObject, new String[] {"createTime"})); + new String[] {"codeExecution"}, + Common.getValueByPath(fromObject, new String[] {"codeExecution"})); } - if (Common.getValueByPath(fromObject, new String[] {"updateTime"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"enterpriseWebSearch"}) != null) { Common.setValueByPath( toObject, - new String[] {"updateTime"}, - Common.getValueByPath(fromObject, new String[] {"updateTime"})); + new String[] {"enterpriseWebSearch"}, + Common.getValueByPath(fromObject, new String[] {"enterpriseWebSearch"})); } - if (Common.getValueByPath(fromObject, new String[] {"expireTime"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"googleSearch"}) != null) { Common.setValueByPath( toObject, - new String[] {"expireTime"}, - Common.getValueByPath(fromObject, new String[] {"expireTime"})); + new String[] {"googleSearch"}, + Common.getValueByPath(fromObject, new String[] {"googleSearch"})); } - if (Common.getValueByPath(fromObject, new String[] {"usageMetadata"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"urlContext"}) != null) { Common.setValueByPath( toObject, - new String[] {"usageMetadata"}, - Common.getValueByPath(fromObject, new String[] {"usageMetadata"})); + new String[] {"urlContext"}, + Common.getValueByPath(fromObject, new String[] {"urlContext"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode deleteCachedContentResponseFromMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode listCachedContentsResponseFromMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode updateCachedContentConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"nextPageToken"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"ttl"}) != null) { Common.setValueByPath( - toObject, - new String[] {"nextPageToken"}, - Common.getValueByPath(fromObject, new String[] {"nextPageToken"})); + parentObject, + new String[] {"ttl"}, + Common.getValueByPath(fromObject, new String[] {"ttl"})); } - if (Common.getValueByPath(fromObject, new String[] {"cachedContents"}) != null) { - ArrayNode keyArray = - (ArrayNode) Common.getValueByPath(fromObject, new String[] {"cachedContents"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add(cachedContentFromMldev(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"cachedContents"}, result); + if (Common.getValueByPath(fromObject, new String[] {"expireTime"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"expireTime"}, + Common.getValueByPath(fromObject, new String[] {"expireTime"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode cachedContentFromVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode updateCachedContentConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"name"}, - Common.getValueByPath(fromObject, new String[] {"name"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"displayName"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"displayName"}, - Common.getValueByPath(fromObject, new String[] {"displayName"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"model"}, - Common.getValueByPath(fromObject, new String[] {"model"})); - } - if (Common.getValueByPath(fromObject, new String[] {"createTime"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"createTime"}, - Common.getValueByPath(fromObject, new String[] {"createTime"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"updateTime"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"ttl"}) != null) { Common.setValueByPath( - toObject, - new String[] {"updateTime"}, - Common.getValueByPath(fromObject, new String[] {"updateTime"})); + parentObject, + new String[] {"ttl"}, + Common.getValueByPath(fromObject, new String[] {"ttl"})); } if (Common.getValueByPath(fromObject, new String[] {"expireTime"}) != null) { Common.setValueByPath( - toObject, + parentObject, new String[] {"expireTime"}, Common.getValueByPath(fromObject, new String[] {"expireTime"})); } - if (Common.getValueByPath(fromObject, new String[] {"usageMetadata"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"usageMetadata"}, - Common.getValueByPath(fromObject, new String[] {"usageMetadata"})); - } - return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode deleteCachedContentResponseFromVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode updateCachedContentParametersToMldev( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"_url", "name"}, + Transformers.tCachedContentName( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"name"}))); + } + + if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + JsonNode unused = + updateCachedContentConfigToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"config"})), + toObject); + } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode listCachedContentsResponseFromVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode updateCachedContentParametersToVertex( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - if (Common.getValueByPath(fromObject, new String[] {"nextPageToken"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { Common.setValueByPath( toObject, - new String[] {"nextPageToken"}, - Common.getValueByPath(fromObject, new String[] {"nextPageToken"})); + new String[] {"_url", "name"}, + Transformers.tCachedContentName( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"name"}))); } - if (Common.getValueByPath(fromObject, new String[] {"cachedContents"}) != null) { - ArrayNode keyArray = - (ArrayNode) Common.getValueByPath(fromObject, new String[] {"cachedContents"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add(cachedContentFromVertex(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"cachedContents"}, result); + if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + JsonNode unused = + updateCachedContentConfigToVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"config"})), + toObject); } return toObject; } - /** - * Creates a cached content resource. - * - * @param model The model to use. - * @param config A {@link CreateCachedContentConfig} for configuring the create request. - * @return A {@link CachedContent} object that contains the info of the created resource. - */ - public CachedContent create(String model, CreateCachedContentConfig config) { + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForCreate(String model, CreateCachedContentConfig config) { CreateCachedContentParameters.Builder parameterBuilder = CreateCachedContentParameters.builder(); @@ -1807,42 +966,48 @@ public CachedContent create(String model, CreateCachedContentConfig config) { } // TODO: Remove the hack that removes config. - body.remove("config"); - Optional requestHttpOptions = Optional.empty(); if (config != null) { requestHttpOptions = config.httpOptions(); } - try (ApiResponse response = - this.apiClient.request( - "post", path, JsonSerializable.toJsonString(body), requestHttpOptions)) { - ResponseBody responseBody = response.getBody(); - String responseString; - try { - responseString = responseBody.string(); - } catch (IOException e) { - throw new GenAiIOException("Failed to read HTTP response.", e); - } + return new BuiltRequest(path, JsonSerializable.toJsonString(body), requestHttpOptions); + } - JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); - if (this.apiClient.vertexAI()) { - responseNode = cachedContentFromVertex(responseNode, null); - } else { - responseNode = cachedContentFromMldev(responseNode, null); - } - return JsonSerializable.fromJsonNode(responseNode, CachedContent.class); + /** A shared processResponse function for both sync and async methods. */ + CachedContent processResponseForCreate(ApiResponse response, CreateCachedContentConfig config) { + ResponseBody responseBody = response.getBody(); + String responseString; + try { + responseString = responseBody.string(); + } catch (IOException e) { + throw new GenAiIOException("Failed to read HTTP response.", e); } + + JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); + + return JsonSerializable.fromJsonNode(responseNode, CachedContent.class); } /** - * Gets a cached content resource. + * Creates a cached content resource. * - * @param name The name(resource id) of the cached content to get. - * @param config A {@link GetCachedContentConfig} for configuring the get request. - * @return A {@link CachedContent} object that contains the info of the cached content. + * @param model The model to use. + * @param config A {@link CreateCachedContentConfig} for configuring the create request. + * @return A {@link CachedContent} object that contains the info of the created resource. */ - public CachedContent get(String name, GetCachedContentConfig config) { + public CachedContent create(String model, CreateCachedContentConfig config) { + BuiltRequest builtRequest = buildRequestForCreate(model, config); + + try (ApiResponse response = + this.apiClient.request( + "post", builtRequest.path, builtRequest.body, builtRequest.httpOptions)) { + return processResponseForCreate(response, config); + } + } + + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForGet(String name, GetCachedContentConfig config) { GetCachedContentParameters.Builder parameterBuilder = GetCachedContentParameters.builder(); @@ -1876,41 +1041,48 @@ public CachedContent get(String name, GetCachedContentConfig config) { } // TODO: Remove the hack that removes config. - body.remove("config"); - Optional requestHttpOptions = Optional.empty(); if (config != null) { requestHttpOptions = config.httpOptions(); } - try (ApiResponse response = - this.apiClient.request( - "get", path, JsonSerializable.toJsonString(body), requestHttpOptions)) { - ResponseBody responseBody = response.getBody(); - String responseString; - try { - responseString = responseBody.string(); - } catch (IOException e) { - throw new GenAiIOException("Failed to read HTTP response.", e); - } + return new BuiltRequest(path, JsonSerializable.toJsonString(body), requestHttpOptions); + } - JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); - if (this.apiClient.vertexAI()) { - responseNode = cachedContentFromVertex(responseNode, null); - } else { - responseNode = cachedContentFromMldev(responseNode, null); - } - return JsonSerializable.fromJsonNode(responseNode, CachedContent.class); + /** A shared processResponse function for both sync and async methods. */ + CachedContent processResponseForGet(ApiResponse response, GetCachedContentConfig config) { + ResponseBody responseBody = response.getBody(); + String responseString; + try { + responseString = responseBody.string(); + } catch (IOException e) { + throw new GenAiIOException("Failed to read HTTP response.", e); } + + JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); + + return JsonSerializable.fromJsonNode(responseNode, CachedContent.class); } /** - * Deletes a cached content resource. + * Gets a cached content resource. * - * @param name The name(resource id) of the cached content to delete. - * @param config A {@link DeleteCachedContentConfig} for configuring the delete request. + * @param name The name(resource id) of the cached content to get. + * @param config A {@link GetCachedContentConfig} for configuring the get request. + * @return A {@link CachedContent} object that contains the info of the cached content. */ - public DeleteCachedContentResponse delete(String name, DeleteCachedContentConfig config) { + public CachedContent get(String name, GetCachedContentConfig config) { + BuiltRequest builtRequest = buildRequestForGet(name, config); + + try (ApiResponse response = + this.apiClient.request( + "get", builtRequest.path, builtRequest.body, builtRequest.httpOptions)) { + return processResponseForGet(response, config); + } + } + + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForDelete(String name, DeleteCachedContentConfig config) { DeleteCachedContentParameters.Builder parameterBuilder = DeleteCachedContentParameters.builder(); @@ -1945,42 +1117,66 @@ public DeleteCachedContentResponse delete(String name, DeleteCachedContentConfig } // TODO: Remove the hack that removes config. - body.remove("config"); - Optional requestHttpOptions = Optional.empty(); if (config != null) { requestHttpOptions = config.httpOptions(); } - try (ApiResponse response = - this.apiClient.request( - "delete", path, JsonSerializable.toJsonString(body), requestHttpOptions)) { - ResponseBody responseBody = response.getBody(); - String responseString; - try { - responseString = responseBody.string(); - } catch (IOException e) { - throw new GenAiIOException("Failed to read HTTP response.", e); - } + return new BuiltRequest(path, JsonSerializable.toJsonString(body), requestHttpOptions); + } - JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); - if (this.apiClient.vertexAI()) { - responseNode = deleteCachedContentResponseFromVertex(responseNode, null); - } else { - responseNode = deleteCachedContentResponseFromMldev(responseNode, null); - } - return JsonSerializable.fromJsonNode(responseNode, DeleteCachedContentResponse.class); + /** A shared processResponse function for both sync and async methods. */ + DeleteCachedContentResponse processResponseForDelete( + ApiResponse response, DeleteCachedContentConfig config) { + ResponseBody responseBody = response.getBody(); + String responseString; + try { + responseString = responseBody.string(); + } catch (IOException e) { + throw new GenAiIOException("Failed to read HTTP response.", e); + } + + JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); + + if (this.apiClient.vertexAI()) { + responseNode = deleteCachedContentResponseFromVertex(responseNode, null); + } + + if (!this.apiClient.vertexAI()) { + responseNode = deleteCachedContentResponseFromMldev(responseNode, null); + } + + DeleteCachedContentResponse sdkResponse = + JsonSerializable.fromJsonNode(responseNode, DeleteCachedContentResponse.class); + Headers responseHeaders = response.getHeaders(); + if (responseHeaders == null) { + return sdkResponse; + } + Map headers = new HashMap<>(); + for (String headerName : responseHeaders.names()) { + headers.put(headerName, responseHeaders.get(headerName)); } + return sdkResponse.toBuilder().sdkHttpResponse(HttpResponse.builder().headers(headers)).build(); } /** - * Updates a cached content resource. + * Deletes a cached content resource. * - * @param name The name(resource id) of the cached content to update. - * @param config A {@link UpdateCachedContentConfig} for configuring the update request. - * @return A {@link CachedContent} object that contains the info of the updated resource. + * @param name The name(resource id) of the cached content to delete. + * @param config A {@link DeleteCachedContentConfig} for configuring the delete request. */ - public CachedContent update(String name, UpdateCachedContentConfig config) { + public DeleteCachedContentResponse delete(String name, DeleteCachedContentConfig config) { + BuiltRequest builtRequest = buildRequestForDelete(name, config); + + try (ApiResponse response = + this.apiClient.request( + "delete", builtRequest.path, builtRequest.body, builtRequest.httpOptions)) { + return processResponseForDelete(response, config); + } + } + + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForUpdate(String name, UpdateCachedContentConfig config) { UpdateCachedContentParameters.Builder parameterBuilder = UpdateCachedContentParameters.builder(); @@ -2015,35 +1211,48 @@ public CachedContent update(String name, UpdateCachedContentConfig config) { } // TODO: Remove the hack that removes config. - body.remove("config"); - Optional requestHttpOptions = Optional.empty(); if (config != null) { requestHttpOptions = config.httpOptions(); } + return new BuiltRequest(path, JsonSerializable.toJsonString(body), requestHttpOptions); + } + + /** A shared processResponse function for both sync and async methods. */ + CachedContent processResponseForUpdate(ApiResponse response, UpdateCachedContentConfig config) { + ResponseBody responseBody = response.getBody(); + String responseString; + try { + responseString = responseBody.string(); + } catch (IOException e) { + throw new GenAiIOException("Failed to read HTTP response.", e); + } + + JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); + + return JsonSerializable.fromJsonNode(responseNode, CachedContent.class); + } + + /** + * Updates a cached content resource. + * + * @param name The name(resource id) of the cached content to update. + * @param config A {@link UpdateCachedContentConfig} for configuring the update request. + * @return A {@link CachedContent} object that contains the info of the updated resource. + */ + public CachedContent update(String name, UpdateCachedContentConfig config) { + BuiltRequest builtRequest = buildRequestForUpdate(name, config); + try (ApiResponse response = this.apiClient.request( - "patch", path, JsonSerializable.toJsonString(body), requestHttpOptions)) { - ResponseBody responseBody = response.getBody(); - String responseString; - try { - responseString = responseBody.string(); - } catch (IOException e) { - throw new GenAiIOException("Failed to read HTTP response.", e); - } - - JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); - if (this.apiClient.vertexAI()) { - responseNode = cachedContentFromVertex(responseNode, null); - } else { - responseNode = cachedContentFromMldev(responseNode, null); - } - return JsonSerializable.fromJsonNode(responseNode, CachedContent.class); + "patch", builtRequest.path, builtRequest.body, builtRequest.httpOptions)) { + return processResponseForUpdate(response, config); } } - ListCachedContentsResponse privateList(ListCachedContentsConfig config) { + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForPrivateList(ListCachedContentsConfig config) { ListCachedContentsParameters.Builder parameterBuilder = ListCachedContentsParameters.builder(); @@ -2074,31 +1283,55 @@ ListCachedContentsResponse privateList(ListCachedContentsConfig config) { } // TODO: Remove the hack that removes config. - body.remove("config"); - Optional requestHttpOptions = Optional.empty(); if (config != null) { requestHttpOptions = config.httpOptions(); } + return new BuiltRequest(path, JsonSerializable.toJsonString(body), requestHttpOptions); + } + + /** A shared processResponse function for both sync and async methods. */ + ListCachedContentsResponse processResponseForPrivateList( + ApiResponse response, ListCachedContentsConfig config) { + ResponseBody responseBody = response.getBody(); + String responseString; + try { + responseString = responseBody.string(); + } catch (IOException e) { + throw new GenAiIOException("Failed to read HTTP response.", e); + } + + JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); + + if (this.apiClient.vertexAI()) { + responseNode = listCachedContentsResponseFromVertex(responseNode, null); + } + + if (!this.apiClient.vertexAI()) { + responseNode = listCachedContentsResponseFromMldev(responseNode, null); + } + + ListCachedContentsResponse sdkResponse = + JsonSerializable.fromJsonNode(responseNode, ListCachedContentsResponse.class); + Headers responseHeaders = response.getHeaders(); + if (responseHeaders == null) { + return sdkResponse; + } + Map headers = new HashMap<>(); + for (String headerName : responseHeaders.names()) { + headers.put(headerName, responseHeaders.get(headerName)); + } + return sdkResponse.toBuilder().sdkHttpResponse(HttpResponse.builder().headers(headers)).build(); + } + + ListCachedContentsResponse privateList(ListCachedContentsConfig config) { + BuiltRequest builtRequest = buildRequestForPrivateList(config); + try (ApiResponse response = this.apiClient.request( - "get", path, JsonSerializable.toJsonString(body), requestHttpOptions)) { - ResponseBody responseBody = response.getBody(); - String responseString; - try { - responseString = responseBody.string(); - } catch (IOException e) { - throw new GenAiIOException("Failed to read HTTP response.", e); - } - - JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); - if (this.apiClient.vertexAI()) { - responseNode = listCachedContentsResponseFromVertex(responseNode, null); - } else { - responseNode = listCachedContentsResponseFromMldev(responseNode, null); - } - return JsonSerializable.fromJsonNode(responseNode, ListCachedContentsResponse.class); + "get", builtRequest.path, builtRequest.body, builtRequest.httpOptions)) { + return processResponseForPrivateList(response, config); } } diff --git a/src/main/java/com/google/genai/Chat.java b/src/main/java/com/google/genai/Chat.java index 1e8bedf794c..e2e5ae1cf62 100644 --- a/src/main/java/com/google/genai/Chat.java +++ b/src/main/java/com/google/genai/Chat.java @@ -27,6 +27,8 @@ * *

This class provides a way to interact with a generative model in a multi-turn chat session. It * keeps track of the chat history and uses it to provide context for subsequent messages. + * + *

Note: this class is NOT thread-safe. */ public class Chat extends ChatBase { private final ApiClient apiClient; diff --git a/src/main/java/com/google/genai/Client.java b/src/main/java/com/google/genai/Client.java index c033cd01fd5..2efca2a4b91 100644 --- a/src/main/java/com/google/genai/Client.java +++ b/src/main/java/com/google/genai/Client.java @@ -26,7 +26,7 @@ import java.io.IOException; import java.util.Optional; -/** Client class for GenAI. */ +/** Client class for GenAI. This class is thread-safe. */ public final class Client implements AutoCloseable { /** Async class for GenAI. */ diff --git a/src/main/java/com/google/genai/Common.java b/src/main/java/com/google/genai/Common.java index a97bd39e4e1..8302c6d83fc 100644 --- a/src/main/java/com/google/genai/Common.java +++ b/src/main/java/com/google/genai/Common.java @@ -19,6 +19,8 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; +import com.google.genai.errors.GenAiIOException; +import com.google.genai.types.HttpOptions; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; @@ -26,15 +28,29 @@ import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.StringJoiner; import org.jspecify.annotations.Nullable; -import com.google.genai.errors.GenAiIOException; /** Common utility methods for the GenAI SDK. */ final class Common { private Common() {} + /** A class that holds the path, body, and http options of an API request. */ + static class BuiltRequest { + final String path; + final String body; + final Optional httpOptions; + + /** Constructor for BuiltRequest. */ + BuiltRequest(String path, String body, Optional httpOptions) { + this.path = path; + this.body = body; + this.httpOptions = httpOptions; + } + } + /** * Sets the value of an object by a path. * @@ -102,8 +118,13 @@ static void setValueByPath(ObjectNode jsonObject, String[] path, Object value) { } String keyToSet = path[path.length - 1]; - JsonNode valueNode = JsonSerializable.toJsonNode(value); - Transformers.updateJsonNode(currentObject, keyToSet, valueNode); + if (keyToSet.equals("_self") && value instanceof ObjectNode) { + ObjectNode sourceNode = (ObjectNode) value; + currentObject.setAll(sourceNode); + } else { + JsonNode valueNode = JsonSerializable.toJsonNode(value); + Transformers.updateJsonNode(currentObject, keyToSet, valueNode); + } } /** @@ -114,8 +135,20 @@ static void setValueByPath(ObjectNode jsonObject, String[] path, Object value) { *

getValueByPath({'a': {'b': [{'c': v1}, {'c': v2}]}}, ['a', 'b[]', 'c']) -> [v1, v2] */ static @Nullable Object getValueByPath(JsonNode object, String[] keys) { + return getValueByPath(object, keys, null); + } + + /** + * Gets the value of an object by a path, returning a default value if the path does not exist. + * + *

getValueByPath({'a': {'b': v}}, ['a', 'b'], 'default') -> v + * + *

getValueByPath({'a': {'c': v}}, ['a', 'b'], 'default') -> 'default' + */ + static @Nullable Object getValueByPath( + JsonNode object, String[] keys, @Nullable Object defaultValue) { if (object == null || keys == null) { - return null; + return defaultValue; } if (keys.length == 1 && keys[0].equals("_self")) { return object; @@ -126,7 +159,7 @@ static void setValueByPath(ObjectNode jsonObject, String[] path, Object value) { String key = keys[i]; if (currentObject == null) { - return null; + return defaultValue; } if (key.endsWith("[]")) { @@ -141,14 +174,16 @@ static void setValueByPath(ObjectNode jsonObject, String[] path, Object value) { ArrayNode result = JsonSerializable.objectMapper.createArrayNode(); for (JsonNode element : arrayNode) { JsonNode node = - (JsonNode) getValueByPath(element, Arrays.copyOfRange(keys, i + 1, keys.length)); + (JsonNode) + getValueByPath( + element, Arrays.copyOfRange(keys, i + 1, keys.length), defaultValue); if (node != null) { result.add(node); } } return result; } else { - return null; + return defaultValue; } } else if (key.endsWith("[0]")) { String keyName = key.substring(0, key.length() - 3); @@ -158,13 +193,13 @@ static void setValueByPath(ObjectNode jsonObject, String[] path, Object value) { && ((ArrayNode) ((ObjectNode) currentObject).get(keyName)).size() > 0) { currentObject = ((ArrayNode) ((ObjectNode) currentObject).get(keyName)).get(0); } else { - return null; + return defaultValue; } } else { if (currentObject.isObject() && ((ObjectNode) currentObject).has(key)) { currentObject = ((ObjectNode) currentObject).get(key); } else { - return null; + return defaultValue; } } } @@ -263,4 +298,138 @@ static String snakeToCamel(String str) { } return sb.toString(); } + + /** + * Moves values from source paths to destination paths. + * + *

Example: moveValueByPath( {'requests': [{'content': v1}, {'content': v2}]}, {'requests[].*': + * 'requests[].request.*'} ) -> {'requests': [{'request': {'content': v1}}, {'request': + * {'content': v2}}]} + */ + static void moveValueByPath(JsonNode data, Map paths) { + if (data == null || paths == null) { + return; + } + + for (Map.Entry entry : paths.entrySet()) { + String sourcePath = entry.getKey(); + String destPath = entry.getValue(); + + String[] sourceKeys = sourcePath.split("\\."); + String[] destKeys = destPath.split("\\."); + + // Determine keys to exclude from wildcard to avoid cyclic references + java.util.Set excludeKeys = new java.util.HashSet<>(); + int wildcardIdx = -1; + + for (int i = 0; i < sourceKeys.length; i++) { + if (sourceKeys[i].equals("*")) { + wildcardIdx = i; + break; + } + } + + if (wildcardIdx != -1 && destKeys.length > wildcardIdx) { + // Extract the intermediate key between source and dest paths + // Example: source=['requests[]', '*'], dest=['requests[]', 'request', '*'] + // We want to exclude 'request' + for (int i = wildcardIdx; i < destKeys.length; i++) { + String key = destKeys[i]; + if (!key.equals("*") && !key.endsWith("[]") && !key.endsWith("[0]")) { + excludeKeys.add(key); + } + } + } + + // Move values recursively + moveValueRecursive(data, sourceKeys, destKeys, 0, excludeKeys); + } + } + + /** + * Recursively moves values from source path to destination path. + * + * @param data The current node being processed + * @param sourceKeys The source path keys + * @param destKeys The destination path keys + * @param keyIdx The current index in the key arrays + * @param excludeKeys Keys to exclude when processing wildcards + */ + private static void moveValueRecursive( + JsonNode data, + String[] sourceKeys, + String[] destKeys, + int keyIdx, + java.util.Set excludeKeys) { + if (keyIdx >= sourceKeys.length || data == null) { + return; + } + + String key = sourceKeys[keyIdx]; + + if (key.endsWith("[]")) { + // Handle array iteration + String keyName = key.substring(0, key.length() - 2); + if (data.isObject() + && ((ObjectNode) data).has(keyName) + && ((ObjectNode) data).get(keyName).isArray()) { + ArrayNode arrayNode = (ArrayNode) ((ObjectNode) data).get(keyName); + for (JsonNode item : arrayNode) { + moveValueRecursive(item, sourceKeys, destKeys, keyIdx + 1, excludeKeys); + } + } + } else if (key.equals("*")) { + // Handle wildcard - move all fields + if (data.isObject()) { + ObjectNode objectNode = (ObjectNode) data; + + // Get all keys to move (excluding specified keys) + java.util.List keysToMove = new java.util.ArrayList<>(); + Iterator fieldNames = objectNode.fieldNames(); + while (fieldNames.hasNext()) { + String fieldName = fieldNames.next(); + if (!fieldName.startsWith("_") && !excludeKeys.contains(fieldName)) { + keysToMove.add(fieldName); + } + } + + // Collect values to move + java.util.Map valuesToMove = new java.util.HashMap<>(); + for (String k : keysToMove) { + valuesToMove.put(k, objectNode.get(k)); + } + + // Set values at destination + for (Map.Entry entry : valuesToMove.entrySet()) { + String k = entry.getKey(); + JsonNode v = entry.getValue(); + + // Build destination keys with the field name + java.util.List newDestKeysList = new java.util.ArrayList<>(); + for (int i = keyIdx; i < destKeys.length; i++) { + String dk = destKeys[i]; + if (dk.equals("*")) { + newDestKeysList.add(k); + } else { + newDestKeysList.add(dk); + } + } + + String[] newDestKeys = newDestKeysList.toArray(new String[0]); + setValueByPath(objectNode, newDestKeys, v); + } + + // Delete from source + for (String k : keysToMove) { + objectNode.remove(k); + } + } + } else { + // Navigate to next level + if (data.isObject() && ((ObjectNode) data).has(key)) { + JsonNode nextNode = ((ObjectNode) data).get(key); + moveValueRecursive(nextNode, sourceKeys, destKeys, keyIdx + 1, excludeKeys); + } + } + } } diff --git a/src/main/java/com/google/genai/Files.java b/src/main/java/com/google/genai/Files.java index f3f4bd14946..c877f1ce8b8 100644 --- a/src/main/java/com/google/genai/Files.java +++ b/src/main/java/com/google/genai/Files.java @@ -21,9 +21,9 @@ import static com.google.common.base.Preconditions.checkNotNull; import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; +import com.google.common.base.Ascii; +import com.google.genai.Common.BuiltRequest; import com.google.genai.errors.GenAiIOException; import com.google.genai.types.CreateFileConfig; import com.google.genai.types.CreateFileParameters; @@ -60,6 +60,7 @@ * `client.files.methodName(...)` directly. */ public final class Files { + final ApiClient apiClient; private final UploadClient uploadClient; @@ -70,191 +71,52 @@ public Files(ApiClient apiClient) { } @ExcludeFromGeneratedCoverageReport - ObjectNode listFilesConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - if (Common.getValueByPath(fromObject, new String[] {"pageSize"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"_query", "pageSize"}, - Common.getValueByPath(fromObject, new String[] {"pageSize"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"pageToken"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"_query", "pageToken"}, - Common.getValueByPath(fromObject, new String[] {"pageToken"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode listFilesParametersToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode createFileParametersToMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"file"}) != null) { Common.setValueByPath( toObject, - new String[] {"config"}, - listFilesConfigToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"config"})), - toObject)); + new String[] {"file"}, + Common.getValueByPath(fromObject, new String[] {"file"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode fileStatusToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode createFileResponseFromMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"details"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"details"}, - Common.getValueByPath(fromObject, new String[] {"details"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"message"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"message"}, - Common.getValueByPath(fromObject, new String[] {"message"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"code"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"}) != null) { Common.setValueByPath( toObject, - new String[] {"code"}, - Common.getValueByPath(fromObject, new String[] {"code"})); + new String[] {"sdkHttpResponse"}, + Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode fileToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode deleteFileParametersToMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { Common.setValueByPath( toObject, - new String[] {"name"}, - Common.getValueByPath(fromObject, new String[] {"name"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"displayName"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"displayName"}, - Common.getValueByPath(fromObject, new String[] {"displayName"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"mimeType"}, - Common.getValueByPath(fromObject, new String[] {"mimeType"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"sizeBytes"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"sizeBytes"}, - Common.getValueByPath(fromObject, new String[] {"sizeBytes"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"createTime"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"createTime"}, - Common.getValueByPath(fromObject, new String[] {"createTime"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"expirationTime"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"expirationTime"}, - Common.getValueByPath(fromObject, new String[] {"expirationTime"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"updateTime"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"updateTime"}, - Common.getValueByPath(fromObject, new String[] {"updateTime"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"sha256Hash"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"sha256Hash"}, - Common.getValueByPath(fromObject, new String[] {"sha256Hash"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"uri"}) != null) { - Common.setValueByPath( - toObject, new String[] {"uri"}, Common.getValueByPath(fromObject, new String[] {"uri"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"downloadUri"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"downloadUri"}, - Common.getValueByPath(fromObject, new String[] {"downloadUri"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"state"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"state"}, - Common.getValueByPath(fromObject, new String[] {"state"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"source"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"source"}, - Common.getValueByPath(fromObject, new String[] {"source"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"videoMetadata"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"videoMetadata"}, - Common.getValueByPath(fromObject, new String[] {"videoMetadata"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"error"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"error"}, - fileStatusToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"error"})), - toObject)); + new String[] {"_url", "file"}, + Transformers.tFileName(Common.getValueByPath(fromObject, new String[] {"name"}))); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode createFileParametersToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode deleteFileResponseFromMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"file"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"file"}, - fileToMldev( - JsonSerializable.toJsonNode(Common.getValueByPath(fromObject, new String[] {"file"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"}) != null) { Common.setValueByPath( toObject, - new String[] {"config"}, - Common.getValueByPath(fromObject, new String[] {"config"})); + new String[] {"sdkHttpResponse"}, + Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"})); } return toObject; @@ -270,163 +132,39 @@ ObjectNode getFileParametersToMldev(JsonNode fromObject, ObjectNode parentObject Transformers.tFileName(Common.getValueByPath(fromObject, new String[] {"name"}))); } - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"config"}, - Common.getValueByPath(fromObject, new String[] {"config"})); - } - return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode deleteFileParametersToMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"_url", "file"}, - Transformers.tFileName(Common.getValueByPath(fromObject, new String[] {"name"}))); - } - - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"config"}, - Common.getValueByPath(fromObject, new String[] {"config"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode fileStatusFromMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode listFilesConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"details"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"details"}, - Common.getValueByPath(fromObject, new String[] {"details"})); - } - if (Common.getValueByPath(fromObject, new String[] {"message"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"pageSize"}) != null) { Common.setValueByPath( - toObject, - new String[] {"message"}, - Common.getValueByPath(fromObject, new String[] {"message"})); + parentObject, + new String[] {"_query", "pageSize"}, + Common.getValueByPath(fromObject, new String[] {"pageSize"})); } - if (Common.getValueByPath(fromObject, new String[] {"code"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"pageToken"}) != null) { Common.setValueByPath( - toObject, - new String[] {"code"}, - Common.getValueByPath(fromObject, new String[] {"code"})); + parentObject, + new String[] {"_query", "pageToken"}, + Common.getValueByPath(fromObject, new String[] {"pageToken"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode fileFromMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode listFilesParametersToMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"name"}, - Common.getValueByPath(fromObject, new String[] {"name"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"displayName"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"displayName"}, - Common.getValueByPath(fromObject, new String[] {"displayName"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"mimeType"}, - Common.getValueByPath(fromObject, new String[] {"mimeType"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"sizeBytes"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"sizeBytes"}, - Common.getValueByPath(fromObject, new String[] {"sizeBytes"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"createTime"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"createTime"}, - Common.getValueByPath(fromObject, new String[] {"createTime"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"expirationTime"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"expirationTime"}, - Common.getValueByPath(fromObject, new String[] {"expirationTime"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"updateTime"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"updateTime"}, - Common.getValueByPath(fromObject, new String[] {"updateTime"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"sha256Hash"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"sha256Hash"}, - Common.getValueByPath(fromObject, new String[] {"sha256Hash"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"uri"}) != null) { - Common.setValueByPath( - toObject, new String[] {"uri"}, Common.getValueByPath(fromObject, new String[] {"uri"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"downloadUri"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"downloadUri"}, - Common.getValueByPath(fromObject, new String[] {"downloadUri"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"state"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"state"}, - Common.getValueByPath(fromObject, new String[] {"state"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"source"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"source"}, - Common.getValueByPath(fromObject, new String[] {"source"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"videoMetadata"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"videoMetadata"}, - Common.getValueByPath(fromObject, new String[] {"videoMetadata"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"error"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"error"}, - fileStatusFromMldev( + if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + JsonNode unused = + listFilesConfigToMldev( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"error"})), - toObject)); + Common.getValueByPath(fromObject, new String[] {"config"})), + toObject); } return toObject; @@ -435,6 +173,12 @@ ObjectNode fileFromMldev(JsonNode fromObject, ObjectNode parentObject) { @ExcludeFromGeneratedCoverageReport ObjectNode listFilesResponseFromMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"sdkHttpResponse"}, + Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"})); + } if (Common.getValueByPath(fromObject, new String[] {"nextPageToken"}) != null) { Common.setValueByPath( @@ -444,46 +188,17 @@ ObjectNode listFilesResponseFromMldev(JsonNode fromObject, ObjectNode parentObje } if (Common.getValueByPath(fromObject, new String[] {"files"}) != null) { - ArrayNode keyArray = (ArrayNode) Common.getValueByPath(fromObject, new String[] {"files"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add(fileFromMldev(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"files"}, result); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode createFileResponseFromMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"}) != null) { Common.setValueByPath( toObject, - new String[] {"sdkHttpResponse"}, - Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"})); + new String[] {"files"}, + Common.getValueByPath(fromObject, new String[] {"files"})); } return toObject; } - @ExcludeFromGeneratedCoverageReport - ObjectNode deleteFileResponseFromMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - return toObject; - } - - /** - * Lists all files from the service. - * - * @param config - Optional, configuration for the list method. - * @return The ListFilesResponse, the response for the list method. - */ - ListFilesResponse privateList(ListFilesConfig config) { + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForPrivateList(ListFilesConfig config) { ListFilesParameters.Builder parameterBuilder = ListFilesParameters.builder(); @@ -514,36 +229,66 @@ ListFilesResponse privateList(ListFilesConfig config) { } // TODO: Remove the hack that removes config. - body.remove("config"); - Optional requestHttpOptions = Optional.empty(); if (config != null) { requestHttpOptions = config.httpOptions(); } + return new BuiltRequest(path, JsonSerializable.toJsonString(body), requestHttpOptions); + } + + /** A shared processResponse function for both sync and async methods. */ + ListFilesResponse processResponseForPrivateList(ApiResponse response, ListFilesConfig config) { + ResponseBody responseBody = response.getBody(); + String responseString; + try { + responseString = responseBody.string(); + } catch (IOException e) { + throw new GenAiIOException("Failed to read HTTP response.", e); + } + + JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); + + if (this.apiClient.vertexAI()) { + throw new UnsupportedOperationException( + "This method is only supported in the Gemini Developer client."); + } + + if (!this.apiClient.vertexAI()) { + responseNode = listFilesResponseFromMldev(responseNode, null); + } + + ListFilesResponse sdkResponse = + JsonSerializable.fromJsonNode(responseNode, ListFilesResponse.class); + Headers responseHeaders = response.getHeaders(); + if (responseHeaders == null) { + return sdkResponse; + } + Map headers = new HashMap<>(); + for (String headerName : responseHeaders.names()) { + headers.put(headerName, responseHeaders.get(headerName)); + } + return sdkResponse.toBuilder().sdkHttpResponse(HttpResponse.builder().headers(headers)).build(); + } + + /** + * Lists all files from the service. + * + * @param config - Optional, configuration for the list method. + * @return The ListFilesResponse, the response for the list method. + */ + ListFilesResponse privateList(ListFilesConfig config) { + BuiltRequest builtRequest = buildRequestForPrivateList(config); + try (ApiResponse response = this.apiClient.request( - "get", path, JsonSerializable.toJsonString(body), requestHttpOptions)) { - ResponseBody responseBody = response.getBody(); - String responseString; - try { - responseString = responseBody.string(); - } catch (IOException e) { - throw new GenAiIOException("Failed to read HTTP response.", e); - } - - JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); - if (this.apiClient.vertexAI()) { - throw new UnsupportedOperationException( - "This method is only supported in the Gemini Developer client."); - } else { - responseNode = listFilesResponseFromMldev(responseNode, null); - } - return JsonSerializable.fromJsonNode(responseNode, ListFilesResponse.class); + "get", builtRequest.path, builtRequest.body, builtRequest.httpOptions)) { + return processResponseForPrivateList(response, config); } } - CreateFileResponse privateCreate(File file, CreateFileConfig config) { + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForPrivateCreate(File file, CreateFileConfig config) { CreateFileParameters.Builder parameterBuilder = CreateFileParameters.builder(); @@ -577,59 +322,67 @@ CreateFileResponse privateCreate(File file, CreateFileConfig config) { } // TODO: Remove the hack that removes config. - body.remove("config"); - Optional requestHttpOptions = Optional.empty(); if (config != null) { requestHttpOptions = config.httpOptions(); } - try (ApiResponse response = - this.apiClient.request( - "post", path, JsonSerializable.toJsonString(body), requestHttpOptions)) { - ResponseBody responseBody = response.getBody(); - String responseString; - try { - responseString = responseBody.string(); - } catch (IOException e) { - throw new GenAiIOException("Failed to read HTTP response.", e); - } + return new BuiltRequest(path, JsonSerializable.toJsonString(body), requestHttpOptions); + } + + /** A shared processResponse function for both sync and async methods. */ + CreateFileResponse processResponseForPrivateCreate( + ApiResponse response, CreateFileConfig config) { + ResponseBody responseBody = response.getBody(); + String responseString; + try { + responseString = responseBody.string(); + } catch (IOException e) { + throw new GenAiIOException("Failed to read HTTP response.", e); + } - if (config.shouldReturnHttpResponse().orElse(false)) { - Headers responseHeaders = response.getHeaders(); - if (responseHeaders == null) { - return CreateFileResponse.builder() - .sdkHttpResponse(HttpResponse.builder().body(responseString)) - .build(); - } - Map headers = new HashMap<>(); - for (String headerName : responseHeaders.names()) { - headers.put(headerName, responseHeaders.get(headerName)); - } + if (config != null && config.shouldReturnHttpResponse().orElse(false)) { + Headers responseHeaders = response.getHeaders(); + if (responseHeaders == null) { return CreateFileResponse.builder() - .sdkHttpResponse(HttpResponse.builder().headers(headers).body(responseString)) + .sdkHttpResponse(HttpResponse.builder().body(responseString)) .build(); } - - JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); - if (this.apiClient.vertexAI()) { - throw new UnsupportedOperationException( - "This method is only supported in the Gemini Developer client."); - } else { - responseNode = createFileResponseFromMldev(responseNode, null); + Map headers = new HashMap<>(); + for (String headerName : responseHeaders.names()) { + headers.put(headerName, responseHeaders.get(headerName)); } - return JsonSerializable.fromJsonNode(responseNode, CreateFileResponse.class); + return CreateFileResponse.builder() + .sdkHttpResponse(HttpResponse.builder().headers(headers).body(responseString)) + .build(); + } + + JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); + + if (this.apiClient.vertexAI()) { + throw new UnsupportedOperationException( + "This method is only supported in the Gemini Developer client."); } + + if (!this.apiClient.vertexAI()) { + responseNode = createFileResponseFromMldev(responseNode, null); + } + + return JsonSerializable.fromJsonNode(responseNode, CreateFileResponse.class); } - /** - * Retrieves the file information from the service. - * - * @param name - The name identifier for the file to retrieve. - * @param config - Optional, configuration for the get method. - * @return A File object representing the file. - */ - public File get(String name, GetFileConfig config) { + CreateFileResponse privateCreate(File file, CreateFileConfig config) { + BuiltRequest builtRequest = buildRequestForPrivateCreate(file, config); + + try (ApiResponse response = + this.apiClient.request( + "post", builtRequest.path, builtRequest.body, builtRequest.httpOptions)) { + return processResponseForPrivateCreate(response, config); + } + } + + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForGet(String name, GetFileConfig config) { GetFileParameters.Builder parameterBuilder = GetFileParameters.builder(); @@ -663,43 +416,53 @@ public File get(String name, GetFileConfig config) { } // TODO: Remove the hack that removes config. - body.remove("config"); - Optional requestHttpOptions = Optional.empty(); if (config != null) { requestHttpOptions = config.httpOptions(); } - try (ApiResponse response = - this.apiClient.request( - "get", path, JsonSerializable.toJsonString(body), requestHttpOptions)) { - ResponseBody responseBody = response.getBody(); - String responseString; - try { - responseString = responseBody.string(); - } catch (IOException e) { - throw new GenAiIOException("Failed to read HTTP response.", e); - } + return new BuiltRequest(path, JsonSerializable.toJsonString(body), requestHttpOptions); + } - JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); - if (this.apiClient.vertexAI()) { - throw new UnsupportedOperationException( - "This method is only supported in the Gemini Developer client."); - } else { - responseNode = fileFromMldev(responseNode, null); - } - return JsonSerializable.fromJsonNode(responseNode, File.class); + /** A shared processResponse function for both sync and async methods. */ + File processResponseForGet(ApiResponse response, GetFileConfig config) { + ResponseBody responseBody = response.getBody(); + String responseString; + try { + responseString = responseBody.string(); + } catch (IOException e) { + throw new GenAiIOException("Failed to read HTTP response.", e); + } + + JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); + + if (this.apiClient.vertexAI()) { + throw new UnsupportedOperationException( + "This method is only supported in the Gemini Developer client."); } + + return JsonSerializable.fromJsonNode(responseNode, File.class); } /** - * Deletes a remotely stored file. + * Retrieves the file information from the service. * - * @param name - The name identifier for the file to delete. - * @param config - Optional, configuration for the delete method. - * @return The DeleteFileResponse, the response for the delete method. + * @param name - The name identifier for the file to retrieve. + * @param config - Optional, configuration for the get method. + * @return A File object representing the file. */ - public DeleteFileResponse delete(String name, DeleteFileConfig config) { + public File get(String name, GetFileConfig config) { + BuiltRequest builtRequest = buildRequestForGet(name, config); + + try (ApiResponse response = + this.apiClient.request( + "get", builtRequest.path, builtRequest.body, builtRequest.httpOptions)) { + return processResponseForGet(response, config); + } + } + + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForDelete(String name, DeleteFileConfig config) { DeleteFileParameters.Builder parameterBuilder = DeleteFileParameters.builder(); @@ -733,32 +496,62 @@ public DeleteFileResponse delete(String name, DeleteFileConfig config) { } // TODO: Remove the hack that removes config. - body.remove("config"); - Optional requestHttpOptions = Optional.empty(); if (config != null) { requestHttpOptions = config.httpOptions(); } + return new BuiltRequest(path, JsonSerializable.toJsonString(body), requestHttpOptions); + } + + /** A shared processResponse function for both sync and async methods. */ + DeleteFileResponse processResponseForDelete(ApiResponse response, DeleteFileConfig config) { + ResponseBody responseBody = response.getBody(); + String responseString; + try { + responseString = responseBody.string(); + } catch (IOException e) { + throw new GenAiIOException("Failed to read HTTP response.", e); + } + + JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); + + if (this.apiClient.vertexAI()) { + throw new UnsupportedOperationException( + "This method is only supported in the Gemini Developer client."); + } + + if (!this.apiClient.vertexAI()) { + responseNode = deleteFileResponseFromMldev(responseNode, null); + } + + DeleteFileResponse sdkResponse = + JsonSerializable.fromJsonNode(responseNode, DeleteFileResponse.class); + Headers responseHeaders = response.getHeaders(); + if (responseHeaders == null) { + return sdkResponse; + } + Map headers = new HashMap<>(); + for (String headerName : responseHeaders.names()) { + headers.put(headerName, responseHeaders.get(headerName)); + } + return sdkResponse.toBuilder().sdkHttpResponse(HttpResponse.builder().headers(headers)).build(); + } + + /** + * Deletes a remotely stored file. + * + * @param name - The name identifier for the file to delete. + * @param config - Optional, configuration for the delete method. + * @return The DeleteFileResponse, the response for the delete method. + */ + public DeleteFileResponse delete(String name, DeleteFileConfig config) { + BuiltRequest builtRequest = buildRequestForDelete(name, config); + try (ApiResponse response = this.apiClient.request( - "delete", path, JsonSerializable.toJsonString(body), requestHttpOptions)) { - ResponseBody responseBody = response.getBody(); - String responseString; - try { - responseString = responseBody.string(); - } catch (IOException e) { - throw new GenAiIOException("Failed to read HTTP response.", e); - } - - JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); - if (this.apiClient.vertexAI()) { - throw new UnsupportedOperationException( - "This method is only supported in the Gemini Developer client."); - } else { - responseNode = deleteFileResponseFromMldev(responseNode, null); - } - return JsonSerializable.fromJsonNode(responseNode, DeleteFileResponse.class); + "delete", builtRequest.path, builtRequest.body, builtRequest.httpOptions)) { + return processResponseForDelete(response, config); } } @@ -772,6 +565,7 @@ public DeleteFileResponse delete(String name, DeleteFileConfig config) { public File upload(java.io.File file, UploadFileConfig config) { try (InputStream inputStream = new FileInputStream(file)) { long size = file.length(); + String fileName = file.getName(); String probedMimeType = java.nio.file.Files.probeContentType(file.toPath()); Optional mimeType; if (probedMimeType != null) { @@ -779,7 +573,7 @@ public File upload(java.io.File file, UploadFileConfig config) { } else { mimeType = Optional.empty(); } - String uploadUrl = createFileInApi(config, mimeType, size); + String uploadUrl = createFileInApi(config, mimeType, Optional.of(fileName), size); ResponseBody responseBody = uploadClient.upload(uploadUrl, inputStream, size); return fileFromUploadResponseBody(responseBody); } catch (IOException e) { @@ -795,7 +589,8 @@ public File upload(java.io.File file, UploadFileConfig config) { * @return The uploaded file. */ public File upload(byte[] bytes, UploadFileConfig config) { - String uploadUrl = createFileInApi(config, Optional.empty(), bytes.length); + String uploadUrl = + createFileInApi(config, Optional.empty(), Optional.empty(), bytes.length); ResponseBody responseBody = uploadClient.upload(uploadUrl, bytes); return fileFromUploadResponseBody(responseBody); } @@ -809,7 +604,8 @@ public File upload(byte[] bytes, UploadFileConfig config) { * @return The uploaded file. */ public File upload(InputStream inputStream, long size, UploadFileConfig config) { - String uploadUrl = createFileInApi(config, Optional.empty(), size); + String uploadUrl = + createFileInApi(config, Optional.empty(), Optional.empty(), size); ResponseBody responseBody = uploadClient.upload(uploadUrl, inputStream, size); return fileFromUploadResponseBody(responseBody); } @@ -835,12 +631,12 @@ private File fileFromUploadResponseBody(ResponseBody responseBody) { } JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); responseNode = responseNode.get("file"); - responseNode = fileFromMldev(responseNode, null); return JsonSerializable.fromJsonNode(responseNode, File.class); } - private String createFileInApi(UploadFileConfig config, Optional mimeType, long size) { + private String createFileInApi( + UploadFileConfig config, Optional mimeType, Optional fileName, long size) { File.Builder apiFileBuilder = File.builder(); if (config != null) { if (config.name().isPresent()) { @@ -876,6 +672,9 @@ private String createFileInApi(UploadFileConfig config, Optional mimeTyp createFileHeaders.put("X-Goog-Upload-Command", "start"); createFileHeaders.put("X-Goog-Upload-Header-Content-Length", "" + size); createFileHeaders.put("X-Goog-Upload-Header-Content-Type", actualMimeType); + if (fileName.isPresent()) { + createFileHeaders.put("X-Goog-Upload-File-Name", fileName.get()); + } HttpOptions createFileHttpOptions = HttpOptions.builder().apiVersion("").headers(createFileHeaders).build(); @@ -888,19 +687,20 @@ private String createFileInApi(UploadFileConfig config, Optional mimeTyp .shouldReturnHttpResponse(true) .build()); - if (!createFileResponse.sdkHttpResponse().isPresent() - || !createFileResponse.sdkHttpResponse().get().headers().isPresent() - || !createFileResponse - .sdkHttpResponse() - .get() - .headers() - .get() - .containsKey("X-Goog-Upload-URL")) { - throw new IllegalStateException( - "Failed to create file. Upload URL was not returned in the create file response."); - } - - return createFileResponse.sdkHttpResponse().get().headers().get().get("X-Goog-Upload-URL"); + return createFileResponse + .sdkHttpResponse() + .flatMap(HttpResponse::headers) + .flatMap( + headers -> + headers.entrySet().stream() + .filter(entry -> Ascii.equalsIgnoreCase("x-goog-upload-url", entry.getKey())) + .map(entry -> entry.getValue()) + .findFirst()) + .orElseThrow( + () -> + new IllegalStateException( + "Failed to create file. Upload URL was not returned in the create file" + + " response.")); } /** diff --git a/src/main/java/com/google/genai/HttpApiClient.java b/src/main/java/com/google/genai/HttpApiClient.java index fe6d02d0c06..19a9e07ae1b 100644 --- a/src/main/java/com/google/genai/HttpApiClient.java +++ b/src/main/java/com/google/genai/HttpApiClient.java @@ -23,7 +23,11 @@ import com.google.genai.types.HttpOptions; import java.io.IOException; import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; import okhttp3.Request; +import okhttp3.Response; /** Base client for the HTTP APIs. This is for internal use only. */ @InternalApi @@ -63,7 +67,7 @@ public HttpApiResponse request( /** Sends a Http request given the http method, path, request bytes, and http options. */ @Override - public ApiResponse request( + public HttpApiResponse request( String httpMethod, String url, byte[] requestBytes, @@ -79,4 +83,54 @@ private HttpApiResponse executeRequest(Request request) { throw new GenAiIOException("Failed to execute HTTP request.", e); } } + + /** + * Sends an asynchronous Http request given the http method, path, request json string, and http + * options. + */ + @Override + public CompletableFuture asyncRequest( + String httpMethod, + String path, + String requestJson, + Optional requestHttpOptions) { + return asyncExecuteRequest(buildRequest(httpMethod, path, requestJson, requestHttpOptions)); + } + + /** + * Sends an asynchronous Http request given the http method, path, request bytes, and http + * options. + */ + @Override + public CompletableFuture asyncRequest( + String httpMethod, + String url, + byte[] requestBytes, + Optional requestHttpOptions) { + return asyncExecuteRequest(buildRequest(httpMethod, url, requestBytes, requestHttpOptions)); + } + + /** Executes the given HTTP request asynchronously, this method is non-blocking. */ + private CompletableFuture asyncExecuteRequest(Request request) { + CompletableFuture future = new CompletableFuture<>(); + + httpClient + .newCall(request) + .enqueue( + new Callback() { + + @Override + public void onFailure(Call call, IOException e) { + future.completeExceptionally( + new GenAiIOException("Failed to execute HTTP request.", e)); + } + + @Override + public void onResponse(Call call, Response response) { + future.complete(new HttpApiResponse(response)); + } + }); + + return future; + } } diff --git a/src/main/java/com/google/genai/JsonSerializable.java b/src/main/java/com/google/genai/JsonSerializable.java index 57874b9600e..a2919940de1 100644 --- a/src/main/java/com/google/genai/JsonSerializable.java +++ b/src/main/java/com/google/genai/JsonSerializable.java @@ -38,7 +38,7 @@ /** A class that can be serialized to JSON and deserialized from JSON. */ public abstract class JsonSerializable { - static final ObjectMapper objectMapper = new ObjectMapper(); + @InternalApi protected static final ObjectMapper objectMapper = new ObjectMapper(); /** Custom Jackson serializer for {@link java.time.Duration} to output "Xs" format. */ static class CustomDurationSerializer extends JsonSerializer { @@ -71,11 +71,15 @@ public java.time.Duration deserialize(JsonParser p, DeserializationContext ctxt) long seconds = Long.parseLong(secondsPart); return java.time.Duration.ofSeconds(seconds); } catch (NumberFormatException e) { - throw ctxt.weirdStringException(value, java.time.Duration.class, "Cannot parse duration from string: " + value + ". Expected format 'Xs'."); + throw ctxt.weirdStringException( + value, + java.time.Duration.class, + "Cannot parse duration from string: " + value + ". Expected format 'Xs'."); } } else { // If it doesn't end with 's', delegate to the default deserializer. - throw ctxt.weirdStringException(value, java.time.Duration.class, "Expected duration in format 'Xs', but got: " + value); + throw ctxt.weirdStringException( + value, java.time.Duration.class, "Expected duration in format 'Xs', but got: " + value); } } } @@ -83,7 +87,6 @@ public java.time.Duration deserialize(JsonParser p, DeserializationContext ctxt) static { objectMapper.setSerializationInclusion(JsonInclude.Include.NON_ABSENT); objectMapper.registerModule(new Jdk8Module()); - objectMapper.registerModule(new JavaTimeModule()); // Disable writing dates as timestamps to use ISO-8601 string format for Instant objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); @@ -98,7 +101,6 @@ public java.time.Duration deserialize(JsonParser p, DeserializationContext ctxt) // provided by JavaTimeModule. objectMapper.registerModule(new JavaTimeModule()); objectMapper.registerModule(customModule); - } /** Serializes the instance to a Json string. */ @@ -132,7 +134,8 @@ protected static T fromJsonString( } /** Deserializes a JsonNode to an object of the given type. */ - static T fromJsonNode(JsonNode jsonNode, Class clazz) { + @InternalApi + protected static T fromJsonNode(JsonNode jsonNode, Class clazz) { try { return objectMapper.treeToValue(jsonNode, clazz); } catch (JsonProcessingException e) { @@ -141,7 +144,7 @@ static T fromJsonNode(JsonNode jsonNode, Class c } /** Converts a Json string to a JsonNode. */ - static JsonNode stringToJsonNode(String string) { + public static JsonNode stringToJsonNode(String string) { try { return objectMapper.readTree(string); } catch (JsonProcessingException e) { diff --git a/src/main/java/com/google/genai/LiveConverters.java b/src/main/java/com/google/genai/LiveConverters.java index 2979be9fd8c..590d8daabf8 100644 --- a/src/main/java/com/google/genai/LiveConverters.java +++ b/src/main/java/com/google/genai/LiveConverters.java @@ -23,6 +23,7 @@ import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; +/** Internal SDK converter functions. */ final class LiveConverters { private final ApiClient apiClient; @@ -31,360 +32,310 @@ public LiveConverters(ApiClient apiClient) { } @ExcludeFromGeneratedCoverageReport - ObjectNode prebuiltVoiceConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"voiceName"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"voiceName"}, - Common.getValueByPath(fromObject, new String[] {"voiceName"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode voiceConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode blobToMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"prebuiltVoiceConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"data"}) != null) { Common.setValueByPath( toObject, - new String[] {"prebuiltVoiceConfig"}, - prebuiltVoiceConfigToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"prebuiltVoiceConfig"})), - toObject)); + new String[] {"data"}, + Common.getValueByPath(fromObject, new String[] {"data"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode speakerVoiceConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"speaker"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"speaker"}, - Common.getValueByPath(fromObject, new String[] {"speaker"})); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"displayName"}))) { + throw new IllegalArgumentException("displayName parameter is not supported in Gemini API."); } - if (Common.getValueByPath(fromObject, new String[] {"voiceConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { Common.setValueByPath( toObject, - new String[] {"voiceConfig"}, - voiceConfigToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"voiceConfig"})), - toObject)); + new String[] {"mimeType"}, + Common.getValueByPath(fromObject, new String[] {"mimeType"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode multiSpeakerVoiceConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode contentToMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"speakerVoiceConfigs"}) != null) { - ArrayNode keyArray = - (ArrayNode) Common.getValueByPath(fromObject, new String[] {"speakerVoiceConfigs"}); + if (Common.getValueByPath(fromObject, new String[] {"parts"}) != null) { + ArrayNode keyArray = (ArrayNode) Common.getValueByPath(fromObject, new String[] {"parts"}); ObjectMapper objectMapper = new ObjectMapper(); ArrayNode result = objectMapper.createArrayNode(); for (JsonNode item : keyArray) { - result.add(speakerVoiceConfigToMldev(JsonSerializable.toJsonNode(item), toObject)); + result.add(partToMldev(JsonSerializable.toJsonNode(item), toObject)); } - Common.setValueByPath(toObject, new String[] {"speakerVoiceConfigs"}, result); + Common.setValueByPath(toObject, new String[] {"parts"}, result); + } + + if (Common.getValueByPath(fromObject, new String[] {"role"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"role"}, + Common.getValueByPath(fromObject, new String[] {"role"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode speechConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode fileDataToMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"voiceConfig"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"voiceConfig"}, - voiceConfigToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"voiceConfig"})), - toObject)); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"displayName"}))) { + throw new IllegalArgumentException("displayName parameter is not supported in Gemini API."); } - if (Common.getValueByPath(fromObject, new String[] {"multiSpeakerVoiceConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"fileUri"}) != null) { Common.setValueByPath( toObject, - new String[] {"multiSpeakerVoiceConfig"}, - multiSpeakerVoiceConfigToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"multiSpeakerVoiceConfig"})), - toObject)); + new String[] {"fileUri"}, + Common.getValueByPath(fromObject, new String[] {"fileUri"})); } - if (Common.getValueByPath(fromObject, new String[] {"languageCode"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { Common.setValueByPath( toObject, - new String[] {"languageCode"}, - Common.getValueByPath(fromObject, new String[] {"languageCode"})); + new String[] {"mimeType"}, + Common.getValueByPath(fromObject, new String[] {"mimeType"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode videoMetadataToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode functionDeclarationToVertex(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"fps"}) != null) { - Common.setValueByPath( - toObject, new String[] {"fps"}, Common.getValueByPath(fromObject, new String[] {"fps"})); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"behavior"}))) { + throw new IllegalArgumentException("behavior parameter is not supported in Vertex AI."); } - if (Common.getValueByPath(fromObject, new String[] {"endOffset"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"description"}) != null) { Common.setValueByPath( toObject, - new String[] {"endOffset"}, - Common.getValueByPath(fromObject, new String[] {"endOffset"})); + new String[] {"description"}, + Common.getValueByPath(fromObject, new String[] {"description"})); } - if (Common.getValueByPath(fromObject, new String[] {"startOffset"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { Common.setValueByPath( toObject, - new String[] {"startOffset"}, - Common.getValueByPath(fromObject, new String[] {"startOffset"})); + new String[] {"name"}, + Common.getValueByPath(fromObject, new String[] {"name"})); } - return toObject; - } + if (Common.getValueByPath(fromObject, new String[] {"parameters"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"parameters"}, + Common.getValueByPath(fromObject, new String[] {"parameters"})); + } - @ExcludeFromGeneratedCoverageReport - ObjectNode blobToMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"displayName"}))) { - throw new IllegalArgumentException("displayName parameter is not supported in Gemini API."); + if (Common.getValueByPath(fromObject, new String[] {"parametersJsonSchema"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"parametersJsonSchema"}, + Common.getValueByPath(fromObject, new String[] {"parametersJsonSchema"})); } - if (Common.getValueByPath(fromObject, new String[] {"data"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"response"}) != null) { Common.setValueByPath( toObject, - new String[] {"data"}, - Common.getValueByPath(fromObject, new String[] {"data"})); + new String[] {"response"}, + Common.getValueByPath(fromObject, new String[] {"response"})); } - if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"responseJsonSchema"}) != null) { Common.setValueByPath( toObject, - new String[] {"mimeType"}, - Common.getValueByPath(fromObject, new String[] {"mimeType"})); + new String[] {"responseJsonSchema"}, + Common.getValueByPath(fromObject, new String[] {"responseJsonSchema"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode fileDataToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode generationConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"displayName"}))) { - throw new IllegalArgumentException("displayName parameter is not supported in Gemini API."); + if (Common.getValueByPath(fromObject, new String[] {"modelSelectionConfig"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"modelConfig"}, + Common.getValueByPath(fromObject, new String[] {"modelSelectionConfig"})); } - if (Common.getValueByPath(fromObject, new String[] {"fileUri"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"audioTimestamp"}) != null) { Common.setValueByPath( toObject, - new String[] {"fileUri"}, - Common.getValueByPath(fromObject, new String[] {"fileUri"})); + new String[] {"audioTimestamp"}, + Common.getValueByPath(fromObject, new String[] {"audioTimestamp"})); } - if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"candidateCount"}) != null) { Common.setValueByPath( toObject, - new String[] {"mimeType"}, - Common.getValueByPath(fromObject, new String[] {"mimeType"})); + new String[] {"candidateCount"}, + Common.getValueByPath(fromObject, new String[] {"candidateCount"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode partToMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"videoMetadata"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"enableAffectiveDialog"}) != null) { Common.setValueByPath( toObject, - new String[] {"videoMetadata"}, - videoMetadataToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"videoMetadata"})), - toObject)); + new String[] {"enableAffectiveDialog"}, + Common.getValueByPath(fromObject, new String[] {"enableAffectiveDialog"})); } - if (Common.getValueByPath(fromObject, new String[] {"thought"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"frequencyPenalty"}) != null) { Common.setValueByPath( toObject, - new String[] {"thought"}, - Common.getValueByPath(fromObject, new String[] {"thought"})); + new String[] {"frequencyPenalty"}, + Common.getValueByPath(fromObject, new String[] {"frequencyPenalty"})); } - if (Common.getValueByPath(fromObject, new String[] {"inlineData"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"logprobs"}) != null) { Common.setValueByPath( toObject, - new String[] {"inlineData"}, - blobToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"inlineData"})), - toObject)); + new String[] {"logprobs"}, + Common.getValueByPath(fromObject, new String[] {"logprobs"})); } - if (Common.getValueByPath(fromObject, new String[] {"fileData"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"maxOutputTokens"}) != null) { Common.setValueByPath( toObject, - new String[] {"fileData"}, - fileDataToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"fileData"})), - toObject)); + new String[] {"maxOutputTokens"}, + Common.getValueByPath(fromObject, new String[] {"maxOutputTokens"})); } - if (Common.getValueByPath(fromObject, new String[] {"thoughtSignature"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"mediaResolution"}) != null) { Common.setValueByPath( toObject, - new String[] {"thoughtSignature"}, - Common.getValueByPath(fromObject, new String[] {"thoughtSignature"})); + new String[] {"mediaResolution"}, + Common.getValueByPath(fromObject, new String[] {"mediaResolution"})); } - if (Common.getValueByPath(fromObject, new String[] {"codeExecutionResult"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"presencePenalty"}) != null) { Common.setValueByPath( toObject, - new String[] {"codeExecutionResult"}, - Common.getValueByPath(fromObject, new String[] {"codeExecutionResult"})); + new String[] {"presencePenalty"}, + Common.getValueByPath(fromObject, new String[] {"presencePenalty"})); } - if (Common.getValueByPath(fromObject, new String[] {"executableCode"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"responseJsonSchema"}) != null) { Common.setValueByPath( toObject, - new String[] {"executableCode"}, - Common.getValueByPath(fromObject, new String[] {"executableCode"})); + new String[] {"responseJsonSchema"}, + Common.getValueByPath(fromObject, new String[] {"responseJsonSchema"})); } - if (Common.getValueByPath(fromObject, new String[] {"functionCall"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"responseLogprobs"}) != null) { Common.setValueByPath( toObject, - new String[] {"functionCall"}, - Common.getValueByPath(fromObject, new String[] {"functionCall"})); + new String[] {"responseLogprobs"}, + Common.getValueByPath(fromObject, new String[] {"responseLogprobs"})); } - if (Common.getValueByPath(fromObject, new String[] {"functionResponse"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"responseMimeType"}) != null) { Common.setValueByPath( toObject, - new String[] {"functionResponse"}, - Common.getValueByPath(fromObject, new String[] {"functionResponse"})); + new String[] {"responseMimeType"}, + Common.getValueByPath(fromObject, new String[] {"responseMimeType"})); } - if (Common.getValueByPath(fromObject, new String[] {"text"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"responseModalities"}) != null) { Common.setValueByPath( toObject, - new String[] {"text"}, - Common.getValueByPath(fromObject, new String[] {"text"})); + new String[] {"responseModalities"}, + Common.getValueByPath(fromObject, new String[] {"responseModalities"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode contentToMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"parts"}) != null) { - ArrayNode keyArray = (ArrayNode) Common.getValueByPath(fromObject, new String[] {"parts"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add(partToMldev(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"parts"}, result); + if (Common.getValueByPath(fromObject, new String[] {"responseSchema"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"responseSchema"}, + Common.getValueByPath(fromObject, new String[] {"responseSchema"})); } - if (Common.getValueByPath(fromObject, new String[] {"role"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"routingConfig"}) != null) { Common.setValueByPath( toObject, - new String[] {"role"}, - Common.getValueByPath(fromObject, new String[] {"role"})); + new String[] {"routingConfig"}, + Common.getValueByPath(fromObject, new String[] {"routingConfig"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode functionDeclarationToMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"behavior"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"seed"}) != null) { Common.setValueByPath( toObject, - new String[] {"behavior"}, - Common.getValueByPath(fromObject, new String[] {"behavior"})); + new String[] {"seed"}, + Common.getValueByPath(fromObject, new String[] {"seed"})); } - if (Common.getValueByPath(fromObject, new String[] {"description"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"speechConfig"}) != null) { Common.setValueByPath( toObject, - new String[] {"description"}, - Common.getValueByPath(fromObject, new String[] {"description"})); + new String[] {"speechConfig"}, + speechConfigToVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"speechConfig"})), + toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"stopSequences"}) != null) { Common.setValueByPath( toObject, - new String[] {"name"}, - Common.getValueByPath(fromObject, new String[] {"name"})); + new String[] {"stopSequences"}, + Common.getValueByPath(fromObject, new String[] {"stopSequences"})); } - if (Common.getValueByPath(fromObject, new String[] {"parameters"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"temperature"}) != null) { Common.setValueByPath( toObject, - new String[] {"parameters"}, - Common.getValueByPath(fromObject, new String[] {"parameters"})); + new String[] {"temperature"}, + Common.getValueByPath(fromObject, new String[] {"temperature"})); } - if (Common.getValueByPath(fromObject, new String[] {"parametersJsonSchema"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"thinkingConfig"}) != null) { Common.setValueByPath( toObject, - new String[] {"parametersJsonSchema"}, - Common.getValueByPath(fromObject, new String[] {"parametersJsonSchema"})); + new String[] {"thinkingConfig"}, + Common.getValueByPath(fromObject, new String[] {"thinkingConfig"})); } - if (Common.getValueByPath(fromObject, new String[] {"response"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"topK"}) != null) { Common.setValueByPath( toObject, - new String[] {"response"}, - Common.getValueByPath(fromObject, new String[] {"response"})); + new String[] {"topK"}, + Common.getValueByPath(fromObject, new String[] {"topK"})); } - if (Common.getValueByPath(fromObject, new String[] {"responseJsonSchema"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"topP"}) != null) { Common.setValueByPath( toObject, - new String[] {"responseJsonSchema"}, - Common.getValueByPath(fromObject, new String[] {"responseJsonSchema"})); + new String[] {"topP"}, + Common.getValueByPath(fromObject, new String[] {"topP"})); + } + + if (!Common.isZero( + Common.getValueByPath(fromObject, new String[] {"enableEnhancedCivicAnswers"}))) { + throw new IllegalArgumentException( + "enableEnhancedCivicAnswers parameter is not supported in Vertex AI."); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode intervalToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode googleMapsToMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"startTime"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"startTime"}, - Common.getValueByPath(fromObject, new String[] {"startTime"})); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"authConfig"}))) { + throw new IllegalArgumentException("authConfig parameter is not supported in Gemini API."); } - if (Common.getValueByPath(fromObject, new String[] {"endTime"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"enableWidget"}) != null) { Common.setValueByPath( toObject, - new String[] {"endTime"}, - Common.getValueByPath(fromObject, new String[] {"endTime"})); + new String[] {"enableWidget"}, + Common.getValueByPath(fromObject, new String[] {"enableWidget"})); } return toObject; @@ -393,356 +344,287 @@ ObjectNode intervalToMldev(JsonNode fromObject, ObjectNode parentObject) { @ExcludeFromGeneratedCoverageReport ObjectNode googleSearchToMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"excludeDomains"}))) { + throw new IllegalArgumentException( + "excludeDomains parameter is not supported in Gemini API."); + } + if (Common.getValueByPath(fromObject, new String[] {"timeRangeFilter"}) != null) { Common.setValueByPath( toObject, new String[] {"timeRangeFilter"}, - intervalToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"timeRangeFilter"})), - toObject)); + Common.getValueByPath(fromObject, new String[] {"timeRangeFilter"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode dynamicRetrievalConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode liveClientContentToMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"mode"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"mode"}, - Common.getValueByPath(fromObject, new String[] {"mode"})); + if (Common.getValueByPath(fromObject, new String[] {"turns"}) != null) { + ArrayNode keyArray = (ArrayNode) Common.getValueByPath(fromObject, new String[] {"turns"}); + ObjectMapper objectMapper = new ObjectMapper(); + ArrayNode result = objectMapper.createArrayNode(); + + for (JsonNode item : keyArray) { + result.add(contentToMldev(JsonSerializable.toJsonNode(item), toObject)); + } + Common.setValueByPath(toObject, new String[] {"turns"}, result); } - if (Common.getValueByPath(fromObject, new String[] {"dynamicThreshold"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"turnComplete"}) != null) { Common.setValueByPath( toObject, - new String[] {"dynamicThreshold"}, - Common.getValueByPath(fromObject, new String[] {"dynamicThreshold"})); + new String[] {"turnComplete"}, + Common.getValueByPath(fromObject, new String[] {"turnComplete"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode googleSearchRetrievalToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode liveClientMessageToMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"dynamicRetrievalConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"setup"}) != null) { Common.setValueByPath( toObject, - new String[] {"dynamicRetrievalConfig"}, - dynamicRetrievalConfigToMldev( + new String[] {"setup"}, + liveClientSetupToMldev( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"dynamicRetrievalConfig"})), + Common.getValueByPath(fromObject, new String[] {"setup"})), toObject)); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode urlContextToMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode toolToMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"functionDeclarations"}) != null) { - ArrayNode keyArray = - (ArrayNode) Common.getValueByPath(fromObject, new String[] {"functionDeclarations"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add(functionDeclarationToMldev(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"functionDeclarations"}, result); - } - - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"retrieval"}))) { - throw new IllegalArgumentException("retrieval parameter is not supported in Gemini API."); - } - - if (Common.getValueByPath(fromObject, new String[] {"googleSearch"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"clientContent"}) != null) { Common.setValueByPath( toObject, - new String[] {"googleSearch"}, - googleSearchToMldev( + new String[] {"clientContent"}, + liveClientContentToMldev( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"googleSearch"})), + Common.getValueByPath(fromObject, new String[] {"clientContent"})), toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"googleSearchRetrieval"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"realtimeInput"}) != null) { Common.setValueByPath( toObject, - new String[] {"googleSearchRetrieval"}, - googleSearchRetrievalToMldev( + new String[] {"realtimeInput"}, + liveClientRealtimeInputToMldev( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"googleSearchRetrieval"})), + Common.getValueByPath(fromObject, new String[] {"realtimeInput"})), toObject)); } - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"enterpriseWebSearch"}))) { - throw new IllegalArgumentException( - "enterpriseWebSearch parameter is not supported in Gemini API."); - } - - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"googleMaps"}))) { - throw new IllegalArgumentException("googleMaps parameter is not supported in Gemini API."); - } - - if (Common.getValueByPath(fromObject, new String[] {"urlContext"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"realtimeInputParameters"}) != null) { Common.setValueByPath( toObject, - new String[] {"urlContext"}, - urlContextToMldev( + new String[] {"realtime_input"}, + liveSendRealtimeInputParametersToMldev( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"urlContext"})), + Common.getValueByPath(fromObject, new String[] {"realtimeInputParameters"})), toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"codeExecution"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"codeExecution"}, - Common.getValueByPath(fromObject, new String[] {"codeExecution"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"computerUse"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"computerUse"}, - Common.getValueByPath(fromObject, new String[] {"computerUse"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode sessionResumptionConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"handle"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"toolResponse"}) != null) { Common.setValueByPath( toObject, - new String[] {"handle"}, - Common.getValueByPath(fromObject, new String[] {"handle"})); - } - - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"transparent"}))) { - throw new IllegalArgumentException("transparent parameter is not supported in Gemini API."); + new String[] {"toolResponse"}, + Common.getValueByPath(fromObject, new String[] {"toolResponse"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode audioTranscriptionConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode automaticActivityDetectionToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode liveClientMessageToVertex(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"disabled"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"setup"}) != null) { Common.setValueByPath( toObject, - new String[] {"disabled"}, - Common.getValueByPath(fromObject, new String[] {"disabled"})); + new String[] {"setup"}, + liveClientSetupToVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"setup"})), + toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"startOfSpeechSensitivity"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"clientContent"}) != null) { Common.setValueByPath( toObject, - new String[] {"startOfSpeechSensitivity"}, - Common.getValueByPath(fromObject, new String[] {"startOfSpeechSensitivity"})); + new String[] {"clientContent"}, + Common.getValueByPath(fromObject, new String[] {"clientContent"})); } - if (Common.getValueByPath(fromObject, new String[] {"endOfSpeechSensitivity"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"realtimeInput"}) != null) { Common.setValueByPath( toObject, - new String[] {"endOfSpeechSensitivity"}, - Common.getValueByPath(fromObject, new String[] {"endOfSpeechSensitivity"})); + new String[] {"realtimeInput"}, + liveClientRealtimeInputToVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"realtimeInput"})), + toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"prefixPaddingMs"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"realtimeInputParameters"}) != null) { Common.setValueByPath( toObject, - new String[] {"prefixPaddingMs"}, - Common.getValueByPath(fromObject, new String[] {"prefixPaddingMs"})); + new String[] {"realtime_input"}, + liveSendRealtimeInputParametersToVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"realtimeInputParameters"})), + toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"silenceDurationMs"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"toolResponse"}) != null) { Common.setValueByPath( toObject, - new String[] {"silenceDurationMs"}, - Common.getValueByPath(fromObject, new String[] {"silenceDurationMs"})); + new String[] {"toolResponse"}, + Common.getValueByPath(fromObject, new String[] {"toolResponse"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode realtimeInputConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode liveClientRealtimeInputToMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"automaticActivityDetection"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"mediaChunks"}) != null) { + ArrayNode keyArray = + (ArrayNode) Common.getValueByPath(fromObject, new String[] {"mediaChunks"}); + ObjectMapper objectMapper = new ObjectMapper(); + ArrayNode result = objectMapper.createArrayNode(); + + for (JsonNode item : keyArray) { + result.add(blobToMldev(JsonSerializable.toJsonNode(item), toObject)); + } + Common.setValueByPath(toObject, new String[] {"mediaChunks"}, result); + } + + if (Common.getValueByPath(fromObject, new String[] {"audio"}) != null) { Common.setValueByPath( toObject, - new String[] {"automaticActivityDetection"}, - automaticActivityDetectionToMldev( + new String[] {"audio"}, + blobToMldev( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"automaticActivityDetection"})), + Common.getValueByPath(fromObject, new String[] {"audio"})), toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"activityHandling"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"audioStreamEnd"}) != null) { Common.setValueByPath( toObject, - new String[] {"activityHandling"}, - Common.getValueByPath(fromObject, new String[] {"activityHandling"})); + new String[] {"audioStreamEnd"}, + Common.getValueByPath(fromObject, new String[] {"audioStreamEnd"})); } - if (Common.getValueByPath(fromObject, new String[] {"turnCoverage"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"video"}) != null) { Common.setValueByPath( toObject, - new String[] {"turnCoverage"}, - Common.getValueByPath(fromObject, new String[] {"turnCoverage"})); + new String[] {"video"}, + blobToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"video"})), + toObject)); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode slidingWindowToMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"targetTokens"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"text"}) != null) { Common.setValueByPath( toObject, - new String[] {"targetTokens"}, - Common.getValueByPath(fromObject, new String[] {"targetTokens"})); + new String[] {"text"}, + Common.getValueByPath(fromObject, new String[] {"text"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode contextWindowCompressionConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"triggerTokens"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"activityStart"}) != null) { Common.setValueByPath( toObject, - new String[] {"triggerTokens"}, - Common.getValueByPath(fromObject, new String[] {"triggerTokens"})); + new String[] {"activityStart"}, + Common.getValueByPath(fromObject, new String[] {"activityStart"})); } - if (Common.getValueByPath(fromObject, new String[] {"slidingWindow"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"activityEnd"}) != null) { Common.setValueByPath( toObject, - new String[] {"slidingWindow"}, - slidingWindowToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"slidingWindow"})), - toObject)); + new String[] {"activityEnd"}, + Common.getValueByPath(fromObject, new String[] {"activityEnd"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode proactivityConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode liveClientRealtimeInputToVertex(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"proactiveAudio"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"mediaChunks"}) != null) { Common.setValueByPath( toObject, - new String[] {"proactiveAudio"}, - Common.getValueByPath(fromObject, new String[] {"proactiveAudio"})); + new String[] {"mediaChunks"}, + Common.getValueByPath(fromObject, new String[] {"mediaChunks"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode liveConnectConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - if (Common.getValueByPath(fromObject, new String[] {"responseModalities"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"audio"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"setup", "generationConfig", "responseModalities"}, - Common.getValueByPath(fromObject, new String[] {"responseModalities"})); + toObject, + new String[] {"audio"}, + Common.getValueByPath(fromObject, new String[] {"audio"})); } - if (Common.getValueByPath(fromObject, new String[] {"temperature"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"setup", "generationConfig", "temperature"}, - Common.getValueByPath(fromObject, new String[] {"temperature"})); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"audioStreamEnd"}))) { + throw new IllegalArgumentException("audioStreamEnd parameter is not supported in Vertex AI."); } - if (Common.getValueByPath(fromObject, new String[] {"topP"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"video"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"setup", "generationConfig", "topP"}, - Common.getValueByPath(fromObject, new String[] {"topP"})); + toObject, + new String[] {"video"}, + Common.getValueByPath(fromObject, new String[] {"video"})); } - if (Common.getValueByPath(fromObject, new String[] {"topK"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"text"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"setup", "generationConfig", "topK"}, - Common.getValueByPath(fromObject, new String[] {"topK"})); + toObject, + new String[] {"text"}, + Common.getValueByPath(fromObject, new String[] {"text"})); } - if (Common.getValueByPath(fromObject, new String[] {"maxOutputTokens"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"activityStart"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"setup", "generationConfig", "maxOutputTokens"}, - Common.getValueByPath(fromObject, new String[] {"maxOutputTokens"})); + toObject, + new String[] {"activityStart"}, + Common.getValueByPath(fromObject, new String[] {"activityStart"})); } - if (Common.getValueByPath(fromObject, new String[] {"mediaResolution"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"activityEnd"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"setup", "generationConfig", "mediaResolution"}, - Common.getValueByPath(fromObject, new String[] {"mediaResolution"})); + toObject, + new String[] {"activityEnd"}, + Common.getValueByPath(fromObject, new String[] {"activityEnd"})); } - if (Common.getValueByPath(fromObject, new String[] {"seed"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"setup", "generationConfig", "seed"}, - Common.getValueByPath(fromObject, new String[] {"seed"})); - } + return toObject; + } - if (Common.getValueByPath(fromObject, new String[] {"speechConfig"}) != null) { + @ExcludeFromGeneratedCoverageReport + ObjectNode liveClientSetupToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"setup", "generationConfig", "speechConfig"}, - speechConfigToMldev( - JsonSerializable.toJsonNode( - Transformers.tLiveSpeechConfig( - Common.getValueByPath(fromObject, new String[] {"speechConfig"}))), - toObject)); + toObject, + new String[] {"model"}, + Common.getValueByPath(fromObject, new String[] {"model"})); } - if (Common.getValueByPath(fromObject, new String[] {"enableAffectiveDialog"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"generationConfig"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"setup", "generationConfig", "enableAffectiveDialog"}, - Common.getValueByPath(fromObject, new String[] {"enableAffectiveDialog"})); + toObject, + new String[] {"generationConfig"}, + Common.getValueByPath(fromObject, new String[] {"generationConfig"})); } if (Common.getValueByPath(fromObject, new String[] {"systemInstruction"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"setup", "systemInstruction"}, + toObject, + new String[] {"systemInstruction"}, contentToMldev( JsonSerializable.toJsonNode( Transformers.tContent( @@ -760,174 +642,59 @@ ObjectNode liveConnectConfigToMldev(JsonNode fromObject, ObjectNode parentObject for (JsonNode item : keyArray) { result.add(toolToMldev(JsonSerializable.toJsonNode(Transformers.tTool(item)), toObject)); } - Common.setValueByPath(parentObject, new String[] {"setup", "tools"}, result); + Common.setValueByPath(toObject, new String[] {"tools"}, result); + } + + if (Common.getValueByPath(fromObject, new String[] {"realtimeInputConfig"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"realtimeInputConfig"}, + Common.getValueByPath(fromObject, new String[] {"realtimeInputConfig"})); } if (Common.getValueByPath(fromObject, new String[] {"sessionResumption"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"setup", "sessionResumption"}, + toObject, + new String[] {"sessionResumption"}, sessionResumptionConfigToMldev( JsonSerializable.toJsonNode( Common.getValueByPath(fromObject, new String[] {"sessionResumption"})), toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"inputAudioTranscription"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"setup", "inputAudioTranscription"}, - audioTranscriptionConfigToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"inputAudioTranscription"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"outputAudioTranscription"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"setup", "outputAudioTranscription"}, - audioTranscriptionConfigToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"outputAudioTranscription"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"realtimeInputConfig"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"setup", "realtimeInputConfig"}, - realtimeInputConfigToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"realtimeInputConfig"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"contextWindowCompression"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"setup", "contextWindowCompression"}, - contextWindowCompressionConfigToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"contextWindowCompression"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"proactivity"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"setup", "proactivity"}, - proactivityConfigToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"proactivity"})), - toObject)); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode liveConnectParametersToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"setup", "model"}, - Transformers.tModel( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); - } - - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"config"}, - liveConnectConfigToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"config"})), - toObject)); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode activityStartToMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode activityEndToMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode liveSendRealtimeInputParametersToMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"media"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"mediaChunks"}, - Transformers.tBlobs(Common.getValueByPath(fromObject, new String[] {"media"}))); - } - - if (Common.getValueByPath(fromObject, new String[] {"audio"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"audio"}, - Transformers.tAudioBlob(Common.getValueByPath(fromObject, new String[] {"audio"}))); - } - - if (Common.getValueByPath(fromObject, new String[] {"audioStreamEnd"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"contextWindowCompression"}) != null) { Common.setValueByPath( toObject, - new String[] {"audioStreamEnd"}, - Common.getValueByPath(fromObject, new String[] {"audioStreamEnd"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"video"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"video"}, - Transformers.tImageBlob(Common.getValueByPath(fromObject, new String[] {"video"}))); + new String[] {"contextWindowCompression"}, + Common.getValueByPath(fromObject, new String[] {"contextWindowCompression"})); } - if (Common.getValueByPath(fromObject, new String[] {"text"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"inputAudioTranscription"}) != null) { Common.setValueByPath( toObject, - new String[] {"text"}, - Common.getValueByPath(fromObject, new String[] {"text"})); + new String[] {"inputAudioTranscription"}, + Common.getValueByPath(fromObject, new String[] {"inputAudioTranscription"})); } - if (Common.getValueByPath(fromObject, new String[] {"activityStart"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"outputAudioTranscription"}) != null) { Common.setValueByPath( toObject, - new String[] {"activityStart"}, - activityStartToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"activityStart"})), - toObject)); + new String[] {"outputAudioTranscription"}, + Common.getValueByPath(fromObject, new String[] {"outputAudioTranscription"})); } - if (Common.getValueByPath(fromObject, new String[] {"activityEnd"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"proactivity"}) != null) { Common.setValueByPath( toObject, - new String[] {"activityEnd"}, - activityEndToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"activityEnd"})), - toObject)); + new String[] {"proactivity"}, + Common.getValueByPath(fromObject, new String[] {"proactivity"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode liveClientSetupToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode liveClientSetupToVertex(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { Common.setValueByPath( @@ -940,18 +707,18 @@ ObjectNode liveClientSetupToMldev(JsonNode fromObject, ObjectNode parentObject) Common.setValueByPath( toObject, new String[] {"generationConfig"}, - Common.getValueByPath(fromObject, new String[] {"generationConfig"})); + generationConfigToVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"generationConfig"})), + toObject)); } if (Common.getValueByPath(fromObject, new String[] {"systemInstruction"}) != null) { Common.setValueByPath( toObject, new String[] {"systemInstruction"}, - contentToMldev( - JsonSerializable.toJsonNode( - Transformers.tContent( - Common.getValueByPath(fromObject, new String[] {"systemInstruction"}))), - toObject)); + Transformers.tContent( + Common.getValueByPath(fromObject, new String[] {"systemInstruction"}))); } if (Common.getValueByPath(fromObject, new String[] {"tools"}) != null) { @@ -962,7 +729,7 @@ ObjectNode liveClientSetupToMldev(JsonNode fromObject, ObjectNode parentObject) ArrayNode result = objectMapper.createArrayNode(); for (JsonNode item : keyArray) { - result.add(toolToMldev(JsonSerializable.toJsonNode(Transformers.tTool(item)), toObject)); + result.add(toolToVertex(JsonSerializable.toJsonNode(Transformers.tTool(item)), toObject)); } Common.setValueByPath(toObject, new String[] {"tools"}, result); } @@ -971,2255 +738,578 @@ ObjectNode liveClientSetupToMldev(JsonNode fromObject, ObjectNode parentObject) Common.setValueByPath( toObject, new String[] {"realtimeInputConfig"}, - realtimeInputConfigToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"realtimeInputConfig"})), - toObject)); + Common.getValueByPath(fromObject, new String[] {"realtimeInputConfig"})); } if (Common.getValueByPath(fromObject, new String[] {"sessionResumption"}) != null) { Common.setValueByPath( toObject, new String[] {"sessionResumption"}, - sessionResumptionConfigToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"sessionResumption"})), - toObject)); + Common.getValueByPath(fromObject, new String[] {"sessionResumption"})); } if (Common.getValueByPath(fromObject, new String[] {"contextWindowCompression"}) != null) { Common.setValueByPath( toObject, new String[] {"contextWindowCompression"}, - contextWindowCompressionConfigToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"contextWindowCompression"})), - toObject)); + Common.getValueByPath(fromObject, new String[] {"contextWindowCompression"})); } if (Common.getValueByPath(fromObject, new String[] {"inputAudioTranscription"}) != null) { Common.setValueByPath( toObject, new String[] {"inputAudioTranscription"}, - audioTranscriptionConfigToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"inputAudioTranscription"})), - toObject)); + Common.getValueByPath(fromObject, new String[] {"inputAudioTranscription"})); } if (Common.getValueByPath(fromObject, new String[] {"outputAudioTranscription"}) != null) { Common.setValueByPath( toObject, new String[] {"outputAudioTranscription"}, - audioTranscriptionConfigToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"outputAudioTranscription"})), - toObject)); + Common.getValueByPath(fromObject, new String[] {"outputAudioTranscription"})); } if (Common.getValueByPath(fromObject, new String[] {"proactivity"}) != null) { Common.setValueByPath( toObject, new String[] {"proactivity"}, - proactivityConfigToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"proactivity"})), - toObject)); + Common.getValueByPath(fromObject, new String[] {"proactivity"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode liveClientContentToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode liveConnectConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"turns"}) != null) { - ArrayNode keyArray = (ArrayNode) Common.getValueByPath(fromObject, new String[] {"turns"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add(contentToMldev(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"turns"}, result); - } - if (Common.getValueByPath(fromObject, new String[] {"turnComplete"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"responseModalities"}) != null) { Common.setValueByPath( - toObject, - new String[] {"turnComplete"}, - Common.getValueByPath(fromObject, new String[] {"turnComplete"})); + parentObject, + new String[] {"setup", "generationConfig", "responseModalities"}, + Common.getValueByPath(fromObject, new String[] {"responseModalities"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode liveClientRealtimeInputToMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"mediaChunks"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"temperature"}) != null) { Common.setValueByPath( - toObject, - new String[] {"mediaChunks"}, - Common.getValueByPath(fromObject, new String[] {"mediaChunks"})); + parentObject, + new String[] {"setup", "generationConfig", "temperature"}, + Common.getValueByPath(fromObject, new String[] {"temperature"})); } - if (Common.getValueByPath(fromObject, new String[] {"audio"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"topP"}) != null) { Common.setValueByPath( - toObject, - new String[] {"audio"}, - Common.getValueByPath(fromObject, new String[] {"audio"})); + parentObject, + new String[] {"setup", "generationConfig", "topP"}, + Common.getValueByPath(fromObject, new String[] {"topP"})); } - if (Common.getValueByPath(fromObject, new String[] {"audioStreamEnd"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"topK"}) != null) { Common.setValueByPath( - toObject, - new String[] {"audioStreamEnd"}, - Common.getValueByPath(fromObject, new String[] {"audioStreamEnd"})); + parentObject, + new String[] {"setup", "generationConfig", "topK"}, + Common.getValueByPath(fromObject, new String[] {"topK"})); } - if (Common.getValueByPath(fromObject, new String[] {"video"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"maxOutputTokens"}) != null) { Common.setValueByPath( - toObject, - new String[] {"video"}, - Common.getValueByPath(fromObject, new String[] {"video"})); + parentObject, + new String[] {"setup", "generationConfig", "maxOutputTokens"}, + Common.getValueByPath(fromObject, new String[] {"maxOutputTokens"})); } - if (Common.getValueByPath(fromObject, new String[] {"text"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"mediaResolution"}) != null) { Common.setValueByPath( - toObject, - new String[] {"text"}, - Common.getValueByPath(fromObject, new String[] {"text"})); + parentObject, + new String[] {"setup", "generationConfig", "mediaResolution"}, + Common.getValueByPath(fromObject, new String[] {"mediaResolution"})); } - if (Common.getValueByPath(fromObject, new String[] {"activityStart"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"seed"}) != null) { Common.setValueByPath( - toObject, - new String[] {"activityStart"}, - activityStartToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"activityStart"})), - toObject)); + parentObject, + new String[] {"setup", "generationConfig", "seed"}, + Common.getValueByPath(fromObject, new String[] {"seed"})); } - if (Common.getValueByPath(fromObject, new String[] {"activityEnd"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"speechConfig"}) != null) { Common.setValueByPath( - toObject, - new String[] {"activityEnd"}, - activityEndToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"activityEnd"})), - toObject)); + parentObject, + new String[] {"setup", "generationConfig", "speechConfig"}, + Transformers.tLiveSpeechConfig( + Common.getValueByPath(fromObject, new String[] {"speechConfig"}))); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode functionResponseToMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"willContinue"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"thinkingConfig"}) != null) { Common.setValueByPath( - toObject, - new String[] {"willContinue"}, - Common.getValueByPath(fromObject, new String[] {"willContinue"})); + parentObject, + new String[] {"setup", "generationConfig", "thinkingConfig"}, + Common.getValueByPath(fromObject, new String[] {"thinkingConfig"})); } - if (Common.getValueByPath(fromObject, new String[] {"scheduling"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"enableAffectiveDialog"}) != null) { Common.setValueByPath( - toObject, - new String[] {"scheduling"}, - Common.getValueByPath(fromObject, new String[] {"scheduling"})); + parentObject, + new String[] {"setup", "generationConfig", "enableAffectiveDialog"}, + Common.getValueByPath(fromObject, new String[] {"enableAffectiveDialog"})); } - if (Common.getValueByPath(fromObject, new String[] {"id"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"systemInstruction"}) != null) { Common.setValueByPath( - toObject, new String[] {"id"}, Common.getValueByPath(fromObject, new String[] {"id"})); + parentObject, + new String[] {"setup", "systemInstruction"}, + contentToMldev( + JsonSerializable.toJsonNode( + Transformers.tContent( + Common.getValueByPath(fromObject, new String[] {"systemInstruction"}))), + toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"name"}, - Common.getValueByPath(fromObject, new String[] {"name"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"response"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"response"}, - Common.getValueByPath(fromObject, new String[] {"response"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode liveClientToolResponseToMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"functionResponses"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"tools"}) != null) { ArrayNode keyArray = - (ArrayNode) Common.getValueByPath(fromObject, new String[] {"functionResponses"}); + (ArrayNode) + Transformers.tTools(Common.getValueByPath(fromObject, new String[] {"tools"})); ObjectMapper objectMapper = new ObjectMapper(); ArrayNode result = objectMapper.createArrayNode(); for (JsonNode item : keyArray) { - result.add(functionResponseToMldev(JsonSerializable.toJsonNode(item), toObject)); + result.add(toolToMldev(JsonSerializable.toJsonNode(Transformers.tTool(item)), toObject)); } - Common.setValueByPath(toObject, new String[] {"functionResponses"}, result); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode liveClientMessageToMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"setup"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"setup"}, - liveClientSetupToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"setup"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"clientContent"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"clientContent"}, - liveClientContentToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"clientContent"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"realtimeInput"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"realtimeInput"}, - liveClientRealtimeInputToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"realtimeInput"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"realtimeInputParameters"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"realtime_input"}, - liveSendRealtimeInputParametersToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"realtimeInputParameters"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"toolResponse"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"toolResponse"}, - liveClientToolResponseToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"toolResponse"})), - toObject)); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode prebuiltVoiceConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"voiceName"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"voiceName"}, - Common.getValueByPath(fromObject, new String[] {"voiceName"})); + Common.setValueByPath(parentObject, new String[] {"setup", "tools"}, result); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode voiceConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"prebuiltVoiceConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"sessionResumption"}) != null) { Common.setValueByPath( - toObject, - new String[] {"prebuiltVoiceConfig"}, - prebuiltVoiceConfigToVertex( + parentObject, + new String[] {"setup", "sessionResumption"}, + sessionResumptionConfigToMldev( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"prebuiltVoiceConfig"})), + Common.getValueByPath(fromObject, new String[] {"sessionResumption"})), toObject)); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode speechConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"voiceConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"inputAudioTranscription"}) != null) { Common.setValueByPath( - toObject, - new String[] {"voiceConfig"}, - voiceConfigToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"voiceConfig"})), - toObject)); - } - - if (!Common.isZero( - Common.getValueByPath(fromObject, new String[] {"multiSpeakerVoiceConfig"}))) { - throw new IllegalArgumentException( - "multiSpeakerVoiceConfig parameter is not supported in Vertex AI."); + parentObject, + new String[] {"setup", "inputAudioTranscription"}, + Common.getValueByPath(fromObject, new String[] {"inputAudioTranscription"})); } - if (Common.getValueByPath(fromObject, new String[] {"languageCode"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"outputAudioTranscription"}) != null) { Common.setValueByPath( - toObject, - new String[] {"languageCode"}, - Common.getValueByPath(fromObject, new String[] {"languageCode"})); + parentObject, + new String[] {"setup", "outputAudioTranscription"}, + Common.getValueByPath(fromObject, new String[] {"outputAudioTranscription"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode videoMetadataToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"fps"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"realtimeInputConfig"}) != null) { Common.setValueByPath( - toObject, new String[] {"fps"}, Common.getValueByPath(fromObject, new String[] {"fps"})); + parentObject, + new String[] {"setup", "realtimeInputConfig"}, + Common.getValueByPath(fromObject, new String[] {"realtimeInputConfig"})); } - if (Common.getValueByPath(fromObject, new String[] {"endOffset"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"contextWindowCompression"}) != null) { Common.setValueByPath( - toObject, - new String[] {"endOffset"}, - Common.getValueByPath(fromObject, new String[] {"endOffset"})); + parentObject, + new String[] {"setup", "contextWindowCompression"}, + Common.getValueByPath(fromObject, new String[] {"contextWindowCompression"})); } - if (Common.getValueByPath(fromObject, new String[] {"startOffset"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"proactivity"}) != null) { Common.setValueByPath( - toObject, - new String[] {"startOffset"}, - Common.getValueByPath(fromObject, new String[] {"startOffset"})); + parentObject, + new String[] {"setup", "proactivity"}, + Common.getValueByPath(fromObject, new String[] {"proactivity"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode blobToVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode liveConnectConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"displayName"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"displayName"}, - Common.getValueByPath(fromObject, new String[] {"displayName"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"data"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"data"}, - Common.getValueByPath(fromObject, new String[] {"data"})); - } - if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"responseModalities"}) != null) { Common.setValueByPath( - toObject, - new String[] {"mimeType"}, - Common.getValueByPath(fromObject, new String[] {"mimeType"})); + parentObject, + new String[] {"setup", "generationConfig", "responseModalities"}, + Common.getValueByPath(fromObject, new String[] {"responseModalities"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode fileDataToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"displayName"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"temperature"}) != null) { Common.setValueByPath( - toObject, - new String[] {"displayName"}, - Common.getValueByPath(fromObject, new String[] {"displayName"})); + parentObject, + new String[] {"setup", "generationConfig", "temperature"}, + Common.getValueByPath(fromObject, new String[] {"temperature"})); } - if (Common.getValueByPath(fromObject, new String[] {"fileUri"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"topP"}) != null) { Common.setValueByPath( - toObject, - new String[] {"fileUri"}, - Common.getValueByPath(fromObject, new String[] {"fileUri"})); + parentObject, + new String[] {"setup", "generationConfig", "topP"}, + Common.getValueByPath(fromObject, new String[] {"topP"})); } - if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"topK"}) != null) { Common.setValueByPath( - toObject, - new String[] {"mimeType"}, - Common.getValueByPath(fromObject, new String[] {"mimeType"})); + parentObject, + new String[] {"setup", "generationConfig", "topK"}, + Common.getValueByPath(fromObject, new String[] {"topK"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode partToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"videoMetadata"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"maxOutputTokens"}) != null) { Common.setValueByPath( - toObject, - new String[] {"videoMetadata"}, - videoMetadataToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"videoMetadata"})), - toObject)); + parentObject, + new String[] {"setup", "generationConfig", "maxOutputTokens"}, + Common.getValueByPath(fromObject, new String[] {"maxOutputTokens"})); } - if (Common.getValueByPath(fromObject, new String[] {"thought"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"mediaResolution"}) != null) { Common.setValueByPath( - toObject, - new String[] {"thought"}, - Common.getValueByPath(fromObject, new String[] {"thought"})); + parentObject, + new String[] {"setup", "generationConfig", "mediaResolution"}, + Common.getValueByPath(fromObject, new String[] {"mediaResolution"})); } - if (Common.getValueByPath(fromObject, new String[] {"inlineData"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"seed"}) != null) { Common.setValueByPath( - toObject, - new String[] {"inlineData"}, - blobToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"inlineData"})), - toObject)); + parentObject, + new String[] {"setup", "generationConfig", "seed"}, + Common.getValueByPath(fromObject, new String[] {"seed"})); } - if (Common.getValueByPath(fromObject, new String[] {"fileData"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"speechConfig"}) != null) { Common.setValueByPath( - toObject, - new String[] {"fileData"}, - fileDataToVertex( + parentObject, + new String[] {"setup", "generationConfig", "speechConfig"}, + speechConfigToVertex( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"fileData"})), + Transformers.tLiveSpeechConfig( + Common.getValueByPath(fromObject, new String[] {"speechConfig"}))), toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"thoughtSignature"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"thoughtSignature"}, - Common.getValueByPath(fromObject, new String[] {"thoughtSignature"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"codeExecutionResult"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"thinkingConfig"}) != null) { Common.setValueByPath( - toObject, - new String[] {"codeExecutionResult"}, - Common.getValueByPath(fromObject, new String[] {"codeExecutionResult"})); + parentObject, + new String[] {"setup", "generationConfig", "thinkingConfig"}, + Common.getValueByPath(fromObject, new String[] {"thinkingConfig"})); } - if (Common.getValueByPath(fromObject, new String[] {"executableCode"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"enableAffectiveDialog"}) != null) { Common.setValueByPath( - toObject, - new String[] {"executableCode"}, - Common.getValueByPath(fromObject, new String[] {"executableCode"})); + parentObject, + new String[] {"setup", "generationConfig", "enableAffectiveDialog"}, + Common.getValueByPath(fromObject, new String[] {"enableAffectiveDialog"})); } - if (Common.getValueByPath(fromObject, new String[] {"functionCall"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"systemInstruction"}) != null) { Common.setValueByPath( - toObject, - new String[] {"functionCall"}, - Common.getValueByPath(fromObject, new String[] {"functionCall"})); + parentObject, + new String[] {"setup", "systemInstruction"}, + Transformers.tContent( + Common.getValueByPath(fromObject, new String[] {"systemInstruction"}))); } - if (Common.getValueByPath(fromObject, new String[] {"functionResponse"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"functionResponse"}, - Common.getValueByPath(fromObject, new String[] {"functionResponse"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"text"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"text"}, - Common.getValueByPath(fromObject, new String[] {"text"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode contentToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"parts"}) != null) { - ArrayNode keyArray = (ArrayNode) Common.getValueByPath(fromObject, new String[] {"parts"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add(partToVertex(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"parts"}, result); - } - - if (Common.getValueByPath(fromObject, new String[] {"role"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"role"}, - Common.getValueByPath(fromObject, new String[] {"role"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode functionDeclarationToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"behavior"}))) { - throw new IllegalArgumentException("behavior parameter is not supported in Vertex AI."); - } - - if (Common.getValueByPath(fromObject, new String[] {"description"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"description"}, - Common.getValueByPath(fromObject, new String[] {"description"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"name"}, - Common.getValueByPath(fromObject, new String[] {"name"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"parameters"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"parameters"}, - Common.getValueByPath(fromObject, new String[] {"parameters"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"parametersJsonSchema"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"parametersJsonSchema"}, - Common.getValueByPath(fromObject, new String[] {"parametersJsonSchema"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"response"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"response"}, - Common.getValueByPath(fromObject, new String[] {"response"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"responseJsonSchema"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"responseJsonSchema"}, - Common.getValueByPath(fromObject, new String[] {"responseJsonSchema"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode intervalToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"startTime"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"startTime"}, - Common.getValueByPath(fromObject, new String[] {"startTime"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"endTime"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"endTime"}, - Common.getValueByPath(fromObject, new String[] {"endTime"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode googleSearchToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"timeRangeFilter"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"timeRangeFilter"}, - intervalToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"timeRangeFilter"})), - toObject)); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode dynamicRetrievalConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"mode"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"mode"}, - Common.getValueByPath(fromObject, new String[] {"mode"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"dynamicThreshold"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"dynamicThreshold"}, - Common.getValueByPath(fromObject, new String[] {"dynamicThreshold"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode googleSearchRetrievalToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"dynamicRetrievalConfig"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"dynamicRetrievalConfig"}, - dynamicRetrievalConfigToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"dynamicRetrievalConfig"})), - toObject)); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode enterpriseWebSearchToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode apiKeyConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"apiKeyString"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"apiKeyString"}, - Common.getValueByPath(fromObject, new String[] {"apiKeyString"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode authConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"apiKeyConfig"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"apiKeyConfig"}, - apiKeyConfigToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"apiKeyConfig"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"authType"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"authType"}, - Common.getValueByPath(fromObject, new String[] {"authType"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"googleServiceAccountConfig"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"googleServiceAccountConfig"}, - Common.getValueByPath(fromObject, new String[] {"googleServiceAccountConfig"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"httpBasicAuthConfig"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"httpBasicAuthConfig"}, - Common.getValueByPath(fromObject, new String[] {"httpBasicAuthConfig"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"oauthConfig"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"oauthConfig"}, - Common.getValueByPath(fromObject, new String[] {"oauthConfig"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"oidcConfig"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"oidcConfig"}, - Common.getValueByPath(fromObject, new String[] {"oidcConfig"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode googleMapsToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"authConfig"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"authConfig"}, - authConfigToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"authConfig"})), - toObject)); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode urlContextToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode toolToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"functionDeclarations"}) != null) { - ArrayNode keyArray = - (ArrayNode) Common.getValueByPath(fromObject, new String[] {"functionDeclarations"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add(functionDeclarationToVertex(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"functionDeclarations"}, result); - } - - if (Common.getValueByPath(fromObject, new String[] {"retrieval"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"retrieval"}, - Common.getValueByPath(fromObject, new String[] {"retrieval"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"googleSearch"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"googleSearch"}, - googleSearchToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"googleSearch"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"googleSearchRetrieval"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"googleSearchRetrieval"}, - googleSearchRetrievalToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"googleSearchRetrieval"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"enterpriseWebSearch"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"enterpriseWebSearch"}, - enterpriseWebSearchToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"enterpriseWebSearch"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"googleMaps"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"googleMaps"}, - googleMapsToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"googleMaps"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"urlContext"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"urlContext"}, - urlContextToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"urlContext"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"codeExecution"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"codeExecution"}, - Common.getValueByPath(fromObject, new String[] {"codeExecution"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"computerUse"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"computerUse"}, - Common.getValueByPath(fromObject, new String[] {"computerUse"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode sessionResumptionConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"handle"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"handle"}, - Common.getValueByPath(fromObject, new String[] {"handle"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"transparent"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"transparent"}, - Common.getValueByPath(fromObject, new String[] {"transparent"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode audioTranscriptionConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode automaticActivityDetectionToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"disabled"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"disabled"}, - Common.getValueByPath(fromObject, new String[] {"disabled"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"startOfSpeechSensitivity"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"startOfSpeechSensitivity"}, - Common.getValueByPath(fromObject, new String[] {"startOfSpeechSensitivity"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"endOfSpeechSensitivity"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"endOfSpeechSensitivity"}, - Common.getValueByPath(fromObject, new String[] {"endOfSpeechSensitivity"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"prefixPaddingMs"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"prefixPaddingMs"}, - Common.getValueByPath(fromObject, new String[] {"prefixPaddingMs"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"silenceDurationMs"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"silenceDurationMs"}, - Common.getValueByPath(fromObject, new String[] {"silenceDurationMs"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode realtimeInputConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"automaticActivityDetection"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"automaticActivityDetection"}, - automaticActivityDetectionToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"automaticActivityDetection"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"activityHandling"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"activityHandling"}, - Common.getValueByPath(fromObject, new String[] {"activityHandling"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"turnCoverage"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"turnCoverage"}, - Common.getValueByPath(fromObject, new String[] {"turnCoverage"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode slidingWindowToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"targetTokens"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"targetTokens"}, - Common.getValueByPath(fromObject, new String[] {"targetTokens"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode contextWindowCompressionConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"triggerTokens"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"triggerTokens"}, - Common.getValueByPath(fromObject, new String[] {"triggerTokens"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"slidingWindow"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"slidingWindow"}, - slidingWindowToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"slidingWindow"})), - toObject)); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode proactivityConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"proactiveAudio"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"proactiveAudio"}, - Common.getValueByPath(fromObject, new String[] {"proactiveAudio"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode liveConnectConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - if (Common.getValueByPath(fromObject, new String[] {"responseModalities"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"setup", "generationConfig", "responseModalities"}, - Common.getValueByPath(fromObject, new String[] {"responseModalities"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"temperature"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"setup", "generationConfig", "temperature"}, - Common.getValueByPath(fromObject, new String[] {"temperature"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"topP"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"setup", "generationConfig", "topP"}, - Common.getValueByPath(fromObject, new String[] {"topP"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"topK"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"setup", "generationConfig", "topK"}, - Common.getValueByPath(fromObject, new String[] {"topK"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"maxOutputTokens"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"setup", "generationConfig", "maxOutputTokens"}, - Common.getValueByPath(fromObject, new String[] {"maxOutputTokens"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"mediaResolution"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"setup", "generationConfig", "mediaResolution"}, - Common.getValueByPath(fromObject, new String[] {"mediaResolution"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"seed"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"setup", "generationConfig", "seed"}, - Common.getValueByPath(fromObject, new String[] {"seed"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"speechConfig"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"setup", "generationConfig", "speechConfig"}, - speechConfigToVertex( - JsonSerializable.toJsonNode( - Transformers.tLiveSpeechConfig( - Common.getValueByPath(fromObject, new String[] {"speechConfig"}))), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"enableAffectiveDialog"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"setup", "generationConfig", "enableAffectiveDialog"}, - Common.getValueByPath(fromObject, new String[] {"enableAffectiveDialog"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"systemInstruction"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"setup", "systemInstruction"}, - contentToVertex( - JsonSerializable.toJsonNode( - Transformers.tContent( - Common.getValueByPath(fromObject, new String[] {"systemInstruction"}))), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"tools"}) != null) { - ArrayNode keyArray = - (ArrayNode) - Transformers.tTools(Common.getValueByPath(fromObject, new String[] {"tools"})); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add(toolToVertex(JsonSerializable.toJsonNode(Transformers.tTool(item)), toObject)); - } - Common.setValueByPath(parentObject, new String[] {"setup", "tools"}, result); - } - - if (Common.getValueByPath(fromObject, new String[] {"sessionResumption"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"setup", "sessionResumption"}, - sessionResumptionConfigToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"sessionResumption"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"inputAudioTranscription"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"setup", "inputAudioTranscription"}, - audioTranscriptionConfigToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"inputAudioTranscription"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"outputAudioTranscription"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"setup", "outputAudioTranscription"}, - audioTranscriptionConfigToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"outputAudioTranscription"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"realtimeInputConfig"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"setup", "realtimeInputConfig"}, - realtimeInputConfigToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"realtimeInputConfig"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"contextWindowCompression"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"setup", "contextWindowCompression"}, - contextWindowCompressionConfigToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"contextWindowCompression"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"proactivity"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"setup", "proactivity"}, - proactivityConfigToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"proactivity"})), - toObject)); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode liveConnectParametersToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"setup", "model"}, - Transformers.tModel( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); - } - - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"config"}, - liveConnectConfigToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"config"})), - toObject)); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode activityStartToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode activityEndToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode liveSendRealtimeInputParametersToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"media"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"mediaChunks"}, - Transformers.tBlobs(Common.getValueByPath(fromObject, new String[] {"media"}))); - } - - if (Common.getValueByPath(fromObject, new String[] {"audio"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"audio"}, - Transformers.tAudioBlob(Common.getValueByPath(fromObject, new String[] {"audio"}))); - } - - if (Common.getValueByPath(fromObject, new String[] {"audioStreamEnd"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"audioStreamEnd"}, - Common.getValueByPath(fromObject, new String[] {"audioStreamEnd"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"video"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"video"}, - Transformers.tImageBlob(Common.getValueByPath(fromObject, new String[] {"video"}))); - } - - if (Common.getValueByPath(fromObject, new String[] {"text"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"text"}, - Common.getValueByPath(fromObject, new String[] {"text"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"activityStart"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"activityStart"}, - activityStartToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"activityStart"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"activityEnd"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"activityEnd"}, - activityEndToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"activityEnd"})), - toObject)); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode liveClientSetupToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"model"}, - Common.getValueByPath(fromObject, new String[] {"model"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"generationConfig"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"generationConfig"}, - Common.getValueByPath(fromObject, new String[] {"generationConfig"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"systemInstruction"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"systemInstruction"}, - contentToVertex( - JsonSerializable.toJsonNode( - Transformers.tContent( - Common.getValueByPath(fromObject, new String[] {"systemInstruction"}))), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"tools"}) != null) { - ArrayNode keyArray = - (ArrayNode) - Transformers.tTools(Common.getValueByPath(fromObject, new String[] {"tools"})); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add(toolToVertex(JsonSerializable.toJsonNode(Transformers.tTool(item)), toObject)); - } - Common.setValueByPath(toObject, new String[] {"tools"}, result); - } - - if (Common.getValueByPath(fromObject, new String[] {"realtimeInputConfig"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"realtimeInputConfig"}, - realtimeInputConfigToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"realtimeInputConfig"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"sessionResumption"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"sessionResumption"}, - sessionResumptionConfigToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"sessionResumption"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"contextWindowCompression"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"contextWindowCompression"}, - contextWindowCompressionConfigToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"contextWindowCompression"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"inputAudioTranscription"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"inputAudioTranscription"}, - audioTranscriptionConfigToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"inputAudioTranscription"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"outputAudioTranscription"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"outputAudioTranscription"}, - audioTranscriptionConfigToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"outputAudioTranscription"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"proactivity"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"proactivity"}, - proactivityConfigToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"proactivity"})), - toObject)); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode liveClientContentToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"turns"}) != null) { - ArrayNode keyArray = (ArrayNode) Common.getValueByPath(fromObject, new String[] {"turns"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add(contentToVertex(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"turns"}, result); - } - - if (Common.getValueByPath(fromObject, new String[] {"turnComplete"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"turnComplete"}, - Common.getValueByPath(fromObject, new String[] {"turnComplete"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode liveClientRealtimeInputToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"mediaChunks"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"mediaChunks"}, - Common.getValueByPath(fromObject, new String[] {"mediaChunks"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"audio"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"audio"}, - Common.getValueByPath(fromObject, new String[] {"audio"})); - } - - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"audioStreamEnd"}))) { - throw new IllegalArgumentException("audioStreamEnd parameter is not supported in Vertex AI."); - } - - if (Common.getValueByPath(fromObject, new String[] {"video"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"video"}, - Common.getValueByPath(fromObject, new String[] {"video"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"text"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"text"}, - Common.getValueByPath(fromObject, new String[] {"text"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"activityStart"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"activityStart"}, - activityStartToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"activityStart"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"activityEnd"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"activityEnd"}, - activityEndToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"activityEnd"})), - toObject)); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode functionResponseToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"willContinue"}))) { - throw new IllegalArgumentException("willContinue parameter is not supported in Vertex AI."); - } - - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"scheduling"}))) { - throw new IllegalArgumentException("scheduling parameter is not supported in Vertex AI."); - } - - if (Common.getValueByPath(fromObject, new String[] {"id"}) != null) { - Common.setValueByPath( - toObject, new String[] {"id"}, Common.getValueByPath(fromObject, new String[] {"id"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"name"}, - Common.getValueByPath(fromObject, new String[] {"name"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"response"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"response"}, - Common.getValueByPath(fromObject, new String[] {"response"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode liveClientToolResponseToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"functionResponses"}) != null) { - ArrayNode keyArray = - (ArrayNode) Common.getValueByPath(fromObject, new String[] {"functionResponses"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add(functionResponseToVertex(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"functionResponses"}, result); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode liveClientMessageToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"setup"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"setup"}, - liveClientSetupToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"setup"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"clientContent"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"clientContent"}, - liveClientContentToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"clientContent"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"realtimeInput"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"realtimeInput"}, - liveClientRealtimeInputToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"realtimeInput"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"realtimeInputParameters"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"realtime_input"}, - liveSendRealtimeInputParametersToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"realtimeInputParameters"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"toolResponse"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"toolResponse"}, - liveClientToolResponseToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"toolResponse"})), - toObject)); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode liveServerSetupCompleteFromMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode videoMetadataFromMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"fps"}) != null) { - Common.setValueByPath( - toObject, new String[] {"fps"}, Common.getValueByPath(fromObject, new String[] {"fps"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"endOffset"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"endOffset"}, - Common.getValueByPath(fromObject, new String[] {"endOffset"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"startOffset"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"startOffset"}, - Common.getValueByPath(fromObject, new String[] {"startOffset"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode blobFromMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - if (Common.getValueByPath(fromObject, new String[] {"data"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"data"}, - Common.getValueByPath(fromObject, new String[] {"data"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"mimeType"}, - Common.getValueByPath(fromObject, new String[] {"mimeType"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode fileDataFromMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - if (Common.getValueByPath(fromObject, new String[] {"fileUri"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"fileUri"}, - Common.getValueByPath(fromObject, new String[] {"fileUri"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"mimeType"}, - Common.getValueByPath(fromObject, new String[] {"mimeType"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode partFromMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"videoMetadata"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"videoMetadata"}, - videoMetadataFromMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"videoMetadata"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"thought"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"thought"}, - Common.getValueByPath(fromObject, new String[] {"thought"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"inlineData"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"inlineData"}, - blobFromMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"inlineData"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"fileData"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"fileData"}, - fileDataFromMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"fileData"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"thoughtSignature"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"thoughtSignature"}, - Common.getValueByPath(fromObject, new String[] {"thoughtSignature"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"codeExecutionResult"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"codeExecutionResult"}, - Common.getValueByPath(fromObject, new String[] {"codeExecutionResult"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"executableCode"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"executableCode"}, - Common.getValueByPath(fromObject, new String[] {"executableCode"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"functionCall"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"functionCall"}, - Common.getValueByPath(fromObject, new String[] {"functionCall"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"functionResponse"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"functionResponse"}, - Common.getValueByPath(fromObject, new String[] {"functionResponse"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"text"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"text"}, - Common.getValueByPath(fromObject, new String[] {"text"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode contentFromMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"parts"}) != null) { - ArrayNode keyArray = (ArrayNode) Common.getValueByPath(fromObject, new String[] {"parts"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add(partFromMldev(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"parts"}, result); - } - - if (Common.getValueByPath(fromObject, new String[] {"role"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"role"}, - Common.getValueByPath(fromObject, new String[] {"role"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode transcriptionFromMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"text"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"text"}, - Common.getValueByPath(fromObject, new String[] {"text"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"finished"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"finished"}, - Common.getValueByPath(fromObject, new String[] {"finished"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode urlMetadataFromMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"retrievedUrl"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"retrievedUrl"}, - Common.getValueByPath(fromObject, new String[] {"retrievedUrl"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"urlRetrievalStatus"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"urlRetrievalStatus"}, - Common.getValueByPath(fromObject, new String[] {"urlRetrievalStatus"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode urlContextMetadataFromMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"urlMetadata"}) != null) { - ArrayNode keyArray = - (ArrayNode) Common.getValueByPath(fromObject, new String[] {"urlMetadata"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add(urlMetadataFromMldev(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"urlMetadata"}, result); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode liveServerContentFromMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"modelTurn"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"modelTurn"}, - contentFromMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"modelTurn"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"turnComplete"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"turnComplete"}, - Common.getValueByPath(fromObject, new String[] {"turnComplete"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"interrupted"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"interrupted"}, - Common.getValueByPath(fromObject, new String[] {"interrupted"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"groundingMetadata"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"groundingMetadata"}, - Common.getValueByPath(fromObject, new String[] {"groundingMetadata"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"generationComplete"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"generationComplete"}, - Common.getValueByPath(fromObject, new String[] {"generationComplete"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"inputTranscription"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"inputTranscription"}, - transcriptionFromMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"inputTranscription"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"outputTranscription"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"outputTranscription"}, - transcriptionFromMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"outputTranscription"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"urlContextMetadata"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"urlContextMetadata"}, - urlContextMetadataFromMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"urlContextMetadata"})), - toObject)); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode functionCallFromMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"id"}) != null) { - Common.setValueByPath( - toObject, new String[] {"id"}, Common.getValueByPath(fromObject, new String[] {"id"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"args"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"args"}, - Common.getValueByPath(fromObject, new String[] {"args"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"name"}, - Common.getValueByPath(fromObject, new String[] {"name"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode liveServerToolCallFromMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"functionCalls"}) != null) { - ArrayNode keyArray = - (ArrayNode) Common.getValueByPath(fromObject, new String[] {"functionCalls"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add(functionCallFromMldev(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"functionCalls"}, result); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode liveServerToolCallCancellationFromMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"ids"}) != null) { - Common.setValueByPath( - toObject, new String[] {"ids"}, Common.getValueByPath(fromObject, new String[] {"ids"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode modalityTokenCountFromMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"modality"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"modality"}, - Common.getValueByPath(fromObject, new String[] {"modality"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"tokenCount"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"tokenCount"}, - Common.getValueByPath(fromObject, new String[] {"tokenCount"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode usageMetadataFromMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"promptTokenCount"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"promptTokenCount"}, - Common.getValueByPath(fromObject, new String[] {"promptTokenCount"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"cachedContentTokenCount"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"cachedContentTokenCount"}, - Common.getValueByPath(fromObject, new String[] {"cachedContentTokenCount"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"responseTokenCount"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"responseTokenCount"}, - Common.getValueByPath(fromObject, new String[] {"responseTokenCount"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"toolUsePromptTokenCount"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"toolUsePromptTokenCount"}, - Common.getValueByPath(fromObject, new String[] {"toolUsePromptTokenCount"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"thoughtsTokenCount"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"thoughtsTokenCount"}, - Common.getValueByPath(fromObject, new String[] {"thoughtsTokenCount"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"totalTokenCount"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"totalTokenCount"}, - Common.getValueByPath(fromObject, new String[] {"totalTokenCount"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"promptTokensDetails"}) != null) { - ArrayNode keyArray = - (ArrayNode) Common.getValueByPath(fromObject, new String[] {"promptTokensDetails"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add(modalityTokenCountFromMldev(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"promptTokensDetails"}, result); - } - - if (Common.getValueByPath(fromObject, new String[] {"cacheTokensDetails"}) != null) { - ArrayNode keyArray = - (ArrayNode) Common.getValueByPath(fromObject, new String[] {"cacheTokensDetails"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add(modalityTokenCountFromMldev(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"cacheTokensDetails"}, result); - } - - if (Common.getValueByPath(fromObject, new String[] {"responseTokensDetails"}) != null) { - ArrayNode keyArray = - (ArrayNode) Common.getValueByPath(fromObject, new String[] {"responseTokensDetails"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add(modalityTokenCountFromMldev(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"responseTokensDetails"}, result); - } - - if (Common.getValueByPath(fromObject, new String[] {"toolUsePromptTokensDetails"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"tools"}) != null) { ArrayNode keyArray = (ArrayNode) - Common.getValueByPath(fromObject, new String[] {"toolUsePromptTokensDetails"}); + Transformers.tTools(Common.getValueByPath(fromObject, new String[] {"tools"})); ObjectMapper objectMapper = new ObjectMapper(); ArrayNode result = objectMapper.createArrayNode(); for (JsonNode item : keyArray) { - result.add(modalityTokenCountFromMldev(JsonSerializable.toJsonNode(item), toObject)); + result.add(toolToVertex(JsonSerializable.toJsonNode(Transformers.tTool(item)), toObject)); } - Common.setValueByPath(toObject, new String[] {"toolUsePromptTokensDetails"}, result); + Common.setValueByPath(parentObject, new String[] {"setup", "tools"}, result); } - return toObject; - } + if (Common.getValueByPath(fromObject, new String[] {"sessionResumption"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"setup", "sessionResumption"}, + Common.getValueByPath(fromObject, new String[] {"sessionResumption"})); + } - @ExcludeFromGeneratedCoverageReport - ObjectNode liveServerGoAwayFromMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"timeLeft"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"inputAudioTranscription"}) != null) { Common.setValueByPath( - toObject, - new String[] {"timeLeft"}, - Common.getValueByPath(fromObject, new String[] {"timeLeft"})); + parentObject, + new String[] {"setup", "inputAudioTranscription"}, + Common.getValueByPath(fromObject, new String[] {"inputAudioTranscription"})); } - return toObject; - } + if (Common.getValueByPath(fromObject, new String[] {"outputAudioTranscription"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"setup", "outputAudioTranscription"}, + Common.getValueByPath(fromObject, new String[] {"outputAudioTranscription"})); + } - @ExcludeFromGeneratedCoverageReport - ObjectNode liveServerSessionResumptionUpdateFromMldev( - JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"newHandle"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"realtimeInputConfig"}) != null) { Common.setValueByPath( - toObject, - new String[] {"newHandle"}, - Common.getValueByPath(fromObject, new String[] {"newHandle"})); + parentObject, + new String[] {"setup", "realtimeInputConfig"}, + Common.getValueByPath(fromObject, new String[] {"realtimeInputConfig"})); } - if (Common.getValueByPath(fromObject, new String[] {"resumable"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"contextWindowCompression"}) != null) { Common.setValueByPath( - toObject, - new String[] {"resumable"}, - Common.getValueByPath(fromObject, new String[] {"resumable"})); + parentObject, + new String[] {"setup", "contextWindowCompression"}, + Common.getValueByPath(fromObject, new String[] {"contextWindowCompression"})); } - if (Common.getValueByPath(fromObject, new String[] {"lastConsumedClientMessageIndex"}) - != null) { + if (Common.getValueByPath(fromObject, new String[] {"proactivity"}) != null) { Common.setValueByPath( - toObject, - new String[] {"lastConsumedClientMessageIndex"}, - Common.getValueByPath(fromObject, new String[] {"lastConsumedClientMessageIndex"})); + parentObject, + new String[] {"setup", "proactivity"}, + Common.getValueByPath(fromObject, new String[] {"proactivity"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode liveServerMessageFromMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode liveConnectParametersToMldev( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"setupComplete"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { Common.setValueByPath( toObject, - new String[] {"setupComplete"}, - liveServerSetupCompleteFromMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"setupComplete"})), - toObject)); + new String[] {"setup", "model"}, + Transformers.tModel( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); } - if (Common.getValueByPath(fromObject, new String[] {"serverContent"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { Common.setValueByPath( toObject, - new String[] {"serverContent"}, - liveServerContentFromMldev( + new String[] {"config"}, + liveConnectConfigToMldev( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"serverContent"})), + Common.getValueByPath(fromObject, new String[] {"config"})), toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"toolCall"}) != null) { + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode liveConnectParametersToVertex( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { Common.setValueByPath( toObject, - new String[] {"toolCall"}, - liveServerToolCallFromMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"toolCall"})), - toObject)); + new String[] {"setup", "model"}, + Transformers.tModel( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); } - if (Common.getValueByPath(fromObject, new String[] {"toolCallCancellation"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { Common.setValueByPath( toObject, - new String[] {"toolCallCancellation"}, - liveServerToolCallCancellationFromMldev( + new String[] {"config"}, + liveConnectConfigToVertex( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"toolCallCancellation"})), + Common.getValueByPath(fromObject, new String[] {"config"})), toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"usageMetadata"}) != null) { + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode liveSendRealtimeInputParametersToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"media"}) != null) { + ArrayNode keyArray = + (ArrayNode) + Transformers.tBlobs(Common.getValueByPath(fromObject, new String[] {"media"})); + ObjectMapper objectMapper = new ObjectMapper(); + ArrayNode result = objectMapper.createArrayNode(); + + for (JsonNode item : keyArray) { + result.add(blobToMldev(JsonSerializable.toJsonNode(item), toObject)); + } + Common.setValueByPath(toObject, new String[] {"mediaChunks"}, result); + } + + if (Common.getValueByPath(fromObject, new String[] {"audio"}) != null) { Common.setValueByPath( toObject, - new String[] {"usageMetadata"}, - usageMetadataFromMldev( + new String[] {"audio"}, + blobToMldev( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"usageMetadata"})), + Transformers.tAudioBlob( + Common.getValueByPath(fromObject, new String[] {"audio"}))), toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"goAway"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"audioStreamEnd"}) != null) { Common.setValueByPath( toObject, - new String[] {"goAway"}, - liveServerGoAwayFromMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"goAway"})), - toObject)); + new String[] {"audioStreamEnd"}, + Common.getValueByPath(fromObject, new String[] {"audioStreamEnd"})); } - if (Common.getValueByPath(fromObject, new String[] {"sessionResumptionUpdate"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"video"}) != null) { Common.setValueByPath( toObject, - new String[] {"sessionResumptionUpdate"}, - liveServerSessionResumptionUpdateFromMldev( + new String[] {"video"}, + blobToMldev( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"sessionResumptionUpdate"})), + Transformers.tImageBlob( + Common.getValueByPath(fromObject, new String[] {"video"}))), toObject)); } - return toObject; - } + if (Common.getValueByPath(fromObject, new String[] {"text"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"text"}, + Common.getValueByPath(fromObject, new String[] {"text"})); + } - @ExcludeFromGeneratedCoverageReport - ObjectNode liveServerSetupCompleteFromVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"sessionId"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"activityStart"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"activityStart"}, + Common.getValueByPath(fromObject, new String[] {"activityStart"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"activityEnd"}) != null) { Common.setValueByPath( toObject, - new String[] {"sessionId"}, - Common.getValueByPath(fromObject, new String[] {"sessionId"})); + new String[] {"activityEnd"}, + Common.getValueByPath(fromObject, new String[] {"activityEnd"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode videoMetadataFromVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode liveSendRealtimeInputParametersToVertex(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"fps"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"media"}) != null) { Common.setValueByPath( - toObject, new String[] {"fps"}, Common.getValueByPath(fromObject, new String[] {"fps"})); + toObject, + new String[] {"mediaChunks"}, + Transformers.tBlobs(Common.getValueByPath(fromObject, new String[] {"media"}))); } - if (Common.getValueByPath(fromObject, new String[] {"endOffset"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"audio"}) != null) { Common.setValueByPath( toObject, - new String[] {"endOffset"}, - Common.getValueByPath(fromObject, new String[] {"endOffset"})); + new String[] {"audio"}, + Transformers.tAudioBlob(Common.getValueByPath(fromObject, new String[] {"audio"}))); } - if (Common.getValueByPath(fromObject, new String[] {"startOffset"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"audioStreamEnd"}) != null) { Common.setValueByPath( toObject, - new String[] {"startOffset"}, - Common.getValueByPath(fromObject, new String[] {"startOffset"})); + new String[] {"audioStreamEnd"}, + Common.getValueByPath(fromObject, new String[] {"audioStreamEnd"})); } - return toObject; - } + if (Common.getValueByPath(fromObject, new String[] {"video"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"video"}, + Transformers.tImageBlob(Common.getValueByPath(fromObject, new String[] {"video"}))); + } - @ExcludeFromGeneratedCoverageReport - ObjectNode blobFromVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"displayName"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"text"}) != null) { Common.setValueByPath( toObject, - new String[] {"displayName"}, - Common.getValueByPath(fromObject, new String[] {"displayName"})); + new String[] {"text"}, + Common.getValueByPath(fromObject, new String[] {"text"})); } - if (Common.getValueByPath(fromObject, new String[] {"data"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"activityStart"}) != null) { Common.setValueByPath( toObject, - new String[] {"data"}, - Common.getValueByPath(fromObject, new String[] {"data"})); + new String[] {"activityStart"}, + Common.getValueByPath(fromObject, new String[] {"activityStart"})); } - if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"activityEnd"}) != null) { Common.setValueByPath( toObject, - new String[] {"mimeType"}, - Common.getValueByPath(fromObject, new String[] {"mimeType"})); + new String[] {"activityEnd"}, + Common.getValueByPath(fromObject, new String[] {"activityEnd"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode fileDataFromVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode liveServerMessageFromVertex(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"displayName"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"setupComplete"}) != null) { Common.setValueByPath( toObject, - new String[] {"displayName"}, - Common.getValueByPath(fromObject, new String[] {"displayName"})); + new String[] {"setupComplete"}, + Common.getValueByPath(fromObject, new String[] {"setupComplete"})); } - if (Common.getValueByPath(fromObject, new String[] {"fileUri"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"serverContent"}) != null) { Common.setValueByPath( toObject, - new String[] {"fileUri"}, - Common.getValueByPath(fromObject, new String[] {"fileUri"})); + new String[] {"serverContent"}, + Common.getValueByPath(fromObject, new String[] {"serverContent"})); } - if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"toolCall"}) != null) { Common.setValueByPath( toObject, - new String[] {"mimeType"}, - Common.getValueByPath(fromObject, new String[] {"mimeType"})); + new String[] {"toolCall"}, + Common.getValueByPath(fromObject, new String[] {"toolCall"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode partFromVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"videoMetadata"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"toolCallCancellation"}) != null) { Common.setValueByPath( toObject, - new String[] {"videoMetadata"}, - videoMetadataFromVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"videoMetadata"})), - toObject)); + new String[] {"toolCallCancellation"}, + Common.getValueByPath(fromObject, new String[] {"toolCallCancellation"})); } - if (Common.getValueByPath(fromObject, new String[] {"thought"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"usageMetadata"}) != null) { Common.setValueByPath( toObject, - new String[] {"thought"}, - Common.getValueByPath(fromObject, new String[] {"thought"})); + new String[] {"usageMetadata"}, + usageMetadataFromVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"usageMetadata"})), + toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"inlineData"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"goAway"}) != null) { Common.setValueByPath( toObject, - new String[] {"inlineData"}, - blobFromVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"inlineData"})), - toObject)); + new String[] {"goAway"}, + Common.getValueByPath(fromObject, new String[] {"goAway"})); } - if (Common.getValueByPath(fromObject, new String[] {"fileData"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"sessionResumptionUpdate"}) != null) { Common.setValueByPath( toObject, - new String[] {"fileData"}, - fileDataFromVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"fileData"})), - toObject)); + new String[] {"sessionResumptionUpdate"}, + Common.getValueByPath(fromObject, new String[] {"sessionResumptionUpdate"})); } - if (Common.getValueByPath(fromObject, new String[] {"thoughtSignature"}) != null) { + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode partToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"functionCall"}) != null) { Common.setValueByPath( toObject, - new String[] {"thoughtSignature"}, - Common.getValueByPath(fromObject, new String[] {"thoughtSignature"})); + new String[] {"functionCall"}, + Common.getValueByPath(fromObject, new String[] {"functionCall"})); } if (Common.getValueByPath(fromObject, new String[] {"codeExecutionResult"}) != null) { @@ -3236,11 +1326,14 @@ ObjectNode partFromVertex(JsonNode fromObject, ObjectNode parentObject) { Common.getValueByPath(fromObject, new String[] {"executableCode"})); } - if (Common.getValueByPath(fromObject, new String[] {"functionCall"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"fileData"}) != null) { Common.setValueByPath( toObject, - new String[] {"functionCall"}, - Common.getValueByPath(fromObject, new String[] {"functionCall"})); + new String[] {"fileData"}, + fileDataToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"fileData"})), + toObject)); } if (Common.getValueByPath(fromObject, new String[] {"functionResponse"}) != null) { @@ -3250,6 +1343,16 @@ ObjectNode partFromVertex(JsonNode fromObject, ObjectNode parentObject) { Common.getValueByPath(fromObject, new String[] {"functionResponse"})); } + if (Common.getValueByPath(fromObject, new String[] {"inlineData"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"inlineData"}, + blobToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"inlineData"})), + toObject)); + } + if (Common.getValueByPath(fromObject, new String[] {"text"}) != null) { Common.setValueByPath( toObject, @@ -3257,183 +1360,212 @@ ObjectNode partFromVertex(JsonNode fromObject, ObjectNode parentObject) { Common.getValueByPath(fromObject, new String[] {"text"})); } + if (Common.getValueByPath(fromObject, new String[] {"thought"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"thought"}, + Common.getValueByPath(fromObject, new String[] {"thought"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"thoughtSignature"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"thoughtSignature"}, + Common.getValueByPath(fromObject, new String[] {"thoughtSignature"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"videoMetadata"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"videoMetadata"}, + Common.getValueByPath(fromObject, new String[] {"videoMetadata"})); + } + return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode contentFromVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode sessionResumptionConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"parts"}) != null) { - ArrayNode keyArray = (ArrayNode) Common.getValueByPath(fromObject, new String[] {"parts"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add(partFromVertex(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"parts"}, result); - } - - if (Common.getValueByPath(fromObject, new String[] {"role"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"handle"}) != null) { Common.setValueByPath( toObject, - new String[] {"role"}, - Common.getValueByPath(fromObject, new String[] {"role"})); + new String[] {"handle"}, + Common.getValueByPath(fromObject, new String[] {"handle"})); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"transparent"}))) { + throw new IllegalArgumentException("transparent parameter is not supported in Gemini API."); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode transcriptionFromVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode speechConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"text"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"languageCode"}) != null) { Common.setValueByPath( toObject, - new String[] {"text"}, - Common.getValueByPath(fromObject, new String[] {"text"})); + new String[] {"languageCode"}, + Common.getValueByPath(fromObject, new String[] {"languageCode"})); } - if (Common.getValueByPath(fromObject, new String[] {"finished"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"voiceConfig"}) != null) { Common.setValueByPath( toObject, - new String[] {"finished"}, - Common.getValueByPath(fromObject, new String[] {"finished"})); + new String[] {"voiceConfig"}, + Common.getValueByPath(fromObject, new String[] {"voiceConfig"})); + } + + if (!Common.isZero( + Common.getValueByPath(fromObject, new String[] {"multiSpeakerVoiceConfig"}))) { + throw new IllegalArgumentException( + "multiSpeakerVoiceConfig parameter is not supported in Vertex AI."); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode liveServerContentFromVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toolToMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"modelTurn"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"functionDeclarations"}) != null) { Common.setValueByPath( toObject, - new String[] {"modelTurn"}, - contentFromVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"modelTurn"})), - toObject)); + new String[] {"functionDeclarations"}, + Common.getValueByPath(fromObject, new String[] {"functionDeclarations"})); } - if (Common.getValueByPath(fromObject, new String[] {"turnComplete"}) != null) { + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"retrieval"}))) { + throw new IllegalArgumentException("retrieval parameter is not supported in Gemini API."); + } + + if (Common.getValueByPath(fromObject, new String[] {"googleSearchRetrieval"}) != null) { Common.setValueByPath( toObject, - new String[] {"turnComplete"}, - Common.getValueByPath(fromObject, new String[] {"turnComplete"})); + new String[] {"googleSearchRetrieval"}, + Common.getValueByPath(fromObject, new String[] {"googleSearchRetrieval"})); } - if (Common.getValueByPath(fromObject, new String[] {"interrupted"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"googleMaps"}) != null) { Common.setValueByPath( toObject, - new String[] {"interrupted"}, - Common.getValueByPath(fromObject, new String[] {"interrupted"})); + new String[] {"googleMaps"}, + googleMapsToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"googleMaps"})), + toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"groundingMetadata"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"computerUse"}) != null) { Common.setValueByPath( toObject, - new String[] {"groundingMetadata"}, - Common.getValueByPath(fromObject, new String[] {"groundingMetadata"})); + new String[] {"computerUse"}, + Common.getValueByPath(fromObject, new String[] {"computerUse"})); } - if (Common.getValueByPath(fromObject, new String[] {"generationComplete"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"codeExecution"}) != null) { Common.setValueByPath( toObject, - new String[] {"generationComplete"}, - Common.getValueByPath(fromObject, new String[] {"generationComplete"})); + new String[] {"codeExecution"}, + Common.getValueByPath(fromObject, new String[] {"codeExecution"})); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"enterpriseWebSearch"}))) { + throw new IllegalArgumentException( + "enterpriseWebSearch parameter is not supported in Gemini API."); } - if (Common.getValueByPath(fromObject, new String[] {"inputTranscription"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"googleSearch"}) != null) { Common.setValueByPath( toObject, - new String[] {"inputTranscription"}, - transcriptionFromVertex( + new String[] {"googleSearch"}, + googleSearchToMldev( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"inputTranscription"})), + Common.getValueByPath(fromObject, new String[] {"googleSearch"})), toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"outputTranscription"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"urlContext"}) != null) { Common.setValueByPath( toObject, - new String[] {"outputTranscription"}, - transcriptionFromVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"outputTranscription"})), - toObject)); + new String[] {"urlContext"}, + Common.getValueByPath(fromObject, new String[] {"urlContext"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode functionCallFromVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toolToVertex(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"functionDeclarations"}) != null) { + ArrayNode keyArray = + (ArrayNode) Common.getValueByPath(fromObject, new String[] {"functionDeclarations"}); + ObjectMapper objectMapper = new ObjectMapper(); + ArrayNode result = objectMapper.createArrayNode(); + + for (JsonNode item : keyArray) { + result.add(functionDeclarationToVertex(JsonSerializable.toJsonNode(item), toObject)); + } + Common.setValueByPath(toObject, new String[] {"functionDeclarations"}, result); + } - if (Common.getValueByPath(fromObject, new String[] {"args"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"retrieval"}) != null) { Common.setValueByPath( toObject, - new String[] {"args"}, - Common.getValueByPath(fromObject, new String[] {"args"})); + new String[] {"retrieval"}, + Common.getValueByPath(fromObject, new String[] {"retrieval"})); } - if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"googleSearchRetrieval"}) != null) { Common.setValueByPath( toObject, - new String[] {"name"}, - Common.getValueByPath(fromObject, new String[] {"name"})); + new String[] {"googleSearchRetrieval"}, + Common.getValueByPath(fromObject, new String[] {"googleSearchRetrieval"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode liveServerToolCallFromVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"functionCalls"}) != null) { - ArrayNode keyArray = - (ArrayNode) Common.getValueByPath(fromObject, new String[] {"functionCalls"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add(functionCallFromVertex(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"functionCalls"}, result); + if (Common.getValueByPath(fromObject, new String[] {"googleMaps"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"googleMaps"}, + Common.getValueByPath(fromObject, new String[] {"googleMaps"})); } - return toObject; - } + if (Common.getValueByPath(fromObject, new String[] {"computerUse"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"computerUse"}, + Common.getValueByPath(fromObject, new String[] {"computerUse"})); + } - @ExcludeFromGeneratedCoverageReport - ObjectNode liveServerToolCallCancellationFromVertex( - JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"ids"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"codeExecution"}) != null) { Common.setValueByPath( - toObject, new String[] {"ids"}, Common.getValueByPath(fromObject, new String[] {"ids"})); + toObject, + new String[] {"codeExecution"}, + Common.getValueByPath(fromObject, new String[] {"codeExecution"})); } - return toObject; - } + if (Common.getValueByPath(fromObject, new String[] {"enterpriseWebSearch"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"enterpriseWebSearch"}, + Common.getValueByPath(fromObject, new String[] {"enterpriseWebSearch"})); + } - @ExcludeFromGeneratedCoverageReport - ObjectNode modalityTokenCountFromVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"modality"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"googleSearch"}) != null) { Common.setValueByPath( toObject, - new String[] {"modality"}, - Common.getValueByPath(fromObject, new String[] {"modality"})); + new String[] {"googleSearch"}, + Common.getValueByPath(fromObject, new String[] {"googleSearch"})); } - if (Common.getValueByPath(fromObject, new String[] {"tokenCount"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"urlContext"}) != null) { Common.setValueByPath( toObject, - new String[] {"tokenCount"}, - Common.getValueByPath(fromObject, new String[] {"tokenCount"})); + new String[] {"urlContext"}, + Common.getValueByPath(fromObject, new String[] {"urlContext"})); } return toObject; @@ -3485,177 +1617,38 @@ ObjectNode usageMetadataFromVertex(JsonNode fromObject, ObjectNode parentObject) } if (Common.getValueByPath(fromObject, new String[] {"promptTokensDetails"}) != null) { - ArrayNode keyArray = - (ArrayNode) Common.getValueByPath(fromObject, new String[] {"promptTokensDetails"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add(modalityTokenCountFromVertex(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"promptTokensDetails"}, result); - } - - if (Common.getValueByPath(fromObject, new String[] {"cacheTokensDetails"}) != null) { - ArrayNode keyArray = - (ArrayNode) Common.getValueByPath(fromObject, new String[] {"cacheTokensDetails"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add(modalityTokenCountFromVertex(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"cacheTokensDetails"}, result); - } - - if (Common.getValueByPath(fromObject, new String[] {"candidatesTokensDetails"}) != null) { - ArrayNode keyArray = - (ArrayNode) Common.getValueByPath(fromObject, new String[] {"candidatesTokensDetails"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add(modalityTokenCountFromVertex(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"responseTokensDetails"}, result); - } - - if (Common.getValueByPath(fromObject, new String[] {"toolUsePromptTokensDetails"}) != null) { - ArrayNode keyArray = - (ArrayNode) - Common.getValueByPath(fromObject, new String[] {"toolUsePromptTokensDetails"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add(modalityTokenCountFromVertex(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"toolUsePromptTokensDetails"}, result); - } - - if (Common.getValueByPath(fromObject, new String[] {"trafficType"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"trafficType"}, - Common.getValueByPath(fromObject, new String[] {"trafficType"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode liveServerGoAwayFromVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"timeLeft"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"timeLeft"}, - Common.getValueByPath(fromObject, new String[] {"timeLeft"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode liveServerSessionResumptionUpdateFromVertex( - JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"newHandle"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"newHandle"}, - Common.getValueByPath(fromObject, new String[] {"newHandle"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"resumable"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"resumable"}, - Common.getValueByPath(fromObject, new String[] {"resumable"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"lastConsumedClientMessageIndex"}) - != null) { - Common.setValueByPath( - toObject, - new String[] {"lastConsumedClientMessageIndex"}, - Common.getValueByPath(fromObject, new String[] {"lastConsumedClientMessageIndex"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode liveServerMessageFromVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"setupComplete"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"setupComplete"}, - liveServerSetupCompleteFromVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"setupComplete"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"serverContent"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"serverContent"}, - liveServerContentFromVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"serverContent"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"toolCall"}) != null) { Common.setValueByPath( toObject, - new String[] {"toolCall"}, - liveServerToolCallFromVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"toolCall"})), - toObject)); + new String[] {"promptTokensDetails"}, + Common.getValueByPath(fromObject, new String[] {"promptTokensDetails"})); } - if (Common.getValueByPath(fromObject, new String[] {"toolCallCancellation"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"cacheTokensDetails"}) != null) { Common.setValueByPath( toObject, - new String[] {"toolCallCancellation"}, - liveServerToolCallCancellationFromVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"toolCallCancellation"})), - toObject)); + new String[] {"cacheTokensDetails"}, + Common.getValueByPath(fromObject, new String[] {"cacheTokensDetails"})); } - if (Common.getValueByPath(fromObject, new String[] {"usageMetadata"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"candidatesTokensDetails"}) != null) { Common.setValueByPath( toObject, - new String[] {"usageMetadata"}, - usageMetadataFromVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"usageMetadata"})), - toObject)); + new String[] {"responseTokensDetails"}, + Common.getValueByPath(fromObject, new String[] {"candidatesTokensDetails"})); } - if (Common.getValueByPath(fromObject, new String[] {"goAway"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"toolUsePromptTokensDetails"}) != null) { Common.setValueByPath( toObject, - new String[] {"goAway"}, - liveServerGoAwayFromVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"goAway"})), - toObject)); + new String[] {"toolUsePromptTokensDetails"}, + Common.getValueByPath(fromObject, new String[] {"toolUsePromptTokensDetails"})); } - if (Common.getValueByPath(fromObject, new String[] {"sessionResumptionUpdate"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"trafficType"}) != null) { Common.setValueByPath( toObject, - new String[] {"sessionResumptionUpdate"}, - liveServerSessionResumptionUpdateFromVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"sessionResumptionUpdate"})), - toObject)); + new String[] {"trafficType"}, + Common.getValueByPath(fromObject, new String[] {"trafficType"})); } return toObject; diff --git a/src/main/java/com/google/genai/LocalTokenizer.java b/src/main/java/com/google/genai/LocalTokenizer.java new file mode 100644 index 00000000000..c17a0f4febc --- /dev/null +++ b/src/main/java/com/google/genai/LocalTokenizer.java @@ -0,0 +1,406 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.genai; + +import com.google.common.annotations.VisibleForTesting; +import com.google.common.collect.ImmutableList; +import com.google.genai.proto.SentencepieceModel.ModelProto; +import com.google.genai.proto.SentencepieceModel.ModelProto.SentencePiece; +import com.google.genai.types.ComputeTokensResult; +import com.google.genai.types.Content; +import com.google.genai.types.CountTokensConfig; +import com.google.genai.types.CountTokensResult; +import com.google.genai.types.FunctionCall; +import com.google.genai.types.FunctionDeclaration; +import com.google.genai.types.FunctionResponse; +import com.google.genai.types.Part; +import com.google.genai.types.Schema; +import com.google.genai.types.Tool; +import com.google.genai.types.TokensInfo; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.logging.Logger; +import java.util.stream.Collectors; + +/** + * [Experimental] Text Only Local Tokenizer. + * + *

This class provides a local tokenizer for text only token counting. + * + *

LIMITATIONS: + * + *

    + *
  • Only supports text based tokenization and no multimodal tokenization. + *
  • Forward compatibility depends on the open-source tokenizer models for future Gemini + * versions. + *
+ * + *

NOTE: The SDK's local tokenizer implementation is experimental and may change in the + * future. It only supports text based tokenization. + */ +public final class LocalTokenizer { + private final ModelProto modelProto; + private final LocalTokenizerProcessor tokenizer; + + /** + * Creates a new LocalTokenizer for the specified model. + * + * @param modelName the name of the model to load (e.g., "gemini-1.5-flash") + * @throws IllegalArgumentException if the model name is not supported or the tokenizer cannot be + * loaded + */ + public LocalTokenizer(String modelName) { + String tokenizerName = LocalTokenizerLoader.getTokenizerName(modelName); + this.modelProto = LocalTokenizerLoader.loadModelProto(tokenizerName); + this.tokenizer = new LocalTokenizerProcessor(this.modelProto); + } + + @VisibleForTesting + LocalTokenizer(ModelProto modelProto, LocalTokenizerProcessor tokenizer) { + this.modelProto = modelProto; + this.tokenizer = tokenizer; + } + + /** + * Counts the number of tokens in a given text. + * + * @param contents The contents to tokenize. + * @param config The configuration for counting tokens. + * @return A {@link CountTokensResult} containing the total number of tokens. + */ + public CountTokensResult countTokens(List contents, CountTokensConfig config) { + List processedContents = contents; + TextsAccumulator textAccumulator = new TextsAccumulator(); + + if (config == null) { + config = CountTokensConfig.builder().build(); + } + + textAccumulator.addContents(processedContents); + if (config.tools().isPresent()) { + textAccumulator.addTools(config.tools().get()); + } + if (config.generationConfig().isPresent() + && config.generationConfig().get().responseSchema().isPresent()) { + textAccumulator.addSchema(config.generationConfig().get().responseSchema().get()); + } + if (config.systemInstruction().isPresent()) { + textAccumulator.addContents(Transformers.tContents(config.systemInstruction().get())); + } + + int totalTokens = 0; + for (String text : textAccumulator.getTexts()) { + totalTokens += tokenizer.encode(text).size(); + } + + return CountTokensResult.builder().totalTokens(totalTokens).build(); + } + + /** + * Counts the number of tokens in a list of content objects using default configuration. + * + * @param contents The contents to tokenize. + * @return A {@link CountTokensResult} containing the total number of tokens. + */ + public CountTokensResult countTokens(List contents) { + return countTokens(contents, null); + } + + /** + * Counts the number of tokens in a single content object. + * + * @param content The content to tokenize. + * @param config The configuration for counting tokens. + * @return A {@link CountTokensResult} containing the total number of tokens. + */ + public CountTokensResult countTokens(Content content, CountTokensConfig config) { + return countTokens(ImmutableList.of(content), config); + } + + /** + * Counts the number of tokens in a single content object using default configuration. + * + * @param content The content to tokenize. + * @return A {@link CountTokensResult} containing the total number of tokens. + */ + public CountTokensResult countTokens(Content content) { + return countTokens(content, null); + } + + /** + * Counts the number of tokens in a text string. + * + * @param content The text content to tokenize. + * @param config The configuration for counting tokens. + * @return A {@link CountTokensResult} containing the total number of tokens. + */ + public CountTokensResult countTokens(String content, CountTokensConfig config) { + return countTokens(Transformers.tContents(content), config); + } + + /** + * Counts the number of tokens in a text string using default configuration. + * + * @param content The text content to tokenize. + * @return A {@link CountTokensResult} containing the total number of tokens. + */ + public CountTokensResult countTokens(String content) { + return countTokens(content, null); + } + + /** + * Computes the tokens ids and string pieces in the input. + * + * @param contents The contents to tokenize. + * @return A {@link ComputeTokensResult} containing the token information. + */ + public ComputeTokensResult computeTokens(List contents) { + List processedContents = contents; + List tokenInfos = new ArrayList<>(); + + for (Content content : processedContents) { + if (content.parts().isPresent()) { + for (Part part : content.parts().get()) { + TextsAccumulator partAccumulator = new TextsAccumulator(); + partAccumulator.addPart(part); + + List allTokenIds = new ArrayList<>(); + List allTokenBytes = new ArrayList<>(); + + for (String text : partAccumulator.getTexts()) { + List tokens = tokenizer.encode(text); + for (Token token : tokens) { + allTokenIds.add((long) token.id()); + allTokenBytes.add( + tokenStrToBytes(token.text(), modelProto.getPieces(token.id()).getType())); + } + } + + tokenInfos.add( + TokensInfo.builder() + .tokenIds(allTokenIds) + .tokens(allTokenBytes) + .role(content.role().orElse(null)) + .build()); + } + } + } + return ComputeTokensResult.builder().tokensInfo(tokenInfos).build(); + } + + /** + * Computes the token ids and string pieces for a single content object. + * + * @param content The content to tokenize. + * @return A {@link ComputeTokensResult} containing the token information. + */ + public ComputeTokensResult computeTokens(Content content) { + return computeTokens(ImmutableList.of(content)); + } + + /** + * Computes the token ids and string pieces for a text string. + * + * @param content The text content to tokenize. + * @return A {@link ComputeTokensResult} containing the token information. + */ + public ComputeTokensResult computeTokens(String content) { + return computeTokens(Transformers.tContents(content)); + } + + private byte[] tokenStrToBytes(String token, SentencePiece.Type type) { + if (type == SentencePiece.Type.BYTE) { + return new byte[] {(byte) parseHexByte(token)}; + } else { + return token.replace('\u2581', ' ').getBytes(StandardCharsets.UTF_8); + } + } + + private int parseHexByte(String token) { + if (token.length() != 6 || !token.startsWith("<0x") || !token.endsWith(">")) { + throw new IllegalArgumentException("Invalid byte format: " + token); + } + try { + int val = Integer.parseInt(token.substring(3, 5), 16); + if (val >= 256) { + throw new IllegalArgumentException("Byte value out of range: " + token); + } + return val; + } catch (NumberFormatException e) { + throw new IllegalArgumentException("Invalid hex value: " + token, e); + } + } + + /** + * Accumulates countable texts from {@link Content} and {@link Tool} objects. + * + *

This class is responsible for traversing complex {@link Content} and {@link Tool} objects + * and extracting all the text content that should be included when calculating token counts. + * + *

A key feature of this class is its ability to detect unsupported fields in {@link Content} + * objects. If a user provides a {@link Content} object with fields that this local tokenizer + * doesn't recognize (e.g., new fields added in a future API update), this class will log a + * warning. + * + *

The detection mechanism for {@link Content} objects works by recursively building a + * "counted" version of the input object. This "counted" object only contains the data that was + * successfully processed and added to the text list for tokenization. After traversing the input, + * the original {@link Content} object is compared to the "counted" object. If they don't match, + * it signifies the presence of unsupported fields, and a warning is logged. + */ + private static class TextsAccumulator { + private static final Logger logger = Logger.getLogger(TextsAccumulator.class.getName()); + private final List texts = new ArrayList<>(); + + public List getTexts() { + return texts; + } + + public void addContents(List contents) { + for (Content content : contents) { + addContent(content); + } + } + + public void addContent(Content content) { + Content countedContent = addContentAndBuildCounted(content); + if (!Objects.equals(content, countedContent)) { + logger.warning( + "Content contains unsupported types for token counting. Supported fields " + + countedContent + + ". Got " + + content + + "."); + } + } + + private Content addContentAndBuildCounted(Content content) { + Content.Builder countedContentBuilder = Content.builder(); + content.role().ifPresent(countedContentBuilder::role); + + if (content.parts().isPresent()) { + List countedParts = + content.parts().get().stream() + .map(this::addPartAndBuildCounted) + .collect(Collectors.toList()); + countedContentBuilder.parts(countedParts); + } + return countedContentBuilder.build(); + } + + private void addPart(Part part) { + addPartAndBuildCounted(part); + } + + private Part addPartAndBuildCounted(Part part) { + Part.Builder countedPartBuilder = Part.builder(); + if (part.fileData().isPresent() || part.inlineData().isPresent()) { + throw new IllegalArgumentException( + "LocalTokenizers do not support non-text content types."); + } + part.videoMetadata().ifPresent(countedPartBuilder::videoMetadata); + part.functionCall() + .ifPresent( + fc -> { + addFunctionCall(fc); + countedPartBuilder.functionCall(fc); + }); + part.functionResponse() + .ifPresent( + fr -> { + addFunctionResponse(fr); + countedPartBuilder.functionResponse(fr); + }); + part.text() + .ifPresent( + text -> { + texts.add(text); + countedPartBuilder.text(text); + }); + return countedPartBuilder.build(); + } + + public void addFunctionCall(FunctionCall functionCall) { + functionCall.name().ifPresent(texts::add); + functionCall.args().ifPresent(this::traverseMap); + } + + public void addFunctionResponse(FunctionResponse functionResponse) { + functionResponse.name().ifPresent(texts::add); + functionResponse.response().ifPresent(this::traverseMap); + } + + public void addTools(List tools) { + for (Tool tool : tools) { + addTool(tool); + } + } + + public void addTool(Tool tool) { + if (tool.functionDeclarations().isPresent()) { + for (FunctionDeclaration functionDeclaration : tool.functionDeclarations().get()) { + addFunctionDeclaration(functionDeclaration); + } + } + } + + private void addFunctionDeclaration(FunctionDeclaration functionDeclaration) { + functionDeclaration.name().ifPresent(texts::add); + functionDeclaration.description().ifPresent(texts::add); + functionDeclaration.parameters().ifPresent(this::addSchema); + } + + public void addSchema(Schema schema) { + schema.format().ifPresent(texts::add); + schema.description().ifPresent(texts::add); + schema.enum_().ifPresent(texts::addAll); + schema.required().ifPresent(texts::addAll); + schema.items().ifPresent(this::addSchema); + if (schema.properties().isPresent()) { + for (Map.Entry entry : schema.properties().get().entrySet()) { + texts.add(entry.getKey()); + addSchema(entry.getValue()); + } + } + schema.example().ifPresent(this::traverseObject); + } + + private void traverseObject(Object value) { + if (value instanceof String) { + texts.add((String) value); + } else if (value instanceof Map) { + @SuppressWarnings("unchecked") + Map map = (Map) value; + traverseMap(map); + } else if (value instanceof List) { + for (Object item : (List) value) { + traverseObject(item); + } + } + } + + private void traverseMap(Map map) { + for (Map.Entry entry : map.entrySet()) { + texts.add(entry.getKey()); + traverseObject(entry.getValue()); + } + } + } +} diff --git a/src/main/java/com/google/genai/LocalTokenizerLoader.java b/src/main/java/com/google/genai/LocalTokenizerLoader.java new file mode 100644 index 00000000000..f99d2effd1a --- /dev/null +++ b/src/main/java/com/google/genai/LocalTokenizerLoader.java @@ -0,0 +1,313 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.genai; + +import com.google.genai.errors.GenAiIOException; +import com.google.genai.proto.SentencepieceModel.ModelProto; +import com.google.protobuf.InvalidProtocolBufferException; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardCopyOption; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.ResponseBody; +import java.util.logging.Logger; + +/** + * Loader for local tokenizers. + * + *

This class handles loading SentencePiece models for tokenization, with local caching to avoid + * repeated downloads. + */ +final class LocalTokenizerLoader { + private static final Map GEMINI_MODELS_TO_TOKENIZER_NAMES; + private static final Logger logger = Logger.getLogger(LocalTokenizerLoader.class.getName()); + + static { + Map modelMap = new HashMap<>(); + modelMap.put("gemini-1.0-pro-001", "gemma2"); + modelMap.put("gemini-1.0-pro-002", "gemma2"); + modelMap.put("gemini-1.0-pro", "gemma2"); + modelMap.put("gemini-1.5-flash-001", "gemma2"); + modelMap.put("gemini-1.5-flash-002", "gemma2"); + modelMap.put("gemini-1.5-flash", "gemma2"); + modelMap.put("gemini-1.5-pro-001", "gemma2"); + modelMap.put("gemini-1.5-pro-002", "gemma2"); + modelMap.put("gemini-1.5-pro", "gemma2"); + modelMap.put("gemini-2.0-flash-001", "gemma3"); + modelMap.put("gemini-2.0-flash-lite-001", "gemma3"); + modelMap.put("gemini-2.0-flash-lite", "gemma3"); + modelMap.put("gemini-2.0-flash", "gemma3"); + modelMap.put("gemini-2.5-flash-lite-preview-06-17", "gemma3"); + modelMap.put("gemini-2.5-flash-lite", "gemma3"); + modelMap.put("gemini-2.5-flash-preview-04-17", "gemma3"); + modelMap.put("gemini-2.5-flash-preview-05-20", "gemma3"); + modelMap.put("gemini-2.5-flash", "gemma3"); + modelMap.put("gemini-2.5-pro-exp-03-25", "gemma3"); + modelMap.put("gemini-2.5-pro-preview-05-06", "gemma3"); + modelMap.put("gemini-2.5-pro-preview-06-05", "gemma3"); + modelMap.put("gemini-2.5-pro", "gemma3"); + modelMap.put("gemini-live-2.5-flash", "gemma3"); + GEMINI_MODELS_TO_TOKENIZER_NAMES = Collections.unmodifiableMap(modelMap); + } + + static final class TokenizerConfig { + private final String modelUrl; + private final String modelHash; + + TokenizerConfig(String modelUrl, String modelHash) { + this.modelUrl = modelUrl; + this.modelHash = modelHash; + } + + String modelUrl() { + return modelUrl; + } + + String modelHash() { + return modelHash; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TokenizerConfig that = (TokenizerConfig) o; + return Objects.equals(modelUrl, that.modelUrl) && Objects.equals(modelHash, that.modelHash); + } + + @Override + public int hashCode() { + return Objects.hash(modelUrl, modelHash); + } + + @Override + public String toString() { + return "TokenizerConfig[modelUrl=" + modelUrl + ", modelHash=" + modelHash + "]"; + } + } + + private static Map TOKENIZERS; + + static { + Map map = new HashMap<>(); + map.put( + "gemma2", + new TokenizerConfig( + "https://raw.githubusercontent.com/google/gemma_pytorch/33b652c465537c6158f9a472ea5700e5e770ad3f/tokenizer/tokenizer.model", + "61a7b147390c64585d6c3543dd6fc636906c9af3865a5548f27f31aee1d4c8e2")); + map.put( + "gemma3", + new TokenizerConfig( + "https://raw.githubusercontent.com/google/gemma_pytorch/014acb7ac4563a5f77c76d7ff98f31b568c16508/tokenizer/gemma3_cleaned_262144_v2.spiece.model", + "1299c11d7cf632ef3b4e11937501358ada021bbdf7c47638d13c0ee982f2e79c")); + TOKENIZERS = Collections.unmodifiableMap(map); + } + + private static final Map modelProtoCache = new ConcurrentHashMap<>(); + private static final Map localTokenizerProcessorCache = + new ConcurrentHashMap<>(); + private static OkHttpClient httpClient = new OkHttpClient(); + + private LocalTokenizerLoader() {} + + /** Gets the tokenizer name for the given model name. */ + public static String getTokenizerName(String modelName) { + if (GEMINI_MODELS_TO_TOKENIZER_NAMES.containsKey(modelName)) { + return GEMINI_MODELS_TO_TOKENIZER_NAMES.get(modelName); + } + throw new IllegalArgumentException( + "Model " + + modelName + + " is not supported. Supported models: " + + String.join(", ", GEMINI_MODELS_TO_TOKENIZER_NAMES.keySet())); + } + + /** Loads model proto from the given tokenizer name. */ + public static ModelProto loadModelProto(String tokenizerName) { + return modelProtoCache.computeIfAbsent( + tokenizerName, + key -> { + try { + byte[] protoBytes = loadModelProtoBytes(key); + return ModelProto.parseFrom(protoBytes); + } catch (InvalidProtocolBufferException e) { + throw new IllegalStateException("Failed to parse model proto", e); + } catch (IOException e) { + throw new GenAiIOException("Failed to load tokenizer model", e); + } + }); + } + + /** Loads sentencepiece tokenizer from the given tokenizer name. */ + public static LocalTokenizerProcessor getSentencePiece(String tokenizerName) { + return localTokenizerProcessorCache.computeIfAbsent( + tokenizerName, + key -> { + try { + LocalTokenizerProcessor processor = new LocalTokenizerProcessor(loadModelProto(key)); + return processor; + } catch (IllegalArgumentException e) { + throw e; + } + }); + } + + private static byte[] loadModelProtoBytes(String tokenizerName) throws IOException { + if (!TOKENIZERS.containsKey(tokenizerName)) { + throw new IllegalArgumentException( + "Tokenizer " + + tokenizerName + + " is not supported. Supported tokenizers: " + + String.join(", ", TOKENIZERS.keySet())); + } + TokenizerConfig config = TOKENIZERS.get(tokenizerName); + return load(config.modelUrl(), config.modelHash()); + } + + private static byte[] load(String fileUrl, String expectedHash) throws IOException { + Path modelDir = Paths.get(System.getProperty("java.io.tmpdir"), "vertexai_tokenizer_model"); + String filename = sha1(fileUrl); + Path modelPath = modelDir.resolve(filename); + + Optional modelData = maybeLoadFromCache(modelPath, expectedHash); + if (modelData.isPresent()) { + return modelData.get(); + } + + byte[] downloadedData = loadFromUrl(fileUrl, expectedHash); + maybeSaveToCache(modelDir, modelPath, downloadedData); + logger.info( + "Downloaded model from " + + fileUrl + + " to " + + modelPath + + " with hash " + + sha256(downloadedData)); + return downloadedData; + } + + private static Optional maybeLoadFromCache(Path filePath, String expectedHash) + throws IOException { + if (!Files.exists(filePath)) { + return Optional.empty(); + } + byte[] content = Files.readAllBytes(filePath); + if (isValidModel(content, expectedHash)) { + return Optional.of(content); + } + + try { + Files.deleteIfExists(filePath); + } catch (IOException e) { + // Don't raise if we cannot remove file. + } + return Optional.empty(); + } + + private static void maybeSaveToCache(Path cacheDir, Path cachePath, byte[] content) { + try { + Files.createDirectories(cacheDir); + Path tmpPath = cacheDir.resolve("." + UUID.randomUUID() + ".tmp"); + Files.write(tmpPath, content); + Files.move(tmpPath, cachePath, StandardCopyOption.REPLACE_EXISTING); + } catch (IOException e) { + // Don't raise if we cannot write file. + } + } + + private static byte[] loadFromUrl(String fileUrl, String expectedHash) throws IOException { + Request request = new Request.Builder().url(fileUrl).build(); + try (Response response = httpClient.newCall(request).execute()) { + if (response == null) { + throw new GenAiIOException("HTTP request failed: response is null"); + } + if (!response.isSuccessful()) { + throw new GenAiIOException("Failed to download tokenizer model: HTTP " + response.code()); + } + ResponseBody body = response.body(); + if (body == null) { + throw new GenAiIOException("Failed to download tokenizer model: Response body is null"); + } + byte[] content = body.bytes(); + + if (!isValidModel(content, expectedHash)) { + String actualHash = sha256(content); + throw new GenAiIOException( + "Downloaded model file is corrupted. Expected hash " + + expectedHash + + ". Got file hash " + + actualHash + + "."); + } + return content; + } + } + + private static boolean isValidModel(byte[] modelData, String expectedHash) { + if (expectedHash == null || expectedHash.isEmpty()) { + throw new IllegalArgumentException("expected_hash is required"); + } + return sha256(modelData).equals(expectedHash); + } + + private static String sha256(byte[] data) { + return hash(data, "SHA-256"); + } + + private static String sha1(String input) { + return hash(input.getBytes(), "SHA-1"); + } + + private static String hash(byte[] data, String algorithm) { + try { + MessageDigest digest = MessageDigest.getInstance(algorithm); + byte[] hash = digest.digest(data); + return bytesToHex(hash); + } catch (NoSuchAlgorithmException e) { + throw new IllegalArgumentException(e); // Should not happen + } + } + + private static String bytesToHex(byte[] hash) { + StringBuilder hexString = new StringBuilder(2 * hash.length); + for (byte b : hash) { + String hex = Integer.toHexString(0xff & b); + if (hex.length() == 1) { + hexString.append('0'); + } + hexString.append(hex); + } + return hexString.toString(); + } +} diff --git a/src/main/java/com/google/genai/LocalTokenizerProcessor.java b/src/main/java/com/google/genai/LocalTokenizerProcessor.java new file mode 100644 index 00000000000..6e6161ca89a --- /dev/null +++ b/src/main/java/com/google/genai/LocalTokenizerProcessor.java @@ -0,0 +1,459 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.genai; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.PriorityQueue; +import java.util.Set; +import java.util.logging.Logger; + +import com.google.genai.proto.SentencepieceModel.ModelProto; +import com.google.genai.proto.SentencepieceModel.ModelProto.SentencePiece; +import com.google.genai.proto.SentencepieceModel.NormalizerSpec; +import com.google.genai.proto.SentencepieceModel.TrainerSpec; + +// IMPORTANT: Fetching tokenizer in unit test can pass locally but will fail in github workflow +// because github test env gets messed up and setup in a file affects other files. +// So the BPE algorithm integration test is excluded from mvn test. +// If you change the code in this file, remember to run the integration test: +// `mvn verify -Dtest=com.google.genai.LocalTokenizerProcessorIT` +final class LocalTokenizerProcessor { + private static final Logger log = Logger.getLogger(LocalTokenizerProcessor.class.getName()); + + private Set userDefined = new HashSet<>(); + private Trie uTrie = new Trie(); + private Map pieces = new HashMap<>(); + private Map reserved = new HashMap<>(); + private Map byte2Token = new HashMap<>(); + private Map idToByte = new HashMap<>(); + + private ModelProto model; + + private int unkID; + + public LocalTokenizerProcessor(ModelProto model) { + this.model = model; + + TrainerSpec tSpec = model.getTrainerSpec(); + if (tSpec.getModelType() != TrainerSpec.ModelType.BPE) { + throw new IllegalArgumentException( + String.format("Unsupported model type %s. Only BPE is supported.", tSpec.getModelType())); + } + + NormalizerSpec nSpec = model.getNormalizerSpec(); + if (nSpec.getAddDummyPrefix() || nSpec.getRemoveExtraWhitespaces()) { + throw new IllegalArgumentException( + String.format("Unsupported model normalizer option: %s", nSpec)); + } + + if (!tSpec.hasUnkId()) { + throw new IllegalArgumentException("Unknown ID is not set."); + } + this.unkID = tSpec.getUnkId(); + + for (int i = 0; i < model.getPiecesCount(); i++) { + SentencePiece p = model.getPieces(i); + if (p.getType() == SentencePiece.Type.NORMAL + || p.getType() == SentencePiece.Type.USER_DEFINED + || p.getType() == SentencePiece.Type.UNUSED) { + this.pieces.put(p.getPiece(), i); + } else if (p.getType() == SentencePiece.Type.BYTE) { + if (!tSpec.getByteFallback()) { + throw new IllegalArgumentException( + String.format( + "byte piece %s is found although byte fallback is not enabled.", p.getPiece())); + } + int bValue = convertHexValue(p.getPiece()); + if (bValue >= 0 && bValue < 256) { + byte2Token.put(Byte.valueOf((byte) bValue), new Token(p.getPiece(), i)); + idToByte.put(i, Byte.valueOf((byte) bValue)); + } + } else { + this.reserved.put(p.getPiece(), i); + } + + if (p.getType() == SentencePiece.Type.USER_DEFINED) { + this.userDefined.add(p.getPiece()); + this.uTrie.insert(p.getPiece()); + } + } + } + + public List encode(String text) throws IllegalStateException { + text = normalize(text); + List symbols = new ArrayList<>(text.length()); + for (int i = 0; i < text.length(); ) { + int len = uTrie.prefixLen(text.substring(i)); + if (len > 0) { + symbols.add( + new Symbol(text.substring(i, i + len), true, symbols.size() - 1, symbols.size() + 1)); + i += len; + } else { + symbols.add( + new Symbol(text.substring(i, i + 1), false, symbols.size() - 1, symbols.size() + 1)); + i++; + } + } + symbols.get(symbols.size() - 1).next = -1; + + PriorityQueue pqSymbols = new PriorityQueue<>(); + for (int i = 1; i < symbols.size(); i++) { + addNewCandidate(symbols, pqSymbols, i - 1, i); + } + + // deadSymbolCount + while (!pqSymbols.isEmpty()) { + MergeCandidate mc = pqSymbols.poll(); + if (!isMergeCandidateValid(symbols, mc)) { + continue; + } + + Symbol leftSymbol = symbols.get(mc.left); + Symbol rightSymbol = symbols.get(mc.right); + + String merged = maybeMerge(leftSymbol.text, rightSymbol.text); + if (merged.length() == 0) { + throw new IllegalStateException( + String.format("error merge symbols, left %s, right %s", leftSymbol, rightSymbol)); + } + + // Do the merge and update prev, next pointers. + leftSymbol.text = merged; + leftSymbol.next = rightSymbol.next; + rightSymbol.text = ""; + if (rightSymbol.next > 0) { + symbols.get(rightSymbol.next).prev = mc.left; + } + + addNewCandidate(symbols, pqSymbols, leftSymbol.prev, mc.left); + addNewCandidate(symbols, pqSymbols, mc.left, rightSymbol.next); + } + + List tokens = new ArrayList<>(); + for (int i = 0; i >= 0; i = symbols.get(i).next) { + Symbol s = symbols.get(i); + int id = this.symbolToID(s); + if (id == this.unkID && this.model.getTrainerSpec().getByteFallback()) { + byte[] bytes = s.text.getBytes(); + for (int j = 0; j < bytes.length; j++) { + tokens.add(byte2Token.get(bytes[j])); + } + } else { + tokens.add(new Token(s.text, id)); + } + } + return tokens; + } + + /** + * Decodes a list of token IDs back into a string. + * + * @param ids The list of token IDs. + * @return The decoded string. + */ + public String decodeIds(List ids) { + StringBuilder sb = new StringBuilder(); + int i = 0; + while (i < ids.size()) { + int nextNonByte = i; + while (nextNonByte < ids.size() && isByteId(ids.get(nextNonByte))) { + nextNonByte++; + } + int numBytes = nextNonByte - i; + + if (numBytes > 0) { + byte[] buf = new byte[numBytes]; + for (int j = 0; j < numBytes; j++) { + buf[j] = this.idToByte.get(ids.get(i + j)); + } + // Java's String constructor handles UTF-8 decoding. + // Invalid sequences will be replaced by the Unicode replacement character + // U+FFFD. + sb.append(new String(buf, StandardCharsets.UTF_8)); + } + + if (nextNonByte >= ids.size()) { + break; + } + + int currentId = ids.get(nextNonByte); + SentencePiece pieceProto = this.model.getPieces(currentId); + + if (pieceProto.getType() == SentencePiece.Type.CONTROL) { + // Don't emit anything for control IDs. + } else if (currentId == this.unkID) { + sb.append(this.model.getTrainerSpec().getUnkSurface()); + } else { + String pieceText = pieceProto.getPiece(); + sb.append(replaceSentencePieceSeparator(pieceText)); + } + i = nextNonByte + 1; + } + return sb.toString(); + } + + private String normalize(String text) { + return text.replaceAll(" ", "▁"); + } + + private void addNewCandidate( + List symbols, PriorityQueue pq, int left, int right) { + if (left == -1 || right == -1 || symbols.get(left).noMerge || symbols.get(right).noMerge) { + return; + } + String merged = maybeMerge(symbols.get(left).text, symbols.get(right).text); + if (merged.length() == 0) { + return; + } + pq.add( + new MergeCandidate( + left, + right, + merged.length(), + this.model.getPieces(this.pieces.get(merged)).getScore())); + // We finalize symbol merge when the symbol is poped from priority queue. + } + + private String maybeMerge(String a, String b) { + String merged = a + b; + if (this.pieces.containsKey(merged)) { + return merged; + } + return ""; + } + + private boolean isMergeCandidateValid(List symbols, MergeCandidate symbol) { + String left = symbols.get(symbol.left).text; + String right = symbols.get(symbol.right).text; + return left != "" && right != "" && left.length() + right.length() == symbol.length; + } + + private int symbolToID(Symbol symbol) { + if (this.pieces.containsKey(symbol.text)) return this.pieces.get(symbol.text); + if (this.reserved.containsKey(symbol.text)) return this.reserved.get(symbol.text); + + return this.unkID; + } + + private boolean isByteId(int id) { + return this.model.getPieces(id).getType() == SentencePiece.Type.BYTE; + } + + // Replaces the SentencePiece space character U+2581 (Lower One Eighth Block) + // with a standard space ' '. + private String replaceSentencePieceSeparator(String pieceText) { + if (pieceText == null) { + return ""; + } + return pieceText.replace('\u2581', ' '); + } + + private int convertHexValue(String bv) { + if (bv == null || !bv.startsWith("<0x") || !bv.endsWith(">")) { + return -1; + } + + String hexPart = bv.substring(3, bv.length() - 1); + + if (hexPart.isEmpty()) { + return -1; // Handle cases like "<0x>" + } + + try { + return Integer.parseInt(hexPart, 16); + } catch (NumberFormatException e) { + return -1; + } + } +} + +class MergeCandidate implements Comparable { + int left, right; + int length; + double score; + + MergeCandidate(int left, int right, int length, double score) { + this.left = left; + this.right = right; + this.length = length; + this.score = score; + } + + @Override + public int compareTo(MergeCandidate other) { + // Primary comparison: score (descending - higher score has higher priority) + int scoreCompare = Double.compare(other.score, this.score); + if (scoreCompare != 0) { + return scoreCompare; + } + // Secondary comparison: left index (ascending - lower index has higher + // priority) + return Integer.compare(this.left, other.left); + } +} + +class Symbol { + String text; + int prev, next; + boolean noMerge; + + public Symbol(String text, boolean noMerge, int prev, int next) { + this.text = text; + this.noMerge = noMerge; + this.prev = prev; + this.next = next; + } + + @Override + public String toString() { + return "Symbol{" + + "text='" + + text + + '\'' + + ", prev=" + + prev + + ", next=" + + next + + ", noMerge=" + + noMerge + + '}'; + } +} + +class TrieNode { + public Map childreNode; + public int freq; + + public TrieNode() { + childreNode = new HashMap<>(); + freq = 0; + } +} + +class Trie { + private TrieNode root; + + public Trie() { + root = new TrieNode(); + } + + // Inserts a word into the trie. + public void insert(String word) { + int index, i; + char ch; + TrieNode node = root; + for (i = 0; i < word.length(); i++) { + ch = word.charAt(i); + index = ch - 'a'; + if (node.childreNode.get(ch) == null) { + node.childreNode.put(ch, new TrieNode()); + } + node = node.childreNode.get(ch); + if (i == word.length() - 1) node.freq++; + } + } + + // Returns if the word is in the trie. + public boolean search(String word) { + int index, i; + char ch; + TrieNode node = root; + for (i = 0; i < word.length(); i++) { + ch = word.charAt(i); + node = node.childreNode.get(ch); + if (node == null) return false; + if (i == word.length() - 1 && node.freq > 0) return true; + } + return false; + } + + public int prefixLen(String word) { + int index, i; + char ch; + TrieNode node = root; + int result = 0; + for (i = 0; i < word.length(); i++) { + ch = word.charAt(i); + node = node.childreNode.get(ch); + if (node == null) break; + if (node.freq > 0) result = i + 1; + } + return result; + } + + // Returns if there is any word in the trie + // that starts with the given prefix. + public boolean startsWith(String prefix) { + int index, i; + char ch; + TrieNode node = root; + for (i = 0; i < prefix.length(); i++) { + ch = prefix.charAt(i); + index = ch - 'a'; + node = node.childreNode.get(ch); + if (node == null) return false; + if (i == prefix.length() - 1) return true; + } + return false; + } +} + +final class Token { + private final String text; + private final int id; + + public Token(String text, int id) { + this.text = text; + this.id = id; + } + + public String text() { + return text; + } + + public int id() { + return id; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Token token = (Token) o; + return id == token.id && Objects.equals(text, token.text); + } + + @Override + public int hashCode() { + return Objects.hash(text, id); + } + + @Override + public String toString() { + return "Token{" + "text='" + text + '\'' + ", id=" + id + '}'; + } +} diff --git a/src/main/java/com/google/genai/Models.java b/src/main/java/com/google/genai/Models.java index f12a7a9046d..e3e74c9b25a 100644 --- a/src/main/java/com/google/genai/Models.java +++ b/src/main/java/com/google/genai/Models.java @@ -25,6 +25,7 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; +import com.google.genai.Common.BuiltRequest; import com.google.genai.errors.GenAiIOException; import com.google.genai.types.ComputeTokensConfig; import com.google.genai.types.ComputeTokensParameters; @@ -51,6 +52,7 @@ import com.google.genai.types.GenerateVideosConfig; import com.google.genai.types.GenerateVideosOperation; import com.google.genai.types.GenerateVideosParameters; +import com.google.genai.types.GenerateVideosSource; import com.google.genai.types.GeneratedImage; import com.google.genai.types.GetModelConfig; import com.google.genai.types.GetModelParameters; @@ -62,9 +64,17 @@ import com.google.genai.types.ListModelsResponse; import com.google.genai.types.Model; import com.google.genai.types.Part; +import com.google.genai.types.RecontextImageConfig; +import com.google.genai.types.RecontextImageParameters; +import com.google.genai.types.RecontextImageResponse; +import com.google.genai.types.RecontextImageSource; import com.google.genai.types.ReferenceImage; import com.google.genai.types.ReferenceImageAPI; import com.google.genai.types.SafetyAttributes; +import com.google.genai.types.SegmentImageConfig; +import com.google.genai.types.SegmentImageParameters; +import com.google.genai.types.SegmentImageResponse; +import com.google.genai.types.SegmentImageSource; import com.google.genai.types.UpdateModelConfig; import com.google.genai.types.UpdateModelParameters; import com.google.genai.types.UpscaleImageAPIConfig; @@ -90,6 +100,7 @@ * `client.models.methodName(...)` directly. */ public final class Models { + final ApiClient apiClient; public Models(ApiClient apiClient) { @@ -97,37 +108,35 @@ public Models(ApiClient apiClient) { } @ExcludeFromGeneratedCoverageReport - ObjectNode videoMetadataToMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"fps"}) != null) { - Common.setValueByPath( - toObject, new String[] {"fps"}, Common.getValueByPath(fromObject, new String[] {"fps"})); + void personGenerationMldevEnumValidate(Object enumValue) { + ImmutableSet invalidEnumValues = ImmutableSet.of("ALLOW_ALL"); + if (invalidEnumValues.contains(enumValue.toString().replace("\"", ""))) { + throw new IllegalArgumentException( + String.format("%s enum value is not supported in Gemini API.", enumValue)); } + } - if (Common.getValueByPath(fromObject, new String[] {"endOffset"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"endOffset"}, - Common.getValueByPath(fromObject, new String[] {"endOffset"})); + @ExcludeFromGeneratedCoverageReport + void safetyFilterLevelMldevEnumValidate(Object enumValue) { + ImmutableSet invalidEnumValues = ImmutableSet.of("BLOCK_NONE"); + if (invalidEnumValues.contains(enumValue.toString().replace("\"", ""))) { + throw new IllegalArgumentException( + String.format("%s enum value is not supported in Gemini API.", enumValue)); } + } - if (Common.getValueByPath(fromObject, new String[] {"startOffset"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"startOffset"}, - Common.getValueByPath(fromObject, new String[] {"startOffset"})); + @ExcludeFromGeneratedCoverageReport + void videoGenerationReferenceTypeMldevEnumValidate(Object enumValue) { + ImmutableSet invalidEnumValues = ImmutableSet.of("STYLE"); + if (invalidEnumValues.contains(enumValue.toString().replace("\"", ""))) { + throw new IllegalArgumentException( + String.format("%s enum value is not supported in Gemini API.", enumValue)); } - - return toObject; } @ExcludeFromGeneratedCoverageReport ObjectNode blobToMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"displayName"}))) { - throw new IllegalArgumentException("displayName parameter is not supported in Gemini API."); - } - if (Common.getValueByPath(fromObject, new String[] {"data"}) != null) { Common.setValueByPath( toObject, @@ -135,30 +144,10 @@ ObjectNode blobToMldev(JsonNode fromObject, ObjectNode parentObject) { Common.getValueByPath(fromObject, new String[] {"data"})); } - if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"mimeType"}, - Common.getValueByPath(fromObject, new String[] {"mimeType"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode fileDataToMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"displayName"}))) { throw new IllegalArgumentException("displayName parameter is not supported in Gemini API."); } - if (Common.getValueByPath(fromObject, new String[] {"fileUri"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"fileUri"}, - Common.getValueByPath(fromObject, new String[] {"fileUri"})); - } - if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { Common.setValueByPath( toObject, @@ -170,1363 +159,1375 @@ ObjectNode fileDataToMldev(JsonNode fromObject, ObjectNode parentObject) { } @ExcludeFromGeneratedCoverageReport - ObjectNode partToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode candidateFromMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"videoMetadata"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"content"}) != null) { Common.setValueByPath( toObject, - new String[] {"videoMetadata"}, - videoMetadataToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"videoMetadata"})), - toObject)); + new String[] {"content"}, + Common.getValueByPath(fromObject, new String[] {"content"})); } - if (Common.getValueByPath(fromObject, new String[] {"thought"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"citationMetadata"}) != null) { Common.setValueByPath( toObject, - new String[] {"thought"}, - Common.getValueByPath(fromObject, new String[] {"thought"})); + new String[] {"citationMetadata"}, + citationMetadataFromMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"citationMetadata"})), + toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"inlineData"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"tokenCount"}) != null) { Common.setValueByPath( toObject, - new String[] {"inlineData"}, - blobToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"inlineData"})), - toObject)); + new String[] {"tokenCount"}, + Common.getValueByPath(fromObject, new String[] {"tokenCount"})); } - if (Common.getValueByPath(fromObject, new String[] {"fileData"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"finishReason"}) != null) { Common.setValueByPath( toObject, - new String[] {"fileData"}, - fileDataToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"fileData"})), - toObject)); + new String[] {"finishReason"}, + Common.getValueByPath(fromObject, new String[] {"finishReason"})); } - if (Common.getValueByPath(fromObject, new String[] {"thoughtSignature"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"avgLogprobs"}) != null) { Common.setValueByPath( toObject, - new String[] {"thoughtSignature"}, - Common.getValueByPath(fromObject, new String[] {"thoughtSignature"})); + new String[] {"avgLogprobs"}, + Common.getValueByPath(fromObject, new String[] {"avgLogprobs"})); } - if (Common.getValueByPath(fromObject, new String[] {"codeExecutionResult"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"groundingMetadata"}) != null) { Common.setValueByPath( toObject, - new String[] {"codeExecutionResult"}, - Common.getValueByPath(fromObject, new String[] {"codeExecutionResult"})); + new String[] {"groundingMetadata"}, + Common.getValueByPath(fromObject, new String[] {"groundingMetadata"})); } - if (Common.getValueByPath(fromObject, new String[] {"executableCode"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"index"}) != null) { Common.setValueByPath( toObject, - new String[] {"executableCode"}, - Common.getValueByPath(fromObject, new String[] {"executableCode"})); + new String[] {"index"}, + Common.getValueByPath(fromObject, new String[] {"index"})); } - if (Common.getValueByPath(fromObject, new String[] {"functionCall"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"logprobsResult"}) != null) { Common.setValueByPath( toObject, - new String[] {"functionCall"}, - Common.getValueByPath(fromObject, new String[] {"functionCall"})); + new String[] {"logprobsResult"}, + Common.getValueByPath(fromObject, new String[] {"logprobsResult"})); } - if (Common.getValueByPath(fromObject, new String[] {"functionResponse"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"safetyRatings"}) != null) { Common.setValueByPath( toObject, - new String[] {"functionResponse"}, - Common.getValueByPath(fromObject, new String[] {"functionResponse"})); + new String[] {"safetyRatings"}, + Common.getValueByPath(fromObject, new String[] {"safetyRatings"})); } - if (Common.getValueByPath(fromObject, new String[] {"text"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"urlContextMetadata"}) != null) { Common.setValueByPath( toObject, - new String[] {"text"}, - Common.getValueByPath(fromObject, new String[] {"text"})); + new String[] {"urlContextMetadata"}, + Common.getValueByPath(fromObject, new String[] {"urlContextMetadata"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode contentToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode citationMetadataFromMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"parts"}) != null) { - ArrayNode keyArray = (ArrayNode) Common.getValueByPath(fromObject, new String[] {"parts"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add(partToMldev(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"parts"}, result); - } - - if (Common.getValueByPath(fromObject, new String[] {"role"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"citationSources"}) != null) { Common.setValueByPath( toObject, - new String[] {"role"}, - Common.getValueByPath(fromObject, new String[] {"role"})); + new String[] {"citations"}, + Common.getValueByPath(fromObject, new String[] {"citationSources"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode schemaToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode computeTokensParametersToVertex( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - if (Common.getValueByPath(fromObject, new String[] {"anyOf"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { Common.setValueByPath( toObject, - new String[] {"anyOf"}, - Common.getValueByPath(fromObject, new String[] {"anyOf"})); + new String[] {"_url", "model"}, + Transformers.tModel( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); } - if (Common.getValueByPath(fromObject, new String[] {"default"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"contents"}) != null) { Common.setValueByPath( toObject, - new String[] {"default"}, - Common.getValueByPath(fromObject, new String[] {"default"})); + new String[] {"contents"}, + Transformers.tContents(Common.getValueByPath(fromObject, new String[] {"contents"}))); } - if (Common.getValueByPath(fromObject, new String[] {"description"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"description"}, - Common.getValueByPath(fromObject, new String[] {"description"})); - } + return toObject; + } - if (Common.getValueByPath(fromObject, new String[] {"enum"}) != null) { + @ExcludeFromGeneratedCoverageReport + ObjectNode computeTokensResponseFromVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"}) != null) { Common.setValueByPath( toObject, - new String[] {"enum"}, - Common.getValueByPath(fromObject, new String[] {"enum"})); + new String[] {"sdkHttpResponse"}, + Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"})); } - if (Common.getValueByPath(fromObject, new String[] {"example"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"tokensInfo"}) != null) { Common.setValueByPath( toObject, - new String[] {"example"}, - Common.getValueByPath(fromObject, new String[] {"example"})); + new String[] {"tokensInfo"}, + Common.getValueByPath(fromObject, new String[] {"tokensInfo"})); } - if (Common.getValueByPath(fromObject, new String[] {"format"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"format"}, - Common.getValueByPath(fromObject, new String[] {"format"})); - } + return toObject; + } - if (Common.getValueByPath(fromObject, new String[] {"items"}) != null) { + @ExcludeFromGeneratedCoverageReport + ObjectNode contentEmbeddingFromVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"values"}) != null) { Common.setValueByPath( toObject, - new String[] {"items"}, - Common.getValueByPath(fromObject, new String[] {"items"})); + new String[] {"values"}, + Common.getValueByPath(fromObject, new String[] {"values"})); } - if (Common.getValueByPath(fromObject, new String[] {"maxItems"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"statistics"}) != null) { Common.setValueByPath( toObject, - new String[] {"maxItems"}, - Common.getValueByPath(fromObject, new String[] {"maxItems"})); + new String[] {"statistics"}, + contentEmbeddingStatisticsFromVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"statistics"})), + toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"maxLength"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"maxLength"}, - Common.getValueByPath(fromObject, new String[] {"maxLength"})); - } + return toObject; + } - if (Common.getValueByPath(fromObject, new String[] {"maxProperties"}) != null) { + @ExcludeFromGeneratedCoverageReport + ObjectNode contentEmbeddingStatisticsFromVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"truncated"}) != null) { Common.setValueByPath( toObject, - new String[] {"maxProperties"}, - Common.getValueByPath(fromObject, new String[] {"maxProperties"})); + new String[] {"truncated"}, + Common.getValueByPath(fromObject, new String[] {"truncated"})); } - if (Common.getValueByPath(fromObject, new String[] {"maximum"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"token_count"}) != null) { Common.setValueByPath( toObject, - new String[] {"maximum"}, - Common.getValueByPath(fromObject, new String[] {"maximum"})); + new String[] {"tokenCount"}, + Common.getValueByPath(fromObject, new String[] {"token_count"})); } - if (Common.getValueByPath(fromObject, new String[] {"minItems"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"minItems"}, - Common.getValueByPath(fromObject, new String[] {"minItems"})); - } + return toObject; + } - if (Common.getValueByPath(fromObject, new String[] {"minLength"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"minLength"}, - Common.getValueByPath(fromObject, new String[] {"minLength"})); - } + @ExcludeFromGeneratedCoverageReport + ObjectNode contentToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"parts"}) != null) { + ArrayNode keyArray = (ArrayNode) Common.getValueByPath(fromObject, new String[] {"parts"}); + ObjectMapper objectMapper = new ObjectMapper(); + ArrayNode result = objectMapper.createArrayNode(); - if (Common.getValueByPath(fromObject, new String[] {"minProperties"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"minProperties"}, - Common.getValueByPath(fromObject, new String[] {"minProperties"})); + for (JsonNode item : keyArray) { + result.add(partToMldev(JsonSerializable.toJsonNode(item), toObject)); + } + Common.setValueByPath(toObject, new String[] {"parts"}, result); } - if (Common.getValueByPath(fromObject, new String[] {"minimum"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"role"}) != null) { Common.setValueByPath( toObject, - new String[] {"minimum"}, - Common.getValueByPath(fromObject, new String[] {"minimum"})); + new String[] {"role"}, + Common.getValueByPath(fromObject, new String[] {"role"})); } - if (Common.getValueByPath(fromObject, new String[] {"nullable"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"nullable"}, - Common.getValueByPath(fromObject, new String[] {"nullable"})); - } + return toObject; + } - if (Common.getValueByPath(fromObject, new String[] {"pattern"}) != null) { + @ExcludeFromGeneratedCoverageReport + ObjectNode controlReferenceConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"controlType"}) != null) { Common.setValueByPath( toObject, - new String[] {"pattern"}, - Common.getValueByPath(fromObject, new String[] {"pattern"})); + new String[] {"controlType"}, + Common.getValueByPath(fromObject, new String[] {"controlType"})); } - if (Common.getValueByPath(fromObject, new String[] {"properties"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"enableControlImageComputation"}) != null) { Common.setValueByPath( toObject, - new String[] {"properties"}, - Common.getValueByPath(fromObject, new String[] {"properties"})); + new String[] {"computeControl"}, + Common.getValueByPath(fromObject, new String[] {"enableControlImageComputation"})); } - if (Common.getValueByPath(fromObject, new String[] {"propertyOrdering"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"propertyOrdering"}, - Common.getValueByPath(fromObject, new String[] {"propertyOrdering"})); - } + return toObject; + } - if (Common.getValueByPath(fromObject, new String[] {"required"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"required"}, - Common.getValueByPath(fromObject, new String[] {"required"})); - } + @ExcludeFromGeneratedCoverageReport + ObjectNode countTokensConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"title"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"title"}, - Common.getValueByPath(fromObject, new String[] {"title"})); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"systemInstruction"}))) { + throw new IllegalArgumentException( + "systemInstruction parameter is not supported in Gemini API."); } - if (Common.getValueByPath(fromObject, new String[] {"type"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"type"}, - Common.getValueByPath(fromObject, new String[] {"type"})); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"tools"}))) { + throw new IllegalArgumentException("tools parameter is not supported in Gemini API."); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"generationConfig"}))) { + throw new IllegalArgumentException( + "generationConfig parameter is not supported in Gemini API."); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode safetySettingToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode countTokensConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"method"}))) { - throw new IllegalArgumentException("method parameter is not supported in Gemini API."); - } - if (Common.getValueByPath(fromObject, new String[] {"category"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"systemInstruction"}) != null) { Common.setValueByPath( - toObject, - new String[] {"category"}, - Common.getValueByPath(fromObject, new String[] {"category"})); + parentObject, + new String[] {"systemInstruction"}, + Transformers.tContent( + Common.getValueByPath(fromObject, new String[] {"systemInstruction"}))); } - if (Common.getValueByPath(fromObject, new String[] {"threshold"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"tools"}) != null) { + ArrayNode keyArray = (ArrayNode) Common.getValueByPath(fromObject, new String[] {"tools"}); + ObjectMapper objectMapper = new ObjectMapper(); + ArrayNode result = objectMapper.createArrayNode(); + + for (JsonNode item : keyArray) { + result.add(toolToVertex(JsonSerializable.toJsonNode(item), toObject)); + } + Common.setValueByPath(parentObject, new String[] {"tools"}, result); + } + + if (Common.getValueByPath(fromObject, new String[] {"generationConfig"}) != null) { Common.setValueByPath( - toObject, - new String[] {"threshold"}, - Common.getValueByPath(fromObject, new String[] {"threshold"})); + parentObject, + new String[] {"generationConfig"}, + generationConfigToVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"generationConfig"})), + toObject)); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode functionDeclarationToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode countTokensParametersToMldev( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"behavior"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { Common.setValueByPath( toObject, - new String[] {"behavior"}, - Common.getValueByPath(fromObject, new String[] {"behavior"})); + new String[] {"_url", "model"}, + Transformers.tModel( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); } - if (Common.getValueByPath(fromObject, new String[] {"description"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"description"}, - Common.getValueByPath(fromObject, new String[] {"description"})); + if (Common.getValueByPath(fromObject, new String[] {"contents"}) != null) { + ArrayNode keyArray = + (ArrayNode) + Transformers.tContents(Common.getValueByPath(fromObject, new String[] {"contents"})); + ObjectMapper objectMapper = new ObjectMapper(); + ArrayNode result = objectMapper.createArrayNode(); + + for (JsonNode item : keyArray) { + result.add(contentToMldev(JsonSerializable.toJsonNode(item), toObject)); + } + Common.setValueByPath(toObject, new String[] {"contents"}, result); } - if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + JsonNode unused = + countTokensConfigToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"config"})), + toObject); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode countTokensParametersToVertex( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { Common.setValueByPath( toObject, - new String[] {"name"}, - Common.getValueByPath(fromObject, new String[] {"name"})); + new String[] {"_url", "model"}, + Transformers.tModel( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); } - if (Common.getValueByPath(fromObject, new String[] {"parameters"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"contents"}) != null) { Common.setValueByPath( toObject, - new String[] {"parameters"}, - Common.getValueByPath(fromObject, new String[] {"parameters"})); + new String[] {"contents"}, + Transformers.tContents(Common.getValueByPath(fromObject, new String[] {"contents"}))); } - if (Common.getValueByPath(fromObject, new String[] {"parametersJsonSchema"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + JsonNode unused = + countTokensConfigToVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"config"})), + toObject); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode countTokensResponseFromMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"}) != null) { Common.setValueByPath( toObject, - new String[] {"parametersJsonSchema"}, - Common.getValueByPath(fromObject, new String[] {"parametersJsonSchema"})); + new String[] {"sdkHttpResponse"}, + Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"})); } - if (Common.getValueByPath(fromObject, new String[] {"response"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"totalTokens"}) != null) { Common.setValueByPath( toObject, - new String[] {"response"}, - Common.getValueByPath(fromObject, new String[] {"response"})); + new String[] {"totalTokens"}, + Common.getValueByPath(fromObject, new String[] {"totalTokens"})); } - if (Common.getValueByPath(fromObject, new String[] {"responseJsonSchema"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"cachedContentTokenCount"}) != null) { Common.setValueByPath( toObject, - new String[] {"responseJsonSchema"}, - Common.getValueByPath(fromObject, new String[] {"responseJsonSchema"})); + new String[] {"cachedContentTokenCount"}, + Common.getValueByPath(fromObject, new String[] {"cachedContentTokenCount"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode intervalToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode countTokensResponseFromVertex(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"startTime"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"}) != null) { Common.setValueByPath( toObject, - new String[] {"startTime"}, - Common.getValueByPath(fromObject, new String[] {"startTime"})); + new String[] {"sdkHttpResponse"}, + Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"})); } - if (Common.getValueByPath(fromObject, new String[] {"endTime"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"totalTokens"}) != null) { Common.setValueByPath( toObject, - new String[] {"endTime"}, - Common.getValueByPath(fromObject, new String[] {"endTime"})); + new String[] {"totalTokens"}, + Common.getValueByPath(fromObject, new String[] {"totalTokens"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode googleSearchToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode deleteModelParametersToMldev( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"timeRangeFilter"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { Common.setValueByPath( toObject, - new String[] {"timeRangeFilter"}, - intervalToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"timeRangeFilter"})), - toObject)); + new String[] {"_url", "name"}, + Transformers.tModel( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode dynamicRetrievalConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode deleteModelParametersToVertex( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"mode"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"mode"}, - Common.getValueByPath(fromObject, new String[] {"mode"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"dynamicThreshold"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { Common.setValueByPath( toObject, - new String[] {"dynamicThreshold"}, - Common.getValueByPath(fromObject, new String[] {"dynamicThreshold"})); + new String[] {"_url", "name"}, + Transformers.tModel( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode googleSearchRetrievalToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode deleteModelResponseFromMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"dynamicRetrievalConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"}) != null) { Common.setValueByPath( toObject, - new String[] {"dynamicRetrievalConfig"}, - dynamicRetrievalConfigToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"dynamicRetrievalConfig"})), - toObject)); + new String[] {"sdkHttpResponse"}, + Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode urlContextToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode deleteModelResponseFromVertex(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"sdkHttpResponse"}, + Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"})); + } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode toolToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode editImageConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"functionDeclarations"}) != null) { - ArrayNode keyArray = - (ArrayNode) Common.getValueByPath(fromObject, new String[] {"functionDeclarations"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - for (JsonNode item : keyArray) { - result.add(functionDeclarationToMldev(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"functionDeclarations"}, result); + if (Common.getValueByPath(fromObject, new String[] {"outputGcsUri"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"parameters", "storageUri"}, + Common.getValueByPath(fromObject, new String[] {"outputGcsUri"})); } - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"retrieval"}))) { - throw new IllegalArgumentException("retrieval parameter is not supported in Gemini API."); + if (Common.getValueByPath(fromObject, new String[] {"negativePrompt"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"parameters", "negativePrompt"}, + Common.getValueByPath(fromObject, new String[] {"negativePrompt"})); } - if (Common.getValueByPath(fromObject, new String[] {"googleSearch"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"numberOfImages"}) != null) { Common.setValueByPath( - toObject, - new String[] {"googleSearch"}, - googleSearchToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"googleSearch"})), - toObject)); + parentObject, + new String[] {"parameters", "sampleCount"}, + Common.getValueByPath(fromObject, new String[] {"numberOfImages"})); } - if (Common.getValueByPath(fromObject, new String[] {"googleSearchRetrieval"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"aspectRatio"}) != null) { Common.setValueByPath( - toObject, - new String[] {"googleSearchRetrieval"}, - googleSearchRetrievalToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"googleSearchRetrieval"})), - toObject)); + parentObject, + new String[] {"parameters", "aspectRatio"}, + Common.getValueByPath(fromObject, new String[] {"aspectRatio"})); } - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"enterpriseWebSearch"}))) { - throw new IllegalArgumentException( - "enterpriseWebSearch parameter is not supported in Gemini API."); + if (Common.getValueByPath(fromObject, new String[] {"guidanceScale"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"parameters", "guidanceScale"}, + Common.getValueByPath(fromObject, new String[] {"guidanceScale"})); } - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"googleMaps"}))) { - throw new IllegalArgumentException("googleMaps parameter is not supported in Gemini API."); + if (Common.getValueByPath(fromObject, new String[] {"seed"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"parameters", "seed"}, + Common.getValueByPath(fromObject, new String[] {"seed"})); } - if (Common.getValueByPath(fromObject, new String[] {"urlContext"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"safetyFilterLevel"}) != null) { Common.setValueByPath( - toObject, - new String[] {"urlContext"}, - urlContextToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"urlContext"})), - toObject)); + parentObject, + new String[] {"parameters", "safetySetting"}, + Common.getValueByPath(fromObject, new String[] {"safetyFilterLevel"})); } - if (Common.getValueByPath(fromObject, new String[] {"codeExecution"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"personGeneration"}) != null) { Common.setValueByPath( - toObject, - new String[] {"codeExecution"}, - Common.getValueByPath(fromObject, new String[] {"codeExecution"})); + parentObject, + new String[] {"parameters", "personGeneration"}, + Common.getValueByPath(fromObject, new String[] {"personGeneration"})); } - if (Common.getValueByPath(fromObject, new String[] {"computerUse"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"includeSafetyAttributes"}) != null) { Common.setValueByPath( - toObject, - new String[] {"computerUse"}, - Common.getValueByPath(fromObject, new String[] {"computerUse"})); + parentObject, + new String[] {"parameters", "includeSafetyAttributes"}, + Common.getValueByPath(fromObject, new String[] {"includeSafetyAttributes"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode functionCallingConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"mode"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"includeRaiReason"}) != null) { Common.setValueByPath( - toObject, - new String[] {"mode"}, - Common.getValueByPath(fromObject, new String[] {"mode"})); + parentObject, + new String[] {"parameters", "includeRaiReason"}, + Common.getValueByPath(fromObject, new String[] {"includeRaiReason"})); } - if (Common.getValueByPath(fromObject, new String[] {"allowedFunctionNames"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"language"}) != null) { Common.setValueByPath( - toObject, - new String[] {"allowedFunctionNames"}, - Common.getValueByPath(fromObject, new String[] {"allowedFunctionNames"})); + parentObject, + new String[] {"parameters", "language"}, + Common.getValueByPath(fromObject, new String[] {"language"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode latLngToMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"latitude"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"outputMimeType"}) != null) { Common.setValueByPath( - toObject, - new String[] {"latitude"}, - Common.getValueByPath(fromObject, new String[] {"latitude"})); + parentObject, + new String[] {"parameters", "outputOptions", "mimeType"}, + Common.getValueByPath(fromObject, new String[] {"outputMimeType"})); } - if (Common.getValueByPath(fromObject, new String[] {"longitude"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"outputCompressionQuality"}) != null) { Common.setValueByPath( - toObject, - new String[] {"longitude"}, - Common.getValueByPath(fromObject, new String[] {"longitude"})); + parentObject, + new String[] {"parameters", "outputOptions", "compressionQuality"}, + Common.getValueByPath(fromObject, new String[] {"outputCompressionQuality"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode retrievalConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"latLng"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"addWatermark"}) != null) { Common.setValueByPath( - toObject, - new String[] {"latLng"}, - latLngToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"latLng"})), - toObject)); + parentObject, + new String[] {"parameters", "addWatermark"}, + Common.getValueByPath(fromObject, new String[] {"addWatermark"})); } - if (Common.getValueByPath(fromObject, new String[] {"languageCode"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"labels"}) != null) { Common.setValueByPath( - toObject, - new String[] {"languageCode"}, - Common.getValueByPath(fromObject, new String[] {"languageCode"})); + parentObject, + new String[] {"labels"}, + Common.getValueByPath(fromObject, new String[] {"labels"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode toolConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"functionCallingConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"editMode"}) != null) { Common.setValueByPath( - toObject, - new String[] {"functionCallingConfig"}, - functionCallingConfigToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"functionCallingConfig"})), - toObject)); + parentObject, + new String[] {"parameters", "editMode"}, + Common.getValueByPath(fromObject, new String[] {"editMode"})); } - if (Common.getValueByPath(fromObject, new String[] {"retrievalConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"baseSteps"}) != null) { Common.setValueByPath( - toObject, - new String[] {"retrievalConfig"}, - retrievalConfigToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"retrievalConfig"})), - toObject)); + parentObject, + new String[] {"parameters", "editConfig", "baseSteps"}, + Common.getValueByPath(fromObject, new String[] {"baseSteps"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode prebuiltVoiceConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode editImageParametersToVertex( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"voiceName"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { Common.setValueByPath( toObject, - new String[] {"voiceName"}, - Common.getValueByPath(fromObject, new String[] {"voiceName"})); + new String[] {"_url", "model"}, + Transformers.tModel( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode voiceConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"prebuiltVoiceConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"prompt"}) != null) { Common.setValueByPath( toObject, - new String[] {"prebuiltVoiceConfig"}, - prebuiltVoiceConfigToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"prebuiltVoiceConfig"})), - toObject)); + new String[] {"instances[0]", "prompt"}, + Common.getValueByPath(fromObject, new String[] {"prompt"})); } - return toObject; - } + if (Common.getValueByPath(fromObject, new String[] {"referenceImages"}) != null) { + ArrayNode keyArray = + (ArrayNode) Common.getValueByPath(fromObject, new String[] {"referenceImages"}); + ObjectMapper objectMapper = new ObjectMapper(); + ArrayNode result = objectMapper.createArrayNode(); - @ExcludeFromGeneratedCoverageReport - ObjectNode speakerVoiceConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"speaker"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"speaker"}, - Common.getValueByPath(fromObject, new String[] {"speaker"})); + for (JsonNode item : keyArray) { + result.add(referenceImageAPIToVertex(JsonSerializable.toJsonNode(item), toObject)); + } + Common.setValueByPath(toObject, new String[] {"instances[0]", "referenceImages"}, result); } - if (Common.getValueByPath(fromObject, new String[] {"voiceConfig"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"voiceConfig"}, - voiceConfigToMldev( + if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + JsonNode unused = + editImageConfigToVertex( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"voiceConfig"})), - toObject)); + Common.getValueByPath(fromObject, new String[] {"config"})), + toObject); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode multiSpeakerVoiceConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode editImageResponseFromVertex(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"speakerVoiceConfigs"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"sdkHttpResponse"}, + Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"predictions"}) != null) { ArrayNode keyArray = - (ArrayNode) Common.getValueByPath(fromObject, new String[] {"speakerVoiceConfigs"}); + (ArrayNode) Common.getValueByPath(fromObject, new String[] {"predictions"}); ObjectMapper objectMapper = new ObjectMapper(); ArrayNode result = objectMapper.createArrayNode(); for (JsonNode item : keyArray) { - result.add(speakerVoiceConfigToMldev(JsonSerializable.toJsonNode(item), toObject)); + result.add(generatedImageFromVertex(JsonSerializable.toJsonNode(item), toObject)); } - Common.setValueByPath(toObject, new String[] {"speakerVoiceConfigs"}, result); + Common.setValueByPath(toObject, new String[] {"generatedImages"}, result); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode speechConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode embedContentConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"voiceConfig"}) != null) { + + if (Common.getValueByPath(fromObject, new String[] {"taskType"}) != null) { Common.setValueByPath( - toObject, - new String[] {"voiceConfig"}, - voiceConfigToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"voiceConfig"})), - toObject)); + parentObject, + new String[] {"requests[]", "taskType"}, + Common.getValueByPath(fromObject, new String[] {"taskType"})); } - if (Common.getValueByPath(fromObject, new String[] {"multiSpeakerVoiceConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"title"}) != null) { Common.setValueByPath( - toObject, - new String[] {"multiSpeakerVoiceConfig"}, - multiSpeakerVoiceConfigToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"multiSpeakerVoiceConfig"})), - toObject)); + parentObject, + new String[] {"requests[]", "title"}, + Common.getValueByPath(fromObject, new String[] {"title"})); } - if (Common.getValueByPath(fromObject, new String[] {"languageCode"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"outputDimensionality"}) != null) { Common.setValueByPath( - toObject, - new String[] {"languageCode"}, - Common.getValueByPath(fromObject, new String[] {"languageCode"})); + parentObject, + new String[] {"requests[]", "outputDimensionality"}, + Common.getValueByPath(fromObject, new String[] {"outputDimensionality"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode thinkingConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"includeThoughts"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"includeThoughts"}, - Common.getValueByPath(fromObject, new String[] {"includeThoughts"})); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"mimeType"}))) { + throw new IllegalArgumentException("mimeType parameter is not supported in Gemini API."); } - if (Common.getValueByPath(fromObject, new String[] {"thinkingBudget"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"thinkingBudget"}, - Common.getValueByPath(fromObject, new String[] {"thinkingBudget"})); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"autoTruncate"}))) { + throw new IllegalArgumentException("autoTruncate parameter is not supported in Gemini API."); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode generateContentConfigToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { + ObjectNode embedContentConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"systemInstruction"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"taskType"}) != null) { Common.setValueByPath( parentObject, - new String[] {"systemInstruction"}, - contentToMldev( - JsonSerializable.toJsonNode( - Transformers.tContent( - Common.getValueByPath(fromObject, new String[] {"systemInstruction"}))), - toObject)); + new String[] {"instances[]", "task_type"}, + Common.getValueByPath(fromObject, new String[] {"taskType"})); } - if (Common.getValueByPath(fromObject, new String[] {"temperature"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"title"}) != null) { Common.setValueByPath( - toObject, - new String[] {"temperature"}, - Common.getValueByPath(fromObject, new String[] {"temperature"})); + parentObject, + new String[] {"instances[]", "title"}, + Common.getValueByPath(fromObject, new String[] {"title"})); } - if (Common.getValueByPath(fromObject, new String[] {"topP"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"outputDimensionality"}) != null) { Common.setValueByPath( - toObject, - new String[] {"topP"}, - Common.getValueByPath(fromObject, new String[] {"topP"})); + parentObject, + new String[] {"parameters", "outputDimensionality"}, + Common.getValueByPath(fromObject, new String[] {"outputDimensionality"})); } - if (Common.getValueByPath(fromObject, new String[] {"topK"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { Common.setValueByPath( - toObject, - new String[] {"topK"}, - Common.getValueByPath(fromObject, new String[] {"topK"})); + parentObject, + new String[] {"instances[]", "mimeType"}, + Common.getValueByPath(fromObject, new String[] {"mimeType"})); } - if (Common.getValueByPath(fromObject, new String[] {"candidateCount"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"autoTruncate"}) != null) { Common.setValueByPath( - toObject, - new String[] {"candidateCount"}, - Common.getValueByPath(fromObject, new String[] {"candidateCount"})); + parentObject, + new String[] {"parameters", "autoTruncate"}, + Common.getValueByPath(fromObject, new String[] {"autoTruncate"})); } - if (Common.getValueByPath(fromObject, new String[] {"maxOutputTokens"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"maxOutputTokens"}, - Common.getValueByPath(fromObject, new String[] {"maxOutputTokens"})); - } + return toObject; + } - if (Common.getValueByPath(fromObject, new String[] {"stopSequences"}) != null) { + @ExcludeFromGeneratedCoverageReport + ObjectNode embedContentParametersToMldev( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { Common.setValueByPath( toObject, - new String[] {"stopSequences"}, - Common.getValueByPath(fromObject, new String[] {"stopSequences"})); + new String[] {"_url", "model"}, + Transformers.tModel( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); } - if (Common.getValueByPath(fromObject, new String[] {"responseLogprobs"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"contents"}) != null) { Common.setValueByPath( toObject, - new String[] {"responseLogprobs"}, - Common.getValueByPath(fromObject, new String[] {"responseLogprobs"})); + new String[] {"requests[]", "content"}, + Transformers.tContentsForEmbed( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"contents"}))); } - if (Common.getValueByPath(fromObject, new String[] {"logprobs"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"logprobs"}, - Common.getValueByPath(fromObject, new String[] {"logprobs"})); + if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + JsonNode unused = + embedContentConfigToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"config"})), + toObject); } - if (Common.getValueByPath(fromObject, new String[] {"presencePenalty"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"requests[]", "model"}, + Transformers.tModel( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode embedContentParametersToVertex( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { Common.setValueByPath( toObject, - new String[] {"presencePenalty"}, - Common.getValueByPath(fromObject, new String[] {"presencePenalty"})); + new String[] {"_url", "model"}, + Transformers.tModel( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); } - if (Common.getValueByPath(fromObject, new String[] {"frequencyPenalty"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"contents"}) != null) { Common.setValueByPath( toObject, - new String[] {"frequencyPenalty"}, - Common.getValueByPath(fromObject, new String[] {"frequencyPenalty"})); + new String[] {"instances[]", "content"}, + Transformers.tContentsForEmbed( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"contents"}))); } - if (Common.getValueByPath(fromObject, new String[] {"seed"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"seed"}, - Common.getValueByPath(fromObject, new String[] {"seed"})); + if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + JsonNode unused = + embedContentConfigToVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"config"})), + toObject); } - if (Common.getValueByPath(fromObject, new String[] {"responseMimeType"}) != null) { + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode embedContentResponseFromMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"}) != null) { Common.setValueByPath( toObject, - new String[] {"responseMimeType"}, - Common.getValueByPath(fromObject, new String[] {"responseMimeType"})); + new String[] {"sdkHttpResponse"}, + Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"})); } - if (Common.getValueByPath(fromObject, new String[] {"responseSchema"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"embeddings"}) != null) { Common.setValueByPath( toObject, - new String[] {"responseSchema"}, - schemaToMldev( - JsonSerializable.toJsonNode( - Transformers.tSchema( - Common.getValueByPath(fromObject, new String[] {"responseSchema"}))), - toObject)); + new String[] {"embeddings"}, + Common.getValueByPath(fromObject, new String[] {"embeddings"})); } - if (Common.getValueByPath(fromObject, new String[] {"responseJsonSchema"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"metadata"}) != null) { Common.setValueByPath( toObject, - new String[] {"responseJsonSchema"}, - Common.getValueByPath(fromObject, new String[] {"responseJsonSchema"})); - } - - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"routingConfig"}))) { - throw new IllegalArgumentException("routingConfig parameter is not supported in Gemini API."); - } - - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"modelSelectionConfig"}))) { - throw new IllegalArgumentException( - "modelSelectionConfig parameter is not supported in Gemini API."); + new String[] {"metadata"}, + Common.getValueByPath(fromObject, new String[] {"metadata"})); } - if (Common.getValueByPath(fromObject, new String[] {"safetySettings"}) != null) { - ArrayNode keyArray = - (ArrayNode) Common.getValueByPath(fromObject, new String[] {"safetySettings"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); + return toObject; + } - for (JsonNode item : keyArray) { - result.add(safetySettingToMldev(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(parentObject, new String[] {"safetySettings"}, result); + @ExcludeFromGeneratedCoverageReport + ObjectNode embedContentResponseFromVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"sdkHttpResponse"}, + Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"})); } - if (Common.getValueByPath(fromObject, new String[] {"tools"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"predictions[]", "embeddings"}) != null) { ArrayNode keyArray = (ArrayNode) - Transformers.tTools(Common.getValueByPath(fromObject, new String[] {"tools"})); + Common.getValueByPath(fromObject, new String[] {"predictions[]", "embeddings"}); ObjectMapper objectMapper = new ObjectMapper(); ArrayNode result = objectMapper.createArrayNode(); for (JsonNode item : keyArray) { - result.add(toolToMldev(JsonSerializable.toJsonNode(Transformers.tTool(item)), toObject)); + result.add(contentEmbeddingFromVertex(JsonSerializable.toJsonNode(item), toObject)); } - Common.setValueByPath(parentObject, new String[] {"tools"}, result); + Common.setValueByPath(toObject, new String[] {"embeddings"}, result); } - if (Common.getValueByPath(fromObject, new String[] {"toolConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"metadata"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"toolConfig"}, - toolConfigToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"toolConfig"})), - toObject)); + toObject, + new String[] {"metadata"}, + Common.getValueByPath(fromObject, new String[] {"metadata"})); } - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"labels"}))) { - throw new IllegalArgumentException("labels parameter is not supported in Gemini API."); - } + return toObject; + } - if (Common.getValueByPath(fromObject, new String[] {"cachedContent"}) != null) { + @ExcludeFromGeneratedCoverageReport + ObjectNode endpointFromVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"endpoint"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"cachedContent"}, - Transformers.tCachedContentName( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"cachedContent"}))); + toObject, + new String[] {"name"}, + Common.getValueByPath(fromObject, new String[] {"endpoint"})); } - if (Common.getValueByPath(fromObject, new String[] {"responseModalities"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"deployedModelId"}) != null) { Common.setValueByPath( toObject, - new String[] {"responseModalities"}, - Common.getValueByPath(fromObject, new String[] {"responseModalities"})); + new String[] {"deployedModelId"}, + Common.getValueByPath(fromObject, new String[] {"deployedModelId"})); } - if (Common.getValueByPath(fromObject, new String[] {"mediaResolution"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"mediaResolution"}, - Common.getValueByPath(fromObject, new String[] {"mediaResolution"})); + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode fileDataToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"displayName"}))) { + throw new IllegalArgumentException("displayName parameter is not supported in Gemini API."); } - if (Common.getValueByPath(fromObject, new String[] {"speechConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"fileUri"}) != null) { Common.setValueByPath( toObject, - new String[] {"speechConfig"}, - speechConfigToMldev( - JsonSerializable.toJsonNode( - Transformers.tSpeechConfig( - Common.getValueByPath(fromObject, new String[] {"speechConfig"}))), - toObject)); - } - - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"audioTimestamp"}))) { - throw new IllegalArgumentException( - "audioTimestamp parameter is not supported in Gemini API."); + new String[] {"fileUri"}, + Common.getValueByPath(fromObject, new String[] {"fileUri"})); } - if (Common.getValueByPath(fromObject, new String[] {"thinkingConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { Common.setValueByPath( toObject, - new String[] {"thinkingConfig"}, - thinkingConfigToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"thinkingConfig"})), - toObject)); + new String[] {"mimeType"}, + Common.getValueByPath(fromObject, new String[] {"mimeType"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode generateContentParametersToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { + ObjectNode functionDeclarationToVertex(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"behavior"}))) { + throw new IllegalArgumentException("behavior parameter is not supported in Vertex AI."); + } + + if (Common.getValueByPath(fromObject, new String[] {"description"}) != null) { Common.setValueByPath( toObject, - new String[] {"_url", "model"}, - Transformers.tModel( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); + new String[] {"description"}, + Common.getValueByPath(fromObject, new String[] {"description"})); } - if (Common.getValueByPath(fromObject, new String[] {"contents"}) != null) { - ArrayNode keyArray = - (ArrayNode) - Transformers.tContents(Common.getValueByPath(fromObject, new String[] {"contents"})); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); + if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"name"}, + Common.getValueByPath(fromObject, new String[] {"name"})); + } - for (JsonNode item : keyArray) { - result.add(contentToMldev(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"contents"}, result); + if (Common.getValueByPath(fromObject, new String[] {"parameters"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"parameters"}, + Common.getValueByPath(fromObject, new String[] {"parameters"})); } - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"parametersJsonSchema"}) != null) { Common.setValueByPath( toObject, - new String[] {"generationConfig"}, - generateContentConfigToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"config"})), - toObject)); + new String[] {"parametersJsonSchema"}, + Common.getValueByPath(fromObject, new String[] {"parametersJsonSchema"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"response"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"response"}, + Common.getValueByPath(fromObject, new String[] {"response"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"responseJsonSchema"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"responseJsonSchema"}, + Common.getValueByPath(fromObject, new String[] {"responseJsonSchema"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode embedContentConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode generateContentConfigToMldev( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"taskType"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"systemInstruction"}) != null) { Common.setValueByPath( parentObject, - new String[] {"requests[]", "taskType"}, - Common.getValueByPath(fromObject, new String[] {"taskType"})); + new String[] {"systemInstruction"}, + contentToMldev( + JsonSerializable.toJsonNode( + Transformers.tContent( + Common.getValueByPath(fromObject, new String[] {"systemInstruction"}))), + toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"title"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"temperature"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"requests[]", "title"}, - Common.getValueByPath(fromObject, new String[] {"title"})); + toObject, + new String[] {"temperature"}, + Common.getValueByPath(fromObject, new String[] {"temperature"})); } - if (Common.getValueByPath(fromObject, new String[] {"outputDimensionality"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"topP"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"requests[]", "outputDimensionality"}, - Common.getValueByPath(fromObject, new String[] {"outputDimensionality"})); + toObject, + new String[] {"topP"}, + Common.getValueByPath(fromObject, new String[] {"topP"})); } - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"mimeType"}))) { - throw new IllegalArgumentException("mimeType parameter is not supported in Gemini API."); + if (Common.getValueByPath(fromObject, new String[] {"topK"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"topK"}, + Common.getValueByPath(fromObject, new String[] {"topK"})); } - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"autoTruncate"}))) { - throw new IllegalArgumentException("autoTruncate parameter is not supported in Gemini API."); + if (Common.getValueByPath(fromObject, new String[] {"candidateCount"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"candidateCount"}, + Common.getValueByPath(fromObject, new String[] {"candidateCount"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode embedContentParametersToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"maxOutputTokens"}) != null) { Common.setValueByPath( toObject, - new String[] {"_url", "model"}, - Transformers.tModel( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); + new String[] {"maxOutputTokens"}, + Common.getValueByPath(fromObject, new String[] {"maxOutputTokens"})); } - if (Common.getValueByPath(fromObject, new String[] {"contents"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"stopSequences"}) != null) { Common.setValueByPath( toObject, - new String[] {"requests[]", "content"}, - Transformers.tContentsForEmbed( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"contents"}))); + new String[] {"stopSequences"}, + Common.getValueByPath(fromObject, new String[] {"stopSequences"})); } - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"responseLogprobs"}) != null) { Common.setValueByPath( toObject, - new String[] {"config"}, - embedContentConfigToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"config"})), - toObject)); + new String[] {"responseLogprobs"}, + Common.getValueByPath(fromObject, new String[] {"responseLogprobs"})); } - Common.setValueByPath( - toObject, - new String[] {"requests[]", "model"}, - Transformers.tModel( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode generateImagesConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"outputGcsUri"}))) { - throw new IllegalArgumentException("outputGcsUri parameter is not supported in Gemini API."); - } - - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"negativePrompt"}))) { - throw new IllegalArgumentException( - "negativePrompt parameter is not supported in Gemini API."); + if (Common.getValueByPath(fromObject, new String[] {"logprobs"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"logprobs"}, + Common.getValueByPath(fromObject, new String[] {"logprobs"})); } - if (Common.getValueByPath(fromObject, new String[] {"numberOfImages"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"presencePenalty"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "sampleCount"}, - Common.getValueByPath(fromObject, new String[] {"numberOfImages"})); + toObject, + new String[] {"presencePenalty"}, + Common.getValueByPath(fromObject, new String[] {"presencePenalty"})); } - if (Common.getValueByPath(fromObject, new String[] {"aspectRatio"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"frequencyPenalty"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "aspectRatio"}, - Common.getValueByPath(fromObject, new String[] {"aspectRatio"})); + toObject, + new String[] {"frequencyPenalty"}, + Common.getValueByPath(fromObject, new String[] {"frequencyPenalty"})); } - if (Common.getValueByPath(fromObject, new String[] {"guidanceScale"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"seed"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "guidanceScale"}, - Common.getValueByPath(fromObject, new String[] {"guidanceScale"})); + toObject, + new String[] {"seed"}, + Common.getValueByPath(fromObject, new String[] {"seed"})); } - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"seed"}))) { - throw new IllegalArgumentException("seed parameter is not supported in Gemini API."); + if (Common.getValueByPath(fromObject, new String[] {"responseMimeType"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"responseMimeType"}, + Common.getValueByPath(fromObject, new String[] {"responseMimeType"})); } - if (Common.getValueByPath(fromObject, new String[] {"safetyFilterLevel"}) != null) { - safetyFilterLevelMldevEnumValidate( - Common.getValueByPath(fromObject, new String[] {"safetyFilterLevel"})); + if (Common.getValueByPath(fromObject, new String[] {"responseSchema"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "safetySetting"}, - Common.getValueByPath(fromObject, new String[] {"safetyFilterLevel"})); + toObject, + new String[] {"responseSchema"}, + Transformers.tSchema(Common.getValueByPath(fromObject, new String[] {"responseSchema"}))); } - if (Common.getValueByPath(fromObject, new String[] {"personGeneration"}) != null) { - personGenerationMldevEnumValidate( - Common.getValueByPath(fromObject, new String[] {"personGeneration"})); + if (Common.getValueByPath(fromObject, new String[] {"responseJsonSchema"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "personGeneration"}, - Common.getValueByPath(fromObject, new String[] {"personGeneration"})); + toObject, + new String[] {"responseJsonSchema"}, + Common.getValueByPath(fromObject, new String[] {"responseJsonSchema"})); } - if (Common.getValueByPath(fromObject, new String[] {"includeSafetyAttributes"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"parameters", "includeSafetyAttributes"}, - Common.getValueByPath(fromObject, new String[] {"includeSafetyAttributes"})); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"routingConfig"}))) { + throw new IllegalArgumentException("routingConfig parameter is not supported in Gemini API."); } - if (Common.getValueByPath(fromObject, new String[] {"includeRaiReason"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"parameters", "includeRaiReason"}, - Common.getValueByPath(fromObject, new String[] {"includeRaiReason"})); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"modelSelectionConfig"}))) { + throw new IllegalArgumentException( + "modelSelectionConfig parameter is not supported in Gemini API."); } - if (Common.getValueByPath(fromObject, new String[] {"language"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"parameters", "language"}, - Common.getValueByPath(fromObject, new String[] {"language"})); + if (Common.getValueByPath(fromObject, new String[] {"safetySettings"}) != null) { + ArrayNode keyArray = + (ArrayNode) Common.getValueByPath(fromObject, new String[] {"safetySettings"}); + ObjectMapper objectMapper = new ObjectMapper(); + ArrayNode result = objectMapper.createArrayNode(); + + for (JsonNode item : keyArray) { + result.add(safetySettingToMldev(JsonSerializable.toJsonNode(item), toObject)); + } + Common.setValueByPath(parentObject, new String[] {"safetySettings"}, result); } - if (Common.getValueByPath(fromObject, new String[] {"outputMimeType"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"parameters", "outputOptions", "mimeType"}, - Common.getValueByPath(fromObject, new String[] {"outputMimeType"})); + if (Common.getValueByPath(fromObject, new String[] {"tools"}) != null) { + ArrayNode keyArray = + (ArrayNode) + Transformers.tTools(Common.getValueByPath(fromObject, new String[] {"tools"})); + ObjectMapper objectMapper = new ObjectMapper(); + ArrayNode result = objectMapper.createArrayNode(); + + for (JsonNode item : keyArray) { + result.add(toolToMldev(JsonSerializable.toJsonNode(Transformers.tTool(item)), toObject)); + } + Common.setValueByPath(parentObject, new String[] {"tools"}, result); } - if (Common.getValueByPath(fromObject, new String[] {"outputCompressionQuality"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"toolConfig"}) != null) { Common.setValueByPath( parentObject, - new String[] {"parameters", "outputOptions", "compressionQuality"}, - Common.getValueByPath(fromObject, new String[] {"outputCompressionQuality"})); - } - - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"addWatermark"}))) { - throw new IllegalArgumentException("addWatermark parameter is not supported in Gemini API."); + new String[] {"toolConfig"}, + Common.getValueByPath(fromObject, new String[] {"toolConfig"})); } - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"imageSize"}))) { - throw new IllegalArgumentException("imageSize parameter is not supported in Gemini API."); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"labels"}))) { + throw new IllegalArgumentException("labels parameter is not supported in Gemini API."); } - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"enhancePrompt"}))) { - throw new IllegalArgumentException("enhancePrompt parameter is not supported in Gemini API."); + if (Common.getValueByPath(fromObject, new String[] {"cachedContent"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"cachedContent"}, + Transformers.tCachedContentName( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"cachedContent"}))); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode generateImagesParametersToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"responseModalities"}) != null) { Common.setValueByPath( toObject, - new String[] {"_url", "model"}, - Transformers.tModel( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); + new String[] {"responseModalities"}, + Common.getValueByPath(fromObject, new String[] {"responseModalities"})); } - if (Common.getValueByPath(fromObject, new String[] {"prompt"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"mediaResolution"}) != null) { Common.setValueByPath( toObject, - new String[] {"instances[0]", "prompt"}, - Common.getValueByPath(fromObject, new String[] {"prompt"})); + new String[] {"mediaResolution"}, + Common.getValueByPath(fromObject, new String[] {"mediaResolution"})); } - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"speechConfig"}) != null) { Common.setValueByPath( toObject, - new String[] {"config"}, - generateImagesConfigToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"config"})), - toObject)); + new String[] {"speechConfig"}, + Transformers.tSpeechConfig( + Common.getValueByPath(fromObject, new String[] {"speechConfig"}))); } - return toObject; - } + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"audioTimestamp"}))) { + throw new IllegalArgumentException( + "audioTimestamp parameter is not supported in Gemini API."); + } - @ExcludeFromGeneratedCoverageReport - ObjectNode getModelParametersToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"thinkingConfig"}) != null) { Common.setValueByPath( toObject, - new String[] {"_url", "name"}, - Transformers.tModel( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); + new String[] {"thinkingConfig"}, + Common.getValueByPath(fromObject, new String[] {"thinkingConfig"})); } - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"imageConfig"}) != null) { Common.setValueByPath( toObject, - new String[] {"config"}, - Common.getValueByPath(fromObject, new String[] {"config"})); + new String[] {"imageConfig"}, + Common.getValueByPath(fromObject, new String[] {"imageConfig"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode listModelsConfigToMldev( + ObjectNode generateContentConfigToVertex( ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"pageSize"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"systemInstruction"}) != null) { Common.setValueByPath( parentObject, - new String[] {"_query", "pageSize"}, - Common.getValueByPath(fromObject, new String[] {"pageSize"})); + new String[] {"systemInstruction"}, + Transformers.tContent( + Common.getValueByPath(fromObject, new String[] {"systemInstruction"}))); } - if (Common.getValueByPath(fromObject, new String[] {"pageToken"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"temperature"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"_query", "pageToken"}, - Common.getValueByPath(fromObject, new String[] {"pageToken"})); + toObject, + new String[] {"temperature"}, + Common.getValueByPath(fromObject, new String[] {"temperature"})); } - if (Common.getValueByPath(fromObject, new String[] {"filter"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"topP"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"_query", "filter"}, - Common.getValueByPath(fromObject, new String[] {"filter"})); + toObject, + new String[] {"topP"}, + Common.getValueByPath(fromObject, new String[] {"topP"})); } - if (Common.getValueByPath(fromObject, new String[] {"queryBase"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"topK"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"_url", "models_url"}, - Transformers.tModelsUrl( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"queryBase"}))); + toObject, + new String[] {"topK"}, + Common.getValueByPath(fromObject, new String[] {"topK"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode listModelsParametersToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"candidateCount"}) != null) { Common.setValueByPath( toObject, - new String[] {"config"}, - listModelsConfigToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"config"})), - toObject)); + new String[] {"candidateCount"}, + Common.getValueByPath(fromObject, new String[] {"candidateCount"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode updateModelConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - if (Common.getValueByPath(fromObject, new String[] {"displayName"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"maxOutputTokens"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"displayName"}, - Common.getValueByPath(fromObject, new String[] {"displayName"})); + toObject, + new String[] {"maxOutputTokens"}, + Common.getValueByPath(fromObject, new String[] {"maxOutputTokens"})); } - if (Common.getValueByPath(fromObject, new String[] {"description"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"stopSequences"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"description"}, - Common.getValueByPath(fromObject, new String[] {"description"})); + toObject, + new String[] {"stopSequences"}, + Common.getValueByPath(fromObject, new String[] {"stopSequences"})); } - if (Common.getValueByPath(fromObject, new String[] {"defaultCheckpointId"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"responseLogprobs"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"defaultCheckpointId"}, - Common.getValueByPath(fromObject, new String[] {"defaultCheckpointId"})); + toObject, + new String[] {"responseLogprobs"}, + Common.getValueByPath(fromObject, new String[] {"responseLogprobs"})); } - return toObject; - } + if (Common.getValueByPath(fromObject, new String[] {"logprobs"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"logprobs"}, + Common.getValueByPath(fromObject, new String[] {"logprobs"})); + } - @ExcludeFromGeneratedCoverageReport - ObjectNode updateModelParametersToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"presencePenalty"}) != null) { Common.setValueByPath( toObject, - new String[] {"_url", "name"}, - Transformers.tModel( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); + new String[] {"presencePenalty"}, + Common.getValueByPath(fromObject, new String[] {"presencePenalty"})); } - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"frequencyPenalty"}) != null) { Common.setValueByPath( toObject, - new String[] {"config"}, - updateModelConfigToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"config"})), - toObject)); + new String[] {"frequencyPenalty"}, + Common.getValueByPath(fromObject, new String[] {"frequencyPenalty"})); } - return toObject; - } + if (Common.getValueByPath(fromObject, new String[] {"seed"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"seed"}, + Common.getValueByPath(fromObject, new String[] {"seed"})); + } - @ExcludeFromGeneratedCoverageReport - ObjectNode deleteModelParametersToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"responseMimeType"}) != null) { Common.setValueByPath( toObject, - new String[] {"_url", "name"}, - Transformers.tModel( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); + new String[] {"responseMimeType"}, + Common.getValueByPath(fromObject, new String[] {"responseMimeType"})); } - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"responseSchema"}) != null) { Common.setValueByPath( toObject, - new String[] {"config"}, - Common.getValueByPath(fromObject, new String[] {"config"})); + new String[] {"responseSchema"}, + Transformers.tSchema(Common.getValueByPath(fromObject, new String[] {"responseSchema"}))); } - return toObject; - } + if (Common.getValueByPath(fromObject, new String[] {"responseJsonSchema"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"responseJsonSchema"}, + Common.getValueByPath(fromObject, new String[] {"responseJsonSchema"})); + } - @ExcludeFromGeneratedCoverageReport - ObjectNode countTokensConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"routingConfig"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"routingConfig"}, + Common.getValueByPath(fromObject, new String[] {"routingConfig"})); + } - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"systemInstruction"}))) { - throw new IllegalArgumentException( - "systemInstruction parameter is not supported in Gemini API."); + if (Common.getValueByPath(fromObject, new String[] {"modelSelectionConfig"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"modelConfig"}, + Common.getValueByPath(fromObject, new String[] {"modelSelectionConfig"})); } - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"tools"}))) { - throw new IllegalArgumentException("tools parameter is not supported in Gemini API."); + if (Common.getValueByPath(fromObject, new String[] {"safetySettings"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"safetySettings"}, + Common.getValueByPath(fromObject, new String[] {"safetySettings"})); } - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"generationConfig"}))) { - throw new IllegalArgumentException( - "generationConfig parameter is not supported in Gemini API."); + if (Common.getValueByPath(fromObject, new String[] {"tools"}) != null) { + ArrayNode keyArray = + (ArrayNode) + Transformers.tTools(Common.getValueByPath(fromObject, new String[] {"tools"})); + ObjectMapper objectMapper = new ObjectMapper(); + ArrayNode result = objectMapper.createArrayNode(); + + for (JsonNode item : keyArray) { + result.add(toolToVertex(JsonSerializable.toJsonNode(Transformers.tTool(item)), toObject)); + } + Common.setValueByPath(parentObject, new String[] {"tools"}, result); + } + + if (Common.getValueByPath(fromObject, new String[] {"toolConfig"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"toolConfig"}, + Common.getValueByPath(fromObject, new String[] {"toolConfig"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"labels"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"labels"}, + Common.getValueByPath(fromObject, new String[] {"labels"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"cachedContent"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"cachedContent"}, + Transformers.tCachedContentName( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"cachedContent"}))); + } + + if (Common.getValueByPath(fromObject, new String[] {"responseModalities"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"responseModalities"}, + Common.getValueByPath(fromObject, new String[] {"responseModalities"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"mediaResolution"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"mediaResolution"}, + Common.getValueByPath(fromObject, new String[] {"mediaResolution"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"speechConfig"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"speechConfig"}, + speechConfigToVertex( + JsonSerializable.toJsonNode( + Transformers.tSpeechConfig( + Common.getValueByPath(fromObject, new String[] {"speechConfig"}))), + toObject)); + } + + if (Common.getValueByPath(fromObject, new String[] {"audioTimestamp"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"audioTimestamp"}, + Common.getValueByPath(fromObject, new String[] {"audioTimestamp"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"thinkingConfig"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"thinkingConfig"}, + Common.getValueByPath(fromObject, new String[] {"thinkingConfig"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"imageConfig"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"imageConfig"}, + Common.getValueByPath(fromObject, new String[] {"imageConfig"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode countTokensParametersToMldev( + ObjectNode generateContentParametersToMldev( ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { @@ -1553,8 +1554,9 @@ ObjectNode countTokensParametersToMldev( if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { Common.setValueByPath( toObject, - new String[] {"config"}, - countTokensConfigToMldev( + new String[] {"generationConfig"}, + generateContentConfigToMldev( + apiClient, JsonSerializable.toJsonNode( Common.getValueByPath(fromObject, new String[] {"config"})), toObject)); @@ -1564,635 +1566,476 @@ ObjectNode countTokensParametersToMldev( } @ExcludeFromGeneratedCoverageReport - ObjectNode imageToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode generateContentParametersToVertex( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"gcsUri"}))) { - throw new IllegalArgumentException("gcsUri parameter is not supported in Gemini API."); + if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"_url", "model"}, + Transformers.tModel( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); } - if (Common.getValueByPath(fromObject, new String[] {"imageBytes"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"contents"}) != null) { Common.setValueByPath( toObject, - new String[] {"bytesBase64Encoded"}, - Transformers.tBytes(Common.getValueByPath(fromObject, new String[] {"imageBytes"}))); + new String[] {"contents"}, + Transformers.tContents(Common.getValueByPath(fromObject, new String[] {"contents"}))); } - if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { Common.setValueByPath( toObject, - new String[] {"mimeType"}, - Common.getValueByPath(fromObject, new String[] {"mimeType"})); + new String[] {"generationConfig"}, + generateContentConfigToVertex( + apiClient, + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"config"})), + toObject)); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode generateVideosSourceToMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode generateVideosConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode generateContentResponseFromMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - if (Common.getValueByPath(fromObject, new String[] {"numberOfVideos"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "sampleCount"}, - Common.getValueByPath(fromObject, new String[] {"numberOfVideos"})); + toObject, + new String[] {"sdkHttpResponse"}, + Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"})); } - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"outputGcsUri"}))) { - throw new IllegalArgumentException("outputGcsUri parameter is not supported in Gemini API."); - } + if (Common.getValueByPath(fromObject, new String[] {"candidates"}) != null) { + ArrayNode keyArray = + (ArrayNode) Common.getValueByPath(fromObject, new String[] {"candidates"}); + ObjectMapper objectMapper = new ObjectMapper(); + ArrayNode result = objectMapper.createArrayNode(); - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"fps"}))) { - throw new IllegalArgumentException("fps parameter is not supported in Gemini API."); + for (JsonNode item : keyArray) { + result.add(candidateFromMldev(JsonSerializable.toJsonNode(item), toObject)); + } + Common.setValueByPath(toObject, new String[] {"candidates"}, result); } - if (Common.getValueByPath(fromObject, new String[] {"durationSeconds"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"modelVersion"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "durationSeconds"}, - Common.getValueByPath(fromObject, new String[] {"durationSeconds"})); + toObject, + new String[] {"modelVersion"}, + Common.getValueByPath(fromObject, new String[] {"modelVersion"})); } - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"seed"}))) { - throw new IllegalArgumentException("seed parameter is not supported in Gemini API."); + if (Common.getValueByPath(fromObject, new String[] {"promptFeedback"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"promptFeedback"}, + Common.getValueByPath(fromObject, new String[] {"promptFeedback"})); } - if (Common.getValueByPath(fromObject, new String[] {"aspectRatio"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"responseId"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "aspectRatio"}, - Common.getValueByPath(fromObject, new String[] {"aspectRatio"})); + toObject, + new String[] {"responseId"}, + Common.getValueByPath(fromObject, new String[] {"responseId"})); } - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"resolution"}))) { - throw new IllegalArgumentException("resolution parameter is not supported in Gemini API."); - } - - if (Common.getValueByPath(fromObject, new String[] {"personGeneration"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"parameters", "personGeneration"}, - Common.getValueByPath(fromObject, new String[] {"personGeneration"})); - } - - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"pubsubTopic"}))) { - throw new IllegalArgumentException("pubsubTopic parameter is not supported in Gemini API."); - } - - if (Common.getValueByPath(fromObject, new String[] {"negativePrompt"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"parameters", "negativePrompt"}, - Common.getValueByPath(fromObject, new String[] {"negativePrompt"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"enhancePrompt"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"parameters", "enhancePrompt"}, - Common.getValueByPath(fromObject, new String[] {"enhancePrompt"})); - } - - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"generateAudio"}))) { - throw new IllegalArgumentException("generateAudio parameter is not supported in Gemini API."); - } - - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"lastFrame"}))) { - throw new IllegalArgumentException("lastFrame parameter is not supported in Gemini API."); - } - - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"compressionQuality"}))) { - throw new IllegalArgumentException( - "compressionQuality parameter is not supported in Gemini API."); + if (Common.getValueByPath(fromObject, new String[] {"usageMetadata"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"usageMetadata"}, + Common.getValueByPath(fromObject, new String[] {"usageMetadata"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode generateVideosParametersToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { + ObjectNode generateContentResponseFromVertex(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"}) != null) { Common.setValueByPath( toObject, - new String[] {"_url", "model"}, - Transformers.tModel( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); + new String[] {"sdkHttpResponse"}, + Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"})); } - if (Common.getValueByPath(fromObject, new String[] {"prompt"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"candidates"}) != null) { Common.setValueByPath( toObject, - new String[] {"instances[0]", "prompt"}, - Common.getValueByPath(fromObject, new String[] {"prompt"})); + new String[] {"candidates"}, + Common.getValueByPath(fromObject, new String[] {"candidates"})); } - if (Common.getValueByPath(fromObject, new String[] {"image"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"createTime"}) != null) { Common.setValueByPath( toObject, - new String[] {"instances[0]", "image"}, - imageToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"image"})), - toObject)); - } - - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"video"}))) { - throw new IllegalArgumentException("video parameter is not supported in Gemini API."); + new String[] {"createTime"}, + Common.getValueByPath(fromObject, new String[] {"createTime"})); } - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"modelVersion"}) != null) { Common.setValueByPath( toObject, - new String[] {"config"}, - generateVideosConfigToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"config"})), - toObject)); + new String[] {"modelVersion"}, + Common.getValueByPath(fromObject, new String[] {"modelVersion"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode videoMetadataToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"fps"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"promptFeedback"}) != null) { Common.setValueByPath( - toObject, new String[] {"fps"}, Common.getValueByPath(fromObject, new String[] {"fps"})); + toObject, + new String[] {"promptFeedback"}, + Common.getValueByPath(fromObject, new String[] {"promptFeedback"})); } - if (Common.getValueByPath(fromObject, new String[] {"endOffset"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"responseId"}) != null) { Common.setValueByPath( toObject, - new String[] {"endOffset"}, - Common.getValueByPath(fromObject, new String[] {"endOffset"})); + new String[] {"responseId"}, + Common.getValueByPath(fromObject, new String[] {"responseId"})); } - if (Common.getValueByPath(fromObject, new String[] {"startOffset"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"usageMetadata"}) != null) { Common.setValueByPath( toObject, - new String[] {"startOffset"}, - Common.getValueByPath(fromObject, new String[] {"startOffset"})); + new String[] {"usageMetadata"}, + Common.getValueByPath(fromObject, new String[] {"usageMetadata"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode blobToVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode generateImagesConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"displayName"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"displayName"}, - Common.getValueByPath(fromObject, new String[] {"displayName"})); - } - if (Common.getValueByPath(fromObject, new String[] {"data"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"data"}, - Common.getValueByPath(fromObject, new String[] {"data"})); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"outputGcsUri"}))) { + throw new IllegalArgumentException("outputGcsUri parameter is not supported in Gemini API."); } - if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"mimeType"}, - Common.getValueByPath(fromObject, new String[] {"mimeType"})); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"negativePrompt"}))) { + throw new IllegalArgumentException( + "negativePrompt parameter is not supported in Gemini API."); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode fileDataToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"displayName"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"numberOfImages"}) != null) { Common.setValueByPath( - toObject, - new String[] {"displayName"}, - Common.getValueByPath(fromObject, new String[] {"displayName"})); + parentObject, + new String[] {"parameters", "sampleCount"}, + Common.getValueByPath(fromObject, new String[] {"numberOfImages"})); } - if (Common.getValueByPath(fromObject, new String[] {"fileUri"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"aspectRatio"}) != null) { Common.setValueByPath( - toObject, - new String[] {"fileUri"}, - Common.getValueByPath(fromObject, new String[] {"fileUri"})); + parentObject, + new String[] {"parameters", "aspectRatio"}, + Common.getValueByPath(fromObject, new String[] {"aspectRatio"})); } - if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"guidanceScale"}) != null) { Common.setValueByPath( - toObject, - new String[] {"mimeType"}, - Common.getValueByPath(fromObject, new String[] {"mimeType"})); + parentObject, + new String[] {"parameters", "guidanceScale"}, + Common.getValueByPath(fromObject, new String[] {"guidanceScale"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode partToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"videoMetadata"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"videoMetadata"}, - videoMetadataToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"videoMetadata"})), - toObject)); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"seed"}))) { + throw new IllegalArgumentException("seed parameter is not supported in Gemini API."); } - if (Common.getValueByPath(fromObject, new String[] {"thought"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"safetyFilterLevel"}) != null) { + safetyFilterLevelMldevEnumValidate( + Common.getValueByPath(fromObject, new String[] {"safetyFilterLevel"})); Common.setValueByPath( - toObject, - new String[] {"thought"}, - Common.getValueByPath(fromObject, new String[] {"thought"})); + parentObject, + new String[] {"parameters", "safetySetting"}, + Common.getValueByPath(fromObject, new String[] {"safetyFilterLevel"})); } - if (Common.getValueByPath(fromObject, new String[] {"inlineData"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"personGeneration"}) != null) { + personGenerationMldevEnumValidate( + Common.getValueByPath(fromObject, new String[] {"personGeneration"})); Common.setValueByPath( - toObject, - new String[] {"inlineData"}, - blobToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"inlineData"})), - toObject)); + parentObject, + new String[] {"parameters", "personGeneration"}, + Common.getValueByPath(fromObject, new String[] {"personGeneration"})); } - if (Common.getValueByPath(fromObject, new String[] {"fileData"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"includeSafetyAttributes"}) != null) { Common.setValueByPath( - toObject, - new String[] {"fileData"}, - fileDataToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"fileData"})), - toObject)); + parentObject, + new String[] {"parameters", "includeSafetyAttributes"}, + Common.getValueByPath(fromObject, new String[] {"includeSafetyAttributes"})); } - if (Common.getValueByPath(fromObject, new String[] {"thoughtSignature"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"includeRaiReason"}) != null) { Common.setValueByPath( - toObject, - new String[] {"thoughtSignature"}, - Common.getValueByPath(fromObject, new String[] {"thoughtSignature"})); + parentObject, + new String[] {"parameters", "includeRaiReason"}, + Common.getValueByPath(fromObject, new String[] {"includeRaiReason"})); } - if (Common.getValueByPath(fromObject, new String[] {"codeExecutionResult"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"language"}) != null) { Common.setValueByPath( - toObject, - new String[] {"codeExecutionResult"}, - Common.getValueByPath(fromObject, new String[] {"codeExecutionResult"})); + parentObject, + new String[] {"parameters", "language"}, + Common.getValueByPath(fromObject, new String[] {"language"})); } - if (Common.getValueByPath(fromObject, new String[] {"executableCode"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"outputMimeType"}) != null) { Common.setValueByPath( - toObject, - new String[] {"executableCode"}, - Common.getValueByPath(fromObject, new String[] {"executableCode"})); + parentObject, + new String[] {"parameters", "outputOptions", "mimeType"}, + Common.getValueByPath(fromObject, new String[] {"outputMimeType"})); } - if (Common.getValueByPath(fromObject, new String[] {"functionCall"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"outputCompressionQuality"}) != null) { Common.setValueByPath( - toObject, - new String[] {"functionCall"}, - Common.getValueByPath(fromObject, new String[] {"functionCall"})); + parentObject, + new String[] {"parameters", "outputOptions", "compressionQuality"}, + Common.getValueByPath(fromObject, new String[] {"outputCompressionQuality"})); } - if (Common.getValueByPath(fromObject, new String[] {"functionResponse"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"functionResponse"}, - Common.getValueByPath(fromObject, new String[] {"functionResponse"})); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"addWatermark"}))) { + throw new IllegalArgumentException("addWatermark parameter is not supported in Gemini API."); } - if (Common.getValueByPath(fromObject, new String[] {"text"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"text"}, - Common.getValueByPath(fromObject, new String[] {"text"})); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"labels"}))) { + throw new IllegalArgumentException("labels parameter is not supported in Gemini API."); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode contentToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"parts"}) != null) { - ArrayNode keyArray = (ArrayNode) Common.getValueByPath(fromObject, new String[] {"parts"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add(partToVertex(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"parts"}, result); + if (Common.getValueByPath(fromObject, new String[] {"imageSize"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"parameters", "sampleImageSize"}, + Common.getValueByPath(fromObject, new String[] {"imageSize"})); } - if (Common.getValueByPath(fromObject, new String[] {"role"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"role"}, - Common.getValueByPath(fromObject, new String[] {"role"})); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"enhancePrompt"}))) { + throw new IllegalArgumentException("enhancePrompt parameter is not supported in Gemini API."); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode schemaToVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode generateImagesConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"anyOf"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"outputGcsUri"}) != null) { Common.setValueByPath( - toObject, - new String[] {"anyOf"}, - Common.getValueByPath(fromObject, new String[] {"anyOf"})); + parentObject, + new String[] {"parameters", "storageUri"}, + Common.getValueByPath(fromObject, new String[] {"outputGcsUri"})); } - if (Common.getValueByPath(fromObject, new String[] {"default"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"negativePrompt"}) != null) { Common.setValueByPath( - toObject, - new String[] {"default"}, - Common.getValueByPath(fromObject, new String[] {"default"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"description"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"description"}, - Common.getValueByPath(fromObject, new String[] {"description"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"enum"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"enum"}, - Common.getValueByPath(fromObject, new String[] {"enum"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"example"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"example"}, - Common.getValueByPath(fromObject, new String[] {"example"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"format"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"format"}, - Common.getValueByPath(fromObject, new String[] {"format"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"items"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"items"}, - Common.getValueByPath(fromObject, new String[] {"items"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"maxItems"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"maxItems"}, - Common.getValueByPath(fromObject, new String[] {"maxItems"})); + parentObject, + new String[] {"parameters", "negativePrompt"}, + Common.getValueByPath(fromObject, new String[] {"negativePrompt"})); } - if (Common.getValueByPath(fromObject, new String[] {"maxLength"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"numberOfImages"}) != null) { Common.setValueByPath( - toObject, - new String[] {"maxLength"}, - Common.getValueByPath(fromObject, new String[] {"maxLength"})); + parentObject, + new String[] {"parameters", "sampleCount"}, + Common.getValueByPath(fromObject, new String[] {"numberOfImages"})); } - if (Common.getValueByPath(fromObject, new String[] {"maxProperties"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"aspectRatio"}) != null) { Common.setValueByPath( - toObject, - new String[] {"maxProperties"}, - Common.getValueByPath(fromObject, new String[] {"maxProperties"})); + parentObject, + new String[] {"parameters", "aspectRatio"}, + Common.getValueByPath(fromObject, new String[] {"aspectRatio"})); } - if (Common.getValueByPath(fromObject, new String[] {"maximum"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"guidanceScale"}) != null) { Common.setValueByPath( - toObject, - new String[] {"maximum"}, - Common.getValueByPath(fromObject, new String[] {"maximum"})); + parentObject, + new String[] {"parameters", "guidanceScale"}, + Common.getValueByPath(fromObject, new String[] {"guidanceScale"})); } - if (Common.getValueByPath(fromObject, new String[] {"minItems"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"seed"}) != null) { Common.setValueByPath( - toObject, - new String[] {"minItems"}, - Common.getValueByPath(fromObject, new String[] {"minItems"})); + parentObject, + new String[] {"parameters", "seed"}, + Common.getValueByPath(fromObject, new String[] {"seed"})); } - if (Common.getValueByPath(fromObject, new String[] {"minLength"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"safetyFilterLevel"}) != null) { Common.setValueByPath( - toObject, - new String[] {"minLength"}, - Common.getValueByPath(fromObject, new String[] {"minLength"})); + parentObject, + new String[] {"parameters", "safetySetting"}, + Common.getValueByPath(fromObject, new String[] {"safetyFilterLevel"})); } - if (Common.getValueByPath(fromObject, new String[] {"minProperties"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"personGeneration"}) != null) { Common.setValueByPath( - toObject, - new String[] {"minProperties"}, - Common.getValueByPath(fromObject, new String[] {"minProperties"})); + parentObject, + new String[] {"parameters", "personGeneration"}, + Common.getValueByPath(fromObject, new String[] {"personGeneration"})); } - if (Common.getValueByPath(fromObject, new String[] {"minimum"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"includeSafetyAttributes"}) != null) { Common.setValueByPath( - toObject, - new String[] {"minimum"}, - Common.getValueByPath(fromObject, new String[] {"minimum"})); + parentObject, + new String[] {"parameters", "includeSafetyAttributes"}, + Common.getValueByPath(fromObject, new String[] {"includeSafetyAttributes"})); } - if (Common.getValueByPath(fromObject, new String[] {"nullable"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"includeRaiReason"}) != null) { Common.setValueByPath( - toObject, - new String[] {"nullable"}, - Common.getValueByPath(fromObject, new String[] {"nullable"})); + parentObject, + new String[] {"parameters", "includeRaiReason"}, + Common.getValueByPath(fromObject, new String[] {"includeRaiReason"})); } - if (Common.getValueByPath(fromObject, new String[] {"pattern"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"language"}) != null) { Common.setValueByPath( - toObject, - new String[] {"pattern"}, - Common.getValueByPath(fromObject, new String[] {"pattern"})); + parentObject, + new String[] {"parameters", "language"}, + Common.getValueByPath(fromObject, new String[] {"language"})); } - if (Common.getValueByPath(fromObject, new String[] {"properties"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"outputMimeType"}) != null) { Common.setValueByPath( - toObject, - new String[] {"properties"}, - Common.getValueByPath(fromObject, new String[] {"properties"})); + parentObject, + new String[] {"parameters", "outputOptions", "mimeType"}, + Common.getValueByPath(fromObject, new String[] {"outputMimeType"})); } - if (Common.getValueByPath(fromObject, new String[] {"propertyOrdering"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"outputCompressionQuality"}) != null) { Common.setValueByPath( - toObject, - new String[] {"propertyOrdering"}, - Common.getValueByPath(fromObject, new String[] {"propertyOrdering"})); + parentObject, + new String[] {"parameters", "outputOptions", "compressionQuality"}, + Common.getValueByPath(fromObject, new String[] {"outputCompressionQuality"})); } - if (Common.getValueByPath(fromObject, new String[] {"required"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"addWatermark"}) != null) { Common.setValueByPath( - toObject, - new String[] {"required"}, - Common.getValueByPath(fromObject, new String[] {"required"})); + parentObject, + new String[] {"parameters", "addWatermark"}, + Common.getValueByPath(fromObject, new String[] {"addWatermark"})); } - if (Common.getValueByPath(fromObject, new String[] {"title"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"labels"}) != null) { Common.setValueByPath( - toObject, - new String[] {"title"}, - Common.getValueByPath(fromObject, new String[] {"title"})); + parentObject, + new String[] {"labels"}, + Common.getValueByPath(fromObject, new String[] {"labels"})); } - if (Common.getValueByPath(fromObject, new String[] {"type"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"imageSize"}) != null) { Common.setValueByPath( - toObject, - new String[] {"type"}, - Common.getValueByPath(fromObject, new String[] {"type"})); + parentObject, + new String[] {"parameters", "sampleImageSize"}, + Common.getValueByPath(fromObject, new String[] {"imageSize"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode modelSelectionConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"featureSelectionPreference"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"enhancePrompt"}) != null) { Common.setValueByPath( - toObject, - new String[] {"featureSelectionPreference"}, - Common.getValueByPath(fromObject, new String[] {"featureSelectionPreference"})); + parentObject, + new String[] {"parameters", "enhancePrompt"}, + Common.getValueByPath(fromObject, new String[] {"enhancePrompt"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode safetySettingToVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode generateImagesParametersToMldev( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"method"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { Common.setValueByPath( toObject, - new String[] {"method"}, - Common.getValueByPath(fromObject, new String[] {"method"})); + new String[] {"_url", "model"}, + Transformers.tModel( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); } - if (Common.getValueByPath(fromObject, new String[] {"category"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"prompt"}) != null) { Common.setValueByPath( toObject, - new String[] {"category"}, - Common.getValueByPath(fromObject, new String[] {"category"})); + new String[] {"instances[0]", "prompt"}, + Common.getValueByPath(fromObject, new String[] {"prompt"})); } - if (Common.getValueByPath(fromObject, new String[] {"threshold"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"threshold"}, - Common.getValueByPath(fromObject, new String[] {"threshold"})); + if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + JsonNode unused = + generateImagesConfigToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"config"})), + toObject); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode functionDeclarationToVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode generateImagesParametersToVertex( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"behavior"}))) { - throw new IllegalArgumentException("behavior parameter is not supported in Vertex AI."); - } - - if (Common.getValueByPath(fromObject, new String[] {"description"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"description"}, - Common.getValueByPath(fromObject, new String[] {"description"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"name"}, - Common.getValueByPath(fromObject, new String[] {"name"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"parameters"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"parameters"}, - Common.getValueByPath(fromObject, new String[] {"parameters"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"parametersJsonSchema"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { Common.setValueByPath( toObject, - new String[] {"parametersJsonSchema"}, - Common.getValueByPath(fromObject, new String[] {"parametersJsonSchema"})); + new String[] {"_url", "model"}, + Transformers.tModel( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); } - if (Common.getValueByPath(fromObject, new String[] {"response"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"prompt"}) != null) { Common.setValueByPath( toObject, - new String[] {"response"}, - Common.getValueByPath(fromObject, new String[] {"response"})); + new String[] {"instances[0]", "prompt"}, + Common.getValueByPath(fromObject, new String[] {"prompt"})); } - if (Common.getValueByPath(fromObject, new String[] {"responseJsonSchema"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"responseJsonSchema"}, - Common.getValueByPath(fromObject, new String[] {"responseJsonSchema"})); + if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + JsonNode unused = + generateImagesConfigToVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"config"})), + toObject); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode intervalToVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode generateImagesResponseFromMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"startTime"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"}) != null) { Common.setValueByPath( toObject, - new String[] {"startTime"}, - Common.getValueByPath(fromObject, new String[] {"startTime"})); + new String[] {"sdkHttpResponse"}, + Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"})); } - if (Common.getValueByPath(fromObject, new String[] {"endTime"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"endTime"}, - Common.getValueByPath(fromObject, new String[] {"endTime"})); - } + if (Common.getValueByPath(fromObject, new String[] {"predictions"}) != null) { + ArrayNode keyArray = + (ArrayNode) Common.getValueByPath(fromObject, new String[] {"predictions"}); + ObjectMapper objectMapper = new ObjectMapper(); + ArrayNode result = objectMapper.createArrayNode(); - return toObject; - } + for (JsonNode item : keyArray) { + result.add(generatedImageFromMldev(JsonSerializable.toJsonNode(item), toObject)); + } + Common.setValueByPath(toObject, new String[] {"generatedImages"}, result); + } - @ExcludeFromGeneratedCoverageReport - ObjectNode googleSearchToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"timeRangeFilter"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"positivePromptSafetyAttributes"}) + != null) { Common.setValueByPath( toObject, - new String[] {"timeRangeFilter"}, - intervalToVertex( + new String[] {"positivePromptSafetyAttributes"}, + safetyAttributesFromMldev( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"timeRangeFilter"})), + Common.getValueByPath( + fromObject, new String[] {"positivePromptSafetyAttributes"})), toObject)); } @@ -2200,35 +2043,36 @@ ObjectNode googleSearchToVertex(JsonNode fromObject, ObjectNode parentObject) { } @ExcludeFromGeneratedCoverageReport - ObjectNode dynamicRetrievalConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode generateImagesResponseFromVertex(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"mode"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"}) != null) { Common.setValueByPath( toObject, - new String[] {"mode"}, - Common.getValueByPath(fromObject, new String[] {"mode"})); + new String[] {"sdkHttpResponse"}, + Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"})); } - if (Common.getValueByPath(fromObject, new String[] {"dynamicThreshold"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"dynamicThreshold"}, - Common.getValueByPath(fromObject, new String[] {"dynamicThreshold"})); - } + if (Common.getValueByPath(fromObject, new String[] {"predictions"}) != null) { + ArrayNode keyArray = + (ArrayNode) Common.getValueByPath(fromObject, new String[] {"predictions"}); + ObjectMapper objectMapper = new ObjectMapper(); + ArrayNode result = objectMapper.createArrayNode(); - return toObject; - } + for (JsonNode item : keyArray) { + result.add(generatedImageFromVertex(JsonSerializable.toJsonNode(item), toObject)); + } + Common.setValueByPath(toObject, new String[] {"generatedImages"}, result); + } - @ExcludeFromGeneratedCoverageReport - ObjectNode googleSearchRetrievalToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"dynamicRetrievalConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"positivePromptSafetyAttributes"}) + != null) { Common.setValueByPath( toObject, - new String[] {"dynamicRetrievalConfig"}, - dynamicRetrievalConfigToVertex( + new String[] {"positivePromptSafetyAttributes"}, + safetyAttributesFromVertex( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"dynamicRetrievalConfig"})), + Common.getValueByPath( + fromObject, new String[] {"positivePromptSafetyAttributes"})), toObject)); } @@ -2236,271 +2080,283 @@ ObjectNode googleSearchRetrievalToVertex(JsonNode fromObject, ObjectNode parentO } @ExcludeFromGeneratedCoverageReport - ObjectNode enterpriseWebSearchToVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode generateVideosConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode apiKeyConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"apiKeyString"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"numberOfVideos"}) != null) { Common.setValueByPath( - toObject, - new String[] {"apiKeyString"}, - Common.getValueByPath(fromObject, new String[] {"apiKeyString"})); + parentObject, + new String[] {"parameters", "sampleCount"}, + Common.getValueByPath(fromObject, new String[] {"numberOfVideos"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode authConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"apiKeyConfig"}) != null) { + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"outputGcsUri"}))) { + throw new IllegalArgumentException("outputGcsUri parameter is not supported in Gemini API."); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"fps"}))) { + throw new IllegalArgumentException("fps parameter is not supported in Gemini API."); + } + + if (Common.getValueByPath(fromObject, new String[] {"durationSeconds"}) != null) { Common.setValueByPath( - toObject, - new String[] {"apiKeyConfig"}, - apiKeyConfigToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"apiKeyConfig"})), - toObject)); + parentObject, + new String[] {"parameters", "durationSeconds"}, + Common.getValueByPath(fromObject, new String[] {"durationSeconds"})); } - if (Common.getValueByPath(fromObject, new String[] {"authType"}) != null) { + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"seed"}))) { + throw new IllegalArgumentException("seed parameter is not supported in Gemini API."); + } + + if (Common.getValueByPath(fromObject, new String[] {"aspectRatio"}) != null) { Common.setValueByPath( - toObject, - new String[] {"authType"}, - Common.getValueByPath(fromObject, new String[] {"authType"})); + parentObject, + new String[] {"parameters", "aspectRatio"}, + Common.getValueByPath(fromObject, new String[] {"aspectRatio"})); } - if (Common.getValueByPath(fromObject, new String[] {"googleServiceAccountConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"resolution"}) != null) { Common.setValueByPath( - toObject, - new String[] {"googleServiceAccountConfig"}, - Common.getValueByPath(fromObject, new String[] {"googleServiceAccountConfig"})); + parentObject, + new String[] {"parameters", "resolution"}, + Common.getValueByPath(fromObject, new String[] {"resolution"})); } - if (Common.getValueByPath(fromObject, new String[] {"httpBasicAuthConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"personGeneration"}) != null) { Common.setValueByPath( - toObject, - new String[] {"httpBasicAuthConfig"}, - Common.getValueByPath(fromObject, new String[] {"httpBasicAuthConfig"})); + parentObject, + new String[] {"parameters", "personGeneration"}, + Common.getValueByPath(fromObject, new String[] {"personGeneration"})); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"pubsubTopic"}))) { + throw new IllegalArgumentException("pubsubTopic parameter is not supported in Gemini API."); } - if (Common.getValueByPath(fromObject, new String[] {"oauthConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"negativePrompt"}) != null) { Common.setValueByPath( - toObject, - new String[] {"oauthConfig"}, - Common.getValueByPath(fromObject, new String[] {"oauthConfig"})); + parentObject, + new String[] {"parameters", "negativePrompt"}, + Common.getValueByPath(fromObject, new String[] {"negativePrompt"})); } - if (Common.getValueByPath(fromObject, new String[] {"oidcConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"enhancePrompt"}) != null) { Common.setValueByPath( - toObject, - new String[] {"oidcConfig"}, - Common.getValueByPath(fromObject, new String[] {"oidcConfig"})); + parentObject, + new String[] {"parameters", "enhancePrompt"}, + Common.getValueByPath(fromObject, new String[] {"enhancePrompt"})); } - return toObject; - } + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"generateAudio"}))) { + throw new IllegalArgumentException("generateAudio parameter is not supported in Gemini API."); + } - @ExcludeFromGeneratedCoverageReport - ObjectNode googleMapsToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"authConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"lastFrame"}) != null) { Common.setValueByPath( - toObject, - new String[] {"authConfig"}, - authConfigToVertex( + parentObject, + new String[] {"instances[0]", "lastFrame"}, + imageToMldev( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"authConfig"})), + Common.getValueByPath(fromObject, new String[] {"lastFrame"})), toObject)); } - return toObject; - } + if (Common.getValueByPath(fromObject, new String[] {"referenceImages"}) != null) { + ArrayNode keyArray = + (ArrayNode) Common.getValueByPath(fromObject, new String[] {"referenceImages"}); + ObjectMapper objectMapper = new ObjectMapper(); + ArrayNode result = objectMapper.createArrayNode(); - @ExcludeFromGeneratedCoverageReport - ObjectNode urlContextToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + for (JsonNode item : keyArray) { + result.add( + videoGenerationReferenceImageToMldev(JsonSerializable.toJsonNode(item), toObject)); + } + Common.setValueByPath(parentObject, new String[] {"instances[0]", "referenceImages"}, result); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"mask"}))) { + throw new IllegalArgumentException("mask parameter is not supported in Gemini API."); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"compressionQuality"}))) { + throw new IllegalArgumentException( + "compressionQuality parameter is not supported in Gemini API."); + } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode toolToVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode generateVideosConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"functionDeclarations"}) != null) { - ArrayNode keyArray = - (ArrayNode) Common.getValueByPath(fromObject, new String[] {"functionDeclarations"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - for (JsonNode item : keyArray) { - result.add(functionDeclarationToVertex(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"functionDeclarations"}, result); + if (Common.getValueByPath(fromObject, new String[] {"numberOfVideos"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"parameters", "sampleCount"}, + Common.getValueByPath(fromObject, new String[] {"numberOfVideos"})); } - if (Common.getValueByPath(fromObject, new String[] {"retrieval"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"outputGcsUri"}) != null) { Common.setValueByPath( - toObject, - new String[] {"retrieval"}, - Common.getValueByPath(fromObject, new String[] {"retrieval"})); + parentObject, + new String[] {"parameters", "storageUri"}, + Common.getValueByPath(fromObject, new String[] {"outputGcsUri"})); } - if (Common.getValueByPath(fromObject, new String[] {"googleSearch"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"fps"}) != null) { Common.setValueByPath( - toObject, - new String[] {"googleSearch"}, - googleSearchToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"googleSearch"})), - toObject)); + parentObject, + new String[] {"parameters", "fps"}, + Common.getValueByPath(fromObject, new String[] {"fps"})); } - if (Common.getValueByPath(fromObject, new String[] {"googleSearchRetrieval"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"durationSeconds"}) != null) { Common.setValueByPath( - toObject, - new String[] {"googleSearchRetrieval"}, - googleSearchRetrievalToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"googleSearchRetrieval"})), - toObject)); + parentObject, + new String[] {"parameters", "durationSeconds"}, + Common.getValueByPath(fromObject, new String[] {"durationSeconds"})); } - if (Common.getValueByPath(fromObject, new String[] {"enterpriseWebSearch"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"seed"}) != null) { Common.setValueByPath( - toObject, - new String[] {"enterpriseWebSearch"}, - enterpriseWebSearchToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"enterpriseWebSearch"})), - toObject)); + parentObject, + new String[] {"parameters", "seed"}, + Common.getValueByPath(fromObject, new String[] {"seed"})); } - if (Common.getValueByPath(fromObject, new String[] {"googleMaps"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"aspectRatio"}) != null) { Common.setValueByPath( - toObject, - new String[] {"googleMaps"}, - googleMapsToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"googleMaps"})), - toObject)); + parentObject, + new String[] {"parameters", "aspectRatio"}, + Common.getValueByPath(fromObject, new String[] {"aspectRatio"})); } - if (Common.getValueByPath(fromObject, new String[] {"urlContext"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"resolution"}) != null) { Common.setValueByPath( - toObject, - new String[] {"urlContext"}, - urlContextToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"urlContext"})), - toObject)); + parentObject, + new String[] {"parameters", "resolution"}, + Common.getValueByPath(fromObject, new String[] {"resolution"})); } - if (Common.getValueByPath(fromObject, new String[] {"codeExecution"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"personGeneration"}) != null) { Common.setValueByPath( - toObject, - new String[] {"codeExecution"}, - Common.getValueByPath(fromObject, new String[] {"codeExecution"})); + parentObject, + new String[] {"parameters", "personGeneration"}, + Common.getValueByPath(fromObject, new String[] {"personGeneration"})); } - if (Common.getValueByPath(fromObject, new String[] {"computerUse"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"pubsubTopic"}) != null) { Common.setValueByPath( - toObject, - new String[] {"computerUse"}, - Common.getValueByPath(fromObject, new String[] {"computerUse"})); + parentObject, + new String[] {"parameters", "pubsubTopic"}, + Common.getValueByPath(fromObject, new String[] {"pubsubTopic"})); } - return toObject; - } + if (Common.getValueByPath(fromObject, new String[] {"negativePrompt"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"parameters", "negativePrompt"}, + Common.getValueByPath(fromObject, new String[] {"negativePrompt"})); + } - @ExcludeFromGeneratedCoverageReport - ObjectNode functionCallingConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"mode"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"enhancePrompt"}) != null) { Common.setValueByPath( - toObject, - new String[] {"mode"}, - Common.getValueByPath(fromObject, new String[] {"mode"})); + parentObject, + new String[] {"parameters", "enhancePrompt"}, + Common.getValueByPath(fromObject, new String[] {"enhancePrompt"})); } - if (Common.getValueByPath(fromObject, new String[] {"allowedFunctionNames"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"generateAudio"}) != null) { Common.setValueByPath( - toObject, - new String[] {"allowedFunctionNames"}, - Common.getValueByPath(fromObject, new String[] {"allowedFunctionNames"})); + parentObject, + new String[] {"parameters", "generateAudio"}, + Common.getValueByPath(fromObject, new String[] {"generateAudio"})); } - return toObject; - } + if (Common.getValueByPath(fromObject, new String[] {"lastFrame"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"instances[0]", "lastFrame"}, + imageToVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"lastFrame"})), + toObject)); + } - @ExcludeFromGeneratedCoverageReport - ObjectNode latLngToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"latitude"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"referenceImages"}) != null) { + ArrayNode keyArray = + (ArrayNode) Common.getValueByPath(fromObject, new String[] {"referenceImages"}); + ObjectMapper objectMapper = new ObjectMapper(); + ArrayNode result = objectMapper.createArrayNode(); + + for (JsonNode item : keyArray) { + result.add( + videoGenerationReferenceImageToVertex(JsonSerializable.toJsonNode(item), toObject)); + } + Common.setValueByPath(parentObject, new String[] {"instances[0]", "referenceImages"}, result); + } + + if (Common.getValueByPath(fromObject, new String[] {"mask"}) != null) { Common.setValueByPath( - toObject, - new String[] {"latitude"}, - Common.getValueByPath(fromObject, new String[] {"latitude"})); + parentObject, + new String[] {"instances[0]", "mask"}, + videoGenerationMaskToVertex( + JsonSerializable.toJsonNode(Common.getValueByPath(fromObject, new String[] {"mask"})), + toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"longitude"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"compressionQuality"}) != null) { Common.setValueByPath( - toObject, - new String[] {"longitude"}, - Common.getValueByPath(fromObject, new String[] {"longitude"})); + parentObject, + new String[] {"parameters", "compressionQuality"}, + Common.getValueByPath(fromObject, new String[] {"compressionQuality"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode retrievalConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode generateVideosOperationFromMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"latLng"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { Common.setValueByPath( toObject, - new String[] {"latLng"}, - latLngToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"latLng"})), - toObject)); + new String[] {"name"}, + Common.getValueByPath(fromObject, new String[] {"name"})); } - if (Common.getValueByPath(fromObject, new String[] {"languageCode"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"metadata"}) != null) { Common.setValueByPath( toObject, - new String[] {"languageCode"}, - Common.getValueByPath(fromObject, new String[] {"languageCode"})); + new String[] {"metadata"}, + Common.getValueByPath(fromObject, new String[] {"metadata"})); } - return toObject; - } + if (Common.getValueByPath(fromObject, new String[] {"done"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"done"}, + Common.getValueByPath(fromObject, new String[] {"done"})); + } - @ExcludeFromGeneratedCoverageReport - ObjectNode toolConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"functionCallingConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"error"}) != null) { Common.setValueByPath( toObject, - new String[] {"functionCallingConfig"}, - functionCallingConfigToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"functionCallingConfig"})), - toObject)); + new String[] {"error"}, + Common.getValueByPath(fromObject, new String[] {"error"})); } - if (Common.getValueByPath(fromObject, new String[] {"retrievalConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"response", "generateVideoResponse"}) + != null) { Common.setValueByPath( toObject, - new String[] {"retrievalConfig"}, - retrievalConfigToVertex( + new String[] {"response"}, + generateVideosResponseFromMldev( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"retrievalConfig"})), + Common.getValueByPath( + fromObject, new String[] {"response", "generateVideoResponse"})), toObject)); } @@ -2508,1414 +2364,102 @@ ObjectNode toolConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { } @ExcludeFromGeneratedCoverageReport - ObjectNode prebuiltVoiceConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode generateVideosOperationFromVertex(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"voiceName"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { Common.setValueByPath( toObject, - new String[] {"voiceName"}, - Common.getValueByPath(fromObject, new String[] {"voiceName"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode voiceConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"prebuiltVoiceConfig"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"prebuiltVoiceConfig"}, - prebuiltVoiceConfigToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"prebuiltVoiceConfig"})), - toObject)); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode speechConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"voiceConfig"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"voiceConfig"}, - voiceConfigToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"voiceConfig"})), - toObject)); - } - - if (!Common.isZero( - Common.getValueByPath(fromObject, new String[] {"multiSpeakerVoiceConfig"}))) { - throw new IllegalArgumentException( - "multiSpeakerVoiceConfig parameter is not supported in Vertex AI."); - } - - if (Common.getValueByPath(fromObject, new String[] {"languageCode"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"languageCode"}, - Common.getValueByPath(fromObject, new String[] {"languageCode"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode thinkingConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"includeThoughts"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"includeThoughts"}, - Common.getValueByPath(fromObject, new String[] {"includeThoughts"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"thinkingBudget"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"thinkingBudget"}, - Common.getValueByPath(fromObject, new String[] {"thinkingBudget"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode generateContentConfigToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - if (Common.getValueByPath(fromObject, new String[] {"systemInstruction"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"systemInstruction"}, - contentToVertex( - JsonSerializable.toJsonNode( - Transformers.tContent( - Common.getValueByPath(fromObject, new String[] {"systemInstruction"}))), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"temperature"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"temperature"}, - Common.getValueByPath(fromObject, new String[] {"temperature"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"topP"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"topP"}, - Common.getValueByPath(fromObject, new String[] {"topP"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"topK"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"topK"}, - Common.getValueByPath(fromObject, new String[] {"topK"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"candidateCount"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"candidateCount"}, - Common.getValueByPath(fromObject, new String[] {"candidateCount"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"maxOutputTokens"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"maxOutputTokens"}, - Common.getValueByPath(fromObject, new String[] {"maxOutputTokens"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"stopSequences"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"stopSequences"}, - Common.getValueByPath(fromObject, new String[] {"stopSequences"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"responseLogprobs"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"responseLogprobs"}, - Common.getValueByPath(fromObject, new String[] {"responseLogprobs"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"logprobs"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"logprobs"}, - Common.getValueByPath(fromObject, new String[] {"logprobs"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"presencePenalty"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"presencePenalty"}, - Common.getValueByPath(fromObject, new String[] {"presencePenalty"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"frequencyPenalty"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"frequencyPenalty"}, - Common.getValueByPath(fromObject, new String[] {"frequencyPenalty"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"seed"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"seed"}, - Common.getValueByPath(fromObject, new String[] {"seed"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"responseMimeType"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"responseMimeType"}, - Common.getValueByPath(fromObject, new String[] {"responseMimeType"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"responseSchema"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"responseSchema"}, - schemaToVertex( - JsonSerializable.toJsonNode( - Transformers.tSchema( - Common.getValueByPath(fromObject, new String[] {"responseSchema"}))), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"responseJsonSchema"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"responseJsonSchema"}, - Common.getValueByPath(fromObject, new String[] {"responseJsonSchema"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"routingConfig"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"routingConfig"}, - Common.getValueByPath(fromObject, new String[] {"routingConfig"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"modelSelectionConfig"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"modelConfig"}, - modelSelectionConfigToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"modelSelectionConfig"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"safetySettings"}) != null) { - ArrayNode keyArray = - (ArrayNode) Common.getValueByPath(fromObject, new String[] {"safetySettings"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add(safetySettingToVertex(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(parentObject, new String[] {"safetySettings"}, result); - } - - if (Common.getValueByPath(fromObject, new String[] {"tools"}) != null) { - ArrayNode keyArray = - (ArrayNode) - Transformers.tTools(Common.getValueByPath(fromObject, new String[] {"tools"})); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add(toolToVertex(JsonSerializable.toJsonNode(Transformers.tTool(item)), toObject)); - } - Common.setValueByPath(parentObject, new String[] {"tools"}, result); - } - - if (Common.getValueByPath(fromObject, new String[] {"toolConfig"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"toolConfig"}, - toolConfigToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"toolConfig"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"labels"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"labels"}, - Common.getValueByPath(fromObject, new String[] {"labels"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"cachedContent"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"cachedContent"}, - Transformers.tCachedContentName( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"cachedContent"}))); - } - - if (Common.getValueByPath(fromObject, new String[] {"responseModalities"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"responseModalities"}, - Common.getValueByPath(fromObject, new String[] {"responseModalities"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"mediaResolution"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"mediaResolution"}, - Common.getValueByPath(fromObject, new String[] {"mediaResolution"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"speechConfig"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"speechConfig"}, - speechConfigToVertex( - JsonSerializable.toJsonNode( - Transformers.tSpeechConfig( - Common.getValueByPath(fromObject, new String[] {"speechConfig"}))), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"audioTimestamp"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"audioTimestamp"}, - Common.getValueByPath(fromObject, new String[] {"audioTimestamp"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"thinkingConfig"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"thinkingConfig"}, - thinkingConfigToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"thinkingConfig"})), - toObject)); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode generateContentParametersToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"_url", "model"}, - Transformers.tModel( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); - } - - if (Common.getValueByPath(fromObject, new String[] {"contents"}) != null) { - ArrayNode keyArray = - (ArrayNode) - Transformers.tContents(Common.getValueByPath(fromObject, new String[] {"contents"})); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add(contentToVertex(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"contents"}, result); - } - - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"generationConfig"}, - generateContentConfigToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"config"})), - toObject)); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode embedContentConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - if (Common.getValueByPath(fromObject, new String[] {"taskType"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"instances[]", "task_type"}, - Common.getValueByPath(fromObject, new String[] {"taskType"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"title"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"instances[]", "title"}, - Common.getValueByPath(fromObject, new String[] {"title"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"outputDimensionality"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"parameters", "outputDimensionality"}, - Common.getValueByPath(fromObject, new String[] {"outputDimensionality"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"instances[]", "mimeType"}, - Common.getValueByPath(fromObject, new String[] {"mimeType"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"autoTruncate"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"parameters", "autoTruncate"}, - Common.getValueByPath(fromObject, new String[] {"autoTruncate"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode embedContentParametersToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"_url", "model"}, - Transformers.tModel( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); - } - - if (Common.getValueByPath(fromObject, new String[] {"contents"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"instances[]", "content"}, - Transformers.tContentsForEmbed( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"contents"}))); - } - - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"config"}, - embedContentConfigToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"config"})), - toObject)); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode generateImagesConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - if (Common.getValueByPath(fromObject, new String[] {"outputGcsUri"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"parameters", "storageUri"}, - Common.getValueByPath(fromObject, new String[] {"outputGcsUri"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"negativePrompt"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"parameters", "negativePrompt"}, - Common.getValueByPath(fromObject, new String[] {"negativePrompt"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"numberOfImages"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"parameters", "sampleCount"}, - Common.getValueByPath(fromObject, new String[] {"numberOfImages"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"aspectRatio"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"parameters", "aspectRatio"}, - Common.getValueByPath(fromObject, new String[] {"aspectRatio"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"guidanceScale"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"parameters", "guidanceScale"}, - Common.getValueByPath(fromObject, new String[] {"guidanceScale"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"seed"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"parameters", "seed"}, - Common.getValueByPath(fromObject, new String[] {"seed"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"safetyFilterLevel"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"parameters", "safetySetting"}, - Common.getValueByPath(fromObject, new String[] {"safetyFilterLevel"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"personGeneration"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"parameters", "personGeneration"}, - Common.getValueByPath(fromObject, new String[] {"personGeneration"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"includeSafetyAttributes"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"parameters", "includeSafetyAttributes"}, - Common.getValueByPath(fromObject, new String[] {"includeSafetyAttributes"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"includeRaiReason"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"parameters", "includeRaiReason"}, - Common.getValueByPath(fromObject, new String[] {"includeRaiReason"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"language"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"parameters", "language"}, - Common.getValueByPath(fromObject, new String[] {"language"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"outputMimeType"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"parameters", "outputOptions", "mimeType"}, - Common.getValueByPath(fromObject, new String[] {"outputMimeType"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"outputCompressionQuality"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"parameters", "outputOptions", "compressionQuality"}, - Common.getValueByPath(fromObject, new String[] {"outputCompressionQuality"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"addWatermark"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"parameters", "addWatermark"}, - Common.getValueByPath(fromObject, new String[] {"addWatermark"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"imageSize"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"parameters", "sampleImageSize"}, - Common.getValueByPath(fromObject, new String[] {"imageSize"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"enhancePrompt"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"parameters", "enhancePrompt"}, - Common.getValueByPath(fromObject, new String[] {"enhancePrompt"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode generateImagesParametersToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"_url", "model"}, - Transformers.tModel( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); - } - - if (Common.getValueByPath(fromObject, new String[] {"prompt"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"instances[0]", "prompt"}, - Common.getValueByPath(fromObject, new String[] {"prompt"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"config"}, - generateImagesConfigToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"config"})), - toObject)); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode imageToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"gcsUri"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"gcsUri"}, - Common.getValueByPath(fromObject, new String[] {"gcsUri"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"imageBytes"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"bytesBase64Encoded"}, - Transformers.tBytes(Common.getValueByPath(fromObject, new String[] {"imageBytes"}))); - } - - if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"mimeType"}, - Common.getValueByPath(fromObject, new String[] {"mimeType"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode maskReferenceConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"maskMode"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"maskMode"}, - Common.getValueByPath(fromObject, new String[] {"maskMode"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"segmentationClasses"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"maskClasses"}, - Common.getValueByPath(fromObject, new String[] {"segmentationClasses"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"maskDilation"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"dilation"}, - Common.getValueByPath(fromObject, new String[] {"maskDilation"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode controlReferenceConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"controlType"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"controlType"}, - Common.getValueByPath(fromObject, new String[] {"controlType"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"enableControlImageComputation"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"computeControl"}, - Common.getValueByPath(fromObject, new String[] {"enableControlImageComputation"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode styleReferenceConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"styleDescription"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"styleDescription"}, - Common.getValueByPath(fromObject, new String[] {"styleDescription"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode subjectReferenceConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"subjectType"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"subjectType"}, - Common.getValueByPath(fromObject, new String[] {"subjectType"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"subjectDescription"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"subjectDescription"}, - Common.getValueByPath(fromObject, new String[] {"subjectDescription"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode referenceImageAPIToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"referenceImage"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"referenceImage"}, - imageToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"referenceImage"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"referenceId"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"referenceId"}, - Common.getValueByPath(fromObject, new String[] {"referenceId"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"referenceType"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"referenceType"}, - Common.getValueByPath(fromObject, new String[] {"referenceType"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"maskImageConfig"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"maskImageConfig"}, - maskReferenceConfigToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"maskImageConfig"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"controlImageConfig"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"controlImageConfig"}, - controlReferenceConfigToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"controlImageConfig"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"styleImageConfig"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"styleImageConfig"}, - styleReferenceConfigToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"styleImageConfig"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"subjectImageConfig"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"subjectImageConfig"}, - subjectReferenceConfigToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"subjectImageConfig"})), - toObject)); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode editImageConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - if (Common.getValueByPath(fromObject, new String[] {"outputGcsUri"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"parameters", "storageUri"}, - Common.getValueByPath(fromObject, new String[] {"outputGcsUri"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"negativePrompt"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"parameters", "negativePrompt"}, - Common.getValueByPath(fromObject, new String[] {"negativePrompt"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"numberOfImages"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"parameters", "sampleCount"}, - Common.getValueByPath(fromObject, new String[] {"numberOfImages"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"aspectRatio"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"parameters", "aspectRatio"}, - Common.getValueByPath(fromObject, new String[] {"aspectRatio"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"guidanceScale"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"parameters", "guidanceScale"}, - Common.getValueByPath(fromObject, new String[] {"guidanceScale"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"seed"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"parameters", "seed"}, - Common.getValueByPath(fromObject, new String[] {"seed"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"safetyFilterLevel"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"parameters", "safetySetting"}, - Common.getValueByPath(fromObject, new String[] {"safetyFilterLevel"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"personGeneration"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"parameters", "personGeneration"}, - Common.getValueByPath(fromObject, new String[] {"personGeneration"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"includeSafetyAttributes"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"parameters", "includeSafetyAttributes"}, - Common.getValueByPath(fromObject, new String[] {"includeSafetyAttributes"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"includeRaiReason"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"parameters", "includeRaiReason"}, - Common.getValueByPath(fromObject, new String[] {"includeRaiReason"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"language"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"parameters", "language"}, - Common.getValueByPath(fromObject, new String[] {"language"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"outputMimeType"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"parameters", "outputOptions", "mimeType"}, - Common.getValueByPath(fromObject, new String[] {"outputMimeType"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"outputCompressionQuality"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"parameters", "outputOptions", "compressionQuality"}, - Common.getValueByPath(fromObject, new String[] {"outputCompressionQuality"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"addWatermark"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"parameters", "addWatermark"}, - Common.getValueByPath(fromObject, new String[] {"addWatermark"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"editMode"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"parameters", "editMode"}, - Common.getValueByPath(fromObject, new String[] {"editMode"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"baseSteps"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"parameters", "editConfig", "baseSteps"}, - Common.getValueByPath(fromObject, new String[] {"baseSteps"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode editImageParametersToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"_url", "model"}, - Transformers.tModel( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); - } - - if (Common.getValueByPath(fromObject, new String[] {"prompt"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"instances[0]", "prompt"}, - Common.getValueByPath(fromObject, new String[] {"prompt"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"referenceImages"}) != null) { - ArrayNode keyArray = - (ArrayNode) Common.getValueByPath(fromObject, new String[] {"referenceImages"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add(referenceImageAPIToVertex(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"instances[0]", "referenceImages"}, result); - } - - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"config"}, - editImageConfigToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"config"})), - toObject)); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode upscaleImageAPIConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - if (Common.getValueByPath(fromObject, new String[] {"includeRaiReason"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"parameters", "includeRaiReason"}, - Common.getValueByPath(fromObject, new String[] {"includeRaiReason"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"outputMimeType"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"parameters", "outputOptions", "mimeType"}, - Common.getValueByPath(fromObject, new String[] {"outputMimeType"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"outputCompressionQuality"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"parameters", "outputOptions", "compressionQuality"}, - Common.getValueByPath(fromObject, new String[] {"outputCompressionQuality"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"enhanceInputImage"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"parameters", "upscaleConfig", "enhanceInputImage"}, - Common.getValueByPath(fromObject, new String[] {"enhanceInputImage"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"imagePreservationFactor"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"parameters", "upscaleConfig", "imagePreservationFactor"}, - Common.getValueByPath(fromObject, new String[] {"imagePreservationFactor"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"numberOfImages"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"parameters", "sampleCount"}, - Common.getValueByPath(fromObject, new String[] {"numberOfImages"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"mode"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"parameters", "mode"}, - Common.getValueByPath(fromObject, new String[] {"mode"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode upscaleImageAPIParametersToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"_url", "model"}, - Transformers.tModel( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); - } - - if (Common.getValueByPath(fromObject, new String[] {"image"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"instances[0]", "image"}, - imageToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"image"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"upscaleFactor"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"parameters", "upscaleConfig", "upscaleFactor"}, - Common.getValueByPath(fromObject, new String[] {"upscaleFactor"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"config"}, - upscaleImageAPIConfigToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"config"})), - toObject)); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode getModelParametersToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"_url", "name"}, - Transformers.tModel( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); - } - - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"config"}, - Common.getValueByPath(fromObject, new String[] {"config"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode listModelsConfigToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - if (Common.getValueByPath(fromObject, new String[] {"pageSize"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"_query", "pageSize"}, - Common.getValueByPath(fromObject, new String[] {"pageSize"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"pageToken"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"_query", "pageToken"}, - Common.getValueByPath(fromObject, new String[] {"pageToken"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"filter"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"_query", "filter"}, - Common.getValueByPath(fromObject, new String[] {"filter"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"queryBase"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"_url", "models_url"}, - Transformers.tModelsUrl( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"queryBase"}))); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode listModelsParametersToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"config"}, - listModelsConfigToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"config"})), - toObject)); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode updateModelConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - if (Common.getValueByPath(fromObject, new String[] {"displayName"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"displayName"}, - Common.getValueByPath(fromObject, new String[] {"displayName"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"description"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"description"}, - Common.getValueByPath(fromObject, new String[] {"description"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"defaultCheckpointId"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"defaultCheckpointId"}, - Common.getValueByPath(fromObject, new String[] {"defaultCheckpointId"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode updateModelParametersToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"_url", "model"}, - Transformers.tModel( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); - } - - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"config"}, - updateModelConfigToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"config"})), - toObject)); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode deleteModelParametersToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"_url", "name"}, - Transformers.tModel( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); - } - - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"config"}, - Common.getValueByPath(fromObject, new String[] {"config"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode countTokensConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - if (Common.getValueByPath(fromObject, new String[] {"systemInstruction"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"systemInstruction"}, - contentToVertex( - JsonSerializable.toJsonNode( - Transformers.tContent( - Common.getValueByPath(fromObject, new String[] {"systemInstruction"}))), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"tools"}) != null) { - ArrayNode keyArray = (ArrayNode) Common.getValueByPath(fromObject, new String[] {"tools"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add(toolToVertex(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(parentObject, new String[] {"tools"}, result); - } - - if (Common.getValueByPath(fromObject, new String[] {"generationConfig"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"generationConfig"}, - Common.getValueByPath(fromObject, new String[] {"generationConfig"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode countTokensParametersToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"_url", "model"}, - Transformers.tModel( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); - } - - if (Common.getValueByPath(fromObject, new String[] {"contents"}) != null) { - ArrayNode keyArray = - (ArrayNode) - Transformers.tContents(Common.getValueByPath(fromObject, new String[] {"contents"})); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add(contentToVertex(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"contents"}, result); - } - - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"config"}, - countTokensConfigToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"config"})), - toObject)); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode computeTokensParametersToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"_url", "model"}, - Transformers.tModel( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); - } - - if (Common.getValueByPath(fromObject, new String[] {"contents"}) != null) { - ArrayNode keyArray = - (ArrayNode) - Transformers.tContents(Common.getValueByPath(fromObject, new String[] {"contents"})); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add(contentToVertex(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"contents"}, result); - } - - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"config"}, - Common.getValueByPath(fromObject, new String[] {"config"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode videoToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"uri"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"gcsUri"}, - Common.getValueByPath(fromObject, new String[] {"uri"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"videoBytes"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"bytesBase64Encoded"}, - Transformers.tBytes(Common.getValueByPath(fromObject, new String[] {"videoBytes"}))); - } - - if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"mimeType"}, - Common.getValueByPath(fromObject, new String[] {"mimeType"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode generateVideosSourceToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode generateVideosConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - if (Common.getValueByPath(fromObject, new String[] {"numberOfVideos"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"parameters", "sampleCount"}, - Common.getValueByPath(fromObject, new String[] {"numberOfVideos"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"outputGcsUri"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"parameters", "storageUri"}, - Common.getValueByPath(fromObject, new String[] {"outputGcsUri"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"fps"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"parameters", "fps"}, - Common.getValueByPath(fromObject, new String[] {"fps"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"durationSeconds"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"parameters", "durationSeconds"}, - Common.getValueByPath(fromObject, new String[] {"durationSeconds"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"seed"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"parameters", "seed"}, - Common.getValueByPath(fromObject, new String[] {"seed"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"aspectRatio"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"parameters", "aspectRatio"}, - Common.getValueByPath(fromObject, new String[] {"aspectRatio"})); + new String[] {"name"}, + Common.getValueByPath(fromObject, new String[] {"name"})); } - if (Common.getValueByPath(fromObject, new String[] {"resolution"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"metadata"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "resolution"}, - Common.getValueByPath(fromObject, new String[] {"resolution"})); + toObject, + new String[] {"metadata"}, + Common.getValueByPath(fromObject, new String[] {"metadata"})); } - if (Common.getValueByPath(fromObject, new String[] {"personGeneration"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"done"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "personGeneration"}, - Common.getValueByPath(fromObject, new String[] {"personGeneration"})); + toObject, + new String[] {"done"}, + Common.getValueByPath(fromObject, new String[] {"done"})); } - if (Common.getValueByPath(fromObject, new String[] {"pubsubTopic"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"error"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "pubsubTopic"}, - Common.getValueByPath(fromObject, new String[] {"pubsubTopic"})); + toObject, + new String[] {"error"}, + Common.getValueByPath(fromObject, new String[] {"error"})); } - if (Common.getValueByPath(fromObject, new String[] {"negativePrompt"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"response"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "negativePrompt"}, - Common.getValueByPath(fromObject, new String[] {"negativePrompt"})); + toObject, + new String[] {"response"}, + generateVideosResponseFromVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"response"})), + toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"enhancePrompt"}) != null) { + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode generateVideosParametersToMldev( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "enhancePrompt"}, - Common.getValueByPath(fromObject, new String[] {"enhancePrompt"})); + toObject, + new String[] {"_url", "model"}, + Transformers.tModel( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); } - if (Common.getValueByPath(fromObject, new String[] {"generateAudio"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"prompt"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "generateAudio"}, - Common.getValueByPath(fromObject, new String[] {"generateAudio"})); + toObject, + new String[] {"instances[0]", "prompt"}, + Common.getValueByPath(fromObject, new String[] {"prompt"})); } - if (Common.getValueByPath(fromObject, new String[] {"lastFrame"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"image"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"instances[0]", "lastFrame"}, - imageToVertex( + toObject, + new String[] {"instances[0]", "image"}, + imageToMldev( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"lastFrame"})), + Common.getValueByPath(fromObject, new String[] {"image"})), toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"compressionQuality"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"video"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "compressionQuality"}, - Common.getValueByPath(fromObject, new String[] {"compressionQuality"})); + toObject, + new String[] {"instances[0]", "video"}, + videoToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"video"})), + toObject)); + } + + if (Common.getValueByPath(fromObject, new String[] {"source"}) != null) { + JsonNode unused = + generateVideosSourceToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"source"})), + toObject); + } + + if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + JsonNode unused = + generateVideosConfigToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"config"})), + toObject); } return toObject; @@ -3960,449 +2504,511 @@ ObjectNode generateVideosParametersToVertex( toObject)); } + if (Common.getValueByPath(fromObject, new String[] {"source"}) != null) { + JsonNode unused = + generateVideosSourceToVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"source"})), + toObject); + } + if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"config"}, + JsonNode unused = generateVideosConfigToVertex( JsonSerializable.toJsonNode( Common.getValueByPath(fromObject, new String[] {"config"})), - toObject)); + toObject); } return toObject; } @ExcludeFromGeneratedCoverageReport - void safetyFilterLevelMldevEnumValidate(Object enumValue) { - ImmutableSet invalidEnumValues = ImmutableSet.of("BLOCK_NONE"); - if (invalidEnumValues.contains(enumValue.toString().replace("\"", ""))) { - throw new IllegalArgumentException( - String.format("%s enum value is not supported in Gemini API.", enumValue)); + ObjectNode generateVideosResponseFromMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"generatedSamples"}) != null) { + ArrayNode keyArray = + (ArrayNode) Common.getValueByPath(fromObject, new String[] {"generatedSamples"}); + ObjectMapper objectMapper = new ObjectMapper(); + ArrayNode result = objectMapper.createArrayNode(); + + for (JsonNode item : keyArray) { + result.add(generatedVideoFromMldev(JsonSerializable.toJsonNode(item), toObject)); + } + Common.setValueByPath(toObject, new String[] {"generatedVideos"}, result); } - } - @ExcludeFromGeneratedCoverageReport - void personGenerationMldevEnumValidate(Object enumValue) { - ImmutableSet invalidEnumValues = ImmutableSet.of("ALLOW_ALL"); - if (invalidEnumValues.contains(enumValue.toString().replace("\"", ""))) { - throw new IllegalArgumentException( - String.format("%s enum value is not supported in Gemini API.", enumValue)); + if (Common.getValueByPath(fromObject, new String[] {"raiMediaFilteredCount"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"raiMediaFilteredCount"}, + Common.getValueByPath(fromObject, new String[] {"raiMediaFilteredCount"})); } - } - @ExcludeFromGeneratedCoverageReport - void behaviorVertexEnumValidate(Object enumValue) { - ImmutableSet invalidEnumValues = - ImmutableSet.of("UNSPECIFIED", "BLOCKING", "NON_BLOCKING"); - if (invalidEnumValues.contains(enumValue.toString().replace("\"", ""))) { - throw new IllegalArgumentException( - String.format("%s enum value is not supported in Vertex AI.", enumValue)); + if (Common.getValueByPath(fromObject, new String[] {"raiMediaFilteredReasons"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"raiMediaFilteredReasons"}, + Common.getValueByPath(fromObject, new String[] {"raiMediaFilteredReasons"})); } + + return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode videoMetadataFromMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode generateVideosResponseFromVertex(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"fps"}) != null) { - Common.setValueByPath( - toObject, new String[] {"fps"}, Common.getValueByPath(fromObject, new String[] {"fps"})); + if (Common.getValueByPath(fromObject, new String[] {"videos"}) != null) { + ArrayNode keyArray = (ArrayNode) Common.getValueByPath(fromObject, new String[] {"videos"}); + ObjectMapper objectMapper = new ObjectMapper(); + ArrayNode result = objectMapper.createArrayNode(); + + for (JsonNode item : keyArray) { + result.add(generatedVideoFromVertex(JsonSerializable.toJsonNode(item), toObject)); + } + Common.setValueByPath(toObject, new String[] {"generatedVideos"}, result); } - if (Common.getValueByPath(fromObject, new String[] {"endOffset"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"raiMediaFilteredCount"}) != null) { Common.setValueByPath( toObject, - new String[] {"endOffset"}, - Common.getValueByPath(fromObject, new String[] {"endOffset"})); + new String[] {"raiMediaFilteredCount"}, + Common.getValueByPath(fromObject, new String[] {"raiMediaFilteredCount"})); } - if (Common.getValueByPath(fromObject, new String[] {"startOffset"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"raiMediaFilteredReasons"}) != null) { Common.setValueByPath( toObject, - new String[] {"startOffset"}, - Common.getValueByPath(fromObject, new String[] {"startOffset"})); + new String[] {"raiMediaFilteredReasons"}, + Common.getValueByPath(fromObject, new String[] {"raiMediaFilteredReasons"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode blobFromMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode generateVideosSourceToMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"prompt"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"instances[0]", "prompt"}, + Common.getValueByPath(fromObject, new String[] {"prompt"})); + } - if (Common.getValueByPath(fromObject, new String[] {"data"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"image"}) != null) { Common.setValueByPath( - toObject, - new String[] {"data"}, - Common.getValueByPath(fromObject, new String[] {"data"})); + parentObject, + new String[] {"instances[0]", "image"}, + imageToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"image"})), + toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"video"}) != null) { Common.setValueByPath( - toObject, - new String[] {"mimeType"}, - Common.getValueByPath(fromObject, new String[] {"mimeType"})); + parentObject, + new String[] {"instances[0]", "video"}, + videoToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"video"})), + toObject)); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode fileDataFromMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode generateVideosSourceToVertex(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"prompt"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"instances[0]", "prompt"}, + Common.getValueByPath(fromObject, new String[] {"prompt"})); + } - if (Common.getValueByPath(fromObject, new String[] {"fileUri"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"image"}) != null) { Common.setValueByPath( - toObject, - new String[] {"fileUri"}, - Common.getValueByPath(fromObject, new String[] {"fileUri"})); + parentObject, + new String[] {"instances[0]", "image"}, + imageToVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"image"})), + toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"video"}) != null) { Common.setValueByPath( - toObject, - new String[] {"mimeType"}, - Common.getValueByPath(fromObject, new String[] {"mimeType"})); + parentObject, + new String[] {"instances[0]", "video"}, + videoToVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"video"})), + toObject)); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode partFromMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode generatedImageFromMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"videoMetadata"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"_self"}) != null) { Common.setValueByPath( toObject, - new String[] {"videoMetadata"}, - videoMetadataFromMldev( + new String[] {"image"}, + imageFromMldev( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"videoMetadata"})), + Common.getValueByPath(fromObject, new String[] {"_self"})), toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"thought"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"raiFilteredReason"}) != null) { Common.setValueByPath( toObject, - new String[] {"thought"}, - Common.getValueByPath(fromObject, new String[] {"thought"})); + new String[] {"raiFilteredReason"}, + Common.getValueByPath(fromObject, new String[] {"raiFilteredReason"})); } - if (Common.getValueByPath(fromObject, new String[] {"inlineData"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"_self"}) != null) { Common.setValueByPath( toObject, - new String[] {"inlineData"}, - blobFromMldev( + new String[] {"safetyAttributes"}, + safetyAttributesFromMldev( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"inlineData"})), + Common.getValueByPath(fromObject, new String[] {"_self"})), toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"fileData"}) != null) { + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode generatedImageFromVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"_self"}) != null) { Common.setValueByPath( toObject, - new String[] {"fileData"}, - fileDataFromMldev( + new String[] {"image"}, + imageFromVertex( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"fileData"})), + Common.getValueByPath(fromObject, new String[] {"_self"})), toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"thoughtSignature"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"thoughtSignature"}, - Common.getValueByPath(fromObject, new String[] {"thoughtSignature"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"codeExecutionResult"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"raiFilteredReason"}) != null) { Common.setValueByPath( - toObject, - new String[] {"codeExecutionResult"}, - Common.getValueByPath(fromObject, new String[] {"codeExecutionResult"})); + toObject, + new String[] {"raiFilteredReason"}, + Common.getValueByPath(fromObject, new String[] {"raiFilteredReason"})); } - if (Common.getValueByPath(fromObject, new String[] {"executableCode"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"_self"}) != null) { Common.setValueByPath( toObject, - new String[] {"executableCode"}, - Common.getValueByPath(fromObject, new String[] {"executableCode"})); + new String[] {"safetyAttributes"}, + safetyAttributesFromVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"_self"})), + toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"functionCall"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"prompt"}) != null) { Common.setValueByPath( toObject, - new String[] {"functionCall"}, - Common.getValueByPath(fromObject, new String[] {"functionCall"})); + new String[] {"enhancedPrompt"}, + Common.getValueByPath(fromObject, new String[] {"prompt"})); } - if (Common.getValueByPath(fromObject, new String[] {"functionResponse"}) != null) { + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode generatedImageMaskFromVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"_self"}) != null) { Common.setValueByPath( toObject, - new String[] {"functionResponse"}, - Common.getValueByPath(fromObject, new String[] {"functionResponse"})); + new String[] {"mask"}, + imageFromVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"_self"})), + toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"text"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"labels"}) != null) { Common.setValueByPath( toObject, - new String[] {"text"}, - Common.getValueByPath(fromObject, new String[] {"text"})); + new String[] {"labels"}, + Common.getValueByPath(fromObject, new String[] {"labels"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode contentFromMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode generatedVideoFromMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"parts"}) != null) { - ArrayNode keyArray = (ArrayNode) Common.getValueByPath(fromObject, new String[] {"parts"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add(partFromMldev(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"parts"}, result); - } - - if (Common.getValueByPath(fromObject, new String[] {"role"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"video"}) != null) { Common.setValueByPath( toObject, - new String[] {"role"}, - Common.getValueByPath(fromObject, new String[] {"role"})); + new String[] {"video"}, + videoFromMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"video"})), + toObject)); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode citationMetadataFromMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode generatedVideoFromVertex(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"citationSources"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"_self"}) != null) { Common.setValueByPath( toObject, - new String[] {"citations"}, - Common.getValueByPath(fromObject, new String[] {"citationSources"})); + new String[] {"video"}, + videoFromVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"_self"})), + toObject)); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode urlMetadataFromMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode generationConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"retrievedUrl"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"modelSelectionConfig"}) != null) { Common.setValueByPath( toObject, - new String[] {"retrievedUrl"}, - Common.getValueByPath(fromObject, new String[] {"retrievedUrl"})); + new String[] {"modelConfig"}, + Common.getValueByPath(fromObject, new String[] {"modelSelectionConfig"})); } - if (Common.getValueByPath(fromObject, new String[] {"urlRetrievalStatus"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"audioTimestamp"}) != null) { Common.setValueByPath( toObject, - new String[] {"urlRetrievalStatus"}, - Common.getValueByPath(fromObject, new String[] {"urlRetrievalStatus"})); + new String[] {"audioTimestamp"}, + Common.getValueByPath(fromObject, new String[] {"audioTimestamp"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode urlContextMetadataFromMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"urlMetadata"}) != null) { - ArrayNode keyArray = - (ArrayNode) Common.getValueByPath(fromObject, new String[] {"urlMetadata"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); + if (Common.getValueByPath(fromObject, new String[] {"candidateCount"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"candidateCount"}, + Common.getValueByPath(fromObject, new String[] {"candidateCount"})); + } - for (JsonNode item : keyArray) { - result.add(urlMetadataFromMldev(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"urlMetadata"}, result); + if (Common.getValueByPath(fromObject, new String[] {"enableAffectiveDialog"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"enableAffectiveDialog"}, + Common.getValueByPath(fromObject, new String[] {"enableAffectiveDialog"})); } - return toObject; - } + if (Common.getValueByPath(fromObject, new String[] {"frequencyPenalty"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"frequencyPenalty"}, + Common.getValueByPath(fromObject, new String[] {"frequencyPenalty"})); + } - @ExcludeFromGeneratedCoverageReport - ObjectNode candidateFromMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"content"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"logprobs"}) != null) { Common.setValueByPath( toObject, - new String[] {"content"}, - contentFromMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"content"})), - toObject)); + new String[] {"logprobs"}, + Common.getValueByPath(fromObject, new String[] {"logprobs"})); } - if (Common.getValueByPath(fromObject, new String[] {"citationMetadata"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"maxOutputTokens"}) != null) { Common.setValueByPath( toObject, - new String[] {"citationMetadata"}, - citationMetadataFromMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"citationMetadata"})), - toObject)); + new String[] {"maxOutputTokens"}, + Common.getValueByPath(fromObject, new String[] {"maxOutputTokens"})); } - if (Common.getValueByPath(fromObject, new String[] {"tokenCount"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"mediaResolution"}) != null) { Common.setValueByPath( toObject, - new String[] {"tokenCount"}, - Common.getValueByPath(fromObject, new String[] {"tokenCount"})); + new String[] {"mediaResolution"}, + Common.getValueByPath(fromObject, new String[] {"mediaResolution"})); } - if (Common.getValueByPath(fromObject, new String[] {"finishReason"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"presencePenalty"}) != null) { Common.setValueByPath( toObject, - new String[] {"finishReason"}, - Common.getValueByPath(fromObject, new String[] {"finishReason"})); + new String[] {"presencePenalty"}, + Common.getValueByPath(fromObject, new String[] {"presencePenalty"})); } - if (Common.getValueByPath(fromObject, new String[] {"urlContextMetadata"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"responseJsonSchema"}) != null) { Common.setValueByPath( toObject, - new String[] {"urlContextMetadata"}, - urlContextMetadataFromMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"urlContextMetadata"})), - toObject)); + new String[] {"responseJsonSchema"}, + Common.getValueByPath(fromObject, new String[] {"responseJsonSchema"})); } - if (Common.getValueByPath(fromObject, new String[] {"avgLogprobs"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"responseLogprobs"}) != null) { Common.setValueByPath( toObject, - new String[] {"avgLogprobs"}, - Common.getValueByPath(fromObject, new String[] {"avgLogprobs"})); + new String[] {"responseLogprobs"}, + Common.getValueByPath(fromObject, new String[] {"responseLogprobs"})); } - if (Common.getValueByPath(fromObject, new String[] {"groundingMetadata"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"responseMimeType"}) != null) { Common.setValueByPath( toObject, - new String[] {"groundingMetadata"}, - Common.getValueByPath(fromObject, new String[] {"groundingMetadata"})); + new String[] {"responseMimeType"}, + Common.getValueByPath(fromObject, new String[] {"responseMimeType"})); } - if (Common.getValueByPath(fromObject, new String[] {"index"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"responseModalities"}) != null) { Common.setValueByPath( toObject, - new String[] {"index"}, - Common.getValueByPath(fromObject, new String[] {"index"})); + new String[] {"responseModalities"}, + Common.getValueByPath(fromObject, new String[] {"responseModalities"})); } - if (Common.getValueByPath(fromObject, new String[] {"logprobsResult"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"responseSchema"}) != null) { Common.setValueByPath( toObject, - new String[] {"logprobsResult"}, - Common.getValueByPath(fromObject, new String[] {"logprobsResult"})); + new String[] {"responseSchema"}, + Common.getValueByPath(fromObject, new String[] {"responseSchema"})); } - if (Common.getValueByPath(fromObject, new String[] {"safetyRatings"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"routingConfig"}) != null) { Common.setValueByPath( toObject, - new String[] {"safetyRatings"}, - Common.getValueByPath(fromObject, new String[] {"safetyRatings"})); + new String[] {"routingConfig"}, + Common.getValueByPath(fromObject, new String[] {"routingConfig"})); } - return toObject; - } + if (Common.getValueByPath(fromObject, new String[] {"seed"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"seed"}, + Common.getValueByPath(fromObject, new String[] {"seed"})); + } - @ExcludeFromGeneratedCoverageReport - ObjectNode generateContentResponseFromMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"speechConfig"}) != null) { Common.setValueByPath( toObject, - new String[] {"sdkHttpResponse"}, - Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"})); + new String[] {"speechConfig"}, + speechConfigToVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"speechConfig"})), + toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"candidates"}) != null) { - ArrayNode keyArray = - (ArrayNode) Common.getValueByPath(fromObject, new String[] {"candidates"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); + if (Common.getValueByPath(fromObject, new String[] {"stopSequences"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"stopSequences"}, + Common.getValueByPath(fromObject, new String[] {"stopSequences"})); + } - for (JsonNode item : keyArray) { - result.add(candidateFromMldev(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"candidates"}, result); + if (Common.getValueByPath(fromObject, new String[] {"temperature"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"temperature"}, + Common.getValueByPath(fromObject, new String[] {"temperature"})); } - if (Common.getValueByPath(fromObject, new String[] {"modelVersion"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"thinkingConfig"}) != null) { Common.setValueByPath( toObject, - new String[] {"modelVersion"}, - Common.getValueByPath(fromObject, new String[] {"modelVersion"})); + new String[] {"thinkingConfig"}, + Common.getValueByPath(fromObject, new String[] {"thinkingConfig"})); } - if (Common.getValueByPath(fromObject, new String[] {"promptFeedback"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"topK"}) != null) { Common.setValueByPath( toObject, - new String[] {"promptFeedback"}, - Common.getValueByPath(fromObject, new String[] {"promptFeedback"})); + new String[] {"topK"}, + Common.getValueByPath(fromObject, new String[] {"topK"})); } - if (Common.getValueByPath(fromObject, new String[] {"usageMetadata"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"topP"}) != null) { Common.setValueByPath( toObject, - new String[] {"usageMetadata"}, - Common.getValueByPath(fromObject, new String[] {"usageMetadata"})); + new String[] {"topP"}, + Common.getValueByPath(fromObject, new String[] {"topP"})); + } + + if (!Common.isZero( + Common.getValueByPath(fromObject, new String[] {"enableEnhancedCivicAnswers"}))) { + throw new IllegalArgumentException( + "enableEnhancedCivicAnswers parameter is not supported in Vertex AI."); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode contentEmbeddingFromMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode getModelParametersToMldev( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"values"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { Common.setValueByPath( toObject, - new String[] {"values"}, - Common.getValueByPath(fromObject, new String[] {"values"})); + new String[] {"_url", "name"}, + Transformers.tModel( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode embedContentMetadataFromMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode getModelParametersToVertex( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"_url", "name"}, + Transformers.tModel( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); + } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode embedContentResponseFromMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode googleMapsToMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"authConfig"}))) { + throw new IllegalArgumentException("authConfig parameter is not supported in Gemini API."); + } - if (Common.getValueByPath(fromObject, new String[] {"embeddings"}) != null) { - ArrayNode keyArray = - (ArrayNode) Common.getValueByPath(fromObject, new String[] {"embeddings"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); + if (Common.getValueByPath(fromObject, new String[] {"enableWidget"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"enableWidget"}, + Common.getValueByPath(fromObject, new String[] {"enableWidget"})); + } + + return toObject; + } - for (JsonNode item : keyArray) { - result.add(contentEmbeddingFromMldev(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"embeddings"}, result); + @ExcludeFromGeneratedCoverageReport + ObjectNode googleSearchToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"excludeDomains"}))) { + throw new IllegalArgumentException( + "excludeDomains parameter is not supported in Gemini API."); } - if (Common.getValueByPath(fromObject, new String[] {"metadata"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"timeRangeFilter"}) != null) { Common.setValueByPath( toObject, - new String[] {"metadata"}, - embedContentMetadataFromMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"metadata"})), - toObject)); + new String[] {"timeRangeFilter"}, + Common.getValueByPath(fromObject, new String[] {"timeRangeFilter"})); } return toObject; @@ -4431,184 +3037,185 @@ ObjectNode imageFromMldev(JsonNode fromObject, ObjectNode parentObject) { } @ExcludeFromGeneratedCoverageReport - ObjectNode safetyAttributesFromMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode imageFromVertex(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"safetyAttributes", "categories"}) - != null) { + if (Common.getValueByPath(fromObject, new String[] {"gcsUri"}) != null) { Common.setValueByPath( toObject, - new String[] {"categories"}, - Common.getValueByPath(fromObject, new String[] {"safetyAttributes", "categories"})); + new String[] {"gcsUri"}, + Common.getValueByPath(fromObject, new String[] {"gcsUri"})); } - if (Common.getValueByPath(fromObject, new String[] {"safetyAttributes", "scores"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"bytesBase64Encoded"}) != null) { Common.setValueByPath( toObject, - new String[] {"scores"}, - Common.getValueByPath(fromObject, new String[] {"safetyAttributes", "scores"})); + new String[] {"imageBytes"}, + Transformers.tBytes( + Common.getValueByPath(fromObject, new String[] {"bytesBase64Encoded"}))); } - if (Common.getValueByPath(fromObject, new String[] {"contentType"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { Common.setValueByPath( toObject, - new String[] {"contentType"}, - Common.getValueByPath(fromObject, new String[] {"contentType"})); + new String[] {"mimeType"}, + Common.getValueByPath(fromObject, new String[] {"mimeType"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode generatedImageFromMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode imageToMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"_self"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"image"}, - imageFromMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"_self"})), - toObject)); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"gcsUri"}))) { + throw new IllegalArgumentException("gcsUri parameter is not supported in Gemini API."); } - if (Common.getValueByPath(fromObject, new String[] {"raiFilteredReason"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"imageBytes"}) != null) { Common.setValueByPath( toObject, - new String[] {"raiFilteredReason"}, - Common.getValueByPath(fromObject, new String[] {"raiFilteredReason"})); + new String[] {"bytesBase64Encoded"}, + Transformers.tBytes(Common.getValueByPath(fromObject, new String[] {"imageBytes"}))); } - if (Common.getValueByPath(fromObject, new String[] {"_self"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { Common.setValueByPath( toObject, - new String[] {"safetyAttributes"}, - safetyAttributesFromMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"_self"})), - toObject)); + new String[] {"mimeType"}, + Common.getValueByPath(fromObject, new String[] {"mimeType"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode generateImagesResponseFromMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode imageToVertex(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"gcsUri"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"gcsUri"}, + Common.getValueByPath(fromObject, new String[] {"gcsUri"})); + } - if (Common.getValueByPath(fromObject, new String[] {"predictions"}) != null) { - ArrayNode keyArray = - (ArrayNode) Common.getValueByPath(fromObject, new String[] {"predictions"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add(generatedImageFromMldev(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"generatedImages"}, result); + if (Common.getValueByPath(fromObject, new String[] {"imageBytes"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"bytesBase64Encoded"}, + Transformers.tBytes(Common.getValueByPath(fromObject, new String[] {"imageBytes"}))); } - if (Common.getValueByPath(fromObject, new String[] {"positivePromptSafetyAttributes"}) - != null) { + if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { Common.setValueByPath( toObject, - new String[] {"positivePromptSafetyAttributes"}, - safetyAttributesFromMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath( - fromObject, new String[] {"positivePromptSafetyAttributes"})), - toObject)); + new String[] {"mimeType"}, + Common.getValueByPath(fromObject, new String[] {"mimeType"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode tunedModelInfoFromMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode listModelsConfigToMldev( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"baseModel"}) != null) { + + if (Common.getValueByPath(fromObject, new String[] {"pageSize"}) != null) { Common.setValueByPath( - toObject, - new String[] {"baseModel"}, - Common.getValueByPath(fromObject, new String[] {"baseModel"})); + parentObject, + new String[] {"_query", "pageSize"}, + Common.getValueByPath(fromObject, new String[] {"pageSize"})); } - if (Common.getValueByPath(fromObject, new String[] {"createTime"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"pageToken"}) != null) { Common.setValueByPath( - toObject, - new String[] {"createTime"}, - Common.getValueByPath(fromObject, new String[] {"createTime"})); + parentObject, + new String[] {"_query", "pageToken"}, + Common.getValueByPath(fromObject, new String[] {"pageToken"})); } - if (Common.getValueByPath(fromObject, new String[] {"updateTime"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"filter"}) != null) { Common.setValueByPath( - toObject, - new String[] {"updateTime"}, - Common.getValueByPath(fromObject, new String[] {"updateTime"})); + parentObject, + new String[] {"_query", "filter"}, + Common.getValueByPath(fromObject, new String[] {"filter"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"queryBase"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"_url", "models_url"}, + Transformers.tModelsUrl( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"queryBase"}))); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode modelFromMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode listModelsConfigToVertex( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"name"}, - Common.getValueByPath(fromObject, new String[] {"name"})); - } - if (Common.getValueByPath(fromObject, new String[] {"displayName"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"pageSize"}) != null) { Common.setValueByPath( - toObject, - new String[] {"displayName"}, - Common.getValueByPath(fromObject, new String[] {"displayName"})); + parentObject, + new String[] {"_query", "pageSize"}, + Common.getValueByPath(fromObject, new String[] {"pageSize"})); } - if (Common.getValueByPath(fromObject, new String[] {"description"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"pageToken"}) != null) { Common.setValueByPath( - toObject, - new String[] {"description"}, - Common.getValueByPath(fromObject, new String[] {"description"})); + parentObject, + new String[] {"_query", "pageToken"}, + Common.getValueByPath(fromObject, new String[] {"pageToken"})); } - if (Common.getValueByPath(fromObject, new String[] {"version"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"filter"}) != null) { Common.setValueByPath( - toObject, - new String[] {"version"}, - Common.getValueByPath(fromObject, new String[] {"version"})); + parentObject, + new String[] {"_query", "filter"}, + Common.getValueByPath(fromObject, new String[] {"filter"})); } - if (Common.getValueByPath(fromObject, new String[] {"_self"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"queryBase"}) != null) { Common.setValueByPath( - toObject, - new String[] {"tunedModelInfo"}, - tunedModelInfoFromMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"_self"})), - toObject)); + parentObject, + new String[] {"_url", "models_url"}, + Transformers.tModelsUrl( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"queryBase"}))); } - if (Common.getValueByPath(fromObject, new String[] {"inputTokenLimit"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"inputTokenLimit"}, - Common.getValueByPath(fromObject, new String[] {"inputTokenLimit"})); - } + return toObject; + } - if (Common.getValueByPath(fromObject, new String[] {"outputTokenLimit"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"outputTokenLimit"}, - Common.getValueByPath(fromObject, new String[] {"outputTokenLimit"})); + @ExcludeFromGeneratedCoverageReport + ObjectNode listModelsParametersToMldev( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + JsonNode unused = + listModelsConfigToMldev( + apiClient, + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"config"})), + toObject); } - if (Common.getValueByPath(fromObject, new String[] {"supportedGenerationMethods"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"supportedActions"}, - Common.getValueByPath(fromObject, new String[] {"supportedGenerationMethods"})); + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode listModelsParametersToVertex( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + JsonNode unused = + listModelsConfigToVertex( + apiClient, + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"config"})), + toObject); } return toObject; @@ -4617,6 +3224,12 @@ ObjectNode modelFromMldev(JsonNode fromObject, ObjectNode parentObject) { @ExcludeFromGeneratedCoverageReport ObjectNode listModelsResponseFromMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"sdkHttpResponse"}, + Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"})); + } if (Common.getValueByPath(fromObject, new String[] {"nextPageToken"}) != null) { Common.setValueByPath( @@ -4643,111 +3256,130 @@ ObjectNode listModelsResponseFromMldev(JsonNode fromObject, ObjectNode parentObj } @ExcludeFromGeneratedCoverageReport - ObjectNode deleteModelResponseFromMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode listModelsResponseFromVertex(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"sdkHttpResponse"}, + Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"nextPageToken"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"nextPageToken"}, + Common.getValueByPath(fromObject, new String[] {"nextPageToken"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"_self"}) != null) { + ArrayNode keyArray = + (ArrayNode) + Transformers.tExtractModels( + Common.getValueByPath(fromObject, new String[] {"_self"})); + ObjectMapper objectMapper = new ObjectMapper(); + ArrayNode result = objectMapper.createArrayNode(); + + for (JsonNode item : keyArray) { + result.add(modelFromVertex(JsonSerializable.toJsonNode(item), toObject)); + } + Common.setValueByPath(toObject, new String[] {"models"}, result); + } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode countTokensResponseFromMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode maskReferenceConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"maskMode"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"maskMode"}, + Common.getValueByPath(fromObject, new String[] {"maskMode"})); + } - if (Common.getValueByPath(fromObject, new String[] {"totalTokens"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"segmentationClasses"}) != null) { Common.setValueByPath( toObject, - new String[] {"totalTokens"}, - Common.getValueByPath(fromObject, new String[] {"totalTokens"})); + new String[] {"maskClasses"}, + Common.getValueByPath(fromObject, new String[] {"segmentationClasses"})); } - if (Common.getValueByPath(fromObject, new String[] {"cachedContentTokenCount"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"maskDilation"}) != null) { Common.setValueByPath( toObject, - new String[] {"cachedContentTokenCount"}, - Common.getValueByPath(fromObject, new String[] {"cachedContentTokenCount"})); + new String[] {"dilation"}, + Common.getValueByPath(fromObject, new String[] {"maskDilation"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode videoFromMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode modelFromMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"video", "uri"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { Common.setValueByPath( toObject, - new String[] {"uri"}, - Common.getValueByPath(fromObject, new String[] {"video", "uri"})); + new String[] {"name"}, + Common.getValueByPath(fromObject, new String[] {"name"})); } - if (Common.getValueByPath(fromObject, new String[] {"video", "encodedVideo"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"displayName"}) != null) { Common.setValueByPath( toObject, - new String[] {"videoBytes"}, - Transformers.tBytes( - Common.getValueByPath(fromObject, new String[] {"video", "encodedVideo"}))); + new String[] {"displayName"}, + Common.getValueByPath(fromObject, new String[] {"displayName"})); } - if (Common.getValueByPath(fromObject, new String[] {"encoding"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"description"}) != null) { Common.setValueByPath( toObject, - new String[] {"mimeType"}, - Common.getValueByPath(fromObject, new String[] {"encoding"})); + new String[] {"description"}, + Common.getValueByPath(fromObject, new String[] {"description"})); } - return toObject; - } + if (Common.getValueByPath(fromObject, new String[] {"version"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"version"}, + Common.getValueByPath(fromObject, new String[] {"version"})); + } - @ExcludeFromGeneratedCoverageReport - ObjectNode generatedVideoFromMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); if (Common.getValueByPath(fromObject, new String[] {"_self"}) != null) { Common.setValueByPath( toObject, - new String[] {"video"}, - videoFromMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"_self"})), - toObject)); + new String[] {"tunedModelInfo"}, + Common.getValueByPath(fromObject, new String[] {"_self"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode generateVideosResponseFromMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"generatedSamples"}) != null) { - ArrayNode keyArray = - (ArrayNode) Common.getValueByPath(fromObject, new String[] {"generatedSamples"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add(generatedVideoFromMldev(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"generatedVideos"}, result); + if (Common.getValueByPath(fromObject, new String[] {"inputTokenLimit"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"inputTokenLimit"}, + Common.getValueByPath(fromObject, new String[] {"inputTokenLimit"})); } - if (Common.getValueByPath(fromObject, new String[] {"raiMediaFilteredCount"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"outputTokenLimit"}) != null) { Common.setValueByPath( toObject, - new String[] {"raiMediaFilteredCount"}, - Common.getValueByPath(fromObject, new String[] {"raiMediaFilteredCount"})); + new String[] {"outputTokenLimit"}, + Common.getValueByPath(fromObject, new String[] {"outputTokenLimit"})); } - if (Common.getValueByPath(fromObject, new String[] {"raiMediaFilteredReasons"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"supportedGenerationMethods"}) != null) { Common.setValueByPath( toObject, - new String[] {"raiMediaFilteredReasons"}, - Common.getValueByPath(fromObject, new String[] {"raiMediaFilteredReasons"})); + new String[] {"supportedActions"}, + Common.getValueByPath(fromObject, new String[] {"supportedGenerationMethods"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode generateVideosOperationFromMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode modelFromVertex(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { Common.setValueByPath( @@ -4756,692 +3388,795 @@ ObjectNode generateVideosOperationFromMldev(JsonNode fromObject, ObjectNode pare Common.getValueByPath(fromObject, new String[] {"name"})); } - if (Common.getValueByPath(fromObject, new String[] {"metadata"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"displayName"}) != null) { Common.setValueByPath( toObject, - new String[] {"metadata"}, - Common.getValueByPath(fromObject, new String[] {"metadata"})); + new String[] {"displayName"}, + Common.getValueByPath(fromObject, new String[] {"displayName"})); } - if (Common.getValueByPath(fromObject, new String[] {"done"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"description"}) != null) { Common.setValueByPath( toObject, - new String[] {"done"}, - Common.getValueByPath(fromObject, new String[] {"done"})); + new String[] {"description"}, + Common.getValueByPath(fromObject, new String[] {"description"})); } - if (Common.getValueByPath(fromObject, new String[] {"error"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"versionId"}) != null) { Common.setValueByPath( toObject, - new String[] {"error"}, - Common.getValueByPath(fromObject, new String[] {"error"})); + new String[] {"version"}, + Common.getValueByPath(fromObject, new String[] {"versionId"})); } - if (Common.getValueByPath(fromObject, new String[] {"response", "generateVideoResponse"}) - != null) { + if (Common.getValueByPath(fromObject, new String[] {"deployedModels"}) != null) { + ArrayNode keyArray = + (ArrayNode) Common.getValueByPath(fromObject, new String[] {"deployedModels"}); + ObjectMapper objectMapper = new ObjectMapper(); + ArrayNode result = objectMapper.createArrayNode(); + + for (JsonNode item : keyArray) { + result.add(endpointFromVertex(JsonSerializable.toJsonNode(item), toObject)); + } + Common.setValueByPath(toObject, new String[] {"endpoints"}, result); + } + + if (Common.getValueByPath(fromObject, new String[] {"labels"}) != null) { Common.setValueByPath( toObject, - new String[] {"response"}, - generateVideosResponseFromMldev( + new String[] {"labels"}, + Common.getValueByPath(fromObject, new String[] {"labels"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"_self"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"tunedModelInfo"}, + tunedModelInfoFromVertex( JsonSerializable.toJsonNode( - Common.getValueByPath( - fromObject, new String[] {"response", "generateVideoResponse"})), + Common.getValueByPath(fromObject, new String[] {"_self"})), toObject)); } + if (Common.getValueByPath(fromObject, new String[] {"defaultCheckpointId"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"defaultCheckpointId"}, + Common.getValueByPath(fromObject, new String[] {"defaultCheckpointId"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"checkpoints"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"checkpoints"}, + Common.getValueByPath(fromObject, new String[] {"checkpoints"})); + } + return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode videoMetadataFromVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode partToMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"fps"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"functionCall"}) != null) { Common.setValueByPath( - toObject, new String[] {"fps"}, Common.getValueByPath(fromObject, new String[] {"fps"})); + toObject, + new String[] {"functionCall"}, + Common.getValueByPath(fromObject, new String[] {"functionCall"})); } - if (Common.getValueByPath(fromObject, new String[] {"endOffset"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"codeExecutionResult"}) != null) { Common.setValueByPath( toObject, - new String[] {"endOffset"}, - Common.getValueByPath(fromObject, new String[] {"endOffset"})); + new String[] {"codeExecutionResult"}, + Common.getValueByPath(fromObject, new String[] {"codeExecutionResult"})); } - if (Common.getValueByPath(fromObject, new String[] {"startOffset"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"executableCode"}) != null) { Common.setValueByPath( toObject, - new String[] {"startOffset"}, - Common.getValueByPath(fromObject, new String[] {"startOffset"})); + new String[] {"executableCode"}, + Common.getValueByPath(fromObject, new String[] {"executableCode"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode blobFromVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"displayName"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"fileData"}) != null) { Common.setValueByPath( toObject, - new String[] {"displayName"}, - Common.getValueByPath(fromObject, new String[] {"displayName"})); + new String[] {"fileData"}, + fileDataToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"fileData"})), + toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"data"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"functionResponse"}) != null) { Common.setValueByPath( toObject, - new String[] {"data"}, - Common.getValueByPath(fromObject, new String[] {"data"})); + new String[] {"functionResponse"}, + Common.getValueByPath(fromObject, new String[] {"functionResponse"})); } - if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"inlineData"}) != null) { Common.setValueByPath( toObject, - new String[] {"mimeType"}, - Common.getValueByPath(fromObject, new String[] {"mimeType"})); + new String[] {"inlineData"}, + blobToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"inlineData"})), + toObject)); } - return toObject; - } + if (Common.getValueByPath(fromObject, new String[] {"text"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"text"}, + Common.getValueByPath(fromObject, new String[] {"text"})); + } - @ExcludeFromGeneratedCoverageReport - ObjectNode fileDataFromVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"displayName"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"thought"}) != null) { Common.setValueByPath( toObject, - new String[] {"displayName"}, - Common.getValueByPath(fromObject, new String[] {"displayName"})); + new String[] {"thought"}, + Common.getValueByPath(fromObject, new String[] {"thought"})); } - if (Common.getValueByPath(fromObject, new String[] {"fileUri"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"thoughtSignature"}) != null) { Common.setValueByPath( toObject, - new String[] {"fileUri"}, - Common.getValueByPath(fromObject, new String[] {"fileUri"})); + new String[] {"thoughtSignature"}, + Common.getValueByPath(fromObject, new String[] {"thoughtSignature"})); } - if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"videoMetadata"}) != null) { Common.setValueByPath( toObject, - new String[] {"mimeType"}, - Common.getValueByPath(fromObject, new String[] {"mimeType"})); + new String[] {"videoMetadata"}, + Common.getValueByPath(fromObject, new String[] {"videoMetadata"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode partFromVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode productImageToVertex(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"videoMetadata"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"productImage"}) != null) { Common.setValueByPath( toObject, - new String[] {"videoMetadata"}, - videoMetadataFromVertex( + new String[] {"image"}, + imageToVertex( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"videoMetadata"})), + Common.getValueByPath(fromObject, new String[] {"productImage"})), toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"thought"}) != null) { + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode recontextImageConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + + if (Common.getValueByPath(fromObject, new String[] {"numberOfImages"}) != null) { Common.setValueByPath( - toObject, - new String[] {"thought"}, - Common.getValueByPath(fromObject, new String[] {"thought"})); + parentObject, + new String[] {"parameters", "sampleCount"}, + Common.getValueByPath(fromObject, new String[] {"numberOfImages"})); } - if (Common.getValueByPath(fromObject, new String[] {"inlineData"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"baseSteps"}) != null) { Common.setValueByPath( - toObject, - new String[] {"inlineData"}, - blobFromVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"inlineData"})), - toObject)); + parentObject, + new String[] {"parameters", "editConfig", "baseSteps"}, + Common.getValueByPath(fromObject, new String[] {"baseSteps"})); } - if (Common.getValueByPath(fromObject, new String[] {"fileData"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"outputGcsUri"}) != null) { Common.setValueByPath( - toObject, - new String[] {"fileData"}, - fileDataFromVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"fileData"})), - toObject)); + parentObject, + new String[] {"parameters", "storageUri"}, + Common.getValueByPath(fromObject, new String[] {"outputGcsUri"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"seed"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"parameters", "seed"}, + Common.getValueByPath(fromObject, new String[] {"seed"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"safetyFilterLevel"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"parameters", "safetySetting"}, + Common.getValueByPath(fromObject, new String[] {"safetyFilterLevel"})); } - if (Common.getValueByPath(fromObject, new String[] {"thoughtSignature"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"personGeneration"}) != null) { Common.setValueByPath( - toObject, - new String[] {"thoughtSignature"}, - Common.getValueByPath(fromObject, new String[] {"thoughtSignature"})); + parentObject, + new String[] {"parameters", "personGeneration"}, + Common.getValueByPath(fromObject, new String[] {"personGeneration"})); } - if (Common.getValueByPath(fromObject, new String[] {"codeExecutionResult"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"addWatermark"}) != null) { Common.setValueByPath( - toObject, - new String[] {"codeExecutionResult"}, - Common.getValueByPath(fromObject, new String[] {"codeExecutionResult"})); + parentObject, + new String[] {"parameters", "addWatermark"}, + Common.getValueByPath(fromObject, new String[] {"addWatermark"})); } - if (Common.getValueByPath(fromObject, new String[] {"executableCode"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"outputMimeType"}) != null) { Common.setValueByPath( - toObject, - new String[] {"executableCode"}, - Common.getValueByPath(fromObject, new String[] {"executableCode"})); + parentObject, + new String[] {"parameters", "outputOptions", "mimeType"}, + Common.getValueByPath(fromObject, new String[] {"outputMimeType"})); } - if (Common.getValueByPath(fromObject, new String[] {"functionCall"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"outputCompressionQuality"}) != null) { Common.setValueByPath( - toObject, - new String[] {"functionCall"}, - Common.getValueByPath(fromObject, new String[] {"functionCall"})); + parentObject, + new String[] {"parameters", "outputOptions", "compressionQuality"}, + Common.getValueByPath(fromObject, new String[] {"outputCompressionQuality"})); } - if (Common.getValueByPath(fromObject, new String[] {"functionResponse"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"enhancePrompt"}) != null) { Common.setValueByPath( - toObject, - new String[] {"functionResponse"}, - Common.getValueByPath(fromObject, new String[] {"functionResponse"})); + parentObject, + new String[] {"parameters", "enhancePrompt"}, + Common.getValueByPath(fromObject, new String[] {"enhancePrompt"})); } - if (Common.getValueByPath(fromObject, new String[] {"text"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"labels"}) != null) { Common.setValueByPath( - toObject, - new String[] {"text"}, - Common.getValueByPath(fromObject, new String[] {"text"})); + parentObject, + new String[] {"labels"}, + Common.getValueByPath(fromObject, new String[] {"labels"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode contentFromVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode recontextImageParametersToVertex( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"parts"}) != null) { - ArrayNode keyArray = (ArrayNode) Common.getValueByPath(fromObject, new String[] {"parts"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); + if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"_url", "model"}, + Transformers.tModel( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); + } - for (JsonNode item : keyArray) { - result.add(partFromVertex(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"parts"}, result); + if (Common.getValueByPath(fromObject, new String[] {"source"}) != null) { + JsonNode unused = + recontextImageSourceToVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"source"})), + toObject); } - if (Common.getValueByPath(fromObject, new String[] {"role"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"role"}, - Common.getValueByPath(fromObject, new String[] {"role"})); + if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + JsonNode unused = + recontextImageConfigToVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"config"})), + toObject); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode citationMetadataFromVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode recontextImageResponseFromVertex(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"citations"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"citations"}, - Common.getValueByPath(fromObject, new String[] {"citations"})); + if (Common.getValueByPath(fromObject, new String[] {"predictions"}) != null) { + ArrayNode keyArray = + (ArrayNode) Common.getValueByPath(fromObject, new String[] {"predictions"}); + ObjectMapper objectMapper = new ObjectMapper(); + ArrayNode result = objectMapper.createArrayNode(); + + for (JsonNode item : keyArray) { + result.add(generatedImageFromVertex(JsonSerializable.toJsonNode(item), toObject)); + } + Common.setValueByPath(toObject, new String[] {"generatedImages"}, result); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode urlMetadataFromVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode recontextImageSourceToVertex(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"retrievedUrl"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"prompt"}) != null) { Common.setValueByPath( - toObject, - new String[] {"retrievedUrl"}, - Common.getValueByPath(fromObject, new String[] {"retrievedUrl"})); + parentObject, + new String[] {"instances[0]", "prompt"}, + Common.getValueByPath(fromObject, new String[] {"prompt"})); } - if (Common.getValueByPath(fromObject, new String[] {"urlRetrievalStatus"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"personImage"}) != null) { Common.setValueByPath( - toObject, - new String[] {"urlRetrievalStatus"}, - Common.getValueByPath(fromObject, new String[] {"urlRetrievalStatus"})); + parentObject, + new String[] {"instances[0]", "personImage", "image"}, + imageToVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"personImage"})), + toObject)); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode urlContextMetadataFromVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"urlMetadata"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"productImages"}) != null) { ArrayNode keyArray = - (ArrayNode) Common.getValueByPath(fromObject, new String[] {"urlMetadata"}); + (ArrayNode) Common.getValueByPath(fromObject, new String[] {"productImages"}); ObjectMapper objectMapper = new ObjectMapper(); ArrayNode result = objectMapper.createArrayNode(); for (JsonNode item : keyArray) { - result.add(urlMetadataFromVertex(JsonSerializable.toJsonNode(item), toObject)); + result.add(productImageToVertex(JsonSerializable.toJsonNode(item), toObject)); } - Common.setValueByPath(toObject, new String[] {"urlMetadata"}, result); + Common.setValueByPath(parentObject, new String[] {"instances[0]", "productImages"}, result); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode candidateFromVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode referenceImageAPIToVertex(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"content"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"referenceImage"}) != null) { Common.setValueByPath( toObject, - new String[] {"content"}, - contentFromVertex( + new String[] {"referenceImage"}, + imageToVertex( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"content"})), + Common.getValueByPath(fromObject, new String[] {"referenceImage"})), toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"citationMetadata"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"referenceId"}) != null) { Common.setValueByPath( toObject, - new String[] {"citationMetadata"}, - citationMetadataFromVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"citationMetadata"})), - toObject)); + new String[] {"referenceId"}, + Common.getValueByPath(fromObject, new String[] {"referenceId"})); } - if (Common.getValueByPath(fromObject, new String[] {"finishMessage"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"referenceType"}) != null) { Common.setValueByPath( toObject, - new String[] {"finishMessage"}, - Common.getValueByPath(fromObject, new String[] {"finishMessage"})); + new String[] {"referenceType"}, + Common.getValueByPath(fromObject, new String[] {"referenceType"})); } - if (Common.getValueByPath(fromObject, new String[] {"finishReason"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"maskImageConfig"}) != null) { Common.setValueByPath( toObject, - new String[] {"finishReason"}, - Common.getValueByPath(fromObject, new String[] {"finishReason"})); + new String[] {"maskImageConfig"}, + maskReferenceConfigToVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"maskImageConfig"})), + toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"urlContextMetadata"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"controlImageConfig"}) != null) { Common.setValueByPath( toObject, - new String[] {"urlContextMetadata"}, - urlContextMetadataFromVertex( + new String[] {"controlImageConfig"}, + controlReferenceConfigToVertex( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"urlContextMetadata"})), + Common.getValueByPath(fromObject, new String[] {"controlImageConfig"})), toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"avgLogprobs"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"styleImageConfig"}) != null) { Common.setValueByPath( toObject, - new String[] {"avgLogprobs"}, - Common.getValueByPath(fromObject, new String[] {"avgLogprobs"})); + new String[] {"styleImageConfig"}, + Common.getValueByPath(fromObject, new String[] {"styleImageConfig"})); } - if (Common.getValueByPath(fromObject, new String[] {"groundingMetadata"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"subjectImageConfig"}) != null) { Common.setValueByPath( toObject, - new String[] {"groundingMetadata"}, - Common.getValueByPath(fromObject, new String[] {"groundingMetadata"})); + new String[] {"subjectImageConfig"}, + Common.getValueByPath(fromObject, new String[] {"subjectImageConfig"})); } - if (Common.getValueByPath(fromObject, new String[] {"index"}) != null) { + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode safetyAttributesFromMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"safetyAttributes", "categories"}) + != null) { Common.setValueByPath( toObject, - new String[] {"index"}, - Common.getValueByPath(fromObject, new String[] {"index"})); + new String[] {"categories"}, + Common.getValueByPath(fromObject, new String[] {"safetyAttributes", "categories"})); } - if (Common.getValueByPath(fromObject, new String[] {"logprobsResult"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"safetyAttributes", "scores"}) != null) { Common.setValueByPath( toObject, - new String[] {"logprobsResult"}, - Common.getValueByPath(fromObject, new String[] {"logprobsResult"})); + new String[] {"scores"}, + Common.getValueByPath(fromObject, new String[] {"safetyAttributes", "scores"})); } - if (Common.getValueByPath(fromObject, new String[] {"safetyRatings"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"contentType"}) != null) { Common.setValueByPath( toObject, - new String[] {"safetyRatings"}, - Common.getValueByPath(fromObject, new String[] {"safetyRatings"})); + new String[] {"contentType"}, + Common.getValueByPath(fromObject, new String[] {"contentType"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode generateContentResponseFromVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode safetyAttributesFromVertex(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"safetyAttributes", "categories"}) + != null) { Common.setValueByPath( toObject, - new String[] {"sdkHttpResponse"}, - Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"})); + new String[] {"categories"}, + Common.getValueByPath(fromObject, new String[] {"safetyAttributes", "categories"})); } - if (Common.getValueByPath(fromObject, new String[] {"candidates"}) != null) { - ArrayNode keyArray = - (ArrayNode) Common.getValueByPath(fromObject, new String[] {"candidates"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add(candidateFromVertex(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"candidates"}, result); + if (Common.getValueByPath(fromObject, new String[] {"safetyAttributes", "scores"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"scores"}, + Common.getValueByPath(fromObject, new String[] {"safetyAttributes", "scores"})); } - if (Common.getValueByPath(fromObject, new String[] {"createTime"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"contentType"}) != null) { Common.setValueByPath( toObject, - new String[] {"createTime"}, - Common.getValueByPath(fromObject, new String[] {"createTime"})); + new String[] {"contentType"}, + Common.getValueByPath(fromObject, new String[] {"contentType"})); } - if (Common.getValueByPath(fromObject, new String[] {"responseId"}) != null) { + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode safetySettingToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"category"}) != null) { Common.setValueByPath( toObject, - new String[] {"responseId"}, - Common.getValueByPath(fromObject, new String[] {"responseId"})); + new String[] {"category"}, + Common.getValueByPath(fromObject, new String[] {"category"})); } - if (Common.getValueByPath(fromObject, new String[] {"modelVersion"}) != null) { + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"method"}))) { + throw new IllegalArgumentException("method parameter is not supported in Gemini API."); + } + + if (Common.getValueByPath(fromObject, new String[] {"threshold"}) != null) { Common.setValueByPath( toObject, - new String[] {"modelVersion"}, - Common.getValueByPath(fromObject, new String[] {"modelVersion"})); + new String[] {"threshold"}, + Common.getValueByPath(fromObject, new String[] {"threshold"})); } - if (Common.getValueByPath(fromObject, new String[] {"promptFeedback"}) != null) { + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode scribbleImageToVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"image"}) != null) { Common.setValueByPath( toObject, - new String[] {"promptFeedback"}, - Common.getValueByPath(fromObject, new String[] {"promptFeedback"})); + new String[] {"image"}, + imageToVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"image"})), + toObject)); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode segmentImageConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + + if (Common.getValueByPath(fromObject, new String[] {"mode"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"parameters", "mode"}, + Common.getValueByPath(fromObject, new String[] {"mode"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"maxPredictions"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"parameters", "maxPredictions"}, + Common.getValueByPath(fromObject, new String[] {"maxPredictions"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"confidenceThreshold"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"parameters", "confidenceThreshold"}, + Common.getValueByPath(fromObject, new String[] {"confidenceThreshold"})); } - if (Common.getValueByPath(fromObject, new String[] {"usageMetadata"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"maskDilation"}) != null) { Common.setValueByPath( - toObject, - new String[] {"usageMetadata"}, - Common.getValueByPath(fromObject, new String[] {"usageMetadata"})); + parentObject, + new String[] {"parameters", "maskDilation"}, + Common.getValueByPath(fromObject, new String[] {"maskDilation"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode contentEmbeddingStatisticsFromVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"truncated"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"binaryColorThreshold"}) != null) { Common.setValueByPath( - toObject, - new String[] {"truncated"}, - Common.getValueByPath(fromObject, new String[] {"truncated"})); + parentObject, + new String[] {"parameters", "binaryColorThreshold"}, + Common.getValueByPath(fromObject, new String[] {"binaryColorThreshold"})); } - if (Common.getValueByPath(fromObject, new String[] {"token_count"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"labels"}) != null) { Common.setValueByPath( - toObject, - new String[] {"tokenCount"}, - Common.getValueByPath(fromObject, new String[] {"token_count"})); + parentObject, + new String[] {"labels"}, + Common.getValueByPath(fromObject, new String[] {"labels"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode contentEmbeddingFromVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode segmentImageParametersToVertex( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"values"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { Common.setValueByPath( toObject, - new String[] {"values"}, - Common.getValueByPath(fromObject, new String[] {"values"})); + new String[] {"_url", "model"}, + Transformers.tModel( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); } - if (Common.getValueByPath(fromObject, new String[] {"statistics"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"statistics"}, - contentEmbeddingStatisticsFromVertex( + if (Common.getValueByPath(fromObject, new String[] {"source"}) != null) { + JsonNode unused = + segmentImageSourceToVertex( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"statistics"})), - toObject)); + Common.getValueByPath(fromObject, new String[] {"source"})), + toObject); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode embedContentMetadataFromVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"billableCharacterCount"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"billableCharacterCount"}, - Common.getValueByPath(fromObject, new String[] {"billableCharacterCount"})); + if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + JsonNode unused = + segmentImageConfigToVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"config"})), + toObject); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode embedContentResponseFromVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode segmentImageResponseFromVertex(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - if (Common.getValueByPath(fromObject, new String[] {"predictions[]", "embeddings"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"predictions"}) != null) { ArrayNode keyArray = - (ArrayNode) - Common.getValueByPath(fromObject, new String[] {"predictions[]", "embeddings"}); + (ArrayNode) Common.getValueByPath(fromObject, new String[] {"predictions"}); ObjectMapper objectMapper = new ObjectMapper(); ArrayNode result = objectMapper.createArrayNode(); for (JsonNode item : keyArray) { - result.add(contentEmbeddingFromVertex(JsonSerializable.toJsonNode(item), toObject)); + result.add(generatedImageMaskFromVertex(JsonSerializable.toJsonNode(item), toObject)); } - Common.setValueByPath(toObject, new String[] {"embeddings"}, result); - } - - if (Common.getValueByPath(fromObject, new String[] {"metadata"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"metadata"}, - embedContentMetadataFromVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"metadata"})), - toObject)); + Common.setValueByPath(toObject, new String[] {"generatedMasks"}, result); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode imageFromVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode segmentImageSourceToVertex(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"gcsUri"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"prompt"}) != null) { Common.setValueByPath( - toObject, - new String[] {"gcsUri"}, - Common.getValueByPath(fromObject, new String[] {"gcsUri"})); + parentObject, + new String[] {"instances[0]", "prompt"}, + Common.getValueByPath(fromObject, new String[] {"prompt"})); } - if (Common.getValueByPath(fromObject, new String[] {"bytesBase64Encoded"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"image"}) != null) { Common.setValueByPath( - toObject, - new String[] {"imageBytes"}, - Transformers.tBytes( - Common.getValueByPath(fromObject, new String[] {"bytesBase64Encoded"}))); + parentObject, + new String[] {"instances[0]", "image"}, + imageToVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"image"})), + toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"scribbleImage"}) != null) { Common.setValueByPath( - toObject, - new String[] {"mimeType"}, - Common.getValueByPath(fromObject, new String[] {"mimeType"})); + parentObject, + new String[] {"instances[0]", "scribble"}, + scribbleImageToVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"scribbleImage"})), + toObject)); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode safetyAttributesFromVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode speechConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"safetyAttributes", "categories"}) - != null) { + if (Common.getValueByPath(fromObject, new String[] {"languageCode"}) != null) { Common.setValueByPath( toObject, - new String[] {"categories"}, - Common.getValueByPath(fromObject, new String[] {"safetyAttributes", "categories"})); + new String[] {"languageCode"}, + Common.getValueByPath(fromObject, new String[] {"languageCode"})); } - if (Common.getValueByPath(fromObject, new String[] {"safetyAttributes", "scores"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"voiceConfig"}) != null) { Common.setValueByPath( toObject, - new String[] {"scores"}, - Common.getValueByPath(fromObject, new String[] {"safetyAttributes", "scores"})); + new String[] {"voiceConfig"}, + Common.getValueByPath(fromObject, new String[] {"voiceConfig"})); } - if (Common.getValueByPath(fromObject, new String[] {"contentType"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"contentType"}, - Common.getValueByPath(fromObject, new String[] {"contentType"})); + if (!Common.isZero( + Common.getValueByPath(fromObject, new String[] {"multiSpeakerVoiceConfig"}))) { + throw new IllegalArgumentException( + "multiSpeakerVoiceConfig parameter is not supported in Vertex AI."); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode generatedImageFromVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toolToMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"_self"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"functionDeclarations"}) != null) { Common.setValueByPath( toObject, - new String[] {"image"}, - imageFromVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"_self"})), - toObject)); + new String[] {"functionDeclarations"}, + Common.getValueByPath(fromObject, new String[] {"functionDeclarations"})); } - if (Common.getValueByPath(fromObject, new String[] {"raiFilteredReason"}) != null) { + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"retrieval"}))) { + throw new IllegalArgumentException("retrieval parameter is not supported in Gemini API."); + } + + if (Common.getValueByPath(fromObject, new String[] {"googleSearchRetrieval"}) != null) { Common.setValueByPath( toObject, - new String[] {"raiFilteredReason"}, - Common.getValueByPath(fromObject, new String[] {"raiFilteredReason"})); + new String[] {"googleSearchRetrieval"}, + Common.getValueByPath(fromObject, new String[] {"googleSearchRetrieval"})); } - if (Common.getValueByPath(fromObject, new String[] {"_self"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"googleMaps"}) != null) { Common.setValueByPath( toObject, - new String[] {"safetyAttributes"}, - safetyAttributesFromVertex( + new String[] {"googleMaps"}, + googleMapsToMldev( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"_self"})), + Common.getValueByPath(fromObject, new String[] {"googleMaps"})), toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"prompt"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"computerUse"}) != null) { Common.setValueByPath( toObject, - new String[] {"enhancedPrompt"}, - Common.getValueByPath(fromObject, new String[] {"prompt"})); + new String[] {"computerUse"}, + Common.getValueByPath(fromObject, new String[] {"computerUse"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode generateImagesResponseFromVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - if (Common.getValueByPath(fromObject, new String[] {"predictions"}) != null) { - ArrayNode keyArray = - (ArrayNode) Common.getValueByPath(fromObject, new String[] {"predictions"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); + if (Common.getValueByPath(fromObject, new String[] {"codeExecution"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"codeExecution"}, + Common.getValueByPath(fromObject, new String[] {"codeExecution"})); + } - for (JsonNode item : keyArray) { - result.add(generatedImageFromVertex(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"generatedImages"}, result); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"enterpriseWebSearch"}))) { + throw new IllegalArgumentException( + "enterpriseWebSearch parameter is not supported in Gemini API."); } - if (Common.getValueByPath(fromObject, new String[] {"positivePromptSafetyAttributes"}) - != null) { + if (Common.getValueByPath(fromObject, new String[] {"googleSearch"}) != null) { Common.setValueByPath( toObject, - new String[] {"positivePromptSafetyAttributes"}, - safetyAttributesFromVertex( + new String[] {"googleSearch"}, + googleSearchToMldev( JsonSerializable.toJsonNode( - Common.getValueByPath( - fromObject, new String[] {"positivePromptSafetyAttributes"})), + Common.getValueByPath(fromObject, new String[] {"googleSearch"})), toObject)); } + if (Common.getValueByPath(fromObject, new String[] {"urlContext"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"urlContext"}, + Common.getValueByPath(fromObject, new String[] {"urlContext"})); + } + return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode editImageResponseFromVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toolToVertex(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - if (Common.getValueByPath(fromObject, new String[] {"predictions"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"functionDeclarations"}) != null) { ArrayNode keyArray = - (ArrayNode) Common.getValueByPath(fromObject, new String[] {"predictions"}); + (ArrayNode) Common.getValueByPath(fromObject, new String[] {"functionDeclarations"}); ObjectMapper objectMapper = new ObjectMapper(); ArrayNode result = objectMapper.createArrayNode(); for (JsonNode item : keyArray) { - result.add(generatedImageFromVertex(JsonSerializable.toJsonNode(item), toObject)); + result.add(functionDeclarationToVertex(JsonSerializable.toJsonNode(item), toObject)); } - Common.setValueByPath(toObject, new String[] {"generatedImages"}, result); + Common.setValueByPath(toObject, new String[] {"functionDeclarations"}, result); } - return toObject; - } + if (Common.getValueByPath(fromObject, new String[] {"retrieval"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"retrieval"}, + Common.getValueByPath(fromObject, new String[] {"retrieval"})); + } - @ExcludeFromGeneratedCoverageReport - ObjectNode upscaleImageResponseFromVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"googleSearchRetrieval"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"googleSearchRetrieval"}, + Common.getValueByPath(fromObject, new String[] {"googleSearchRetrieval"})); + } - if (Common.getValueByPath(fromObject, new String[] {"predictions"}) != null) { - ArrayNode keyArray = - (ArrayNode) Common.getValueByPath(fromObject, new String[] {"predictions"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); + if (Common.getValueByPath(fromObject, new String[] {"googleMaps"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"googleMaps"}, + Common.getValueByPath(fromObject, new String[] {"googleMaps"})); + } - for (JsonNode item : keyArray) { - result.add(generatedImageFromVertex(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"generatedImages"}, result); + if (Common.getValueByPath(fromObject, new String[] {"computerUse"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"computerUse"}, + Common.getValueByPath(fromObject, new String[] {"computerUse"})); } - return toObject; - } + if (Common.getValueByPath(fromObject, new String[] {"codeExecution"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"codeExecution"}, + Common.getValueByPath(fromObject, new String[] {"codeExecution"})); + } - @ExcludeFromGeneratedCoverageReport - ObjectNode endpointFromVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"endpoint"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"enterpriseWebSearch"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"enterpriseWebSearch"}, + Common.getValueByPath(fromObject, new String[] {"enterpriseWebSearch"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"googleSearch"}) != null) { Common.setValueByPath( toObject, - new String[] {"name"}, - Common.getValueByPath(fromObject, new String[] {"endpoint"})); + new String[] {"googleSearch"}, + Common.getValueByPath(fromObject, new String[] {"googleSearch"})); } - if (Common.getValueByPath(fromObject, new String[] {"deployedModelId"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"urlContext"}) != null) { Common.setValueByPath( toObject, - new String[] {"deployedModelId"}, - Common.getValueByPath(fromObject, new String[] {"deployedModelId"})); + new String[] {"urlContext"}, + Common.getValueByPath(fromObject, new String[] {"urlContext"})); } return toObject; @@ -5478,172 +4213,276 @@ ObjectNode tunedModelInfoFromVertex(JsonNode fromObject, ObjectNode parentObject } @ExcludeFromGeneratedCoverageReport - ObjectNode checkpointFromVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode updateModelConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"checkpointId"}) != null) { + + if (Common.getValueByPath(fromObject, new String[] {"displayName"}) != null) { Common.setValueByPath( - toObject, - new String[] {"checkpointId"}, - Common.getValueByPath(fromObject, new String[] {"checkpointId"})); + parentObject, + new String[] {"displayName"}, + Common.getValueByPath(fromObject, new String[] {"displayName"})); } - if (Common.getValueByPath(fromObject, new String[] {"epoch"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"description"}) != null) { Common.setValueByPath( - toObject, - new String[] {"epoch"}, - Common.getValueByPath(fromObject, new String[] {"epoch"})); + parentObject, + new String[] {"description"}, + Common.getValueByPath(fromObject, new String[] {"description"})); } - if (Common.getValueByPath(fromObject, new String[] {"step"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"defaultCheckpointId"}) != null) { Common.setValueByPath( - toObject, - new String[] {"step"}, - Common.getValueByPath(fromObject, new String[] {"step"})); + parentObject, + new String[] {"defaultCheckpointId"}, + Common.getValueByPath(fromObject, new String[] {"defaultCheckpointId"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode modelFromVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode updateModelConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"name"}, - Common.getValueByPath(fromObject, new String[] {"name"})); - } if (Common.getValueByPath(fromObject, new String[] {"displayName"}) != null) { Common.setValueByPath( - toObject, + parentObject, new String[] {"displayName"}, Common.getValueByPath(fromObject, new String[] {"displayName"})); } if (Common.getValueByPath(fromObject, new String[] {"description"}) != null) { Common.setValueByPath( - toObject, + parentObject, new String[] {"description"}, Common.getValueByPath(fromObject, new String[] {"description"})); } - if (Common.getValueByPath(fromObject, new String[] {"versionId"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"defaultCheckpointId"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"defaultCheckpointId"}, + Common.getValueByPath(fromObject, new String[] {"defaultCheckpointId"})); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode updateModelParametersToMldev( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { Common.setValueByPath( toObject, - new String[] {"version"}, - Common.getValueByPath(fromObject, new String[] {"versionId"})); + new String[] {"_url", "name"}, + Transformers.tModel( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); } - if (Common.getValueByPath(fromObject, new String[] {"deployedModels"}) != null) { - ArrayNode keyArray = - (ArrayNode) Common.getValueByPath(fromObject, new String[] {"deployedModels"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); + if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + JsonNode unused = + updateModelConfigToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"config"})), + toObject); + } - for (JsonNode item : keyArray) { - result.add(endpointFromVertex(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"endpoints"}, result); + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode updateModelParametersToVertex( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"_url", "model"}, + Transformers.tModel( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); + } + + if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + JsonNode unused = + updateModelConfigToVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"config"})), + toObject); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode upscaleImageAPIConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + + if (Common.getValueByPath(fromObject, new String[] {"outputGcsUri"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"parameters", "storageUri"}, + Common.getValueByPath(fromObject, new String[] {"outputGcsUri"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"safetyFilterLevel"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"parameters", "safetySetting"}, + Common.getValueByPath(fromObject, new String[] {"safetyFilterLevel"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"personGeneration"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"parameters", "personGeneration"}, + Common.getValueByPath(fromObject, new String[] {"personGeneration"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"includeRaiReason"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"parameters", "includeRaiReason"}, + Common.getValueByPath(fromObject, new String[] {"includeRaiReason"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"outputMimeType"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"parameters", "outputOptions", "mimeType"}, + Common.getValueByPath(fromObject, new String[] {"outputMimeType"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"outputCompressionQuality"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"parameters", "outputOptions", "compressionQuality"}, + Common.getValueByPath(fromObject, new String[] {"outputCompressionQuality"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"enhanceInputImage"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"parameters", "upscaleConfig", "enhanceInputImage"}, + Common.getValueByPath(fromObject, new String[] {"enhanceInputImage"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"imagePreservationFactor"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"parameters", "upscaleConfig", "imagePreservationFactor"}, + Common.getValueByPath(fromObject, new String[] {"imagePreservationFactor"})); } if (Common.getValueByPath(fromObject, new String[] {"labels"}) != null) { Common.setValueByPath( - toObject, + parentObject, new String[] {"labels"}, Common.getValueByPath(fromObject, new String[] {"labels"})); } - if (Common.getValueByPath(fromObject, new String[] {"_self"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"numberOfImages"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"parameters", "sampleCount"}, + Common.getValueByPath(fromObject, new String[] {"numberOfImages"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"mode"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"parameters", "mode"}, + Common.getValueByPath(fromObject, new String[] {"mode"})); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode upscaleImageAPIParametersToVertex( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { Common.setValueByPath( toObject, - new String[] {"tunedModelInfo"}, - tunedModelInfoFromVertex( + new String[] {"_url", "model"}, + Transformers.tModel( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); + } + + if (Common.getValueByPath(fromObject, new String[] {"image"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"instances[0]", "image"}, + imageToVertex( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"_self"})), + Common.getValueByPath(fromObject, new String[] {"image"})), toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"defaultCheckpointId"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"upscaleFactor"}) != null) { Common.setValueByPath( toObject, - new String[] {"defaultCheckpointId"}, - Common.getValueByPath(fromObject, new String[] {"defaultCheckpointId"})); + new String[] {"parameters", "upscaleConfig", "upscaleFactor"}, + Common.getValueByPath(fromObject, new String[] {"upscaleFactor"})); } - if (Common.getValueByPath(fromObject, new String[] {"checkpoints"}) != null) { - ArrayNode keyArray = - (ArrayNode) Common.getValueByPath(fromObject, new String[] {"checkpoints"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add(checkpointFromVertex(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"checkpoints"}, result); + if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + JsonNode unused = + upscaleImageAPIConfigToVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"config"})), + toObject); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode listModelsResponseFromVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode upscaleImageResponseFromVertex(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - if (Common.getValueByPath(fromObject, new String[] {"nextPageToken"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"}) != null) { Common.setValueByPath( toObject, - new String[] {"nextPageToken"}, - Common.getValueByPath(fromObject, new String[] {"nextPageToken"})); + new String[] {"sdkHttpResponse"}, + Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"})); } - if (Common.getValueByPath(fromObject, new String[] {"_self"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"predictions"}) != null) { ArrayNode keyArray = - (ArrayNode) - Transformers.tExtractModels( - Common.getValueByPath(fromObject, new String[] {"_self"})); + (ArrayNode) Common.getValueByPath(fromObject, new String[] {"predictions"}); ObjectMapper objectMapper = new ObjectMapper(); ArrayNode result = objectMapper.createArrayNode(); for (JsonNode item : keyArray) { - result.add(modelFromVertex(JsonSerializable.toJsonNode(item), toObject)); + result.add(generatedImageFromVertex(JsonSerializable.toJsonNode(item), toObject)); } - Common.setValueByPath(toObject, new String[] {"models"}, result); + Common.setValueByPath(toObject, new String[] {"generatedImages"}, result); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode deleteModelResponseFromVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode countTokensResponseFromVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode videoFromMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"uri"}) != null) { + Common.setValueByPath( + toObject, new String[] {"uri"}, Common.getValueByPath(fromObject, new String[] {"uri"})); + } - if (Common.getValueByPath(fromObject, new String[] {"totalTokens"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"encodedVideo"}) != null) { Common.setValueByPath( toObject, - new String[] {"totalTokens"}, - Common.getValueByPath(fromObject, new String[] {"totalTokens"})); + new String[] {"videoBytes"}, + Transformers.tBytes(Common.getValueByPath(fromObject, new String[] {"encodedVideo"}))); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode computeTokensResponseFromVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - if (Common.getValueByPath(fromObject, new String[] {"tokensInfo"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"encoding"}) != null) { Common.setValueByPath( toObject, - new String[] {"tokensInfo"}, - Common.getValueByPath(fromObject, new String[] {"tokensInfo"})); + new String[] {"mimeType"}, + Common.getValueByPath(fromObject, new String[] {"encoding"})); } return toObject; @@ -5678,97 +4517,130 @@ ObjectNode videoFromVertex(JsonNode fromObject, ObjectNode parentObject) { } @ExcludeFromGeneratedCoverageReport - ObjectNode generatedVideoFromVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode videoGenerationMaskToVertex(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"_self"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"image"}) != null) { Common.setValueByPath( toObject, - new String[] {"video"}, - videoFromVertex( + new String[] {"_self"}, + imageToVertex( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"_self"})), + Common.getValueByPath(fromObject, new String[] {"image"})), toObject)); } + if (Common.getValueByPath(fromObject, new String[] {"maskMode"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"maskMode"}, + Common.getValueByPath(fromObject, new String[] {"maskMode"})); + } + return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode generateVideosResponseFromVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode videoGenerationReferenceImageToMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"videos"}) != null) { - ArrayNode keyArray = (ArrayNode) Common.getValueByPath(fromObject, new String[] {"videos"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); + if (Common.getValueByPath(fromObject, new String[] {"image"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"image"}, + imageToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"image"})), + toObject)); + } - for (JsonNode item : keyArray) { - result.add(generatedVideoFromVertex(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"generatedVideos"}, result); + if (Common.getValueByPath(fromObject, new String[] {"referenceType"}) != null) { + videoGenerationReferenceTypeMldevEnumValidate( + Common.getValueByPath(fromObject, new String[] {"referenceType"})); + Common.setValueByPath( + toObject, + new String[] {"referenceType"}, + Common.getValueByPath(fromObject, new String[] {"referenceType"})); } - if (Common.getValueByPath(fromObject, new String[] {"raiMediaFilteredCount"}) != null) { + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode videoGenerationReferenceImageToVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"image"}) != null) { Common.setValueByPath( toObject, - new String[] {"raiMediaFilteredCount"}, - Common.getValueByPath(fromObject, new String[] {"raiMediaFilteredCount"})); + new String[] {"image"}, + imageToVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"image"})), + toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"raiMediaFilteredReasons"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"referenceType"}) != null) { Common.setValueByPath( toObject, - new String[] {"raiMediaFilteredReasons"}, - Common.getValueByPath(fromObject, new String[] {"raiMediaFilteredReasons"})); + new String[] {"referenceType"}, + Common.getValueByPath(fromObject, new String[] {"referenceType"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode generateVideosOperationFromVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode videoToMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"uri"}) != null) { + Common.setValueByPath( + toObject, new String[] {"uri"}, Common.getValueByPath(fromObject, new String[] {"uri"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"videoBytes"}) != null) { Common.setValueByPath( toObject, - new String[] {"name"}, - Common.getValueByPath(fromObject, new String[] {"name"})); + new String[] {"encodedVideo"}, + Transformers.tBytes(Common.getValueByPath(fromObject, new String[] {"videoBytes"}))); } - if (Common.getValueByPath(fromObject, new String[] {"metadata"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { Common.setValueByPath( toObject, - new String[] {"metadata"}, - Common.getValueByPath(fromObject, new String[] {"metadata"})); + new String[] {"encoding"}, + Common.getValueByPath(fromObject, new String[] {"mimeType"})); } - if (Common.getValueByPath(fromObject, new String[] {"done"}) != null) { + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode videoToVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"uri"}) != null) { Common.setValueByPath( toObject, - new String[] {"done"}, - Common.getValueByPath(fromObject, new String[] {"done"})); + new String[] {"gcsUri"}, + Common.getValueByPath(fromObject, new String[] {"uri"})); } - if (Common.getValueByPath(fromObject, new String[] {"error"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"videoBytes"}) != null) { Common.setValueByPath( toObject, - new String[] {"error"}, - Common.getValueByPath(fromObject, new String[] {"error"})); + new String[] {"bytesBase64Encoded"}, + Transformers.tBytes(Common.getValueByPath(fromObject, new String[] {"videoBytes"}))); } - if (Common.getValueByPath(fromObject, new String[] {"response"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { Common.setValueByPath( toObject, - new String[] {"response"}, - generateVideosResponseFromVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"response"})), - toObject)); + new String[] {"mimeType"}, + Common.getValueByPath(fromObject, new String[] {"mimeType"})); } return toObject; } - GenerateContentResponse privateGenerateContent( + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForPrivateGenerateContent( String model, List contents, GenerateContentConfig config) { GenerateContentParameters.Builder parameterBuilder = GenerateContentParameters.builder(); @@ -5806,48 +4678,77 @@ GenerateContentResponse privateGenerateContent( } // TODO: Remove the hack that removes config. - body.remove("config"); - Optional requestHttpOptions = Optional.empty(); if (config != null) { requestHttpOptions = config.httpOptions(); } - try (ApiResponse response = - this.apiClient.request( - "post", path, JsonSerializable.toJsonString(body), requestHttpOptions)) { - ResponseBody responseBody = response.getBody(); - String responseString; - try { - responseString = responseBody.string(); - } catch (IOException e) { - throw new GenAiIOException("Failed to read HTTP response.", e); - } + return new BuiltRequest(path, JsonSerializable.toJsonString(body), requestHttpOptions); + } - JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); - if (this.apiClient.vertexAI()) { - responseNode = generateContentResponseFromVertex(responseNode, null); - } else { - responseNode = generateContentResponseFromMldev(responseNode, null); - } + /** A shared processResponse function for both sync and async methods. */ + GenerateContentResponse processResponseForPrivateGenerateContent( + ApiResponse response, GenerateContentConfig config) { + ResponseBody responseBody = response.getBody(); + String responseString; + try { + responseString = responseBody.string(); + } catch (IOException e) { + throw new GenAiIOException("Failed to read HTTP response.", e); + } - GenerateContentResponse sdkResponse = - JsonSerializable.fromJsonNode(responseNode, GenerateContentResponse.class); + if (config != null && config.shouldReturnHttpResponse().orElse(false)) { Headers responseHeaders = response.getHeaders(); if (responseHeaders == null) { - return sdkResponse; + return GenerateContentResponse.builder() + .sdkHttpResponse(HttpResponse.builder().body(responseString)) + .build(); } Map headers = new HashMap<>(); for (String headerName : responseHeaders.names()) { headers.put(headerName, responseHeaders.get(headerName)); } - return sdkResponse.toBuilder() - .sdkHttpResponse(HttpResponse.builder().headers(headers)) + return GenerateContentResponse.builder() + .sdkHttpResponse(HttpResponse.builder().headers(headers).body(responseString)) .build(); } + + JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); + + if (this.apiClient.vertexAI()) { + responseNode = generateContentResponseFromVertex(responseNode, null); + } + + if (!this.apiClient.vertexAI()) { + responseNode = generateContentResponseFromMldev(responseNode, null); + } + + GenerateContentResponse sdkResponse = + JsonSerializable.fromJsonNode(responseNode, GenerateContentResponse.class); + Headers responseHeaders = response.getHeaders(); + if (responseHeaders == null) { + return sdkResponse; + } + Map headers = new HashMap<>(); + for (String headerName : responseHeaders.names()) { + headers.put(headerName, responseHeaders.get(headerName)); + } + return sdkResponse.toBuilder().sdkHttpResponse(HttpResponse.builder().headers(headers)).build(); } - ResponseStream privateGenerateContentStream( + GenerateContentResponse privateGenerateContent( + String model, List contents, GenerateContentConfig config) { + BuiltRequest builtRequest = buildRequestForPrivateGenerateContent(model, contents, config); + + try (ApiResponse response = + this.apiClient.request( + "post", builtRequest.path, builtRequest.body, builtRequest.httpOptions)) { + return processResponseForPrivateGenerateContent(response, config); + } + } + + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForPrivateGenerateContentStream( String model, List contents, GenerateContentConfig config) { GenerateContentParameters.Builder parameterBuilder = GenerateContentParameters.builder(); @@ -5885,37 +4786,241 @@ ResponseStream privateGenerateContentStream( } // TODO: Remove the hack that removes config. - body.remove("config"); + Optional requestHttpOptions = Optional.empty(); + if (config != null) { + requestHttpOptions = config.httpOptions(); + } + + return new BuiltRequest(path, JsonSerializable.toJsonString(body), requestHttpOptions); + } + + /** A shared processResponse function for both sync and async methods. */ + ResponseStream processResponseForPrivateGenerateContentStream( + ApiResponse response, GenerateContentConfig config) { + String converterName; + + if (this.apiClient.vertexAI()) { + converterName = "generateContentResponseFromVertex"; + } else { + converterName = "generateContentResponseFromMldev"; + } + return new ResponseStream( + GenerateContentResponse.class, response, this, converterName, false); + } + + ResponseStream privateGenerateContentStream( + String model, List contents, GenerateContentConfig config) { + BuiltRequest builtRequest = + buildRequestForPrivateGenerateContentStream(model, contents, config); + + ApiResponse response = + this.apiClient.request( + "post", builtRequest.path, builtRequest.body, builtRequest.httpOptions); + return processResponseForPrivateGenerateContentStream(response, config); + } + + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForPrivateEmbedContent( + String model, List contents, EmbedContentConfig config) { + + EmbedContentParameters.Builder parameterBuilder = EmbedContentParameters.builder(); + + if (!Common.isZero(model)) { + parameterBuilder.model(model); + } + if (!Common.isZero(contents)) { + parameterBuilder.contents(contents); + } + if (!Common.isZero(config)) { + parameterBuilder.config(config); + } + JsonNode parameterNode = JsonSerializable.toJsonNode(parameterBuilder.build()); + + ObjectNode body; + String path; + if (this.apiClient.vertexAI()) { + body = embedContentParametersToVertex(this.apiClient, parameterNode, null); + path = Common.formatMap("{model}:predict", body.get("_url")); + } else { + body = embedContentParametersToMldev(this.apiClient, parameterNode, null); + if (body.get("_url") != null) { + path = Common.formatMap("{model}:batchEmbedContents", body.get("_url")); + } else { + path = "{model}:batchEmbedContents"; + } + } + body.remove("_url"); + + JsonNode queryParams = body.get("_query"); + if (queryParams != null) { + body.remove("_query"); + path = String.format("%s?%s", path, Common.urlEncode((ObjectNode) queryParams)); + } + + // TODO: Remove the hack that removes config. + Optional requestHttpOptions = Optional.empty(); + if (config != null) { + requestHttpOptions = config.httpOptions(); + } + + return new BuiltRequest(path, JsonSerializable.toJsonString(body), requestHttpOptions); + } + + /** A shared processResponse function for both sync and async methods. */ + EmbedContentResponse processResponseForPrivateEmbedContent( + ApiResponse response, EmbedContentConfig config) { + ResponseBody responseBody = response.getBody(); + String responseString; + try { + responseString = responseBody.string(); + } catch (IOException e) { + throw new GenAiIOException("Failed to read HTTP response.", e); + } + + JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); + + if (this.apiClient.vertexAI()) { + responseNode = embedContentResponseFromVertex(responseNode, null); + } + + if (!this.apiClient.vertexAI()) { + responseNode = embedContentResponseFromMldev(responseNode, null); + } + + EmbedContentResponse sdkResponse = + JsonSerializable.fromJsonNode(responseNode, EmbedContentResponse.class); + Headers responseHeaders = response.getHeaders(); + if (responseHeaders == null) { + return sdkResponse; + } + Map headers = new HashMap<>(); + for (String headerName : responseHeaders.names()) { + headers.put(headerName, responseHeaders.get(headerName)); + } + return sdkResponse.toBuilder().sdkHttpResponse(HttpResponse.builder().headers(headers)).build(); + } + + EmbedContentResponse privateEmbedContent( + String model, List contents, EmbedContentConfig config) { + BuiltRequest builtRequest = buildRequestForPrivateEmbedContent(model, contents, config); + + try (ApiResponse response = + this.apiClient.request( + "post", builtRequest.path, builtRequest.body, builtRequest.httpOptions)) { + return processResponseForPrivateEmbedContent(response, config); + } + } + + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForPrivateGenerateImages( + String model, String prompt, GenerateImagesConfig config) { + + GenerateImagesParameters.Builder parameterBuilder = GenerateImagesParameters.builder(); + + if (!Common.isZero(model)) { + parameterBuilder.model(model); + } + if (!Common.isZero(prompt)) { + parameterBuilder.prompt(prompt); + } + if (!Common.isZero(config)) { + parameterBuilder.config(config); + } + JsonNode parameterNode = JsonSerializable.toJsonNode(parameterBuilder.build()); + + ObjectNode body; + String path; + if (this.apiClient.vertexAI()) { + body = generateImagesParametersToVertex(this.apiClient, parameterNode, null); + path = Common.formatMap("{model}:predict", body.get("_url")); + } else { + body = generateImagesParametersToMldev(this.apiClient, parameterNode, null); + if (body.get("_url") != null) { + path = Common.formatMap("{model}:predict", body.get("_url")); + } else { + path = "{model}:predict"; + } + } + body.remove("_url"); + + JsonNode queryParams = body.get("_query"); + if (queryParams != null) { + body.remove("_query"); + path = String.format("%s?%s", path, Common.urlEncode((ObjectNode) queryParams)); + } + // TODO: Remove the hack that removes config. Optional requestHttpOptions = Optional.empty(); if (config != null) { requestHttpOptions = config.httpOptions(); } - ApiResponse response = - this.apiClient.request( - "post", path, JsonSerializable.toJsonString(body), requestHttpOptions); - String converterName; + return new BuiltRequest(path, JsonSerializable.toJsonString(body), requestHttpOptions); + } + + /** A shared processResponse function for both sync and async methods. */ + GenerateImagesResponse processResponseForPrivateGenerateImages( + ApiResponse response, GenerateImagesConfig config) { + ResponseBody responseBody = response.getBody(); + String responseString; + try { + responseString = responseBody.string(); + } catch (IOException e) { + throw new GenAiIOException("Failed to read HTTP response.", e); + } + + JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); if (this.apiClient.vertexAI()) { - converterName = "generateContentResponseFromVertex"; - } else { - converterName = "generateContentResponseFromMldev"; + responseNode = generateImagesResponseFromVertex(responseNode, null); } - return new ResponseStream( - GenerateContentResponse.class, response, this, converterName); + + if (!this.apiClient.vertexAI()) { + responseNode = generateImagesResponseFromMldev(responseNode, null); + } + + GenerateImagesResponse sdkResponse = + JsonSerializable.fromJsonNode(responseNode, GenerateImagesResponse.class); + Headers responseHeaders = response.getHeaders(); + if (responseHeaders == null) { + return sdkResponse; + } + Map headers = new HashMap<>(); + for (String headerName : responseHeaders.names()) { + headers.put(headerName, responseHeaders.get(headerName)); + } + return sdkResponse.toBuilder().sdkHttpResponse(HttpResponse.builder().headers(headers)).build(); } - EmbedContentResponse privateEmbedContent( - String model, List contents, EmbedContentConfig config) { + /** Private method for generating images. */ + GenerateImagesResponse privateGenerateImages( + String model, String prompt, GenerateImagesConfig config) { + BuiltRequest builtRequest = buildRequestForPrivateGenerateImages(model, prompt, config); - EmbedContentParameters.Builder parameterBuilder = EmbedContentParameters.builder(); + try (ApiResponse response = + this.apiClient.request( + "post", builtRequest.path, builtRequest.body, builtRequest.httpOptions)) { + return processResponseForPrivateGenerateImages(response, config); + } + } + + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForPrivateEditImage( + String model, + String prompt, + List referenceImages, + EditImageConfig config) { + + EditImageParameters.Builder parameterBuilder = EditImageParameters.builder(); if (!Common.isZero(model)) { parameterBuilder.model(model); } - if (!Common.isZero(contents)) { - parameterBuilder.contents(contents); + if (!Common.isZero(prompt)) { + parameterBuilder.prompt(prompt); + } + if (!Common.isZero(referenceImages)) { + parameterBuilder.referenceImages(referenceImages); } if (!Common.isZero(config)) { parameterBuilder.config(config); @@ -5925,15 +5030,11 @@ EmbedContentResponse privateEmbedContent( ObjectNode body; String path; if (this.apiClient.vertexAI()) { - body = embedContentParametersToVertex(this.apiClient, parameterNode, null); + body = editImageParametersToVertex(this.apiClient, parameterNode, null); path = Common.formatMap("{model}:predict", body.get("_url")); } else { - body = embedContentParametersToMldev(this.apiClient, parameterNode, null); - if (body.get("_url") != null) { - path = Common.formatMap("{model}:batchEmbedContents", body.get("_url")); - } else { - path = "{model}:batchEmbedContents"; - } + throw new UnsupportedOperationException( + "This method is only supported in the Vertex AI client."); } body.remove("_url"); @@ -5944,44 +5045,79 @@ EmbedContentResponse privateEmbedContent( } // TODO: Remove the hack that removes config. - body.remove("config"); - Optional requestHttpOptions = Optional.empty(); if (config != null) { requestHttpOptions = config.httpOptions(); } + return new BuiltRequest(path, JsonSerializable.toJsonString(body), requestHttpOptions); + } + + /** A shared processResponse function for both sync and async methods. */ + EditImageResponse processResponseForPrivateEditImage( + ApiResponse response, EditImageConfig config) { + ResponseBody responseBody = response.getBody(); + String responseString; + try { + responseString = responseBody.string(); + } catch (IOException e) { + throw new GenAiIOException("Failed to read HTTP response.", e); + } + + JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); + + if (this.apiClient.vertexAI()) { + responseNode = editImageResponseFromVertex(responseNode, null); + } + + if (!this.apiClient.vertexAI()) { + throw new UnsupportedOperationException( + "This method is only supported in the Vertex AI client."); + } + + EditImageResponse sdkResponse = + JsonSerializable.fromJsonNode(responseNode, EditImageResponse.class); + Headers responseHeaders = response.getHeaders(); + if (responseHeaders == null) { + return sdkResponse; + } + Map headers = new HashMap<>(); + for (String headerName : responseHeaders.names()) { + headers.put(headerName, responseHeaders.get(headerName)); + } + return sdkResponse.toBuilder().sdkHttpResponse(HttpResponse.builder().headers(headers)).build(); + } + + /** Private method for editing an image. */ + EditImageResponse privateEditImage( + String model, + String prompt, + List referenceImages, + EditImageConfig config) { + BuiltRequest builtRequest = + buildRequestForPrivateEditImage(model, prompt, referenceImages, config); + try (ApiResponse response = this.apiClient.request( - "post", path, JsonSerializable.toJsonString(body), requestHttpOptions)) { - ResponseBody responseBody = response.getBody(); - String responseString; - try { - responseString = responseBody.string(); - } catch (IOException e) { - throw new GenAiIOException("Failed to read HTTP response.", e); - } - - JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); - if (this.apiClient.vertexAI()) { - responseNode = embedContentResponseFromVertex(responseNode, null); - } else { - responseNode = embedContentResponseFromMldev(responseNode, null); - } - return JsonSerializable.fromJsonNode(responseNode, EmbedContentResponse.class); + "post", builtRequest.path, builtRequest.body, builtRequest.httpOptions)) { + return processResponseForPrivateEditImage(response, config); } } - GenerateImagesResponse privateGenerateImages( - String model, String prompt, GenerateImagesConfig config) { + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForPrivateUpscaleImage( + String model, Image image, String upscaleFactor, UpscaleImageAPIConfig config) { - GenerateImagesParameters.Builder parameterBuilder = GenerateImagesParameters.builder(); + UpscaleImageAPIParameters.Builder parameterBuilder = UpscaleImageAPIParameters.builder(); if (!Common.isZero(model)) { parameterBuilder.model(model); } - if (!Common.isZero(prompt)) { - parameterBuilder.prompt(prompt); + if (!Common.isZero(image)) { + parameterBuilder.image(image); + } + if (!Common.isZero(upscaleFactor)) { + parameterBuilder.upscaleFactor(upscaleFactor); } if (!Common.isZero(config)) { parameterBuilder.config(config); @@ -5991,15 +5127,11 @@ GenerateImagesResponse privateGenerateImages( ObjectNode body; String path; if (this.apiClient.vertexAI()) { - body = generateImagesParametersToVertex(this.apiClient, parameterNode, null); + body = upscaleImageAPIParametersToVertex(this.apiClient, parameterNode, null); path = Common.formatMap("{model}:predict", body.get("_url")); } else { - body = generateImagesParametersToMldev(this.apiClient, parameterNode, null); - if (body.get("_url") != null) { - path = Common.formatMap("{model}:predict", body.get("_url")); - } else { - path = "{model}:predict"; - } + throw new UnsupportedOperationException( + "This method is only supported in the Vertex AI client."); } body.remove("_url"); @@ -6010,50 +5142,73 @@ GenerateImagesResponse privateGenerateImages( } // TODO: Remove the hack that removes config. - body.remove("config"); - Optional requestHttpOptions = Optional.empty(); if (config != null) { requestHttpOptions = config.httpOptions(); } + return new BuiltRequest(path, JsonSerializable.toJsonString(body), requestHttpOptions); + } + + /** A shared processResponse function for both sync and async methods. */ + UpscaleImageResponse processResponseForPrivateUpscaleImage( + ApiResponse response, UpscaleImageAPIConfig config) { + ResponseBody responseBody = response.getBody(); + String responseString; + try { + responseString = responseBody.string(); + } catch (IOException e) { + throw new GenAiIOException("Failed to read HTTP response.", e); + } + + JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); + + if (this.apiClient.vertexAI()) { + responseNode = upscaleImageResponseFromVertex(responseNode, null); + } + + if (!this.apiClient.vertexAI()) { + throw new UnsupportedOperationException( + "This method is only supported in the Vertex AI client."); + } + + UpscaleImageResponse sdkResponse = + JsonSerializable.fromJsonNode(responseNode, UpscaleImageResponse.class); + Headers responseHeaders = response.getHeaders(); + if (responseHeaders == null) { + return sdkResponse; + } + Map headers = new HashMap<>(); + for (String headerName : responseHeaders.names()) { + headers.put(headerName, responseHeaders.get(headerName)); + } + return sdkResponse.toBuilder().sdkHttpResponse(HttpResponse.builder().headers(headers)).build(); + } + + /** Private method for upscaling an image. */ + UpscaleImageResponse privateUpscaleImage( + String model, Image image, String upscaleFactor, UpscaleImageAPIConfig config) { + BuiltRequest builtRequest = + buildRequestForPrivateUpscaleImage(model, image, upscaleFactor, config); + try (ApiResponse response = this.apiClient.request( - "post", path, JsonSerializable.toJsonString(body), requestHttpOptions)) { - ResponseBody responseBody = response.getBody(); - String responseString; - try { - responseString = responseBody.string(); - } catch (IOException e) { - throw new GenAiIOException("Failed to read HTTP response.", e); - } - - JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); - if (this.apiClient.vertexAI()) { - responseNode = generateImagesResponseFromVertex(responseNode, null); - } else { - responseNode = generateImagesResponseFromMldev(responseNode, null); - } - return JsonSerializable.fromJsonNode(responseNode, GenerateImagesResponse.class); + "post", builtRequest.path, builtRequest.body, builtRequest.httpOptions)) { + return processResponseForPrivateUpscaleImage(response, config); } } - EditImageResponse privateEditImage( - String model, - String prompt, - List referenceImages, - EditImageConfig config) { + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForRecontextImage( + String model, RecontextImageSource source, RecontextImageConfig config) { - EditImageParameters.Builder parameterBuilder = EditImageParameters.builder(); + RecontextImageParameters.Builder parameterBuilder = RecontextImageParameters.builder(); if (!Common.isZero(model)) { parameterBuilder.model(model); } - if (!Common.isZero(prompt)) { - parameterBuilder.prompt(prompt); - } - if (!Common.isZero(referenceImages)) { - parameterBuilder.referenceImages(referenceImages); + if (!Common.isZero(source)) { + parameterBuilder.source(source); } if (!Common.isZero(config)) { parameterBuilder.config(config); @@ -6063,7 +5218,7 @@ EditImageResponse privateEditImage( ObjectNode body; String path; if (this.apiClient.vertexAI()) { - body = editImageParametersToVertex(this.apiClient, parameterNode, null); + body = recontextImageParametersToVertex(this.apiClient, parameterNode, null); path = Common.formatMap("{model}:predict", body.get("_url")); } else { throw new UnsupportedOperationException( @@ -6078,48 +5233,81 @@ EditImageResponse privateEditImage( } // TODO: Remove the hack that removes config. - body.remove("config"); - Optional requestHttpOptions = Optional.empty(); if (config != null) { requestHttpOptions = config.httpOptions(); } + return new BuiltRequest(path, JsonSerializable.toJsonString(body), requestHttpOptions); + } + + /** A shared processResponse function for both sync and async methods. */ + RecontextImageResponse processResponseForRecontextImage( + ApiResponse response, RecontextImageConfig config) { + ResponseBody responseBody = response.getBody(); + String responseString; + try { + responseString = responseBody.string(); + } catch (IOException e) { + throw new GenAiIOException("Failed to read HTTP response.", e); + } + + JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); + + if (this.apiClient.vertexAI()) { + responseNode = recontextImageResponseFromVertex(responseNode, null); + } + + if (!this.apiClient.vertexAI()) { + throw new UnsupportedOperationException( + "This method is only supported in the Vertex AI client."); + } + + return JsonSerializable.fromJsonNode(responseNode, RecontextImageResponse.class); + } + + /** + * Recontextualizes an image. + * + *

There are two types of recontextualization currently supported: 1) Imagen Product Recontext + * - Generate images of products in new scenes and contexts. 2) Virtual Try-On: Generate images of + * persons modeling fashion products. + * + * @param model the name of the GenAI model to use for image recontext + * @param source a {@link com.google.genai.types.RecontextImageSource} An object containing the + * source inputs (prompt, personImage, productImages) for image recontext. prompt is optional + * for product recontext and disallowed for virtual try-on. personImage is required for + * virtual try-on, disallowed for product recontext. productImages is required for both + * product recontext and virtual try-on. Only one product image is supported for virtual + * try-on, and up to 3 product images (different angles of the same product) are supported for + * product recontext. + * @param config a {@link com.google.genai.types.RecontextImageConfig} instance that specifies the + * optional configurations + * @return a {@link com.google.genai.types.RecontextImageResponse} instance that contains the + * generated images. + */ + public RecontextImageResponse recontextImage( + String model, RecontextImageSource source, RecontextImageConfig config) { + BuiltRequest builtRequest = buildRequestForRecontextImage(model, source, config); + try (ApiResponse response = this.apiClient.request( - "post", path, JsonSerializable.toJsonString(body), requestHttpOptions)) { - ResponseBody responseBody = response.getBody(); - String responseString; - try { - responseString = responseBody.string(); - } catch (IOException e) { - throw new GenAiIOException("Failed to read HTTP response.", e); - } - - JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); - if (this.apiClient.vertexAI()) { - responseNode = editImageResponseFromVertex(responseNode, null); - } else { - throw new UnsupportedOperationException( - "This method is only supported in the Vertex AI client."); - } - return JsonSerializable.fromJsonNode(responseNode, EditImageResponse.class); + "post", builtRequest.path, builtRequest.body, builtRequest.httpOptions)) { + return processResponseForRecontextImage(response, config); } } - UpscaleImageResponse privateUpscaleImage( - String model, Image image, String upscaleFactor, UpscaleImageAPIConfig config) { + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForSegmentImage( + String model, SegmentImageSource source, SegmentImageConfig config) { - UpscaleImageAPIParameters.Builder parameterBuilder = UpscaleImageAPIParameters.builder(); + SegmentImageParameters.Builder parameterBuilder = SegmentImageParameters.builder(); if (!Common.isZero(model)) { parameterBuilder.model(model); } - if (!Common.isZero(image)) { - parameterBuilder.image(image); - } - if (!Common.isZero(upscaleFactor)) { - parameterBuilder.upscaleFactor(upscaleFactor); + if (!Common.isZero(source)) { + parameterBuilder.source(source); } if (!Common.isZero(config)) { parameterBuilder.config(config); @@ -6129,7 +5317,7 @@ UpscaleImageResponse privateUpscaleImage( ObjectNode body; String path; if (this.apiClient.vertexAI()) { - body = upscaleImageAPIParametersToVertex(this.apiClient, parameterNode, null); + body = segmentImageParametersToVertex(this.apiClient, parameterNode, null); path = Common.formatMap("{model}:predict", body.get("_url")); } else { throw new UnsupportedOperationException( @@ -6144,41 +5332,65 @@ UpscaleImageResponse privateUpscaleImage( } // TODO: Remove the hack that removes config. - body.remove("config"); - Optional requestHttpOptions = Optional.empty(); if (config != null) { requestHttpOptions = config.httpOptions(); } - try (ApiResponse response = - this.apiClient.request( - "post", path, JsonSerializable.toJsonString(body), requestHttpOptions)) { - ResponseBody responseBody = response.getBody(); - String responseString; - try { - responseString = responseBody.string(); - } catch (IOException e) { - throw new GenAiIOException("Failed to read HTTP response.", e); - } + return new BuiltRequest(path, JsonSerializable.toJsonString(body), requestHttpOptions); + } - JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); - if (this.apiClient.vertexAI()) { - responseNode = upscaleImageResponseFromVertex(responseNode, null); - } else { - throw new UnsupportedOperationException( - "This method is only supported in the Vertex AI client."); - } - return JsonSerializable.fromJsonNode(responseNode, UpscaleImageResponse.class); + /** A shared processResponse function for both sync and async methods. */ + SegmentImageResponse processResponseForSegmentImage( + ApiResponse response, SegmentImageConfig config) { + ResponseBody responseBody = response.getBody(); + String responseString; + try { + responseString = responseBody.string(); + } catch (IOException e) { + throw new GenAiIOException("Failed to read HTTP response.", e); } + + JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); + + if (this.apiClient.vertexAI()) { + responseNode = segmentImageResponseFromVertex(responseNode, null); + } + + if (!this.apiClient.vertexAI()) { + throw new UnsupportedOperationException( + "This method is only supported in the Vertex AI client."); + } + + return JsonSerializable.fromJsonNode(responseNode, SegmentImageResponse.class); } /** - * Fetches information about a model by name. + * Segments an image, creating a mask of a specified area. * - * @example ```java Model model = client.models.get("gemini-2.0-flash"); ``` + * @param model the name of the GenAI model to use for image segmentation + * @param source a {@link com.google.genai.types.SegmentImageSource} An object containing the + * source inputs (prompt, image, scribbleImmage) for image segmentation. The prompt is + * required for prompt mode and semantic mode, disallowed for other modes. scribbleImage is + * required for the interactive mode, disallowed for other modes. + * @param config a {@link com.google.genai.types.SegmentImageConfig} instance that specifies the + * optional configurations + * @return a {@link com.google.genai.types.SegmentImageResponse} instance that contains the + * generated mask. */ - public Model get(String model, GetModelConfig config) { + public SegmentImageResponse segmentImage( + String model, SegmentImageSource source, SegmentImageConfig config) { + BuiltRequest builtRequest = buildRequestForSegmentImage(model, source, config); + + try (ApiResponse response = + this.apiClient.request( + "post", builtRequest.path, builtRequest.body, builtRequest.httpOptions)) { + return processResponseForSegmentImage(response, config); + } + } + + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForGet(String model, GetModelConfig config) { GetModelParameters.Builder parameterBuilder = GetModelParameters.builder(); @@ -6212,35 +5424,54 @@ public Model get(String model, GetModelConfig config) { } // TODO: Remove the hack that removes config. - body.remove("config"); - Optional requestHttpOptions = Optional.empty(); if (config != null) { requestHttpOptions = config.httpOptions(); } + return new BuiltRequest(path, JsonSerializable.toJsonString(body), requestHttpOptions); + } + + /** A shared processResponse function for both sync and async methods. */ + Model processResponseForGet(ApiResponse response, GetModelConfig config) { + ResponseBody responseBody = response.getBody(); + String responseString; + try { + responseString = responseBody.string(); + } catch (IOException e) { + throw new GenAiIOException("Failed to read HTTP response.", e); + } + + JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); + + if (this.apiClient.vertexAI()) { + responseNode = modelFromVertex(responseNode, null); + } + + if (!this.apiClient.vertexAI()) { + responseNode = modelFromMldev(responseNode, null); + } + + return JsonSerializable.fromJsonNode(responseNode, Model.class); + } + + /** + * Fetches information about a model by name. + * + * @example ```java Model model = client.models.get("gemini-2.0-flash"); ``` + */ + public Model get(String model, GetModelConfig config) { + BuiltRequest builtRequest = buildRequestForGet(model, config); + try (ApiResponse response = this.apiClient.request( - "get", path, JsonSerializable.toJsonString(body), requestHttpOptions)) { - ResponseBody responseBody = response.getBody(); - String responseString; - try { - responseString = responseBody.string(); - } catch (IOException e) { - throw new GenAiIOException("Failed to read HTTP response.", e); - } - - JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); - if (this.apiClient.vertexAI()) { - responseNode = modelFromVertex(responseNode, null); - } else { - responseNode = modelFromMldev(responseNode, null); - } - return JsonSerializable.fromJsonNode(responseNode, Model.class); + "get", builtRequest.path, builtRequest.body, builtRequest.httpOptions)) { + return processResponseForGet(response, config); } } - ListModelsResponse privateList(ListModelsConfig config) { + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForPrivateList(ListModelsConfig config) { ListModelsParameters.Builder parameterBuilder = ListModelsParameters.builder(); @@ -6271,46 +5502,59 @@ ListModelsResponse privateList(ListModelsConfig config) { } // TODO: Remove the hack that removes config. - body.remove("config"); - Optional requestHttpOptions = Optional.empty(); if (config != null) { requestHttpOptions = config.httpOptions(); } + return new BuiltRequest(path, JsonSerializable.toJsonString(body), requestHttpOptions); + } + + /** A shared processResponse function for both sync and async methods. */ + ListModelsResponse processResponseForPrivateList(ApiResponse response, ListModelsConfig config) { + ResponseBody responseBody = response.getBody(); + String responseString; + try { + responseString = responseBody.string(); + } catch (IOException e) { + throw new GenAiIOException("Failed to read HTTP response.", e); + } + + JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); + + if (this.apiClient.vertexAI()) { + responseNode = listModelsResponseFromVertex(responseNode, null); + } + + if (!this.apiClient.vertexAI()) { + responseNode = listModelsResponseFromMldev(responseNode, null); + } + + ListModelsResponse sdkResponse = + JsonSerializable.fromJsonNode(responseNode, ListModelsResponse.class); + Headers responseHeaders = response.getHeaders(); + if (responseHeaders == null) { + return sdkResponse; + } + Map headers = new HashMap<>(); + for (String headerName : responseHeaders.names()) { + headers.put(headerName, responseHeaders.get(headerName)); + } + return sdkResponse.toBuilder().sdkHttpResponse(HttpResponse.builder().headers(headers)).build(); + } + + ListModelsResponse privateList(ListModelsConfig config) { + BuiltRequest builtRequest = buildRequestForPrivateList(config); + try (ApiResponse response = this.apiClient.request( - "get", path, JsonSerializable.toJsonString(body), requestHttpOptions)) { - ResponseBody responseBody = response.getBody(); - String responseString; - try { - responseString = responseBody.string(); - } catch (IOException e) { - throw new GenAiIOException("Failed to read HTTP response.", e); - } - - JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); - if (this.apiClient.vertexAI()) { - responseNode = listModelsResponseFromVertex(responseNode, null); - } else { - responseNode = listModelsResponseFromMldev(responseNode, null); - } - return JsonSerializable.fromJsonNode(responseNode, ListModelsResponse.class); + "get", builtRequest.path, builtRequest.body, builtRequest.httpOptions)) { + return processResponseForPrivateList(response, config); } } - /** - * Updates a tuned model by its name. - * - * @param model The name of the tuned model to update - * @param config A {@link com.google.genai.types.UpdateModelConfig} instance that specifies the - * optional configurations - * @return A {@link com.google.genai.types.Model} instance - * @example ```java Model model = client.models.update( "tunedModels/12345", - * UpdateModelConfig.builder() .displayName("New display name") .description("New - * description") .build()); ``` - */ - public Model update(String model, UpdateModelConfig config) { + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForUpdate(String model, UpdateModelConfig config) { UpdateModelParameters.Builder parameterBuilder = UpdateModelParameters.builder(); @@ -6344,40 +5588,60 @@ public Model update(String model, UpdateModelConfig config) { } // TODO: Remove the hack that removes config. - body.remove("config"); - Optional requestHttpOptions = Optional.empty(); if (config != null) { requestHttpOptions = config.httpOptions(); } - try (ApiResponse response = - this.apiClient.request( - "patch", path, JsonSerializable.toJsonString(body), requestHttpOptions)) { - ResponseBody responseBody = response.getBody(); - String responseString; - try { - responseString = responseBody.string(); - } catch (IOException e) { - throw new GenAiIOException("Failed to read HTTP response.", e); - } + return new BuiltRequest(path, JsonSerializable.toJsonString(body), requestHttpOptions); + } + + /** A shared processResponse function for both sync and async methods. */ + Model processResponseForUpdate(ApiResponse response, UpdateModelConfig config) { + ResponseBody responseBody = response.getBody(); + String responseString; + try { + responseString = responseBody.string(); + } catch (IOException e) { + throw new GenAiIOException("Failed to read HTTP response.", e); + } + + JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); - JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); - if (this.apiClient.vertexAI()) { - responseNode = modelFromVertex(responseNode, null); - } else { - responseNode = modelFromMldev(responseNode, null); - } - return JsonSerializable.fromJsonNode(responseNode, Model.class); + if (this.apiClient.vertexAI()) { + responseNode = modelFromVertex(responseNode, null); } + + if (!this.apiClient.vertexAI()) { + responseNode = modelFromMldev(responseNode, null); + } + + return JsonSerializable.fromJsonNode(responseNode, Model.class); } /** - * Fetches information about a model by name. + * Updates a tuned model by its name. * - * @example ```java Model model = client.models.delete("tunedModels/12345"); ``` + * @param model The name of the tuned model to update + * @param config A {@link com.google.genai.types.UpdateModelConfig} instance that specifies the + * optional configurations + * @return A {@link com.google.genai.types.Model} instance + * @example ```java Model model = client.models.update( "tunedModels/12345", + * UpdateModelConfig.builder() .displayName("New display name") .description("New + * description") .build()); ``` */ - public DeleteModelResponse delete(String model, DeleteModelConfig config) { + public Model update(String model, UpdateModelConfig config) { + BuiltRequest builtRequest = buildRequestForUpdate(model, config); + + try (ApiResponse response = + this.apiClient.request( + "patch", builtRequest.path, builtRequest.body, builtRequest.httpOptions)) { + return processResponseForUpdate(response, config); + } + } + + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForDelete(String model, DeleteModelConfig config) { DeleteModelParameters.Builder parameterBuilder = DeleteModelParameters.builder(); @@ -6411,45 +5675,64 @@ public DeleteModelResponse delete(String model, DeleteModelConfig config) { } // TODO: Remove the hack that removes config. - body.remove("config"); - Optional requestHttpOptions = Optional.empty(); if (config != null) { requestHttpOptions = config.httpOptions(); } - try (ApiResponse response = - this.apiClient.request( - "delete", path, JsonSerializable.toJsonString(body), requestHttpOptions)) { - ResponseBody responseBody = response.getBody(); - String responseString; - try { - responseString = responseBody.string(); - } catch (IOException e) { - throw new GenAiIOException("Failed to read HTTP response.", e); - } + return new BuiltRequest(path, JsonSerializable.toJsonString(body), requestHttpOptions); + } - JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); - if (this.apiClient.vertexAI()) { - responseNode = deleteModelResponseFromVertex(responseNode, null); - } else { - responseNode = deleteModelResponseFromMldev(responseNode, null); - } - return JsonSerializable.fromJsonNode(responseNode, DeleteModelResponse.class); + /** A shared processResponse function for both sync and async methods. */ + DeleteModelResponse processResponseForDelete(ApiResponse response, DeleteModelConfig config) { + ResponseBody responseBody = response.getBody(); + String responseString; + try { + responseString = responseBody.string(); + } catch (IOException e) { + throw new GenAiIOException("Failed to read HTTP response.", e); + } + + JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); + + if (this.apiClient.vertexAI()) { + responseNode = deleteModelResponseFromVertex(responseNode, null); } + + if (!this.apiClient.vertexAI()) { + responseNode = deleteModelResponseFromMldev(responseNode, null); + } + + DeleteModelResponse sdkResponse = + JsonSerializable.fromJsonNode(responseNode, DeleteModelResponse.class); + Headers responseHeaders = response.getHeaders(); + if (responseHeaders == null) { + return sdkResponse; + } + Map headers = new HashMap<>(); + for (String headerName : responseHeaders.names()) { + headers.put(headerName, responseHeaders.get(headerName)); + } + return sdkResponse.toBuilder().sdkHttpResponse(HttpResponse.builder().headers(headers)).build(); } /** - * Counts tokens given a GenAI model and a list of content. + * Fetches information about a model by name. * - * @param model the name of the GenAI model to use. - * @param contents a {@link List} to send to count tokens for. - * @param config a {@link com.google.genai.types.CountTokensConfig} instance that specifies the - * optional configurations - * @return a {@link com.google.genai.types.CountTokensResponse} instance that contains tokens - * count. + * @example ```java Model model = client.models.delete("tunedModels/12345"); ``` */ - public CountTokensResponse countTokens( + public DeleteModelResponse delete(String model, DeleteModelConfig config) { + BuiltRequest builtRequest = buildRequestForDelete(model, config); + + try (ApiResponse response = + this.apiClient.request( + "delete", builtRequest.path, builtRequest.body, builtRequest.httpOptions)) { + return processResponseForDelete(response, config); + } + } + + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForCountTokens( String model, List contents, CountTokensConfig config) { CountTokensParameters.Builder parameterBuilder = CountTokensParameters.builder(); @@ -6487,45 +5770,71 @@ public CountTokensResponse countTokens( } // TODO: Remove the hack that removes config. - body.remove("config"); - Optional requestHttpOptions = Optional.empty(); if (config != null) { requestHttpOptions = config.httpOptions(); } - try (ApiResponse response = - this.apiClient.request( - "post", path, JsonSerializable.toJsonString(body), requestHttpOptions)) { - ResponseBody responseBody = response.getBody(); - String responseString; - try { - responseString = responseBody.string(); - } catch (IOException e) { - throw new GenAiIOException("Failed to read HTTP response.", e); - } + return new BuiltRequest(path, JsonSerializable.toJsonString(body), requestHttpOptions); + } - JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); - if (this.apiClient.vertexAI()) { - responseNode = countTokensResponseFromVertex(responseNode, null); - } else { - responseNode = countTokensResponseFromMldev(responseNode, null); - } - return JsonSerializable.fromJsonNode(responseNode, CountTokensResponse.class); + /** A shared processResponse function for both sync and async methods. */ + CountTokensResponse processResponseForCountTokens( + ApiResponse response, CountTokensConfig config) { + ResponseBody responseBody = response.getBody(); + String responseString; + try { + responseString = responseBody.string(); + } catch (IOException e) { + throw new GenAiIOException("Failed to read HTTP response.", e); + } + + JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); + + if (this.apiClient.vertexAI()) { + responseNode = countTokensResponseFromVertex(responseNode, null); + } + + if (!this.apiClient.vertexAI()) { + responseNode = countTokensResponseFromMldev(responseNode, null); + } + + CountTokensResponse sdkResponse = + JsonSerializable.fromJsonNode(responseNode, CountTokensResponse.class); + Headers responseHeaders = response.getHeaders(); + if (responseHeaders == null) { + return sdkResponse; + } + Map headers = new HashMap<>(); + for (String headerName : responseHeaders.names()) { + headers.put(headerName, responseHeaders.get(headerName)); } + return sdkResponse.toBuilder().sdkHttpResponse(HttpResponse.builder().headers(headers)).build(); } /** - * Computes tokens given a GenAI model and a list of content. + * Counts tokens given a GenAI model and a list of content. * * @param model the name of the GenAI model to use. - * @param contents a {@link List} to send to compute tokens for. - * @param config a {@link com.google.genai.types.ComputeTokensConfig} instance that specifies the + * @param contents a {@link List} to send to count tokens for. + * @param config a {@link com.google.genai.types.CountTokensConfig} instance that specifies the * optional configurations - * @return a {@link com.google.genai.types.ComputeTokensResponse} instance that contains tokens - * results. + * @return a {@link com.google.genai.types.CountTokensResponse} instance that contains tokens + * count. */ - public ComputeTokensResponse computeTokens( + public CountTokensResponse countTokens( + String model, List contents, CountTokensConfig config) { + BuiltRequest builtRequest = buildRequestForCountTokens(model, contents, config); + + try (ApiResponse response = + this.apiClient.request( + "post", builtRequest.path, builtRequest.body, builtRequest.httpOptions)) { + return processResponseForCountTokens(response, config); + } + } + + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForComputeTokens( String model, List contents, ComputeTokensConfig config) { ComputeTokensParameters.Builder parameterBuilder = ComputeTokensParameters.builder(); @@ -6559,53 +5868,78 @@ public ComputeTokensResponse computeTokens( } // TODO: Remove the hack that removes config. - body.remove("config"); - Optional requestHttpOptions = Optional.empty(); if (config != null) { requestHttpOptions = config.httpOptions(); } - try (ApiResponse response = - this.apiClient.request( - "post", path, JsonSerializable.toJsonString(body), requestHttpOptions)) { - ResponseBody responseBody = response.getBody(); - String responseString; - try { - responseString = responseBody.string(); - } catch (IOException e) { - throw new GenAiIOException("Failed to read HTTP response.", e); - } + return new BuiltRequest(path, JsonSerializable.toJsonString(body), requestHttpOptions); + } - JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); - if (this.apiClient.vertexAI()) { - responseNode = computeTokensResponseFromVertex(responseNode, null); - } else { - throw new UnsupportedOperationException( - "This method is only supported in the Vertex AI client."); - } - return JsonSerializable.fromJsonNode(responseNode, ComputeTokensResponse.class); + /** A shared processResponse function for both sync and async methods. */ + ComputeTokensResponse processResponseForComputeTokens( + ApiResponse response, ComputeTokensConfig config) { + ResponseBody responseBody = response.getBody(); + String responseString; + try { + responseString = responseBody.string(); + } catch (IOException e) { + throw new GenAiIOException("Failed to read HTTP response.", e); + } + + JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); + + if (this.apiClient.vertexAI()) { + responseNode = computeTokensResponseFromVertex(responseNode, null); + } + + if (!this.apiClient.vertexAI()) { + throw new UnsupportedOperationException( + "This method is only supported in the Vertex AI client."); } + + ComputeTokensResponse sdkResponse = + JsonSerializable.fromJsonNode(responseNode, ComputeTokensResponse.class); + Headers responseHeaders = response.getHeaders(); + if (responseHeaders == null) { + return sdkResponse; + } + Map headers = new HashMap<>(); + for (String headerName : responseHeaders.names()) { + headers.put(headerName, responseHeaders.get(headerName)); + } + return sdkResponse.toBuilder().sdkHttpResponse(HttpResponse.builder().headers(headers)).build(); } /** - * Generates videos given a GenAI model, and an input (text, image, or video). - * - *

This method is experimental. + * Computes tokens given a GenAI model and a list of content. * - * @param model the name of the GenAI model to use for generating videos - * @param prompt the text prompt for generating the videos. Optional for image to video and video - * extension use cases. - * @param image the input image for generating the videos. Optional if prompt is provided. - * @param video the input video for video extension use cases. Optional if prompt or image is - * provided. - * @param config a {@link com.google.genai.types.GenerateVideosConfig} instance that specifies the + * @param model the name of the GenAI model to use. + * @param contents a {@link List} to send to compute tokens for. + * @param config a {@link com.google.genai.types.ComputeTokensConfig} instance that specifies the * optional configurations - * @return a {@link com.google.genai.types.GenerateVideosOperation} instance that contains the - * generated videos. + * @return a {@link com.google.genai.types.ComputeTokensResponse} instance that contains tokens + * results. */ - GenerateVideosOperation privateGenerateVideos( - String model, String prompt, Image image, Video video, GenerateVideosConfig config) { + public ComputeTokensResponse computeTokens( + String model, List contents, ComputeTokensConfig config) { + BuiltRequest builtRequest = buildRequestForComputeTokens(model, contents, config); + + try (ApiResponse response = + this.apiClient.request( + "post", builtRequest.path, builtRequest.body, builtRequest.httpOptions)) { + return processResponseForComputeTokens(response, config); + } + } + + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForPrivateGenerateVideos( + String model, + String prompt, + Image image, + Video video, + GenerateVideosSource source, + GenerateVideosConfig config) { GenerateVideosParameters.Builder parameterBuilder = GenerateVideosParameters.builder(); @@ -6621,6 +5955,9 @@ GenerateVideosOperation privateGenerateVideos( if (!Common.isZero(video)) { parameterBuilder.video(video); } + if (!Common.isZero(source)) { + parameterBuilder.source(source); + } if (!Common.isZero(config)) { parameterBuilder.config(config); } @@ -6648,31 +5985,53 @@ GenerateVideosOperation privateGenerateVideos( } // TODO: Remove the hack that removes config. - body.remove("config"); - Optional requestHttpOptions = Optional.empty(); if (config != null) { requestHttpOptions = config.httpOptions(); } + return new BuiltRequest(path, JsonSerializable.toJsonString(body), requestHttpOptions); + } + + /** A shared processResponse function for both sync and async methods. */ + GenerateVideosOperation processResponseForPrivateGenerateVideos( + ApiResponse response, GenerateVideosConfig config) { + ResponseBody responseBody = response.getBody(); + String responseString; + try { + responseString = responseBody.string(); + } catch (IOException e) { + throw new GenAiIOException("Failed to read HTTP response.", e); + } + + JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); + + if (this.apiClient.vertexAI()) { + responseNode = generateVideosOperationFromVertex(responseNode, null); + } + + if (!this.apiClient.vertexAI()) { + responseNode = generateVideosOperationFromMldev(responseNode, null); + } + + return JsonSerializable.fromJsonNode(responseNode, GenerateVideosOperation.class); + } + + /** Private method for generating videos. */ + GenerateVideosOperation privateGenerateVideos( + String model, + String prompt, + Image image, + Video video, + GenerateVideosSource source, + GenerateVideosConfig config) { + BuiltRequest builtRequest = + buildRequestForPrivateGenerateVideos(model, prompt, image, video, source, config); + try (ApiResponse response = this.apiClient.request( - "post", path, JsonSerializable.toJsonString(body), requestHttpOptions)) { - ResponseBody responseBody = response.getBody(); - String responseString; - try { - responseString = responseBody.string(); - } catch (IOException e) { - throw new GenAiIOException("Failed to read HTTP response.", e); - } - - JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); - if (this.apiClient.vertexAI()) { - responseNode = generateVideosOperationFromVertex(responseNode, null); - } else { - responseNode = generateVideosOperationFromMldev(responseNode, null); - } - return JsonSerializable.fromJsonNode(responseNode, GenerateVideosOperation.class); + "post", builtRequest.path, builtRequest.body, builtRequest.httpOptions)) { + return processResponseForPrivateGenerateVideos(response, config); } } @@ -6856,21 +6215,8 @@ public ComputeTokensResponse computeTokens( return computeTokens(model, Transformers.tContents(text), config); } - /** - * Generates images given a GenAI model and a prompt. - * - * @param model the name of the GenAI model to use for generating images - * @param prompt the prompt to generate images - * @param config a {@link com.google.genai.types.GenerateImagesConfig} instance that specifies the - * optional configurations - * @return a {@link com.google.genai.types.GenerateImagesResponse} instance that contains the - * generated images. - */ - public GenerateImagesResponse generateImages( - String model, String prompt, GenerateImagesConfig config) { - - GenerateImagesResponse apiResponse = privateGenerateImages(model, prompt, config); - + /** Post processes the GenerateImagesResponse from the API. */ + GenerateImagesResponse postProcessGenerateImagesResponse(GenerateImagesResponse apiResponse) { SafetyAttributes positivePromptSafetyAttributes = null; List generatedImages = new ArrayList<>(); @@ -6898,8 +6244,22 @@ public GenerateImagesResponse generateImages( builder = builder.positivePromptSafetyAttributes(positivePromptSafetyAttributes); } - GenerateImagesResponse response = builder.build(); - return response; + return builder.build(); + } + + /** + * Generates images given a GenAI model and a prompt. + * + * @param model the name of the GenAI model to use for generating images + * @param prompt the prompt to generate images + * @param config a {@link com.google.genai.types.GenerateImagesConfig} instance that specifies the + * optional configurations + * @return a {@link com.google.genai.types.GenerateImagesResponse} instance that contains the + * generated images. + */ + public GenerateImagesResponse generateImages( + String model, String prompt, GenerateImagesConfig config) { + return postProcessGenerateImagesResponse(privateGenerateImages(model, prompt, config)); } /** @@ -6908,12 +6268,13 @@ public GenerateImagesResponse generateImages( * @param model the name of the GenAI model to use for editing capabilities * @param prompt the prompt to edit the image * @param referenceImages a {@link List} to send to use for - * editing. The 5 types of reference images are: {@link + * editing. The 6 types of reference images are: {@link * com.google.genai.types.RawReferenceImage}, {@link * com.google.genai.types.MaskReferenceImage}, {@link * com.google.genai.types.ControlReferenceImage}, {@link * com.google.genai.types.StyleReferenceImage}, {@link - * com.google.genai.types.SubjectReferenceImage}, + * com.google.genai.types.SubjectReferenceImage}, {@link + * com.google.genai.types.ContentReferenceImage} * @param config a {@link com.google.genai.types.EditImageConfig} instance that specifies the * optional configurations * @return a {@link com.google.genai.types.EditImageResponse} instance that contains the edited @@ -6930,28 +6291,25 @@ public EditImageResponse editImage( return privateEditImage(model, prompt, referenceImagesAPI, config); } - /** - * Upscales an image given a GenAI model and an image and an upscale factor. - * - * @param model the name of the GenAI model to use for upscaling - * @param image a {@link com.google.genai.types.Image} to send to the generative model - * @param upscaleFactor the factor to upscale the image - * @param config a {@link com.google.genai.types.UpscaleImageConfig} instance that specifies the - * optional configurations - * @return a {@link com.google.genai.types.UpscaleImageResponse} instance that contains the - * upscaled image. - */ - public UpscaleImageResponse upscaleImage( - String model, Image image, String upscaleFactor, UpscaleImageConfig config) { - + /** Preprocesses the UpscaleImageConfig for the API. */ + UpscaleImageAPIConfig preProcessUpscaleImageConfig(UpscaleImageConfig config) { UpscaleImageAPIConfig.Builder builder = UpscaleImageAPIConfig.builder(); if (config != null) { + if (config.outputGcsUri().isPresent()) { + builder = builder.outputGcsUri(config.outputGcsUri().get()); + } if (config.outputMimeType().isPresent()) { builder = builder.outputMimeType(config.outputMimeType().get()); } if (config.outputCompressionQuality().isPresent()) { builder = builder.outputCompressionQuality(config.outputCompressionQuality().get()); } + if (config.safetyFilterLevel().isPresent()) { + builder = builder.safetyFilterLevel(config.safetyFilterLevel().get()); + } + if (config.personGeneration().isPresent()) { + builder = builder.personGeneration(config.personGeneration().get()); + } if (config.includeRaiReason().isPresent()) { builder = builder.includeRaiReason(config.includeRaiReason().get()); } @@ -6961,14 +6319,92 @@ public UpscaleImageResponse upscaleImage( if (config.imagePreservationFactor().isPresent()) { builder = builder.imagePreservationFactor(config.imagePreservationFactor().get()); } + if (config.labels().isPresent()) { + builder = builder.labels(config.labels().get()); + } } builder = builder.mode("upscale"); builder = builder.numberOfImages(1); - UpscaleImageAPIConfig apiConfig = builder.build(); + return builder.build(); + } + + /** + * Upscales an image given a GenAI model and an image and an upscale factor. + * + * @param model the name of the GenAI model to use for upscaling + * @param image a {@link com.google.genai.types.Image} to send to the generative model + * @param upscaleFactor the factor to upscale the image + * @param config a {@link com.google.genai.types.UpscaleImageConfig} instance that specifies the + * optional configurations + * @return a {@link com.google.genai.types.UpscaleImageResponse} instance that contains the + * upscaled image. + */ + public UpscaleImageResponse upscaleImage( + String model, Image image, String upscaleFactor, UpscaleImageConfig config) { + return privateUpscaleImage(model, image, upscaleFactor, preProcessUpscaleImageConfig(config)); + } + + /** Preprocesses the GenerateVideosSource for the API. */ + GenerateVideosSource preProcessGenerateVideosSource(GenerateVideosSource source) { + if (!this.apiClient.vertexAI()) { + if (source != null + && source.video().isPresent() + && source.video().get().uri().isPresent() + && source.video().get().videoBytes().isPresent()) { + + Video.Builder videoBuilder = Video.builder().uri(source.video().get().uri().get()); + if (source.video().get().mimeType().isPresent()) { + videoBuilder = videoBuilder.mimeType(source.video().get().mimeType().get()); + } + + GenerateVideosSource.Builder sourceBuilder = + GenerateVideosSource.builder().video(videoBuilder.build()); + if (source.prompt().isPresent()) { + sourceBuilder = sourceBuilder.prompt(source.prompt().get()); + } + if (source.image().isPresent()) { + sourceBuilder = sourceBuilder.image(source.image().get()); + } + source = sourceBuilder.build(); + } + } + return source; + } + + /** + * Generates videos given a GenAI model, and a GenerateVideosSource source. + * + *

This method is experimental. + * + * @param model the name of the GenAI model to use for generating videos + * @param source a {@link com.google.genai.types.GenerateVideosSource} that specifies the inputs + * (prompt, image, and/or video) to generate videos. + * @param config a {@link com.google.genai.types.GenerateVideosConfig} instance that specifies the + * optional configurations + * @return a {@link com.google.genai.types.GenerateVideosOperation} instance that contains the + * generated videos. + */ + public GenerateVideosOperation generateVideos( + String model, GenerateVideosSource source, GenerateVideosConfig config) { + return privateGenerateVideos( + model, null, null, null, preProcessGenerateVideosSource(source), config); + } - return privateUpscaleImage(model, image, upscaleFactor, apiConfig); + /** Preprocesses the Video for the API. */ + Video preProcessVideo(Video video) { + if (!this.apiClient.vertexAI()) { + if (video != null && video.uri().isPresent() && video.videoBytes().isPresent()) { + + Video.Builder videoBuilder = Video.builder().uri(video.uri().get()); + if (video.mimeType().isPresent()) { + videoBuilder = videoBuilder.mimeType(video.mimeType().get()); + } + video = videoBuilder.build(); + } + } + return video; } /** @@ -6989,7 +6425,7 @@ public UpscaleImageResponse upscaleImage( */ public GenerateVideosOperation generateVideos( String model, String prompt, Image image, Video video, GenerateVideosConfig config) { - return privateGenerateVideos(model, prompt, image, video, config); + return privateGenerateVideos(model, prompt, image, preProcessVideo(video), null, config); } /** diff --git a/src/main/java/com/google/genai/Operations.java b/src/main/java/com/google/genai/Operations.java index fa69713e752..b8bfcbd36ae 100644 --- a/src/main/java/com/google/genai/Operations.java +++ b/src/main/java/com/google/genai/Operations.java @@ -22,6 +22,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; +import com.google.genai.Common.BuiltRequest; import com.google.genai.errors.GenAiIOException; import com.google.genai.types.FetchPredictOperationConfig; import com.google.genai.types.FetchPredictOperationParameters; @@ -29,6 +30,7 @@ import com.google.genai.types.GetOperationConfig; import com.google.genai.types.GetOperationParameters; import com.google.genai.types.HttpOptions; +import com.google.genai.types.Operation; import java.io.IOException; import java.util.Optional; import okhttp3.ResponseBody; @@ -41,6 +43,7 @@ *

This module is experimental. */ public final class Operations { + final ApiClient apiClient; public Operations(ApiClient apiClient) { @@ -48,110 +51,109 @@ public Operations(ApiClient apiClient) { } @ExcludeFromGeneratedCoverageReport - ObjectNode getOperationParametersToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode fetchPredictOperationParametersToVertex(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); if (Common.getValueByPath(fromObject, new String[] {"operationName"}) != null) { Common.setValueByPath( toObject, - new String[] {"_url", "operationName"}, + new String[] {"operationName"}, Common.getValueByPath(fromObject, new String[] {"operationName"})); } - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"resourceName"}) != null) { Common.setValueByPath( toObject, - new String[] {"config"}, - Common.getValueByPath(fromObject, new String[] {"config"})); + new String[] {"_url", "resourceName"}, + Common.getValueByPath(fromObject, new String[] {"resourceName"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode getOperationParametersToVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode generateVideosOperationFromMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"operationName"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { Common.setValueByPath( toObject, - new String[] {"_url", "operationName"}, - Common.getValueByPath(fromObject, new String[] {"operationName"})); + new String[] {"name"}, + Common.getValueByPath(fromObject, new String[] {"name"})); } - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"metadata"}) != null) { Common.setValueByPath( toObject, - new String[] {"config"}, - Common.getValueByPath(fromObject, new String[] {"config"})); + new String[] {"metadata"}, + Common.getValueByPath(fromObject, new String[] {"metadata"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode fetchPredictOperationParametersToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"operationName"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"done"}) != null) { Common.setValueByPath( toObject, - new String[] {"operationName"}, - Common.getValueByPath(fromObject, new String[] {"operationName"})); + new String[] {"done"}, + Common.getValueByPath(fromObject, new String[] {"done"})); } - if (Common.getValueByPath(fromObject, new String[] {"resourceName"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"error"}) != null) { Common.setValueByPath( toObject, - new String[] {"_url", "resourceName"}, - Common.getValueByPath(fromObject, new String[] {"resourceName"})); + new String[] {"error"}, + Common.getValueByPath(fromObject, new String[] {"error"})); } - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"response", "generateVideoResponse"}) + != null) { Common.setValueByPath( toObject, - new String[] {"config"}, - Common.getValueByPath(fromObject, new String[] {"config"})); + new String[] {"response"}, + generateVideosResponseFromMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath( + fromObject, new String[] {"response", "generateVideoResponse"})), + toObject)); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode videoFromMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode generateVideosOperationFromVertex(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"video", "uri"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { Common.setValueByPath( toObject, - new String[] {"uri"}, - Common.getValueByPath(fromObject, new String[] {"video", "uri"})); + new String[] {"name"}, + Common.getValueByPath(fromObject, new String[] {"name"})); } - if (Common.getValueByPath(fromObject, new String[] {"video", "encodedVideo"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"metadata"}) != null) { Common.setValueByPath( toObject, - new String[] {"videoBytes"}, - Transformers.tBytes( - Common.getValueByPath(fromObject, new String[] {"video", "encodedVideo"}))); + new String[] {"metadata"}, + Common.getValueByPath(fromObject, new String[] {"metadata"})); } - if (Common.getValueByPath(fromObject, new String[] {"encoding"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"done"}) != null) { Common.setValueByPath( toObject, - new String[] {"mimeType"}, - Common.getValueByPath(fromObject, new String[] {"encoding"})); + new String[] {"done"}, + Common.getValueByPath(fromObject, new String[] {"done"})); } - return toObject; - } + if (Common.getValueByPath(fromObject, new String[] {"error"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"error"}, + Common.getValueByPath(fromObject, new String[] {"error"})); + } - @ExcludeFromGeneratedCoverageReport - ObjectNode generatedVideoFromMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"_self"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"response"}) != null) { Common.setValueByPath( toObject, - new String[] {"video"}, - videoFromMldev( + new String[] {"response"}, + generateVideosResponseFromVertex( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"_self"})), + Common.getValueByPath(fromObject, new String[] {"response"})), toObject)); } @@ -191,74 +193,47 @@ ObjectNode generateVideosResponseFromMldev(JsonNode fromObject, ObjectNode paren } @ExcludeFromGeneratedCoverageReport - ObjectNode generateVideosOperationFromMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode generateVideosResponseFromVertex(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"name"}, - Common.getValueByPath(fromObject, new String[] {"name"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"metadata"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"metadata"}, - Common.getValueByPath(fromObject, new String[] {"metadata"})); - } + if (Common.getValueByPath(fromObject, new String[] {"videos"}) != null) { + ArrayNode keyArray = (ArrayNode) Common.getValueByPath(fromObject, new String[] {"videos"}); + ObjectMapper objectMapper = new ObjectMapper(); + ArrayNode result = objectMapper.createArrayNode(); - if (Common.getValueByPath(fromObject, new String[] {"done"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"done"}, - Common.getValueByPath(fromObject, new String[] {"done"})); + for (JsonNode item : keyArray) { + result.add(generatedVideoFromVertex(JsonSerializable.toJsonNode(item), toObject)); + } + Common.setValueByPath(toObject, new String[] {"generatedVideos"}, result); } - if (Common.getValueByPath(fromObject, new String[] {"error"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"raiMediaFilteredCount"}) != null) { Common.setValueByPath( toObject, - new String[] {"error"}, - Common.getValueByPath(fromObject, new String[] {"error"})); + new String[] {"raiMediaFilteredCount"}, + Common.getValueByPath(fromObject, new String[] {"raiMediaFilteredCount"})); } - if (Common.getValueByPath(fromObject, new String[] {"response", "generateVideoResponse"}) - != null) { + if (Common.getValueByPath(fromObject, new String[] {"raiMediaFilteredReasons"}) != null) { Common.setValueByPath( toObject, - new String[] {"response"}, - generateVideosResponseFromMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath( - fromObject, new String[] {"response", "generateVideoResponse"})), - toObject)); + new String[] {"raiMediaFilteredReasons"}, + Common.getValueByPath(fromObject, new String[] {"raiMediaFilteredReasons"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode videoFromVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode generatedVideoFromMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"gcsUri"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"uri"}, - Common.getValueByPath(fromObject, new String[] {"gcsUri"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"bytesBase64Encoded"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"videoBytes"}, - Transformers.tBytes( - Common.getValueByPath(fromObject, new String[] {"bytesBase64Encoded"}))); - } - - if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"video"}) != null) { Common.setValueByPath( toObject, - new String[] {"mimeType"}, - Common.getValueByPath(fromObject, new String[] {"mimeType"})); + new String[] {"video"}, + videoFromMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"video"})), + toObject)); } return toObject; @@ -281,81 +256,86 @@ ObjectNode generatedVideoFromVertex(JsonNode fromObject, ObjectNode parentObject } @ExcludeFromGeneratedCoverageReport - ObjectNode generateVideosResponseFromVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode getOperationParametersToMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"videos"}) != null) { - ArrayNode keyArray = (ArrayNode) Common.getValueByPath(fromObject, new String[] {"videos"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add(generatedVideoFromVertex(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"generatedVideos"}, result); - } - - if (Common.getValueByPath(fromObject, new String[] {"raiMediaFilteredCount"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"operationName"}) != null) { Common.setValueByPath( toObject, - new String[] {"raiMediaFilteredCount"}, - Common.getValueByPath(fromObject, new String[] {"raiMediaFilteredCount"})); + new String[] {"_url", "operationName"}, + Common.getValueByPath(fromObject, new String[] {"operationName"})); } - if (Common.getValueByPath(fromObject, new String[] {"raiMediaFilteredReasons"}) != null) { + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode getOperationParametersToVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"operationName"}) != null) { Common.setValueByPath( toObject, - new String[] {"raiMediaFilteredReasons"}, - Common.getValueByPath(fromObject, new String[] {"raiMediaFilteredReasons"})); + new String[] {"_url", "operationName"}, + Common.getValueByPath(fromObject, new String[] {"operationName"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode generateVideosOperationFromVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode videoFromMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"uri"}) != null) { + Common.setValueByPath( + toObject, new String[] {"uri"}, Common.getValueByPath(fromObject, new String[] {"uri"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"encodedVideo"}) != null) { Common.setValueByPath( toObject, - new String[] {"name"}, - Common.getValueByPath(fromObject, new String[] {"name"})); + new String[] {"videoBytes"}, + Transformers.tBytes(Common.getValueByPath(fromObject, new String[] {"encodedVideo"}))); } - if (Common.getValueByPath(fromObject, new String[] {"metadata"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"encoding"}) != null) { Common.setValueByPath( toObject, - new String[] {"metadata"}, - Common.getValueByPath(fromObject, new String[] {"metadata"})); + new String[] {"mimeType"}, + Common.getValueByPath(fromObject, new String[] {"encoding"})); } - if (Common.getValueByPath(fromObject, new String[] {"done"}) != null) { + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode videoFromVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"gcsUri"}) != null) { Common.setValueByPath( toObject, - new String[] {"done"}, - Common.getValueByPath(fromObject, new String[] {"done"})); + new String[] {"uri"}, + Common.getValueByPath(fromObject, new String[] {"gcsUri"})); } - if (Common.getValueByPath(fromObject, new String[] {"error"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"bytesBase64Encoded"}) != null) { Common.setValueByPath( toObject, - new String[] {"error"}, - Common.getValueByPath(fromObject, new String[] {"error"})); + new String[] {"videoBytes"}, + Transformers.tBytes( + Common.getValueByPath(fromObject, new String[] {"bytesBase64Encoded"}))); } - if (Common.getValueByPath(fromObject, new String[] {"response"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { Common.setValueByPath( toObject, - new String[] {"response"}, - generateVideosResponseFromVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"response"})), - toObject)); + new String[] {"mimeType"}, + Common.getValueByPath(fromObject, new String[] {"mimeType"})); } return toObject; } - GenerateVideosOperation privateGetVideosOperation( + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForPrivateGetVideosOperation( String operationName, GetOperationConfig config) { GetOperationParameters.Builder parameterBuilder = GetOperationParameters.builder(); @@ -390,35 +370,40 @@ GenerateVideosOperation privateGetVideosOperation( } // TODO: Remove the hack that removes config. - body.remove("config"); - Optional requestHttpOptions = Optional.empty(); if (config != null) { requestHttpOptions = config.httpOptions(); } + return new BuiltRequest(path, JsonSerializable.toJsonString(body), requestHttpOptions); + } + + /** A shared processResponse function for both sync and async methods. */ + JsonNode processResponseForPrivateGetVideosOperation( + ApiResponse response, GetOperationConfig config) { + ResponseBody responseBody = response.getBody(); + String responseString; + try { + responseString = responseBody.string(); + } catch (IOException e) { + throw new GenAiIOException("Failed to read HTTP response.", e); + } + + return JsonSerializable.stringToJsonNode(responseString); + } + + JsonNode privateGetVideosOperation(String operationName, GetOperationConfig config) { + BuiltRequest builtRequest = buildRequestForPrivateGetVideosOperation(operationName, config); + try (ApiResponse response = this.apiClient.request( - "get", path, JsonSerializable.toJsonString(body), requestHttpOptions)) { - ResponseBody responseBody = response.getBody(); - String responseString; - try { - responseString = responseBody.string(); - } catch (IOException e) { - throw new GenAiIOException("Failed to read HTTP response.", e); - } - - JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); - if (this.apiClient.vertexAI()) { - responseNode = generateVideosOperationFromVertex(responseNode, null); - } else { - responseNode = generateVideosOperationFromMldev(responseNode, null); - } - return JsonSerializable.fromJsonNode(responseNode, GenerateVideosOperation.class); + "get", builtRequest.path, builtRequest.body, builtRequest.httpOptions)) { + return processResponseForPrivateGetVideosOperation(response, config); } } - GenerateVideosOperation privateFetchPredictVideosOperation( + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForPrivateFetchPredictVideosOperation( String operationName, String resourceName, FetchPredictOperationConfig config) { FetchPredictOperationParameters.Builder parameterBuilder = @@ -453,32 +438,37 @@ GenerateVideosOperation privateFetchPredictVideosOperation( } // TODO: Remove the hack that removes config. - body.remove("config"); - Optional requestHttpOptions = Optional.empty(); if (config != null) { requestHttpOptions = config.httpOptions(); } + return new BuiltRequest(path, JsonSerializable.toJsonString(body), requestHttpOptions); + } + + /** A shared processResponse function for both sync and async methods. */ + JsonNode processResponseForPrivateFetchPredictVideosOperation( + ApiResponse response, FetchPredictOperationConfig config) { + ResponseBody responseBody = response.getBody(); + String responseString; + try { + responseString = responseBody.string(); + } catch (IOException e) { + throw new GenAiIOException("Failed to read HTTP response.", e); + } + + return JsonSerializable.stringToJsonNode(responseString); + } + + JsonNode privateFetchPredictVideosOperation( + String operationName, String resourceName, FetchPredictOperationConfig config) { + BuiltRequest builtRequest = + buildRequestForPrivateFetchPredictVideosOperation(operationName, resourceName, config); + try (ApiResponse response = this.apiClient.request( - "post", path, JsonSerializable.toJsonString(body), requestHttpOptions)) { - ResponseBody responseBody = response.getBody(); - String responseString; - try { - responseString = responseBody.string(); - } catch (IOException e) { - throw new GenAiIOException("Failed to read HTTP response.", e); - } - - JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); - if (this.apiClient.vertexAI()) { - responseNode = generateVideosOperationFromVertex(responseNode, null); - } else { - throw new UnsupportedOperationException( - "This method is only supported in the Vertex AI client."); - } - return JsonSerializable.fromJsonNode(responseNode, GenerateVideosOperation.class); + "post", builtRequest.path, builtRequest.body, builtRequest.httpOptions)) { + return processResponseForPrivateFetchPredictVideosOperation(response, config); } } @@ -491,20 +481,29 @@ GenerateVideosOperation privateFetchPredictVideosOperation( */ public GenerateVideosOperation getVideosOperation( GenerateVideosOperation operation, GetOperationConfig config) { + return get(operation, config); + } + /** + * Gets the status of an Operation. + * + * @param operation An Operation. + * @param config The configuration for getting the operation. + * @return An Operation with the updated status of the operation. + */ + public > U get(U operation, GetOperationConfig config) { if (!operation.name().isPresent()) { - throw new Error("Operation name is required."); + throw new IllegalArgumentException("Operation name is required."); } if (this.apiClient.vertexAI()) { String resourceName = operation.name().get().split("/operations/")[0]; - - FetchPredictOperationConfig fetchConfig = FetchPredictOperationConfig.builder().build(); - - return this.privateFetchPredictVideosOperation( - operation.name().get(), resourceName, fetchConfig); + JsonNode response = + this.privateFetchPredictVideosOperation(operation.name().get(), resourceName, null); + return operation.fromApiResponse(response, true); } else { - return this.privateGetVideosOperation(operation.name().get(), config); + JsonNode response = this.privateGetVideosOperation(operation.name().get(), config); + return operation.fromApiResponse(response, false); } } } diff --git a/src/main/java/com/google/genai/OperationsConverters.java b/src/main/java/com/google/genai/OperationsConverters.java new file mode 100644 index 00000000000..5c48d2fc114 --- /dev/null +++ b/src/main/java/com/google/genai/OperationsConverters.java @@ -0,0 +1,352 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Auto-generated code. Do not edit. + +package com.google.genai; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.google.api.core.InternalApi; + +/** Internal SDK converter functions. */ +@InternalApi +public final class OperationsConverters { + private final ApiClient apiClient; + + public OperationsConverters(ApiClient apiClient) { + this.apiClient = apiClient; + } + + @ExcludeFromGeneratedCoverageReport + @InternalApi + public ObjectNode fetchPredictOperationParametersToMldev( + JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"operationName"}))) { + throw new IllegalArgumentException("operationName parameter is not supported in Gemini API."); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"resourceName"}))) { + throw new IllegalArgumentException("resourceName parameter is not supported in Gemini API."); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"config"}))) { + throw new IllegalArgumentException("config parameter is not supported in Gemini API."); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + @InternalApi + public ObjectNode fetchPredictOperationParametersToVertex( + JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"operationName"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"operationName"}, + Common.getValueByPath(fromObject, new String[] {"operationName"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"resourceName"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"_url", "resourceName"}, + Common.getValueByPath(fromObject, new String[] {"resourceName"})); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + @InternalApi + public ObjectNode generateVideosOperationFromMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"name"}, + Common.getValueByPath(fromObject, new String[] {"name"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"metadata"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"metadata"}, + Common.getValueByPath(fromObject, new String[] {"metadata"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"done"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"done"}, + Common.getValueByPath(fromObject, new String[] {"done"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"error"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"error"}, + Common.getValueByPath(fromObject, new String[] {"error"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"response", "generateVideoResponse"}) + != null) { + Common.setValueByPath( + toObject, + new String[] {"response"}, + generateVideosResponseFromMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath( + fromObject, new String[] {"response", "generateVideoResponse"})), + toObject)); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + @InternalApi + public ObjectNode generateVideosOperationFromVertex( + JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"name"}, + Common.getValueByPath(fromObject, new String[] {"name"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"metadata"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"metadata"}, + Common.getValueByPath(fromObject, new String[] {"metadata"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"done"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"done"}, + Common.getValueByPath(fromObject, new String[] {"done"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"error"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"error"}, + Common.getValueByPath(fromObject, new String[] {"error"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"response"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"response"}, + generateVideosResponseFromVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"response"})), + toObject)); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + @InternalApi + public ObjectNode generateVideosResponseFromMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"generatedSamples"}) != null) { + ArrayNode keyArray = + (ArrayNode) Common.getValueByPath(fromObject, new String[] {"generatedSamples"}); + ObjectMapper objectMapper = new ObjectMapper(); + ArrayNode result = objectMapper.createArrayNode(); + + for (JsonNode item : keyArray) { + result.add(generatedVideoFromMldev(JsonSerializable.toJsonNode(item), toObject)); + } + Common.setValueByPath(toObject, new String[] {"generatedVideos"}, result); + } + + if (Common.getValueByPath(fromObject, new String[] {"raiMediaFilteredCount"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"raiMediaFilteredCount"}, + Common.getValueByPath(fromObject, new String[] {"raiMediaFilteredCount"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"raiMediaFilteredReasons"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"raiMediaFilteredReasons"}, + Common.getValueByPath(fromObject, new String[] {"raiMediaFilteredReasons"})); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + @InternalApi + public ObjectNode generateVideosResponseFromVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"videos"}) != null) { + ArrayNode keyArray = (ArrayNode) Common.getValueByPath(fromObject, new String[] {"videos"}); + ObjectMapper objectMapper = new ObjectMapper(); + ArrayNode result = objectMapper.createArrayNode(); + + for (JsonNode item : keyArray) { + result.add(generatedVideoFromVertex(JsonSerializable.toJsonNode(item), toObject)); + } + Common.setValueByPath(toObject, new String[] {"generatedVideos"}, result); + } + + if (Common.getValueByPath(fromObject, new String[] {"raiMediaFilteredCount"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"raiMediaFilteredCount"}, + Common.getValueByPath(fromObject, new String[] {"raiMediaFilteredCount"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"raiMediaFilteredReasons"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"raiMediaFilteredReasons"}, + Common.getValueByPath(fromObject, new String[] {"raiMediaFilteredReasons"})); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + @InternalApi + public ObjectNode generatedVideoFromMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"video"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"video"}, + videoFromMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"video"})), + toObject)); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + @InternalApi + public ObjectNode generatedVideoFromVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"_self"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"video"}, + videoFromVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"_self"})), + toObject)); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + @InternalApi + public ObjectNode getOperationParametersToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"operationName"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"_url", "operationName"}, + Common.getValueByPath(fromObject, new String[] {"operationName"})); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + @InternalApi + public ObjectNode getOperationParametersToVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"operationName"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"_url", "operationName"}, + Common.getValueByPath(fromObject, new String[] {"operationName"})); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + @InternalApi + public ObjectNode videoFromMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"uri"}) != null) { + Common.setValueByPath( + toObject, new String[] {"uri"}, Common.getValueByPath(fromObject, new String[] {"uri"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"encodedVideo"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"videoBytes"}, + Transformers.tBytes(Common.getValueByPath(fromObject, new String[] {"encodedVideo"}))); + } + + if (Common.getValueByPath(fromObject, new String[] {"encoding"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"mimeType"}, + Common.getValueByPath(fromObject, new String[] {"encoding"})); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + @InternalApi + public ObjectNode videoFromVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"gcsUri"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"uri"}, + Common.getValueByPath(fromObject, new String[] {"gcsUri"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"bytesBase64Encoded"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"videoBytes"}, + Transformers.tBytes( + Common.getValueByPath(fromObject, new String[] {"bytesBase64Encoded"}))); + } + + if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"mimeType"}, + Common.getValueByPath(fromObject, new String[] {"mimeType"})); + } + + return toObject; + } +} diff --git a/src/main/java/com/google/genai/Pager.java b/src/main/java/com/google/genai/Pager.java index 92b0a563229..f9387f1244e 100644 --- a/src/main/java/com/google/genai/Pager.java +++ b/src/main/java/com/google/genai/Pager.java @@ -20,7 +20,9 @@ import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.common.collect.ImmutableList; import com.google.genai.errors.GenAiIOException; +import com.google.genai.types.HttpResponse; import java.util.Iterator; +import java.util.Optional; import java.util.function.Function; /** Pager class for iterating through paginated results. */ @@ -71,6 +73,14 @@ public ImmutableList page() { return page; } + /** + * Returns an Optional of the {@link HttpResponse} for the current page, which can be used to get + * the http headers. + */ + public Optional sdkHttpResponse() { + return Optional.ofNullable(sdkHttpResponse); + } + /** Iterator for the Pager. */ private class PagerIterator implements Iterator { private final Function request; diff --git a/src/main/java/com/google/genai/ReplayApiClient.java b/src/main/java/com/google/genai/ReplayApiClient.java index 31f16a14a33..91b037e0111 100644 --- a/src/main/java/com/google/genai/ReplayApiClient.java +++ b/src/main/java/com/google/genai/ReplayApiClient.java @@ -42,6 +42,7 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; +import java.util.concurrent.CompletableFuture; import java.util.stream.Stream; import okhttp3.Headers; import okhttp3.MediaType; @@ -146,6 +147,26 @@ public ApiResponse request( throw new UnsupportedOperationException("Not implemented yet."); } + /** + * Sends an asynchronous Http request given the http method, path, request json string, and http + * options. + */ + @Override + public CompletableFuture asyncRequest( + String httpMethod, String path, String requestJson, Optional httpOptions) { + return CompletableFuture.completedFuture(request(httpMethod, path, requestJson, httpOptions)); + } + + /** + * Sends an asynchronous Http request given the http method, path, request bytes, and http + * options. + */ + @Override + public CompletableFuture asyncRequest( + String httpMethod, String path, byte[] requestBytes, Optional httpOptions) { + throw new UnsupportedOperationException("Not implemented yet."); + } + /** Makes sure the replay request matches the actual request message. */ private void matchRequest(ReplayRequest replayRequest, Request actualRequest) { if (replayRequest == null) { diff --git a/src/main/java/com/google/genai/ResponseStream.java b/src/main/java/com/google/genai/ResponseStream.java index d8619d053fa..83cb46855e1 100644 --- a/src/main/java/com/google/genai/ResponseStream.java +++ b/src/main/java/com/google/genai/ResponseStream.java @@ -50,16 +50,29 @@ class ResponseStreamIterator implements Iterator { private final Method converter; private String nextJson; private boolean consumed = false; + private boolean needsRootObject = false; ResponseStreamIterator( - Class clazz, BufferedReader reader, Object obj, String converterName) { + Class clazz, + BufferedReader reader, + Object obj, + String converterName, + boolean needsRootObject) { this.reader = reader; this.clazz = clazz; this.nextJson = readNextJson(); this.obj = obj; + this.needsRootObject = needsRootObject; try { - this.converter = - obj.getClass().getDeclaredMethod(converterName, JsonNode.class, ObjectNode.class); + if (needsRootObject) { + this.converter = + obj.getClass() + .getDeclaredMethod( + converterName, JsonNode.class, ObjectNode.class, JsonNode.class); + } else { + this.converter = + obj.getClass().getDeclaredMethod(converterName, JsonNode.class, ObjectNode.class); + } } catch (NoSuchMethodException e) { throw new IllegalStateException("Failed to find converter method " + converterName, e); } @@ -97,7 +110,11 @@ public T next() { nextJson = readNextJson(); try { JsonNode currentJsonNode = JsonSerializable.stringToJsonNode(currentJson); - currentJsonNode = (JsonNode) converter.invoke(obj, currentJsonNode, null); + if (needsRootObject) { + currentJsonNode = (JsonNode) converter.invoke(obj, currentJsonNode, null, currentJsonNode); + } else { + currentJsonNode = (JsonNode) converter.invoke(obj, currentJsonNode, null); + } if (recordingHistory) { T response = JsonSerializable.fromJsonNode(currentJsonNode, clazz); history.add(response); @@ -137,10 +154,21 @@ private String readNextJson() { private final ApiResponse response; private final BufferedReader reader; - public ResponseStream(Class clazz, ApiResponse response, Object obj, String converterName) { + public ResponseStream( + Class clazz, ApiResponse response, Object obj, String converterName) { + this(clazz, response, obj, converterName, false); + } + + ResponseStream( + Class clazz, + ApiResponse response, + Object obj, + String converterName, + boolean needsRootObject) { InputStream responseStream = response.getBody().byteStream(); this.reader = new BufferedReader(new InputStreamReader(responseStream, StandardCharsets.UTF_8)); - this.iterator = new ResponseStreamIterator(clazz, this.reader, obj, converterName); + this.iterator = + new ResponseStreamIterator(clazz, this.reader, obj, converterName, needsRootObject); this.response = response; } diff --git a/src/main/java/com/google/genai/RetryInterceptor.java b/src/main/java/com/google/genai/RetryInterceptor.java new file mode 100644 index 00000000000..dc103e9dd2c --- /dev/null +++ b/src/main/java/com/google/genai/RetryInterceptor.java @@ -0,0 +1,128 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.genai; + +import com.google.common.collect.ImmutableList; +import com.google.genai.types.HttpRetryOptions; +import java.io.IOException; +import java.util.List; +import java.util.Random; +import okhttp3.Interceptor; +import okhttp3.Request; +import okhttp3.Response; + +/** Retry interceptor for the API requests. */ +class RetryInterceptor implements Interceptor { + + // Default retry options. + private static final int RETRY_MAX_ATTEMPTS = 5; + private static final double RETRY_INITIAL_DELAY = 1.0; // in seconds + private static final double RETRY_MAX_DELAY = 60.0; // in seconds + private static final double RETRY_EXP_BASE = 2.0; + private static final double RETRY_JITTER = 1.0; + private static final ImmutableList RETRY_HTTP_STATUS_CODES = + ImmutableList.of( + 408, // Request timeout. + 429, // Too many requests. + 500, // Internal server error. + 502, // Bad gateway. + 503, // Service unavailable. + 504 // Gateway timeout + ); + + private final HttpRetryOptions retryOptions; + private final Random random; + + /** Creates an interceptor with a retry strategy. */ + RetryInterceptor(HttpRetryOptions retryOptions) { + this(retryOptions, new Random()); + } + + /** Constructor for testing. Allows injecting a mock Random. */ + RetryInterceptor(HttpRetryOptions retryOptions, Random random) { + this.retryOptions = retryOptions; + this.random = random; + } + + @Override + public Response intercept(Chain chain) throws IOException { + Request request = chain.request(); + + // Check if the request has a *per-request* retry options object attached as a tag. + HttpRetryOptions perRequestOptions = request.tag(HttpRetryOptions.class); + + // Use per-request options if present, otherwise fall back to client-default options. + HttpRetryOptions options = (perRequestOptions != null) ? perRequestOptions : this.retryOptions; + + if (options == null) { + return chain.proceed(request); + } + + Response response = null; + int maxAttempts = options.attempts().orElse(RETRY_MAX_ATTEMPTS); + maxAttempts = Math.max(maxAttempts, 1); + List httpStatusCodes = options.httpStatusCodes().orElse(RETRY_HTTP_STATUS_CODES); + + for (int attempt = 1; attempt <= maxAttempts; attempt++) { + try { + response = chain.proceed(request); + // If the response is successful or the response code is not in the retry list, exist the + // attempt loop. + if (response.isSuccessful() || !httpStatusCodes.contains(response.code())) { + break; + } else if (attempt < maxAttempts) { + // Close the unsuccessful response so that the connection can be reused for the next + // attempt. + response.close(); + } + } catch (IOException e) { + if (attempt == maxAttempts) { + throw e; + } + } + + try { + // Blocking sleep before retrying. + Thread.sleep(calculateDelay(options, attempt)); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IOException("Retry was interrupted.", e); + } + } + return response; + } + + /** Calculates the delay (in milliseconds) using exponential backoff with jitter. */ + long calculateDelay(HttpRetryOptions options, int attempt) { + double initialDelay = options.initialDelay().orElse(RETRY_INITIAL_DELAY); + double maxDelay = options.maxDelay().orElse(RETRY_MAX_DELAY); + double expBase = options.expBase().orElse(RETRY_EXP_BASE); + double jitter = options.jitter().orElse(RETRY_JITTER); + + double factor = + Math.pow(expBase, attempt - 1) * (1.0 + jitter * (random.nextDouble() * 2.0 - 1.0)); + + double delay = Math.min(maxDelay, initialDelay * factor); + + return (long) (delay * 1000); // Convert to milliseconds. + } + + /** Returns the client-level retry options. */ + HttpRetryOptions retryOptions() { + return retryOptions; + } +} diff --git a/src/main/java/com/google/genai/TokensConverters.java b/src/main/java/com/google/genai/TokensConverters.java index d08f9ed8e5e..5e1c190cf9e 100644 --- a/src/main/java/com/google/genai/TokensConverters.java +++ b/src/main/java/com/google/genai/TokensConverters.java @@ -23,6 +23,7 @@ import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; +/** Internal SDK converter functions. */ final class TokensConverters { private final ApiClient apiClient; @@ -403,6 +404,11 @@ ObjectNode googleSearchToMldev(JsonNode fromObject, ObjectNode parentObject) { toObject)); } + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"excludeDomains"}))) { + throw new IllegalArgumentException( + "excludeDomains parameter is not supported in Gemini API."); + } + return toObject; } @@ -449,6 +455,19 @@ ObjectNode urlContextToMldev(JsonNode fromObject, ObjectNode parentObject) { return toObject; } + @ExcludeFromGeneratedCoverageReport + ObjectNode toolComputerUseToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"environment"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"environment"}, + Common.getValueByPath(fromObject, new String[] {"environment"})); + } + + return toObject; + } + @ExcludeFromGeneratedCoverageReport ObjectNode toolToMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); @@ -507,18 +526,21 @@ ObjectNode toolToMldev(JsonNode fromObject, ObjectNode parentObject) { toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"codeExecution"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"computerUse"}) != null) { Common.setValueByPath( toObject, - new String[] {"codeExecution"}, - Common.getValueByPath(fromObject, new String[] {"codeExecution"})); + new String[] {"computerUse"}, + toolComputerUseToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"computerUse"})), + toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"computerUse"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"codeExecution"}) != null) { Common.setValueByPath( toObject, - new String[] {"computerUse"}, - Common.getValueByPath(fromObject, new String[] {"computerUse"})); + new String[] {"codeExecution"}, + Common.getValueByPath(fromObject, new String[] {"codeExecution"})); } return toObject; @@ -897,32 +919,4 @@ ObjectNode createAuthTokenConfigToMldev( return toObject; } - - @ExcludeFromGeneratedCoverageReport - ObjectNode createAuthTokenParametersToMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode createAuthTokenParametersToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode authTokenFromMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode authTokenFromVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - return toObject; - } } diff --git a/src/main/java/com/google/genai/Transformers.java b/src/main/java/com/google/genai/Transformers.java index 159efc4c8ae..3569f89fd14 100644 --- a/src/main/java/com/google/genai/Transformers.java +++ b/src/main/java/com/google/genai/Transformers.java @@ -578,6 +578,10 @@ public static Object tBatchJobDestination(Object dest) { return dest; } + public static Object tRecvBatchJobDestination(Object dest) { + return dest; + } + /** * It validates and extracts the batch job name based on the backend (Vertex AI or MLDev). * @@ -646,12 +650,16 @@ public static Object tJobState(Object state) { return JobState.Known.JOB_STATE_UNSPECIFIED; case "BATCH_STATE_PENDING": return JobState.Known.JOB_STATE_PENDING; + case "BATCH_STATE_RUNNING": + return JobState.Known.JOB_STATE_RUNNING; case "BATCH_STATE_SUCCEEDED": return JobState.Known.JOB_STATE_SUCCEEDED; case "BATCH_STATE_FAILED": return JobState.Known.JOB_STATE_FAILED; case "BATCH_STATE_CANCELLED": return JobState.Known.JOB_STATE_CANCELLED; + case "BATCH_STATE_EXPIRED": + return JobState.Known.JOB_STATE_EXPIRED; default: return state; } diff --git a/src/main/java/com/google/genai/Tunings.java b/src/main/java/com/google/genai/Tunings.java index 364c77d2a14..7f5305ce299 100644 --- a/src/main/java/com/google/genai/Tunings.java +++ b/src/main/java/com/google/genai/Tunings.java @@ -22,25 +22,34 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; +import com.google.genai.Common.BuiltRequest; import com.google.genai.errors.GenAiIOException; +import com.google.genai.types.CancelTuningJobConfig; +import com.google.genai.types.CancelTuningJobParameters; import com.google.genai.types.CreateTuningJobConfig; -import com.google.genai.types.CreateTuningJobParameters; +import com.google.genai.types.CreateTuningJobParametersPrivate; import com.google.genai.types.GetTuningJobConfig; import com.google.genai.types.GetTuningJobParameters; import com.google.genai.types.HttpOptions; +import com.google.genai.types.HttpResponse; import com.google.genai.types.JobState; import com.google.genai.types.ListTuningJobsConfig; import com.google.genai.types.ListTuningJobsParameters; import com.google.genai.types.ListTuningJobsResponse; +import com.google.genai.types.PreTunedModel; import com.google.genai.types.TuningDataset; import com.google.genai.types.TuningJob; import com.google.genai.types.TuningOperation; import java.io.IOException; +import java.util.HashMap; +import java.util.Map; import java.util.Optional; import java.util.function.Function; +import okhttp3.Headers; import okhttp3.ResponseBody; public final class Tunings { + final ApiClient apiClient; public Tunings(ApiClient apiClient) { @@ -48,7 +57,8 @@ public Tunings(ApiClient apiClient) { } @ExcludeFromGeneratedCoverageReport - ObjectNode getTuningJobParametersToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode cancelTuningJobParametersToMldev( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { Common.setValueByPath( @@ -57,108 +67,26 @@ ObjectNode getTuningJobParametersToMldev(JsonNode fromObject, ObjectNode parentO Common.getValueByPath(fromObject, new String[] {"name"})); } - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"config"}, - Common.getValueByPath(fromObject, new String[] {"config"})); - } - return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode listTuningJobsConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode cancelTuningJobParametersToVertex( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - if (Common.getValueByPath(fromObject, new String[] {"pageSize"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"_query", "pageSize"}, - Common.getValueByPath(fromObject, new String[] {"pageSize"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"pageToken"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"_query", "pageToken"}, - Common.getValueByPath(fromObject, new String[] {"pageToken"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"filter"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"_query", "filter"}, - Common.getValueByPath(fromObject, new String[] {"filter"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode listTuningJobsParametersToMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"config"}, - listTuningJobsConfigToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"config"})), - toObject)); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode tuningExampleToMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"textInput"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"textInput"}, - Common.getValueByPath(fromObject, new String[] {"textInput"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"output"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { Common.setValueByPath( toObject, - new String[] {"output"}, - Common.getValueByPath(fromObject, new String[] {"output"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode tuningDatasetToMldev(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"gcsUri"}))) { - throw new IllegalArgumentException("gcsUri parameter is not supported in Gemini API."); - } - - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"vertexDatasetResource"}))) { - throw new IllegalArgumentException( - "vertexDatasetResource parameter is not supported in Gemini API."); - } - - if (Common.getValueByPath(fromObject, new String[] {"examples"}) != null) { - ArrayNode keyArray = (ArrayNode) Common.getValueByPath(fromObject, new String[] {"examples"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add(tuningExampleToMldev(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"examples", "examples"}, result); + new String[] {"_url", "name"}, + Common.getValueByPath(fromObject, new String[] {"name"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode createTuningJobConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode createTuningJobConfigToMldev( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"validationDataset"}))) { @@ -197,6 +125,12 @@ ObjectNode createTuningJobConfigToMldev(JsonNode fromObject, ObjectNode parentOb "exportLastCheckpointOnly parameter is not supported in Gemini API."); } + if (!Common.isZero( + Common.getValueByPath(fromObject, new String[] {"preTunedModelCheckpointId"}))) { + throw new IllegalArgumentException( + "preTunedModelCheckpointId parameter is not supported in Gemini API."); + } + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"adapterSize"}))) { throw new IllegalArgumentException("adapterSize parameter is not supported in Gemini API."); } @@ -215,521 +149,609 @@ ObjectNode createTuningJobConfigToMldev(JsonNode fromObject, ObjectNode parentOb Common.getValueByPath(fromObject, new String[] {"learningRate"})); } + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"labels"}))) { + throw new IllegalArgumentException("labels parameter is not supported in Gemini API."); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"beta"}))) { + throw new IllegalArgumentException("beta parameter is not supported in Gemini API."); + } + return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode createTuningJobParametersToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode createTuningJobConfigToVertex( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"baseModel"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"baseModel"}, - Common.getValueByPath(fromObject, new String[] {"baseModel"})); - } - if (Common.getValueByPath(fromObject, new String[] {"trainingDataset"}) != null) { + JsonNode discriminatorValidationDataset = + (JsonNode) Common.getValueByPath(rootObject, new String[] {"config", "method"}); + String discriminatorValueValidationDataset = + discriminatorValidationDataset == null + ? "SUPERVISED_FINE_TUNING" + : discriminatorValidationDataset.asText(); + if (discriminatorValueValidationDataset.equals("SUPERVISED_FINE_TUNING")) { + if (Common.getValueByPath(fromObject, new String[] {"validationDataset"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"supervisedTuningSpec"}, + tuningValidationDatasetToVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"validationDataset"})), + toObject, + rootObject)); + } + } else if (discriminatorValueValidationDataset.equals("PREFERENCE_TUNING")) { + if (Common.getValueByPath(fromObject, new String[] {"validationDataset"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"preferenceOptimizationSpec"}, + tuningValidationDatasetToVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"validationDataset"})), + toObject, + rootObject)); + } + } + if (Common.getValueByPath(fromObject, new String[] {"tunedModelDisplayName"}) != null) { Common.setValueByPath( - toObject, - new String[] {"tuningTask", "trainingData"}, - tuningDatasetToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"trainingDataset"})), - toObject)); + parentObject, + new String[] {"tunedModelDisplayName"}, + Common.getValueByPath(fromObject, new String[] {"tunedModelDisplayName"})); } - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"description"}) != null) { Common.setValueByPath( - toObject, - new String[] {"config"}, - createTuningJobConfigToMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"config"})), - toObject)); + parentObject, + new String[] {"description"}, + Common.getValueByPath(fromObject, new String[] {"description"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode getTuningJobParametersToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"_url", "name"}, - Common.getValueByPath(fromObject, new String[] {"name"})); + JsonNode discriminatorEpochCount = + (JsonNode) Common.getValueByPath(rootObject, new String[] {"config", "method"}); + String discriminatorValueEpochCount = + discriminatorEpochCount == null + ? "SUPERVISED_FINE_TUNING" + : discriminatorEpochCount.asText(); + if (discriminatorValueEpochCount.equals("SUPERVISED_FINE_TUNING")) { + if (Common.getValueByPath(fromObject, new String[] {"epochCount"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"supervisedTuningSpec", "hyperParameters", "epochCount"}, + Common.getValueByPath(fromObject, new String[] {"epochCount"})); + } + } else if (discriminatorValueEpochCount.equals("PREFERENCE_TUNING")) { + if (Common.getValueByPath(fromObject, new String[] {"epochCount"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"preferenceOptimizationSpec", "hyperParameters", "epochCount"}, + Common.getValueByPath(fromObject, new String[] {"epochCount"})); + } } - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"config"}, - Common.getValueByPath(fromObject, new String[] {"config"})); + JsonNode discriminatorLearningRateMultiplier = + (JsonNode) Common.getValueByPath(rootObject, new String[] {"config", "method"}); + String discriminatorValueLearningRateMultiplier = + discriminatorLearningRateMultiplier == null + ? "SUPERVISED_FINE_TUNING" + : discriminatorLearningRateMultiplier.asText(); + if (discriminatorValueLearningRateMultiplier.equals("SUPERVISED_FINE_TUNING")) { + if (Common.getValueByPath(fromObject, new String[] {"learningRateMultiplier"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"supervisedTuningSpec", "hyperParameters", "learningRateMultiplier"}, + Common.getValueByPath(fromObject, new String[] {"learningRateMultiplier"})); + } + } else if (discriminatorValueLearningRateMultiplier.equals("PREFERENCE_TUNING")) { + if (Common.getValueByPath(fromObject, new String[] {"learningRateMultiplier"}) != null) { + Common.setValueByPath( + parentObject, + new String[] { + "preferenceOptimizationSpec", "hyperParameters", "learningRateMultiplier" + }, + Common.getValueByPath(fromObject, new String[] {"learningRateMultiplier"})); + } } - return toObject; - } + JsonNode discriminatorExportLastCheckpointOnly = + (JsonNode) Common.getValueByPath(rootObject, new String[] {"config", "method"}); + String discriminatorValueExportLastCheckpointOnly = + discriminatorExportLastCheckpointOnly == null + ? "SUPERVISED_FINE_TUNING" + : discriminatorExportLastCheckpointOnly.asText(); + if (discriminatorValueExportLastCheckpointOnly.equals("SUPERVISED_FINE_TUNING")) { + if (Common.getValueByPath(fromObject, new String[] {"exportLastCheckpointOnly"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"supervisedTuningSpec", "exportLastCheckpointOnly"}, + Common.getValueByPath(fromObject, new String[] {"exportLastCheckpointOnly"})); + } + } else if (discriminatorValueExportLastCheckpointOnly.equals("PREFERENCE_TUNING")) { + if (Common.getValueByPath(fromObject, new String[] {"exportLastCheckpointOnly"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"preferenceOptimizationSpec", "exportLastCheckpointOnly"}, + Common.getValueByPath(fromObject, new String[] {"exportLastCheckpointOnly"})); + } + } - @ExcludeFromGeneratedCoverageReport - ObjectNode listTuningJobsConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + JsonNode discriminatorAdapterSize = + (JsonNode) Common.getValueByPath(rootObject, new String[] {"config", "method"}); + String discriminatorValueAdapterSize = + discriminatorAdapterSize == null + ? "SUPERVISED_FINE_TUNING" + : discriminatorAdapterSize.asText(); + if (discriminatorValueAdapterSize.equals("SUPERVISED_FINE_TUNING")) { + if (Common.getValueByPath(fromObject, new String[] {"adapterSize"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"supervisedTuningSpec", "hyperParameters", "adapterSize"}, + Common.getValueByPath(fromObject, new String[] {"adapterSize"})); + } + } else if (discriminatorValueAdapterSize.equals("PREFERENCE_TUNING")) { + if (Common.getValueByPath(fromObject, new String[] {"adapterSize"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"preferenceOptimizationSpec", "hyperParameters", "adapterSize"}, + Common.getValueByPath(fromObject, new String[] {"adapterSize"})); + } + } + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"batchSize"}))) { + throw new IllegalArgumentException("batchSize parameter is not supported in Vertex AI."); + } - if (Common.getValueByPath(fromObject, new String[] {"pageSize"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"_query", "pageSize"}, - Common.getValueByPath(fromObject, new String[] {"pageSize"})); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"learningRate"}))) { + throw new IllegalArgumentException("learningRate parameter is not supported in Vertex AI."); } - if (Common.getValueByPath(fromObject, new String[] {"pageToken"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"labels"}) != null) { Common.setValueByPath( parentObject, - new String[] {"_query", "pageToken"}, - Common.getValueByPath(fromObject, new String[] {"pageToken"})); + new String[] {"labels"}, + Common.getValueByPath(fromObject, new String[] {"labels"})); } - if (Common.getValueByPath(fromObject, new String[] {"filter"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"beta"}) != null) { Common.setValueByPath( parentObject, - new String[] {"_query", "filter"}, - Common.getValueByPath(fromObject, new String[] {"filter"})); + new String[] {"preferenceOptimizationSpec", "hyperParameters", "beta"}, + Common.getValueByPath(fromObject, new String[] {"beta"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode listTuningJobsParametersToVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode createTuningJobParametersPrivateToMldev( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"baseModel"}) != null) { Common.setValueByPath( toObject, - new String[] {"config"}, - listTuningJobsConfigToVertex( + new String[] {"baseModel"}, + Common.getValueByPath(fromObject, new String[] {"baseModel"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"preTunedModel"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"preTunedModel"}, + Common.getValueByPath(fromObject, new String[] {"preTunedModel"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"trainingDataset"}) != null) { + JsonNode unused = + tuningDatasetToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"trainingDataset"})), + toObject, + rootObject); + } + + if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + JsonNode unused = + createTuningJobConfigToMldev( JsonSerializable.toJsonNode( Common.getValueByPath(fromObject, new String[] {"config"})), - toObject)); + toObject, + rootObject); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode tuningDatasetToVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode createTuningJobParametersPrivateToVertex( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"gcsUri"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"baseModel"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"supervisedTuningSpec", "trainingDatasetUri"}, - Common.getValueByPath(fromObject, new String[] {"gcsUri"})); + toObject, + new String[] {"baseModel"}, + Common.getValueByPath(fromObject, new String[] {"baseModel"})); } - if (Common.getValueByPath(fromObject, new String[] {"vertexDatasetResource"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"preTunedModel"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"supervisedTuningSpec", "trainingDatasetUri"}, - Common.getValueByPath(fromObject, new String[] {"vertexDatasetResource"})); + toObject, + new String[] {"preTunedModel"}, + Common.getValueByPath(fromObject, new String[] {"preTunedModel"})); } - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"examples"}))) { - throw new IllegalArgumentException("examples parameter is not supported in Vertex AI."); + if (Common.getValueByPath(fromObject, new String[] {"trainingDataset"}) != null) { + JsonNode unused = + tuningDatasetToVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"trainingDataset"})), + toObject, + rootObject); + } + + if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + JsonNode unused = + createTuningJobConfigToVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"config"})), + toObject, + rootObject); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode tuningValidationDatasetToVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode getTuningJobParametersToMldev( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"gcsUri"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { Common.setValueByPath( toObject, - new String[] {"validationDatasetUri"}, - Common.getValueByPath(fromObject, new String[] {"gcsUri"})); + new String[] {"_url", "name"}, + Common.getValueByPath(fromObject, new String[] {"name"})); } - if (Common.getValueByPath(fromObject, new String[] {"vertexDatasetResource"}) != null) { + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode getTuningJobParametersToVertex( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"supervisedTuningSpec", "trainingDatasetUri"}, - Common.getValueByPath(fromObject, new String[] {"vertexDatasetResource"})); + toObject, + new String[] {"_url", "name"}, + Common.getValueByPath(fromObject, new String[] {"name"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode createTuningJobConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode listTuningJobsConfigToMldev( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"validationDataset"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"pageSize"}) != null) { Common.setValueByPath( parentObject, - new String[] {"supervisedTuningSpec"}, - tuningValidationDatasetToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"validationDataset"})), - toObject)); + new String[] {"_query", "pageSize"}, + Common.getValueByPath(fromObject, new String[] {"pageSize"})); } - if (Common.getValueByPath(fromObject, new String[] {"tunedModelDisplayName"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"pageToken"}) != null) { Common.setValueByPath( parentObject, - new String[] {"tunedModelDisplayName"}, - Common.getValueByPath(fromObject, new String[] {"tunedModelDisplayName"})); + new String[] {"_query", "pageToken"}, + Common.getValueByPath(fromObject, new String[] {"pageToken"})); } - if (Common.getValueByPath(fromObject, new String[] {"description"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"filter"}) != null) { Common.setValueByPath( parentObject, - new String[] {"description"}, - Common.getValueByPath(fromObject, new String[] {"description"})); + new String[] {"_query", "filter"}, + Common.getValueByPath(fromObject, new String[] {"filter"})); } - if (Common.getValueByPath(fromObject, new String[] {"epochCount"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"supervisedTuningSpec", "hyperParameters", "epochCount"}, - Common.getValueByPath(fromObject, new String[] {"epochCount"})); - } + return toObject; + } - if (Common.getValueByPath(fromObject, new String[] {"learningRateMultiplier"}) != null) { + @ExcludeFromGeneratedCoverageReport + ObjectNode listTuningJobsConfigToVertex( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + + if (Common.getValueByPath(fromObject, new String[] {"pageSize"}) != null) { Common.setValueByPath( parentObject, - new String[] {"supervisedTuningSpec", "hyperParameters", "learningRateMultiplier"}, - Common.getValueByPath(fromObject, new String[] {"learningRateMultiplier"})); + new String[] {"_query", "pageSize"}, + Common.getValueByPath(fromObject, new String[] {"pageSize"})); } - if (Common.getValueByPath(fromObject, new String[] {"exportLastCheckpointOnly"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"pageToken"}) != null) { Common.setValueByPath( parentObject, - new String[] {"supervisedTuningSpec", "exportLastCheckpointOnly"}, - Common.getValueByPath(fromObject, new String[] {"exportLastCheckpointOnly"})); + new String[] {"_query", "pageToken"}, + Common.getValueByPath(fromObject, new String[] {"pageToken"})); } - if (Common.getValueByPath(fromObject, new String[] {"adapterSize"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"filter"}) != null) { Common.setValueByPath( parentObject, - new String[] {"supervisedTuningSpec", "hyperParameters", "adapterSize"}, - Common.getValueByPath(fromObject, new String[] {"adapterSize"})); - } - - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"batchSize"}))) { - throw new IllegalArgumentException("batchSize parameter is not supported in Vertex AI."); - } - - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"learningRate"}))) { - throw new IllegalArgumentException("learningRate parameter is not supported in Vertex AI."); + new String[] {"_query", "filter"}, + Common.getValueByPath(fromObject, new String[] {"filter"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode createTuningJobParametersToVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode listTuningJobsParametersToMldev( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"baseModel"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"baseModel"}, - Common.getValueByPath(fromObject, new String[] {"baseModel"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"trainingDataset"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"supervisedTuningSpec", "trainingDatasetUri"}, - tuningDatasetToVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"trainingDataset"})), - toObject)); - } - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"config"}, - createTuningJobConfigToVertex( + JsonNode unused = + listTuningJobsConfigToMldev( JsonSerializable.toJsonNode( Common.getValueByPath(fromObject, new String[] {"config"})), - toObject)); + toObject, + rootObject); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode tunedModelFromMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode listTuningJobsParametersToVertex( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"model"}, - Common.getValueByPath(fromObject, new String[] {"name"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"endpoint"}, - Common.getValueByPath(fromObject, new String[] {"name"})); + if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + JsonNode unused = + listTuningJobsConfigToVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"config"})), + toObject, + rootObject); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode tuningJobFromMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode listTuningJobsResponseFromMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"name"}, - Common.getValueByPath(fromObject, new String[] {"name"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"state"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"}) != null) { Common.setValueByPath( toObject, - new String[] {"state"}, - Transformers.tTuningJobStatus(Common.getValueByPath(fromObject, new String[] {"state"}))); + new String[] {"sdkHttpResponse"}, + Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"})); } - if (Common.getValueByPath(fromObject, new String[] {"createTime"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"nextPageToken"}) != null) { Common.setValueByPath( toObject, - new String[] {"createTime"}, - Common.getValueByPath(fromObject, new String[] {"createTime"})); + new String[] {"nextPageToken"}, + Common.getValueByPath(fromObject, new String[] {"nextPageToken"})); } - if (Common.getValueByPath(fromObject, new String[] {"tuningTask", "startTime"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"startTime"}, - Common.getValueByPath(fromObject, new String[] {"tuningTask", "startTime"})); - } + if (Common.getValueByPath(fromObject, new String[] {"tunedModels"}) != null) { + ArrayNode keyArray = + (ArrayNode) Common.getValueByPath(fromObject, new String[] {"tunedModels"}); + ObjectMapper objectMapper = new ObjectMapper(); + ArrayNode result = objectMapper.createArrayNode(); - if (Common.getValueByPath(fromObject, new String[] {"tuningTask", "completeTime"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"endTime"}, - Common.getValueByPath(fromObject, new String[] {"tuningTask", "completeTime"})); + for (JsonNode item : keyArray) { + result.add(tuningJobFromMldev(JsonSerializable.toJsonNode(item), toObject)); + } + Common.setValueByPath(toObject, new String[] {"tuningJobs"}, result); } - if (Common.getValueByPath(fromObject, new String[] {"updateTime"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"updateTime"}, - Common.getValueByPath(fromObject, new String[] {"updateTime"})); - } + return toObject; + } - if (Common.getValueByPath(fromObject, new String[] {"description"}) != null) { + @ExcludeFromGeneratedCoverageReport + ObjectNode listTuningJobsResponseFromVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"}) != null) { Common.setValueByPath( toObject, - new String[] {"description"}, - Common.getValueByPath(fromObject, new String[] {"description"})); + new String[] {"sdkHttpResponse"}, + Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"})); } - if (Common.getValueByPath(fromObject, new String[] {"baseModel"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"nextPageToken"}) != null) { Common.setValueByPath( toObject, - new String[] {"baseModel"}, - Common.getValueByPath(fromObject, new String[] {"baseModel"})); + new String[] {"nextPageToken"}, + Common.getValueByPath(fromObject, new String[] {"nextPageToken"})); } - if (Common.getValueByPath(fromObject, new String[] {"_self"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"tunedModel"}, - tunedModelFromMldev( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"_self"})), - toObject)); - } + if (Common.getValueByPath(fromObject, new String[] {"tuningJobs"}) != null) { + ArrayNode keyArray = + (ArrayNode) Common.getValueByPath(fromObject, new String[] {"tuningJobs"}); + ObjectMapper objectMapper = new ObjectMapper(); + ArrayNode result = objectMapper.createArrayNode(); - if (Common.getValueByPath(fromObject, new String[] {"distillationSpec"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"distillationSpec"}, - Common.getValueByPath(fromObject, new String[] {"distillationSpec"})); + for (JsonNode item : keyArray) { + result.add(tuningJobFromVertex(JsonSerializable.toJsonNode(item), toObject)); + } + Common.setValueByPath(toObject, new String[] {"tuningJobs"}, result); } - if (Common.getValueByPath(fromObject, new String[] {"experiment"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"experiment"}, - Common.getValueByPath(fromObject, new String[] {"experiment"})); - } + return toObject; + } - if (Common.getValueByPath(fromObject, new String[] {"labels"}) != null) { + @ExcludeFromGeneratedCoverageReport + ObjectNode tunedModelFromMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { Common.setValueByPath( toObject, - new String[] {"labels"}, - Common.getValueByPath(fromObject, new String[] {"labels"})); + new String[] {"model"}, + Common.getValueByPath(fromObject, new String[] {"name"})); } - if (Common.getValueByPath(fromObject, new String[] {"pipelineJob"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { Common.setValueByPath( toObject, - new String[] {"pipelineJob"}, - Common.getValueByPath(fromObject, new String[] {"pipelineJob"})); + new String[] {"endpoint"}, + Common.getValueByPath(fromObject, new String[] {"name"})); } - if (Common.getValueByPath(fromObject, new String[] {"satisfiesPzi"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"satisfiesPzi"}, - Common.getValueByPath(fromObject, new String[] {"satisfiesPzi"})); - } + return toObject; + } - if (Common.getValueByPath(fromObject, new String[] {"satisfiesPzs"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"satisfiesPzs"}, - Common.getValueByPath(fromObject, new String[] {"satisfiesPzs"})); + @ExcludeFromGeneratedCoverageReport + ObjectNode tuningDatasetToMldev( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"gcsUri"}))) { + throw new IllegalArgumentException("gcsUri parameter is not supported in Gemini API."); } - if (Common.getValueByPath(fromObject, new String[] {"serviceAccount"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"serviceAccount"}, - Common.getValueByPath(fromObject, new String[] {"serviceAccount"})); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"vertexDatasetResource"}))) { + throw new IllegalArgumentException( + "vertexDatasetResource parameter is not supported in Gemini API."); } - if (Common.getValueByPath(fromObject, new String[] {"tunedModelDisplayName"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"examples"}) != null) { Common.setValueByPath( toObject, - new String[] {"tunedModelDisplayName"}, - Common.getValueByPath(fromObject, new String[] {"tunedModelDisplayName"})); + new String[] {"examples", "examples"}, + Common.getValueByPath(fromObject, new String[] {"examples"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode listTuningJobsResponseFromMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode tuningDatasetToVertex( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"nextPageToken"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"nextPageToken"}, - Common.getValueByPath(fromObject, new String[] {"nextPageToken"})); + JsonNode discriminatorGcsUri = + (JsonNode) Common.getValueByPath(rootObject, new String[] {"config", "method"}); + String discriminatorValueGcsUri = + discriminatorGcsUri == null ? "SUPERVISED_FINE_TUNING" : discriminatorGcsUri.asText(); + if (discriminatorValueGcsUri.equals("SUPERVISED_FINE_TUNING")) { + if (Common.getValueByPath(fromObject, new String[] {"gcsUri"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"supervisedTuningSpec", "trainingDatasetUri"}, + Common.getValueByPath(fromObject, new String[] {"gcsUri"})); + } + } else if (discriminatorValueGcsUri.equals("PREFERENCE_TUNING")) { + if (Common.getValueByPath(fromObject, new String[] {"gcsUri"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"preferenceOptimizationSpec", "trainingDatasetUri"}, + Common.getValueByPath(fromObject, new String[] {"gcsUri"})); + } } - if (Common.getValueByPath(fromObject, new String[] {"tunedModels"}) != null) { - ArrayNode keyArray = - (ArrayNode) Common.getValueByPath(fromObject, new String[] {"tunedModels"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add(tuningJobFromMldev(JsonSerializable.toJsonNode(item), toObject)); + JsonNode discriminatorVertexDatasetResource = + (JsonNode) Common.getValueByPath(rootObject, new String[] {"config", "method"}); + String discriminatorValueVertexDatasetResource = + discriminatorVertexDatasetResource == null + ? "SUPERVISED_FINE_TUNING" + : discriminatorVertexDatasetResource.asText(); + if (discriminatorValueVertexDatasetResource.equals("SUPERVISED_FINE_TUNING")) { + if (Common.getValueByPath(fromObject, new String[] {"vertexDatasetResource"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"supervisedTuningSpec", "trainingDatasetUri"}, + Common.getValueByPath(fromObject, new String[] {"vertexDatasetResource"})); } - Common.setValueByPath(toObject, new String[] {"tuningJobs"}, result); + } else if (discriminatorValueVertexDatasetResource.equals("PREFERENCE_TUNING")) { + if (Common.getValueByPath(fromObject, new String[] {"vertexDatasetResource"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"preferenceOptimizationSpec", "trainingDatasetUri"}, + Common.getValueByPath(fromObject, new String[] {"vertexDatasetResource"})); + } + } + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"examples"}))) { + throw new IllegalArgumentException("examples parameter is not supported in Vertex AI."); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode tuningOperationFromMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode tuningJobFromMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"}) != null) { Common.setValueByPath( toObject, - new String[] {"name"}, - Common.getValueByPath(fromObject, new String[] {"name"})); + new String[] {"sdkHttpResponse"}, + Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"})); } - if (Common.getValueByPath(fromObject, new String[] {"metadata"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { Common.setValueByPath( toObject, - new String[] {"metadata"}, - Common.getValueByPath(fromObject, new String[] {"metadata"})); + new String[] {"name"}, + Common.getValueByPath(fromObject, new String[] {"name"})); } - if (Common.getValueByPath(fromObject, new String[] {"done"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"state"}) != null) { Common.setValueByPath( toObject, - new String[] {"done"}, - Common.getValueByPath(fromObject, new String[] {"done"})); + new String[] {"state"}, + Transformers.tTuningJobStatus(Common.getValueByPath(fromObject, new String[] {"state"}))); } - if (Common.getValueByPath(fromObject, new String[] {"error"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"createTime"}) != null) { Common.setValueByPath( toObject, - new String[] {"error"}, - Common.getValueByPath(fromObject, new String[] {"error"})); + new String[] {"createTime"}, + Common.getValueByPath(fromObject, new String[] {"createTime"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode tunedModelCheckpointFromVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"checkpointId"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"tuningTask", "startTime"}) != null) { Common.setValueByPath( toObject, - new String[] {"checkpointId"}, - Common.getValueByPath(fromObject, new String[] {"checkpointId"})); + new String[] {"startTime"}, + Common.getValueByPath(fromObject, new String[] {"tuningTask", "startTime"})); } - if (Common.getValueByPath(fromObject, new String[] {"epoch"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"tuningTask", "completeTime"}) != null) { Common.setValueByPath( toObject, - new String[] {"epoch"}, - Common.getValueByPath(fromObject, new String[] {"epoch"})); + new String[] {"endTime"}, + Common.getValueByPath(fromObject, new String[] {"tuningTask", "completeTime"})); } - if (Common.getValueByPath(fromObject, new String[] {"step"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"updateTime"}) != null) { Common.setValueByPath( toObject, - new String[] {"step"}, - Common.getValueByPath(fromObject, new String[] {"step"})); + new String[] {"updateTime"}, + Common.getValueByPath(fromObject, new String[] {"updateTime"})); } - if (Common.getValueByPath(fromObject, new String[] {"endpoint"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"description"}) != null) { Common.setValueByPath( toObject, - new String[] {"endpoint"}, - Common.getValueByPath(fromObject, new String[] {"endpoint"})); + new String[] {"description"}, + Common.getValueByPath(fromObject, new String[] {"description"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode tunedModelFromVertex(JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"baseModel"}) != null) { Common.setValueByPath( toObject, - new String[] {"model"}, - Common.getValueByPath(fromObject, new String[] {"model"})); + new String[] {"baseModel"}, + Common.getValueByPath(fromObject, new String[] {"baseModel"})); } - if (Common.getValueByPath(fromObject, new String[] {"endpoint"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"_self"}) != null) { Common.setValueByPath( toObject, - new String[] {"endpoint"}, - Common.getValueByPath(fromObject, new String[] {"endpoint"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"checkpoints"}) != null) { - ArrayNode keyArray = - (ArrayNode) Common.getValueByPath(fromObject, new String[] {"checkpoints"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add(tunedModelCheckpointFromVertex(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"checkpoints"}, result); + new String[] {"tunedModel"}, + tunedModelFromMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"_self"})), + toObject)); } return toObject; @@ -738,6 +760,12 @@ ObjectNode tunedModelFromVertex(JsonNode fromObject, ObjectNode parentObject) { @ExcludeFromGeneratedCoverageReport ObjectNode tuningJobFromVertex(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"sdkHttpResponse"}, + Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"})); + } if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { Common.setValueByPath( @@ -806,10 +834,14 @@ ObjectNode tuningJobFromVertex(JsonNode fromObject, ObjectNode parentObject) { Common.setValueByPath( toObject, new String[] {"tunedModel"}, - tunedModelFromVertex( - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"tunedModel"})), - toObject)); + Common.getValueByPath(fromObject, new String[] {"tunedModel"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"preTunedModel"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"preTunedModel"}, + Common.getValueByPath(fromObject, new String[] {"preTunedModel"})); } if (Common.getValueByPath(fromObject, new String[] {"supervisedTuningSpec"}) != null) { @@ -819,6 +851,13 @@ ObjectNode tuningJobFromVertex(JsonNode fromObject, ObjectNode parentObject) { Common.getValueByPath(fromObject, new String[] {"supervisedTuningSpec"})); } + if (Common.getValueByPath(fromObject, new String[] {"preferenceOptimizationSpec"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"preferenceOptimizationSpec"}, + Common.getValueByPath(fromObject, new String[] {"preferenceOptimizationSpec"})); + } + if (Common.getValueByPath(fromObject, new String[] {"tuningDataStats"}) != null) { Common.setValueByPath( toObject, @@ -840,11 +879,11 @@ ObjectNode tuningJobFromVertex(JsonNode fromObject, ObjectNode parentObject) { Common.getValueByPath(fromObject, new String[] {"partnerModelTuningSpec"})); } - if (Common.getValueByPath(fromObject, new String[] {"distillationSpec"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"customBaseModel"}) != null) { Common.setValueByPath( toObject, - new String[] {"distillationSpec"}, - Common.getValueByPath(fromObject, new String[] {"distillationSpec"})); + new String[] {"customBaseModel"}, + Common.getValueByPath(fromObject, new String[] {"customBaseModel"})); } if (Common.getValueByPath(fromObject, new String[] {"experiment"}) != null) { @@ -861,25 +900,18 @@ ObjectNode tuningJobFromVertex(JsonNode fromObject, ObjectNode parentObject) { Common.getValueByPath(fromObject, new String[] {"labels"})); } - if (Common.getValueByPath(fromObject, new String[] {"pipelineJob"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"pipelineJob"}, - Common.getValueByPath(fromObject, new String[] {"pipelineJob"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"satisfiesPzi"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"outputUri"}) != null) { Common.setValueByPath( toObject, - new String[] {"satisfiesPzi"}, - Common.getValueByPath(fromObject, new String[] {"satisfiesPzi"})); + new String[] {"outputUri"}, + Common.getValueByPath(fromObject, new String[] {"outputUri"})); } - if (Common.getValueByPath(fromObject, new String[] {"satisfiesPzs"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"pipelineJob"}) != null) { Common.setValueByPath( toObject, - new String[] {"satisfiesPzs"}, - Common.getValueByPath(fromObject, new String[] {"satisfiesPzs"})); + new String[] {"pipelineJob"}, + Common.getValueByPath(fromObject, new String[] {"pipelineJob"})); } if (Common.getValueByPath(fromObject, new String[] {"serviceAccount"}) != null) { @@ -896,36 +928,80 @@ ObjectNode tuningJobFromVertex(JsonNode fromObject, ObjectNode parentObject) { Common.getValueByPath(fromObject, new String[] {"tunedModelDisplayName"})); } + if (Common.getValueByPath(fromObject, new String[] {"veoTuningSpec"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"veoTuningSpec"}, + Common.getValueByPath(fromObject, new String[] {"veoTuningSpec"})); + } + return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode listTuningJobsResponseFromVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode tuningOperationFromMldev(JsonNode fromObject, ObjectNode parentObject) { ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"sdkHttpResponse"}, + Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"})); + } - if (Common.getValueByPath(fromObject, new String[] {"nextPageToken"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { Common.setValueByPath( toObject, - new String[] {"nextPageToken"}, - Common.getValueByPath(fromObject, new String[] {"nextPageToken"})); + new String[] {"name"}, + Common.getValueByPath(fromObject, new String[] {"name"})); } - if (Common.getValueByPath(fromObject, new String[] {"tuningJobs"}) != null) { - ArrayNode keyArray = - (ArrayNode) Common.getValueByPath(fromObject, new String[] {"tuningJobs"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); + if (Common.getValueByPath(fromObject, new String[] {"metadata"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"metadata"}, + Common.getValueByPath(fromObject, new String[] {"metadata"})); + } - for (JsonNode item : keyArray) { - result.add(tuningJobFromVertex(JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"tuningJobs"}, result); + if (Common.getValueByPath(fromObject, new String[] {"done"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"done"}, + Common.getValueByPath(fromObject, new String[] {"done"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"error"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"error"}, + Common.getValueByPath(fromObject, new String[] {"error"})); } return toObject; } - TuningJob privateGet(String name, GetTuningJobConfig config) { + @ExcludeFromGeneratedCoverageReport + ObjectNode tuningValidationDatasetToVertex( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"gcsUri"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"validationDatasetUri"}, + Common.getValueByPath(fromObject, new String[] {"gcsUri"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"vertexDatasetResource"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"validationDatasetUri"}, + Common.getValueByPath(fromObject, new String[] {"vertexDatasetResource"})); + } + + return toObject; + } + + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForPrivateGet(String name, GetTuningJobConfig config) { GetTuningJobParameters.Builder parameterBuilder = GetTuningJobParameters.builder(); @@ -940,10 +1016,10 @@ TuningJob privateGet(String name, GetTuningJobConfig config) { ObjectNode body; String path; if (this.apiClient.vertexAI()) { - body = getTuningJobParametersToVertex(parameterNode, null); + body = getTuningJobParametersToVertex(parameterNode, null, parameterNode); path = Common.formatMap("{name}", body.get("_url")); } else { - body = getTuningJobParametersToMldev(parameterNode, null); + body = getTuningJobParametersToMldev(parameterNode, null, parameterNode); if (body.get("_url") != null) { path = Common.formatMap("{name}", body.get("_url")); } else { @@ -959,35 +1035,58 @@ TuningJob privateGet(String name, GetTuningJobConfig config) { } // TODO: Remove the hack that removes config. - body.remove("config"); - Optional requestHttpOptions = Optional.empty(); if (config != null) { requestHttpOptions = config.httpOptions(); } + return new BuiltRequest(path, JsonSerializable.toJsonString(body), requestHttpOptions); + } + + /** A shared processResponse function for both sync and async methods. */ + TuningJob processResponseForPrivateGet(ApiResponse response, GetTuningJobConfig config) { + ResponseBody responseBody = response.getBody(); + String responseString; + try { + responseString = responseBody.string(); + } catch (IOException e) { + throw new GenAiIOException("Failed to read HTTP response.", e); + } + + JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); + + if (this.apiClient.vertexAI()) { + responseNode = tuningJobFromVertex(responseNode, null); + } + + if (!this.apiClient.vertexAI()) { + responseNode = tuningJobFromMldev(responseNode, null); + } + + TuningJob sdkResponse = JsonSerializable.fromJsonNode(responseNode, TuningJob.class); + Headers responseHeaders = response.getHeaders(); + if (responseHeaders == null) { + return sdkResponse; + } + Map headers = new HashMap<>(); + for (String headerName : responseHeaders.names()) { + headers.put(headerName, responseHeaders.get(headerName)); + } + return sdkResponse.toBuilder().sdkHttpResponse(HttpResponse.builder().headers(headers)).build(); + } + + TuningJob privateGet(String name, GetTuningJobConfig config) { + BuiltRequest builtRequest = buildRequestForPrivateGet(name, config); + try (ApiResponse response = this.apiClient.request( - "get", path, JsonSerializable.toJsonString(body), requestHttpOptions)) { - ResponseBody responseBody = response.getBody(); - String responseString; - try { - responseString = responseBody.string(); - } catch (IOException e) { - throw new GenAiIOException("Failed to read HTTP response.", e); - } - - JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); - if (this.apiClient.vertexAI()) { - responseNode = tuningJobFromVertex(responseNode, null); - } else { - responseNode = tuningJobFromMldev(responseNode, null); - } - return JsonSerializable.fromJsonNode(responseNode, TuningJob.class); + "get", builtRequest.path, builtRequest.body, builtRequest.httpOptions)) { + return processResponseForPrivateGet(response, config); } } - ListTuningJobsResponse privateList(ListTuningJobsConfig config) { + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForPrivateList(ListTuningJobsConfig config) { ListTuningJobsParameters.Builder parameterBuilder = ListTuningJobsParameters.builder(); @@ -999,10 +1098,10 @@ ListTuningJobsResponse privateList(ListTuningJobsConfig config) { ObjectNode body; String path; if (this.apiClient.vertexAI()) { - body = listTuningJobsParametersToVertex(parameterNode, null); + body = listTuningJobsParametersToVertex(parameterNode, null, parameterNode); path = Common.formatMap("tuningJobs", body.get("_url")); } else { - body = listTuningJobsParametersToMldev(parameterNode, null); + body = listTuningJobsParametersToMldev(parameterNode, null, parameterNode); if (body.get("_url") != null) { path = Common.formatMap("tunedModels", body.get("_url")); } else { @@ -1018,42 +1117,134 @@ ListTuningJobsResponse privateList(ListTuningJobsConfig config) { } // TODO: Remove the hack that removes config. - body.remove("config"); - Optional requestHttpOptions = Optional.empty(); if (config != null) { requestHttpOptions = config.httpOptions(); } + return new BuiltRequest(path, JsonSerializable.toJsonString(body), requestHttpOptions); + } + + /** A shared processResponse function for both sync and async methods. */ + ListTuningJobsResponse processResponseForPrivateList( + ApiResponse response, ListTuningJobsConfig config) { + ResponseBody responseBody = response.getBody(); + String responseString; + try { + responseString = responseBody.string(); + } catch (IOException e) { + throw new GenAiIOException("Failed to read HTTP response.", e); + } + + JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); + + if (this.apiClient.vertexAI()) { + responseNode = listTuningJobsResponseFromVertex(responseNode, null); + } + + if (!this.apiClient.vertexAI()) { + responseNode = listTuningJobsResponseFromMldev(responseNode, null); + } + + ListTuningJobsResponse sdkResponse = + JsonSerializable.fromJsonNode(responseNode, ListTuningJobsResponse.class); + Headers responseHeaders = response.getHeaders(); + if (responseHeaders == null) { + return sdkResponse; + } + Map headers = new HashMap<>(); + for (String headerName : responseHeaders.names()) { + headers.put(headerName, responseHeaders.get(headerName)); + } + return sdkResponse.toBuilder().sdkHttpResponse(HttpResponse.builder().headers(headers)).build(); + } + + ListTuningJobsResponse privateList(ListTuningJobsConfig config) { + BuiltRequest builtRequest = buildRequestForPrivateList(config); + try (ApiResponse response = this.apiClient.request( - "get", path, JsonSerializable.toJsonString(body), requestHttpOptions)) { - ResponseBody responseBody = response.getBody(); - String responseString; - try { - responseString = responseBody.string(); - } catch (IOException e) { - throw new GenAiIOException("Failed to read HTTP response.", e); - } + "get", builtRequest.path, builtRequest.body, builtRequest.httpOptions)) { + return processResponseForPrivateList(response, config); + } + } + + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForCancel(String name, CancelTuningJobConfig config) { + + CancelTuningJobParameters.Builder parameterBuilder = CancelTuningJobParameters.builder(); + + if (!Common.isZero(name)) { + parameterBuilder.name(name); + } + if (!Common.isZero(config)) { + parameterBuilder.config(config); + } + JsonNode parameterNode = JsonSerializable.toJsonNode(parameterBuilder.build()); - JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); - if (this.apiClient.vertexAI()) { - responseNode = listTuningJobsResponseFromVertex(responseNode, null); + ObjectNode body; + String path; + if (this.apiClient.vertexAI()) { + body = cancelTuningJobParametersToVertex(parameterNode, null, parameterNode); + path = Common.formatMap("{name}:cancel", body.get("_url")); + } else { + body = cancelTuningJobParametersToMldev(parameterNode, null, parameterNode); + if (body.get("_url") != null) { + path = Common.formatMap("{name}:cancel", body.get("_url")); } else { - responseNode = listTuningJobsResponseFromMldev(responseNode, null); + path = "{name}:cancel"; } - return JsonSerializable.fromJsonNode(responseNode, ListTuningJobsResponse.class); + } + body.remove("_url"); + + JsonNode queryParams = body.get("_query"); + if (queryParams != null) { + body.remove("_query"); + path = String.format("%s?%s", path, Common.urlEncode((ObjectNode) queryParams)); + } + + // TODO: Remove the hack that removes config. + Optional requestHttpOptions = Optional.empty(); + if (config != null) { + requestHttpOptions = config.httpOptions(); + } + + return new BuiltRequest(path, JsonSerializable.toJsonString(body), requestHttpOptions); + } + + /** + * Cancels a tuning job resource. + * + * @param name The resource name of the tuning job. For Vertex, this is the full resource name. + * For Gemini API, this is `tunedModels/{id}`. + * @param config A {@link CancelTuningJobConfig} for configuring the cancel request. + */ + public void cancel(String name, CancelTuningJobConfig config) { + BuiltRequest builtRequest = buildRequestForCancel(name, config); + + try (ApiResponse response = + this.apiClient.request( + "post", builtRequest.path, builtRequest.body, builtRequest.httpOptions)) { + return; } } - TuningJob privateTune( - String baseModel, TuningDataset trainingDataset, CreateTuningJobConfig config) { + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForPrivateTune( + String baseModel, + PreTunedModel preTunedModel, + TuningDataset trainingDataset, + CreateTuningJobConfig config) { - CreateTuningJobParameters.Builder parameterBuilder = CreateTuningJobParameters.builder(); + CreateTuningJobParametersPrivate.Builder parameterBuilder = + CreateTuningJobParametersPrivate.builder(); if (!Common.isZero(baseModel)) { parameterBuilder.baseModel(baseModel); } + if (!Common.isZero(preTunedModel)) { + parameterBuilder.preTunedModel(preTunedModel); + } if (!Common.isZero(trainingDataset)) { parameterBuilder.trainingDataset(trainingDataset); } @@ -1065,7 +1256,7 @@ TuningJob privateTune( ObjectNode body; String path; if (this.apiClient.vertexAI()) { - body = createTuningJobParametersToVertex(parameterNode, null); + body = createTuningJobParametersPrivateToVertex(parameterNode, null, parameterNode); path = Common.formatMap("tuningJobs", body.get("_url")); } else { throw new UnsupportedOperationException( @@ -1080,43 +1271,78 @@ TuningJob privateTune( } // TODO: Remove the hack that removes config. - body.remove("config"); - Optional requestHttpOptions = Optional.empty(); if (config != null) { requestHttpOptions = config.httpOptions(); } + return new BuiltRequest(path, JsonSerializable.toJsonString(body), requestHttpOptions); + } + + /** A shared processResponse function for both sync and async methods. */ + TuningJob processResponseForPrivateTune(ApiResponse response, CreateTuningJobConfig config) { + ResponseBody responseBody = response.getBody(); + String responseString; + try { + responseString = responseBody.string(); + } catch (IOException e) { + throw new GenAiIOException("Failed to read HTTP response.", e); + } + + JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); + + if (this.apiClient.vertexAI()) { + responseNode = tuningJobFromVertex(responseNode, null); + } + + if (!this.apiClient.vertexAI()) { + throw new UnsupportedOperationException( + "This method is only supported in the Vertex AI client."); + } + + TuningJob sdkResponse = JsonSerializable.fromJsonNode(responseNode, TuningJob.class); + Headers responseHeaders = response.getHeaders(); + if (responseHeaders == null) { + return sdkResponse; + } + Map headers = new HashMap<>(); + for (String headerName : responseHeaders.names()) { + headers.put(headerName, responseHeaders.get(headerName)); + } + return sdkResponse.toBuilder().sdkHttpResponse(HttpResponse.builder().headers(headers)).build(); + } + + TuningJob privateTune( + String baseModel, + PreTunedModel preTunedModel, + TuningDataset trainingDataset, + CreateTuningJobConfig config) { + BuiltRequest builtRequest = + buildRequestForPrivateTune(baseModel, preTunedModel, trainingDataset, config); + try (ApiResponse response = this.apiClient.request( - "post", path, JsonSerializable.toJsonString(body), requestHttpOptions)) { - ResponseBody responseBody = response.getBody(); - String responseString; - try { - responseString = responseBody.string(); - } catch (IOException e) { - throw new GenAiIOException("Failed to read HTTP response.", e); - } - - JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); - if (this.apiClient.vertexAI()) { - responseNode = tuningJobFromVertex(responseNode, null); - } else { - throw new UnsupportedOperationException( - "This method is only supported in the Vertex AI client."); - } - return JsonSerializable.fromJsonNode(responseNode, TuningJob.class); + "post", builtRequest.path, builtRequest.body, builtRequest.httpOptions)) { + return processResponseForPrivateTune(response, config); } } - TuningOperation privateTuneMldev( - String baseModel, TuningDataset trainingDataset, CreateTuningJobConfig config) { + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForPrivateTuneMldev( + String baseModel, + PreTunedModel preTunedModel, + TuningDataset trainingDataset, + CreateTuningJobConfig config) { - CreateTuningJobParameters.Builder parameterBuilder = CreateTuningJobParameters.builder(); + CreateTuningJobParametersPrivate.Builder parameterBuilder = + CreateTuningJobParametersPrivate.builder(); if (!Common.isZero(baseModel)) { parameterBuilder.baseModel(baseModel); } + if (!Common.isZero(preTunedModel)) { + parameterBuilder.preTunedModel(preTunedModel); + } if (!Common.isZero(trainingDataset)) { parameterBuilder.trainingDataset(trainingDataset); } @@ -1131,7 +1357,7 @@ TuningOperation privateTuneMldev( throw new UnsupportedOperationException( "This method is only supported in the Gemini Developer client."); } else { - body = createTuningJobParametersToMldev(parameterNode, null); + body = createTuningJobParametersPrivateToMldev(parameterNode, null, parameterNode); if (body.get("_url") != null) { path = Common.formatMap("tunedModels", body.get("_url")); } else { @@ -1147,32 +1373,61 @@ TuningOperation privateTuneMldev( } // TODO: Remove the hack that removes config. - body.remove("config"); - Optional requestHttpOptions = Optional.empty(); if (config != null) { requestHttpOptions = config.httpOptions(); } + return new BuiltRequest(path, JsonSerializable.toJsonString(body), requestHttpOptions); + } + + /** A shared processResponse function for both sync and async methods. */ + TuningOperation processResponseForPrivateTuneMldev( + ApiResponse response, CreateTuningJobConfig config) { + ResponseBody responseBody = response.getBody(); + String responseString; + try { + responseString = responseBody.string(); + } catch (IOException e) { + throw new GenAiIOException("Failed to read HTTP response.", e); + } + + JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); + + if (this.apiClient.vertexAI()) { + throw new UnsupportedOperationException( + "This method is only supported in the Gemini Developer client."); + } + + if (!this.apiClient.vertexAI()) { + responseNode = tuningOperationFromMldev(responseNode, null); + } + + TuningOperation sdkResponse = + JsonSerializable.fromJsonNode(responseNode, TuningOperation.class); + Headers responseHeaders = response.getHeaders(); + if (responseHeaders == null) { + return sdkResponse; + } + Map headers = new HashMap<>(); + for (String headerName : responseHeaders.names()) { + headers.put(headerName, responseHeaders.get(headerName)); + } + return sdkResponse.toBuilder().sdkHttpResponse(HttpResponse.builder().headers(headers)).build(); + } + + TuningOperation privateTuneMldev( + String baseModel, + PreTunedModel preTunedModel, + TuningDataset trainingDataset, + CreateTuningJobConfig config) { + BuiltRequest builtRequest = + buildRequestForPrivateTuneMldev(baseModel, preTunedModel, trainingDataset, config); + try (ApiResponse response = this.apiClient.request( - "post", path, JsonSerializable.toJsonString(body), requestHttpOptions)) { - ResponseBody responseBody = response.getBody(); - String responseString; - try { - responseString = responseBody.string(); - } catch (IOException e) { - throw new GenAiIOException("Failed to read HTTP response.", e); - } - - JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); - if (this.apiClient.vertexAI()) { - throw new UnsupportedOperationException( - "This method is only supported in the Gemini Developer client."); - } else { - responseNode = tuningOperationFromMldev(responseNode, null); - } - return JsonSerializable.fromJsonNode(responseNode, TuningOperation.class); + "post", builtRequest.path, builtRequest.body, builtRequest.httpOptions)) { + return processResponseForPrivateTuneMldev(response, config); } } @@ -1228,9 +1483,18 @@ public Pager list(ListTuningJobsConfig config) { public TuningJob tune( String baseModel, TuningDataset trainingDataset, CreateTuningJobConfig config) { if (this.apiClient.vertexAI()) { - return this.privateTune(baseModel, trainingDataset, config); + if (baseModel.startsWith("projects/")) { + PreTunedModel.Builder preTunedModelBuilder = + PreTunedModel.builder().tunedModelName(baseModel); + if (config != null && config.preTunedModelCheckpointId().isPresent()) { + preTunedModelBuilder.checkpointId(config.preTunedModelCheckpointId().get()); + } + return this.privateTune(null, preTunedModelBuilder.build(), trainingDataset, config); + } else { + return this.privateTune(baseModel, null, trainingDataset, config); + } } else { - TuningOperation operation = this.privateTuneMldev(baseModel, trainingDataset, config); + TuningOperation operation = this.privateTuneMldev(baseModel, null, trainingDataset, config); String tunedModelName = ""; if (operation.metadata().isPresent() && operation.metadata().get().containsKey("tunedModel")) { diff --git a/src/main/java/com/google/genai/types/ActivityEnd.java b/src/main/java/com/google/genai/types/ActivityEnd.java index 98778d34ba4..24446b34a68 100644 --- a/src/main/java/com/google/genai/types/ActivityEnd.java +++ b/src/main/java/com/google/genai/types/ActivityEnd.java @@ -32,6 +32,7 @@ @JsonDeserialize(builder = ActivityEnd.Builder.class) public abstract class ActivityEnd extends JsonSerializable { /** Instantiates a builder for ActivityEnd. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_ActivityEnd.Builder(); } @@ -52,6 +53,7 @@ private static Builder create() { } /** Deserializes a JSON string to a ActivityEnd object. */ + @ExcludeFromGeneratedCoverageReport public static ActivityEnd fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, ActivityEnd.class); } diff --git a/src/main/java/com/google/genai/types/ActivityHandling.java b/src/main/java/com/google/genai/types/ActivityHandling.java index 1f14255254e..d2c39aacfac 100644 --- a/src/main/java/com/google/genai/types/ActivityHandling.java +++ b/src/main/java/com/google/genai/types/ActivityHandling.java @@ -64,12 +64,14 @@ public ActivityHandling(Known knownValue) { this.value = knownValue.toString(); } + @ExcludeFromGeneratedCoverageReport @Override @JsonValue public String toString() { return this.value; } + @ExcludeFromGeneratedCoverageReport @SuppressWarnings("PatternMatchingInstanceof") @Override public boolean equals(Object o) { @@ -96,6 +98,7 @@ public boolean equals(Object o) { return false; } + @ExcludeFromGeneratedCoverageReport @Override public int hashCode() { if (this.activityHandlingEnum != Known.ACTIVITY_HANDLING_UNSPECIFIED) { @@ -105,6 +108,7 @@ public int hashCode() { } } + @ExcludeFromGeneratedCoverageReport public Known knownEnum() { return this.activityHandlingEnum; } diff --git a/src/main/java/com/google/genai/types/ActivityStart.java b/src/main/java/com/google/genai/types/ActivityStart.java index 7945ad51cdd..1686db78195 100644 --- a/src/main/java/com/google/genai/types/ActivityStart.java +++ b/src/main/java/com/google/genai/types/ActivityStart.java @@ -32,6 +32,7 @@ @JsonDeserialize(builder = ActivityStart.Builder.class) public abstract class ActivityStart extends JsonSerializable { /** Instantiates a builder for ActivityStart. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_ActivityStart.Builder(); } @@ -52,6 +53,7 @@ private static Builder create() { } /** Deserializes a JSON string to a ActivityStart object. */ + @ExcludeFromGeneratedCoverageReport public static ActivityStart fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, ActivityStart.class); } diff --git a/src/main/java/com/google/genai/types/AdapterSize.java b/src/main/java/com/google/genai/types/AdapterSize.java index fa47b3d31e6..6a7c765000a 100644 --- a/src/main/java/com/google/genai/types/AdapterSize.java +++ b/src/main/java/com/google/genai/types/AdapterSize.java @@ -23,7 +23,7 @@ import com.google.common.base.Ascii; import java.util.Objects; -/** Optional. Adapter size for tuning. */ +/** Adapter size for tuning. This enum is not supported in Gemini API. */ public class AdapterSize { /** Enum representing the known values for AdapterSize. */ @@ -72,12 +72,14 @@ public AdapterSize(Known knownValue) { this.value = knownValue.toString(); } + @ExcludeFromGeneratedCoverageReport @Override @JsonValue public String toString() { return this.value; } + @ExcludeFromGeneratedCoverageReport @SuppressWarnings("PatternMatchingInstanceof") @Override public boolean equals(Object o) { @@ -104,6 +106,7 @@ public boolean equals(Object o) { return false; } + @ExcludeFromGeneratedCoverageReport @Override public int hashCode() { if (this.adapterSizeEnum != Known.ADAPTER_SIZE_UNSPECIFIED) { @@ -113,6 +116,7 @@ public int hashCode() { } } + @ExcludeFromGeneratedCoverageReport public Known knownEnum() { return this.adapterSizeEnum; } diff --git a/src/main/java/com/google/genai/types/ApiAuth.java b/src/main/java/com/google/genai/types/ApiAuth.java index 2ae9cc777e3..d89dd8048f0 100644 --- a/src/main/java/com/google/genai/types/ApiAuth.java +++ b/src/main/java/com/google/genai/types/ApiAuth.java @@ -27,7 +27,8 @@ /** * The generic reusable api auth config. Deprecated. Please use AuthConfig - * (google/cloud/aiplatform/master/auth.proto) instead. + * (google/cloud/aiplatform/master/auth.proto) instead. This data type is not supported in Gemini + * API. */ @AutoValue @JsonDeserialize(builder = ApiAuth.Builder.class) @@ -37,6 +38,7 @@ public abstract class ApiAuth extends JsonSerializable { public abstract Optional apiKeyConfig(); /** Instantiates a builder for ApiAuth. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_ApiAuth.Builder(); } @@ -74,6 +76,7 @@ public Builder apiKeyConfig(ApiAuthApiKeyConfig.Builder apiKeyConfigBuilder) { } /** Deserializes a JSON string to a ApiAuth object. */ + @ExcludeFromGeneratedCoverageReport public static ApiAuth fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, ApiAuth.class); } diff --git a/src/main/java/com/google/genai/types/ApiAuthApiKeyConfig.java b/src/main/java/com/google/genai/types/ApiAuthApiKeyConfig.java index 2211294f2d8..c4f1583d7ff 100644 --- a/src/main/java/com/google/genai/types/ApiAuthApiKeyConfig.java +++ b/src/main/java/com/google/genai/types/ApiAuthApiKeyConfig.java @@ -25,7 +25,7 @@ import com.google.genai.JsonSerializable; import java.util.Optional; -/** The API secret. */ +/** The API secret. This data type is not supported in Gemini API. */ @AutoValue @JsonDeserialize(builder = ApiAuthApiKeyConfig.Builder.class) public abstract class ApiAuthApiKeyConfig extends JsonSerializable { @@ -41,6 +41,7 @@ public abstract class ApiAuthApiKeyConfig extends JsonSerializable { public abstract Optional apiKeyString(); /** Instantiates a builder for ApiAuthApiKeyConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_ApiAuthApiKeyConfig.Builder(); } @@ -78,6 +79,7 @@ private static Builder create() { } /** Deserializes a JSON string to a ApiAuthApiKeyConfig object. */ + @ExcludeFromGeneratedCoverageReport public static ApiAuthApiKeyConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, ApiAuthApiKeyConfig.class); } diff --git a/src/main/java/com/google/genai/types/ApiKeyConfig.java b/src/main/java/com/google/genai/types/ApiKeyConfig.java index 6ffd2019679..d8c1cb63433 100644 --- a/src/main/java/com/google/genai/types/ApiKeyConfig.java +++ b/src/main/java/com/google/genai/types/ApiKeyConfig.java @@ -34,6 +34,7 @@ public abstract class ApiKeyConfig extends JsonSerializable { public abstract Optional apiKeyString(); /** Instantiates a builder for ApiKeyConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_ApiKeyConfig.Builder(); } @@ -62,6 +63,7 @@ private static Builder create() { } /** Deserializes a JSON string to a ApiKeyConfig object. */ + @ExcludeFromGeneratedCoverageReport public static ApiKeyConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, ApiKeyConfig.class); } diff --git a/src/main/java/com/google/genai/types/ApiSpec.java b/src/main/java/com/google/genai/types/ApiSpec.java index 17283d5724c..d52ef5f5a74 100644 --- a/src/main/java/com/google/genai/types/ApiSpec.java +++ b/src/main/java/com/google/genai/types/ApiSpec.java @@ -23,7 +23,7 @@ import com.google.common.base.Ascii; import java.util.Objects; -/** The API spec that the external API implements. */ +/** The API spec that the external API implements. This enum is not supported in Gemini API. */ public class ApiSpec { /** Enum representing the known values for ApiSpec. */ @@ -60,12 +60,14 @@ public ApiSpec(Known knownValue) { this.value = knownValue.toString(); } + @ExcludeFromGeneratedCoverageReport @Override @JsonValue public String toString() { return this.value; } + @ExcludeFromGeneratedCoverageReport @SuppressWarnings("PatternMatchingInstanceof") @Override public boolean equals(Object o) { @@ -92,6 +94,7 @@ public boolean equals(Object o) { return false; } + @ExcludeFromGeneratedCoverageReport @Override public int hashCode() { if (this.apiSpecEnum != Known.API_SPEC_UNSPECIFIED) { @@ -101,6 +104,7 @@ public int hashCode() { } } + @ExcludeFromGeneratedCoverageReport public Known knownEnum() { return this.apiSpecEnum; } diff --git a/src/main/java/com/google/genai/types/AudioTranscriptionConfig.java b/src/main/java/com/google/genai/types/AudioTranscriptionConfig.java index a444bcea7f3..61a54d4c9db 100644 --- a/src/main/java/com/google/genai/types/AudioTranscriptionConfig.java +++ b/src/main/java/com/google/genai/types/AudioTranscriptionConfig.java @@ -28,6 +28,7 @@ @JsonDeserialize(builder = AudioTranscriptionConfig.Builder.class) public abstract class AudioTranscriptionConfig extends JsonSerializable { /** Instantiates a builder for AudioTranscriptionConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_AudioTranscriptionConfig.Builder(); } @@ -48,6 +49,7 @@ private static Builder create() { } /** Deserializes a JSON string to a AudioTranscriptionConfig object. */ + @ExcludeFromGeneratedCoverageReport public static AudioTranscriptionConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, AudioTranscriptionConfig.class); } diff --git a/src/main/java/com/google/genai/types/AuthConfig.java b/src/main/java/com/google/genai/types/AuthConfig.java index eec5deb5f22..d2cb708191f 100644 --- a/src/main/java/com/google/genai/types/AuthConfig.java +++ b/src/main/java/com/google/genai/types/AuthConfig.java @@ -55,6 +55,7 @@ public abstract class AuthConfig extends JsonSerializable { public abstract Optional oidcConfig(); /** Instantiates a builder for AuthConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_AuthConfig.Builder(); } @@ -191,6 +192,7 @@ public Builder oidcConfig(AuthConfigOidcConfig.Builder oidcConfigBuilder) { } /** Deserializes a JSON string to a AuthConfig object. */ + @ExcludeFromGeneratedCoverageReport public static AuthConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, AuthConfig.class); } diff --git a/src/main/java/com/google/genai/types/AuthConfigGoogleServiceAccountConfig.java b/src/main/java/com/google/genai/types/AuthConfigGoogleServiceAccountConfig.java index 9bbf124d26f..ce93390779f 100644 --- a/src/main/java/com/google/genai/types/AuthConfigGoogleServiceAccountConfig.java +++ b/src/main/java/com/google/genai/types/AuthConfigGoogleServiceAccountConfig.java @@ -25,7 +25,9 @@ import com.google.genai.JsonSerializable; import java.util.Optional; -/** Config for Google Service Account Authentication. */ +/** + * Config for Google Service Account Authentication. This data type is not supported in Gemini API. + */ @AutoValue @JsonDeserialize(builder = AuthConfigGoogleServiceAccountConfig.Builder.class) public abstract class AuthConfigGoogleServiceAccountConfig extends JsonSerializable { @@ -41,6 +43,7 @@ public abstract class AuthConfigGoogleServiceAccountConfig extends JsonSerializa public abstract Optional serviceAccount(); /** Instantiates a builder for AuthConfigGoogleServiceAccountConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_AuthConfigGoogleServiceAccountConfig.Builder(); } @@ -77,6 +80,7 @@ private static Builder create() { } /** Deserializes a JSON string to a AuthConfigGoogleServiceAccountConfig object. */ + @ExcludeFromGeneratedCoverageReport public static AuthConfigGoogleServiceAccountConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, AuthConfigGoogleServiceAccountConfig.class); } diff --git a/src/main/java/com/google/genai/types/AuthConfigHttpBasicAuthConfig.java b/src/main/java/com/google/genai/types/AuthConfigHttpBasicAuthConfig.java index 34e55ddf9d8..240c40ecfa3 100644 --- a/src/main/java/com/google/genai/types/AuthConfigHttpBasicAuthConfig.java +++ b/src/main/java/com/google/genai/types/AuthConfigHttpBasicAuthConfig.java @@ -25,7 +25,7 @@ import com.google.genai.JsonSerializable; import java.util.Optional; -/** Config for HTTP Basic Authentication. */ +/** Config for HTTP Basic Authentication. This data type is not supported in Gemini API. */ @AutoValue @JsonDeserialize(builder = AuthConfigHttpBasicAuthConfig.Builder.class) public abstract class AuthConfigHttpBasicAuthConfig extends JsonSerializable { @@ -40,6 +40,7 @@ public abstract class AuthConfigHttpBasicAuthConfig extends JsonSerializable { public abstract Optional credentialSecret(); /** Instantiates a builder for AuthConfigHttpBasicAuthConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_AuthConfigHttpBasicAuthConfig.Builder(); } @@ -75,6 +76,7 @@ private static Builder create() { } /** Deserializes a JSON string to a AuthConfigHttpBasicAuthConfig object. */ + @ExcludeFromGeneratedCoverageReport public static AuthConfigHttpBasicAuthConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, AuthConfigHttpBasicAuthConfig.class); } diff --git a/src/main/java/com/google/genai/types/AuthConfigOauthConfig.java b/src/main/java/com/google/genai/types/AuthConfigOauthConfig.java index 42082cf4bd6..22976903310 100644 --- a/src/main/java/com/google/genai/types/AuthConfigOauthConfig.java +++ b/src/main/java/com/google/genai/types/AuthConfigOauthConfig.java @@ -25,7 +25,7 @@ import com.google.genai.JsonSerializable; import java.util.Optional; -/** Config for user oauth. */ +/** Config for user oauth. This data type is not supported in Gemini API. */ @AutoValue @JsonDeserialize(builder = AuthConfigOauthConfig.Builder.class) public abstract class AuthConfigOauthConfig extends JsonSerializable { @@ -47,6 +47,7 @@ public abstract class AuthConfigOauthConfig extends JsonSerializable { public abstract Optional serviceAccount(); /** Instantiates a builder for AuthConfigOauthConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_AuthConfigOauthConfig.Builder(); } @@ -88,6 +89,7 @@ private static Builder create() { } /** Deserializes a JSON string to a AuthConfigOauthConfig object. */ + @ExcludeFromGeneratedCoverageReport public static AuthConfigOauthConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, AuthConfigOauthConfig.class); } diff --git a/src/main/java/com/google/genai/types/AuthConfigOidcConfig.java b/src/main/java/com/google/genai/types/AuthConfigOidcConfig.java index 4f5339f09e6..a2301e43e30 100644 --- a/src/main/java/com/google/genai/types/AuthConfigOidcConfig.java +++ b/src/main/java/com/google/genai/types/AuthConfigOidcConfig.java @@ -25,7 +25,7 @@ import com.google.genai.JsonSerializable; import java.util.Optional; -/** Config for user OIDC auth. */ +/** Config for user OIDC auth. This data type is not supported in Gemini API. */ @AutoValue @JsonDeserialize(builder = AuthConfigOidcConfig.Builder.class) public abstract class AuthConfigOidcConfig extends JsonSerializable { @@ -49,6 +49,7 @@ public abstract class AuthConfigOidcConfig extends JsonSerializable { public abstract Optional serviceAccount(); /** Instantiates a builder for AuthConfigOidcConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_AuthConfigOidcConfig.Builder(); } @@ -92,6 +93,7 @@ private static Builder create() { } /** Deserializes a JSON string to a AuthConfigOidcConfig object. */ + @ExcludeFromGeneratedCoverageReport public static AuthConfigOidcConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, AuthConfigOidcConfig.class); } diff --git a/src/main/java/com/google/genai/types/AuthType.java b/src/main/java/com/google/genai/types/AuthType.java index 4ac09d48c8a..5bbe1559c92 100644 --- a/src/main/java/com/google/genai/types/AuthType.java +++ b/src/main/java/com/google/genai/types/AuthType.java @@ -23,7 +23,7 @@ import com.google.common.base.Ascii; import java.util.Objects; -/** Type of auth scheme. */ +/** Type of auth scheme. This enum is not supported in Gemini API. */ public class AuthType { /** Enum representing the known values for AuthType. */ @@ -71,12 +71,14 @@ public AuthType(Known knownValue) { this.value = knownValue.toString(); } + @ExcludeFromGeneratedCoverageReport @Override @JsonValue public String toString() { return this.value; } + @ExcludeFromGeneratedCoverageReport @SuppressWarnings("PatternMatchingInstanceof") @Override public boolean equals(Object o) { @@ -103,6 +105,7 @@ public boolean equals(Object o) { return false; } + @ExcludeFromGeneratedCoverageReport @Override public int hashCode() { if (this.authTypeEnum != Known.AUTH_TYPE_UNSPECIFIED) { @@ -112,6 +115,7 @@ public int hashCode() { } } + @ExcludeFromGeneratedCoverageReport public Known knownEnum() { return this.authTypeEnum; } diff --git a/src/main/java/com/google/genai/types/AutomaticActivityDetection.java b/src/main/java/com/google/genai/types/AutomaticActivityDetection.java index 17f587ea59b..cd381f2aec6 100644 --- a/src/main/java/com/google/genai/types/AutomaticActivityDetection.java +++ b/src/main/java/com/google/genai/types/AutomaticActivityDetection.java @@ -62,6 +62,7 @@ public abstract class AutomaticActivityDetection extends JsonSerializable { public abstract Optional silenceDurationMs(); /** Instantiates a builder for AutomaticActivityDetection. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_AutomaticActivityDetection.Builder(); } @@ -168,6 +169,7 @@ public Builder endOfSpeechSensitivity(String endOfSpeechSensitivity) { } /** Deserializes a JSON string to a AutomaticActivityDetection object. */ + @ExcludeFromGeneratedCoverageReport public static AutomaticActivityDetection fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, AutomaticActivityDetection.class); } diff --git a/src/main/java/com/google/genai/types/AutomaticFunctionCallingConfig.java b/src/main/java/com/google/genai/types/AutomaticFunctionCallingConfig.java index e161a75f312..252e8df5c31 100644 --- a/src/main/java/com/google/genai/types/AutomaticFunctionCallingConfig.java +++ b/src/main/java/com/google/genai/types/AutomaticFunctionCallingConfig.java @@ -53,6 +53,7 @@ public abstract class AutomaticFunctionCallingConfig extends JsonSerializable { public abstract Optional ignoreCallHistory(); /** Instantiates a builder for AutomaticFunctionCallingConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_AutomaticFunctionCallingConfig.Builder(); } @@ -104,6 +105,7 @@ private static Builder create() { } /** Deserializes a JSON string to a AutomaticFunctionCallingConfig object. */ + @ExcludeFromGeneratedCoverageReport public static AutomaticFunctionCallingConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, AutomaticFunctionCallingConfig.class); } diff --git a/src/main/java/com/google/genai/types/BatchJob.java b/src/main/java/com/google/genai/types/BatchJob.java index 87f829a4d70..b4394be60fc 100644 --- a/src/main/java/com/google/genai/types/BatchJob.java +++ b/src/main/java/com/google/genai/types/BatchJob.java @@ -78,6 +78,7 @@ public abstract class BatchJob extends JsonSerializable { public abstract Optional dest(); /** Instantiates a builder for BatchJob. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_BatchJob.Builder(); } @@ -236,6 +237,7 @@ public Builder dest(BatchJobDestination.Builder destBuilder) { } /** Deserializes a JSON string to a BatchJob object. */ + @ExcludeFromGeneratedCoverageReport public static BatchJob fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, BatchJob.class); } diff --git a/src/main/java/com/google/genai/types/BatchJobDestination.java b/src/main/java/com/google/genai/types/BatchJobDestination.java index 49c7f2933df..9d1c0ebfa86 100644 --- a/src/main/java/com/google/genai/types/BatchJobDestination.java +++ b/src/main/java/com/google/genai/types/BatchJobDestination.java @@ -61,7 +61,15 @@ public abstract class BatchJobDestination extends JsonSerializable { @JsonProperty("inlinedResponses") public abstract Optional> inlinedResponses(); + /** + * The responses to the requests in the batch. Returned when the batch was built using inlined + * requests. The responses will be in the same order as the input requests. + */ + @JsonProperty("inlinedEmbedContentResponses") + public abstract Optional> inlinedEmbedContentResponses(); + /** Instantiates a builder for BatchJobDestination. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_BatchJobDestination.Builder(); } @@ -145,10 +153,49 @@ public Builder inlinedResponses(InlinedResponse.Builder... inlinedResponsesBuild .collect(toImmutableList())); } + /** + * Setter for inlinedEmbedContentResponses. + * + *

inlinedEmbedContentResponses: The responses to the requests in the batch. Returned when + * the batch was built using inlined requests. The responses will be in the same order as the + * input requests. + */ + @JsonProperty("inlinedEmbedContentResponses") + public abstract Builder inlinedEmbedContentResponses( + List inlinedEmbedContentResponses); + + /** + * Setter for inlinedEmbedContentResponses. + * + *

inlinedEmbedContentResponses: The responses to the requests in the batch. Returned when + * the batch was built using inlined requests. The responses will be in the same order as the + * input requests. + */ + public Builder inlinedEmbedContentResponses( + InlinedEmbedContentResponse... inlinedEmbedContentResponses) { + return inlinedEmbedContentResponses(Arrays.asList(inlinedEmbedContentResponses)); + } + + /** + * Setter for inlinedEmbedContentResponses builder. + * + *

inlinedEmbedContentResponses: The responses to the requests in the batch. Returned when + * the batch was built using inlined requests. The responses will be in the same order as the + * input requests. + */ + public Builder inlinedEmbedContentResponses( + InlinedEmbedContentResponse.Builder... inlinedEmbedContentResponsesBuilders) { + return inlinedEmbedContentResponses( + Arrays.asList(inlinedEmbedContentResponsesBuilders).stream() + .map(InlinedEmbedContentResponse.Builder::build) + .collect(toImmutableList())); + } + public abstract BatchJobDestination build(); } /** Deserializes a JSON string to a BatchJobDestination object. */ + @ExcludeFromGeneratedCoverageReport public static BatchJobDestination fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, BatchJobDestination.class); } diff --git a/src/main/java/com/google/genai/types/BatchJobSource.java b/src/main/java/com/google/genai/types/BatchJobSource.java index d56d3f69011..d45dd9e196b 100644 --- a/src/main/java/com/google/genai/types/BatchJobSource.java +++ b/src/main/java/com/google/genai/types/BatchJobSource.java @@ -54,6 +54,7 @@ public abstract class BatchJobSource extends JsonSerializable { public abstract Optional> inlinedRequests(); /** Instantiates a builder for BatchJobSource. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_BatchJobSource.Builder(); } @@ -145,6 +146,7 @@ public Builder inlinedRequests(InlinedRequest.Builder... inlinedRequestsBuilders } /** Deserializes a JSON string to a BatchJobSource object. */ + @ExcludeFromGeneratedCoverageReport public static BatchJobSource fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, BatchJobSource.class); } diff --git a/src/main/java/com/google/genai/types/Behavior.java b/src/main/java/com/google/genai/types/Behavior.java index baff1526f3f..4b043a4484e 100644 --- a/src/main/java/com/google/genai/types/Behavior.java +++ b/src/main/java/com/google/genai/types/Behavior.java @@ -69,12 +69,14 @@ public Behavior(Known knownValue) { this.value = knownValue.toString(); } + @ExcludeFromGeneratedCoverageReport @Override @JsonValue public String toString() { return this.value; } + @ExcludeFromGeneratedCoverageReport @SuppressWarnings("PatternMatchingInstanceof") @Override public boolean equals(Object o) { @@ -101,6 +103,7 @@ public boolean equals(Object o) { return false; } + @ExcludeFromGeneratedCoverageReport @Override public int hashCode() { if (this.behaviorEnum != Known.BEHAVIOR_UNSPECIFIED) { @@ -110,6 +113,7 @@ public int hashCode() { } } + @ExcludeFromGeneratedCoverageReport public Known knownEnum() { return this.behaviorEnum; } diff --git a/src/main/java/com/google/genai/types/Blob.java b/src/main/java/com/google/genai/types/Blob.java index 923319396c5..f3db4a94a8f 100644 --- a/src/main/java/com/google/genai/types/Blob.java +++ b/src/main/java/com/google/genai/types/Blob.java @@ -29,22 +29,25 @@ @AutoValue @JsonDeserialize(builder = Blob.Builder.class) public abstract class Blob extends JsonSerializable { + /** Required. Raw bytes. */ + @JsonProperty("data") + public abstract Optional data(); + /** * Optional. Display name of the blob. Used to provide a label or filename to distinguish blobs. - * This field is not currently used in the Gemini GenerateContent calls. + * This field is only returned in PromptMessage for prompt management. It is currently used in the + * Gemini GenerateContent calls only when server side tools (code_execution, google_search, and + * url_context) are enabled. This field is not supported in Gemini API. */ @JsonProperty("displayName") public abstract Optional displayName(); - /** Required. Raw bytes. */ - @JsonProperty("data") - public abstract Optional data(); - /** Required. The IANA standard MIME type of the source data. */ @JsonProperty("mimeType") public abstract Optional mimeType(); /** Instantiates a builder for Blob. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_Blob.Builder(); } @@ -61,15 +64,6 @@ private static Builder create() { return new AutoValue_Blob.Builder(); } - /** - * Setter for displayName. - * - *

displayName: Optional. Display name of the blob. Used to provide a label or filename to - * distinguish blobs. This field is not currently used in the Gemini GenerateContent calls. - */ - @JsonProperty("displayName") - public abstract Builder displayName(String displayName); - /** * Setter for data. * @@ -78,6 +72,18 @@ private static Builder create() { @JsonProperty("data") public abstract Builder data(byte[] data); + /** + * Setter for displayName. + * + *

displayName: Optional. Display name of the blob. Used to provide a label or filename to + * distinguish blobs. This field is only returned in PromptMessage for prompt management. It is + * currently used in the Gemini GenerateContent calls only when server side tools + * (code_execution, google_search, and url_context) are enabled. This field is not supported in + * Gemini API. + */ + @JsonProperty("displayName") + public abstract Builder displayName(String displayName); + /** * Setter for mimeType. * @@ -90,6 +96,7 @@ private static Builder create() { } /** Deserializes a JSON string to a Blob object. */ + @ExcludeFromGeneratedCoverageReport public static Blob fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, Blob.class); } diff --git a/src/main/java/com/google/genai/types/BlockedReason.java b/src/main/java/com/google/genai/types/BlockedReason.java index fc652ee35d9..399ff88b7a2 100644 --- a/src/main/java/com/google/genai/types/BlockedReason.java +++ b/src/main/java/com/google/genai/types/BlockedReason.java @@ -23,28 +23,40 @@ import com.google.common.base.Ascii; import java.util.Objects; -/** Output only. Blocked reason. */ +/** Output only. The reason why the prompt was blocked. */ public class BlockedReason { /** Enum representing the known values for BlockedReason. */ public enum Known { - /** Unspecified blocked reason. */ + /** The blocked reason is unspecified. */ BLOCKED_REASON_UNSPECIFIED, - /** Candidates blocked due to safety. */ + /** The prompt was blocked for safety reasons. */ SAFETY, - /** Candidates blocked due to other reason. */ + /** + * The prompt was blocked for other reasons. For example, it may be due to the prompt's + * language, or because it contains other harmful content. + */ OTHER, - /** Candidates blocked due to the terms which are included from the terminology blocklist. */ + /** The prompt was blocked because it contains a term from the terminology blocklist. */ BLOCKLIST, - /** Candidates blocked due to prohibited content. */ + /** The prompt was blocked because it contains prohibited content. */ PROHIBITED_CONTENT, - /** Candidates blocked due to unsafe image generation content. */ - IMAGE_SAFETY + /** The prompt was blocked because it contains content that is unsafe for image generation. */ + IMAGE_SAFETY, + + /** The prompt was blocked by Model Armor. This enum value is not supported in Gemini API. */ + MODEL_ARMOR, + + /** + * The prompt was blocked as a jailbreak attempt. This enum value is not supported in Gemini + * API. + */ + JAILBREAK } private Known blockedReasonEnum; @@ -69,12 +81,14 @@ public BlockedReason(Known knownValue) { this.value = knownValue.toString(); } + @ExcludeFromGeneratedCoverageReport @Override @JsonValue public String toString() { return this.value; } + @ExcludeFromGeneratedCoverageReport @SuppressWarnings("PatternMatchingInstanceof") @Override public boolean equals(Object o) { @@ -101,6 +115,7 @@ public boolean equals(Object o) { return false; } + @ExcludeFromGeneratedCoverageReport @Override public int hashCode() { if (this.blockedReasonEnum != Known.BLOCKED_REASON_UNSPECIFIED) { @@ -110,6 +125,7 @@ public int hashCode() { } } + @ExcludeFromGeneratedCoverageReport public Known knownEnum() { return this.blockedReasonEnum; } diff --git a/src/main/java/com/google/genai/types/CachedContent.java b/src/main/java/com/google/genai/types/CachedContent.java index dfc6ba16ba6..0072b18ddad 100644 --- a/src/main/java/com/google/genai/types/CachedContent.java +++ b/src/main/java/com/google/genai/types/CachedContent.java @@ -59,6 +59,7 @@ public abstract class CachedContent extends JsonSerializable { public abstract Optional usageMetadata(); /** Instantiates a builder for CachedContent. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_CachedContent.Builder(); } @@ -144,6 +145,7 @@ public Builder usageMetadata(CachedContentUsageMetadata.Builder usageMetadataBui } /** Deserializes a JSON string to a CachedContent object. */ + @ExcludeFromGeneratedCoverageReport public static CachedContent fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, CachedContent.class); } diff --git a/src/main/java/com/google/genai/types/CachedContentUsageMetadata.java b/src/main/java/com/google/genai/types/CachedContentUsageMetadata.java index d9d19731ec4..96e7d299e48 100644 --- a/src/main/java/com/google/genai/types/CachedContentUsageMetadata.java +++ b/src/main/java/com/google/genai/types/CachedContentUsageMetadata.java @@ -29,15 +29,15 @@ @AutoValue @JsonDeserialize(builder = CachedContentUsageMetadata.Builder.class) public abstract class CachedContentUsageMetadata extends JsonSerializable { - /** Duration of audio in seconds. */ + /** Duration of audio in seconds. This field is not supported in Gemini API. */ @JsonProperty("audioDurationSeconds") public abstract Optional audioDurationSeconds(); - /** Number of images. */ + /** Number of images. This field is not supported in Gemini API. */ @JsonProperty("imageCount") public abstract Optional imageCount(); - /** Number of text characters. */ + /** Number of text characters. This field is not supported in Gemini API. */ @JsonProperty("textCount") public abstract Optional textCount(); @@ -45,11 +45,12 @@ public abstract class CachedContentUsageMetadata extends JsonSerializable { @JsonProperty("totalTokenCount") public abstract Optional totalTokenCount(); - /** Duration of video in seconds. */ + /** Duration of video in seconds. This field is not supported in Gemini API. */ @JsonProperty("videoDurationSeconds") public abstract Optional videoDurationSeconds(); /** Instantiates a builder for CachedContentUsageMetadata. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_CachedContentUsageMetadata.Builder(); } @@ -69,7 +70,8 @@ private static Builder create() { /** * Setter for audioDurationSeconds. * - *

audioDurationSeconds: Duration of audio in seconds. + *

audioDurationSeconds: Duration of audio in seconds. This field is not supported in Gemini + * API. */ @JsonProperty("audioDurationSeconds") public abstract Builder audioDurationSeconds(Integer audioDurationSeconds); @@ -77,7 +79,7 @@ private static Builder create() { /** * Setter for imageCount. * - *

imageCount: Number of images. + *

imageCount: Number of images. This field is not supported in Gemini API. */ @JsonProperty("imageCount") public abstract Builder imageCount(Integer imageCount); @@ -85,7 +87,7 @@ private static Builder create() { /** * Setter for textCount. * - *

textCount: Number of text characters. + *

textCount: Number of text characters. This field is not supported in Gemini API. */ @JsonProperty("textCount") public abstract Builder textCount(Integer textCount); @@ -101,7 +103,8 @@ private static Builder create() { /** * Setter for videoDurationSeconds. * - *

videoDurationSeconds: Duration of video in seconds. + *

videoDurationSeconds: Duration of video in seconds. This field is not supported in Gemini + * API. */ @JsonProperty("videoDurationSeconds") public abstract Builder videoDurationSeconds(Integer videoDurationSeconds); @@ -110,6 +113,7 @@ private static Builder create() { } /** Deserializes a JSON string to a CachedContentUsageMetadata object. */ + @ExcludeFromGeneratedCoverageReport public static CachedContentUsageMetadata fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, CachedContentUsageMetadata.class); } diff --git a/src/main/java/com/google/genai/types/CancelBatchJobConfig.java b/src/main/java/com/google/genai/types/CancelBatchJobConfig.java index 5a06b0cf176..fb3f7e4cd57 100644 --- a/src/main/java/com/google/genai/types/CancelBatchJobConfig.java +++ b/src/main/java/com/google/genai/types/CancelBatchJobConfig.java @@ -34,6 +34,7 @@ public abstract class CancelBatchJobConfig extends JsonSerializable { public abstract Optional httpOptions(); /** Instantiates a builder for CancelBatchJobConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_CancelBatchJobConfig.Builder(); } @@ -71,6 +72,7 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { } /** Deserializes a JSON string to a CancelBatchJobConfig object. */ + @ExcludeFromGeneratedCoverageReport public static CancelBatchJobConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, CancelBatchJobConfig.class); } diff --git a/src/main/java/com/google/genai/types/CancelBatchJobParameters.java b/src/main/java/com/google/genai/types/CancelBatchJobParameters.java index 83201a43cdd..a8300c880c7 100644 --- a/src/main/java/com/google/genai/types/CancelBatchJobParameters.java +++ b/src/main/java/com/google/genai/types/CancelBatchJobParameters.java @@ -44,6 +44,7 @@ public abstract class CancelBatchJobParameters extends JsonSerializable { public abstract Optional config(); /** Instantiates a builder for CancelBatchJobParameters. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_CancelBatchJobParameters.Builder(); } @@ -91,6 +92,7 @@ public Builder config(CancelBatchJobConfig.Builder configBuilder) { } /** Deserializes a JSON string to a CancelBatchJobParameters object. */ + @ExcludeFromGeneratedCoverageReport public static CancelBatchJobParameters fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, CancelBatchJobParameters.class); } diff --git a/src/main/java/com/google/genai/types/CancelTuningJobConfig.java b/src/main/java/com/google/genai/types/CancelTuningJobConfig.java new file mode 100644 index 00000000000..418617e2ed0 --- /dev/null +++ b/src/main/java/com/google/genai/types/CancelTuningJobConfig.java @@ -0,0 +1,79 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Auto-generated code. Do not edit. + +package com.google.genai.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.google.auto.value.AutoValue; +import com.google.genai.JsonSerializable; +import java.util.Optional; + +/** Optional parameters for tunings.cancel method. */ +@AutoValue +@JsonDeserialize(builder = CancelTuningJobConfig.Builder.class) +public abstract class CancelTuningJobConfig extends JsonSerializable { + /** Used to override HTTP request options. */ + @JsonProperty("httpOptions") + public abstract Optional httpOptions(); + + /** Instantiates a builder for CancelTuningJobConfig. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_CancelTuningJobConfig.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for CancelTuningJobConfig. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `CancelTuningJobConfig.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_CancelTuningJobConfig.Builder(); + } + + /** + * Setter for httpOptions. + * + *

httpOptions: Used to override HTTP request options. + */ + @JsonProperty("httpOptions") + public abstract Builder httpOptions(HttpOptions httpOptions); + + /** + * Setter for httpOptions builder. + * + *

httpOptions: Used to override HTTP request options. + */ + public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { + return httpOptions(httpOptionsBuilder.build()); + } + + public abstract CancelTuningJobConfig build(); + } + + /** Deserializes a JSON string to a CancelTuningJobConfig object. */ + @ExcludeFromGeneratedCoverageReport + public static CancelTuningJobConfig fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, CancelTuningJobConfig.class); + } +} diff --git a/src/main/java/com/google/genai/types/CancelTuningJobParameters.java b/src/main/java/com/google/genai/types/CancelTuningJobParameters.java new file mode 100644 index 00000000000..d7502593e99 --- /dev/null +++ b/src/main/java/com/google/genai/types/CancelTuningJobParameters.java @@ -0,0 +1,93 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Auto-generated code. Do not edit. + +package com.google.genai.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.google.api.core.InternalApi; +import com.google.auto.value.AutoValue; +import com.google.genai.JsonSerializable; +import java.util.Optional; + +/** Parameters for the cancel method. */ +@AutoValue +@InternalApi +@JsonDeserialize(builder = CancelTuningJobParameters.Builder.class) +public abstract class CancelTuningJobParameters extends JsonSerializable { + /** The resource name of the tuning job. */ + @JsonProperty("name") + public abstract Optional name(); + + /** Optional parameters for the request. */ + @JsonProperty("config") + public abstract Optional config(); + + /** Instantiates a builder for CancelTuningJobParameters. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_CancelTuningJobParameters.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for CancelTuningJobParameters. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `CancelTuningJobParameters.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_CancelTuningJobParameters.Builder(); + } + + /** + * Setter for name. + * + *

name: The resource name of the tuning job. + */ + @JsonProperty("name") + public abstract Builder name(String name); + + /** + * Setter for config. + * + *

config: Optional parameters for the request. + */ + @JsonProperty("config") + public abstract Builder config(CancelTuningJobConfig config); + + /** + * Setter for config builder. + * + *

config: Optional parameters for the request. + */ + public Builder config(CancelTuningJobConfig.Builder configBuilder) { + return config(configBuilder.build()); + } + + public abstract CancelTuningJobParameters build(); + } + + /** Deserializes a JSON string to a CancelTuningJobParameters object. */ + @ExcludeFromGeneratedCoverageReport + public static CancelTuningJobParameters fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, CancelTuningJobParameters.class); + } +} diff --git a/src/main/java/com/google/genai/types/Candidate.java b/src/main/java/com/google/genai/types/Candidate.java index 22d7e83006b..950787bfd55 100644 --- a/src/main/java/com/google/genai/types/Candidate.java +++ b/src/main/java/com/google/genai/types/Candidate.java @@ -57,10 +57,6 @@ public abstract class Candidate extends JsonSerializable { @JsonProperty("finishReason") public abstract Optional finishReason(); - /** Metadata related to url context retrieval tool. */ - @JsonProperty("urlContextMetadata") - public abstract Optional urlContextMetadata(); - /** Output only. Average log probability score of the candidate. */ @JsonProperty("avgLogprobs") public abstract Optional avgLogprobs(); @@ -84,7 +80,12 @@ public abstract class Candidate extends JsonSerializable { @JsonProperty("safetyRatings") public abstract Optional> safetyRatings(); + /** Output only. Metadata related to url context retrieval tool. */ + @JsonProperty("urlContextMetadata") + public abstract Optional urlContextMetadata(); + /** Instantiates a builder for Candidate. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_Candidate.Builder(); } @@ -182,23 +183,6 @@ public Builder finishReason(String finishReason) { return finishReason(new FinishReason(finishReason)); } - /** - * Setter for urlContextMetadata. - * - *

urlContextMetadata: Metadata related to url context retrieval tool. - */ - @JsonProperty("urlContextMetadata") - public abstract Builder urlContextMetadata(UrlContextMetadata urlContextMetadata); - - /** - * Setter for urlContextMetadata builder. - * - *

urlContextMetadata: Metadata related to url context retrieval tool. - */ - public Builder urlContextMetadata(UrlContextMetadata.Builder urlContextMetadataBuilder) { - return urlContextMetadata(urlContextMetadataBuilder.build()); - } - /** * Setter for avgLogprobs. * @@ -283,10 +267,28 @@ public Builder safetyRatings(SafetyRating.Builder... safetyRatingsBuilders) { .collect(toImmutableList())); } + /** + * Setter for urlContextMetadata. + * + *

urlContextMetadata: Output only. Metadata related to url context retrieval tool. + */ + @JsonProperty("urlContextMetadata") + public abstract Builder urlContextMetadata(UrlContextMetadata urlContextMetadata); + + /** + * Setter for urlContextMetadata builder. + * + *

urlContextMetadata: Output only. Metadata related to url context retrieval tool. + */ + public Builder urlContextMetadata(UrlContextMetadata.Builder urlContextMetadataBuilder) { + return urlContextMetadata(urlContextMetadataBuilder.build()); + } + public abstract Candidate build(); } /** Deserializes a JSON string to a Candidate object. */ + @ExcludeFromGeneratedCoverageReport public static Candidate fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, Candidate.class); } diff --git a/src/main/java/com/google/genai/types/Checkpoint.java b/src/main/java/com/google/genai/types/Checkpoint.java index 41dd53b0256..9cc5bf87d27 100644 --- a/src/main/java/com/google/genai/types/Checkpoint.java +++ b/src/main/java/com/google/genai/types/Checkpoint.java @@ -42,6 +42,7 @@ public abstract class Checkpoint extends JsonSerializable { public abstract Optional step(); /** Instantiates a builder for Checkpoint. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_Checkpoint.Builder(); } @@ -86,6 +87,7 @@ private static Builder create() { } /** Deserializes a JSON string to a Checkpoint object. */ + @ExcludeFromGeneratedCoverageReport public static Checkpoint fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, Checkpoint.class); } diff --git a/src/main/java/com/google/genai/types/Citation.java b/src/main/java/com/google/genai/types/Citation.java index 63c0fa41c3a..a75cff990aa 100644 --- a/src/main/java/com/google/genai/types/Citation.java +++ b/src/main/java/com/google/genai/types/Citation.java @@ -25,7 +25,7 @@ import com.google.genai.JsonSerializable; import java.util.Optional; -/** Source attributions for content. */ +/** Source attributions for content. This data type is not supported in Gemini API. */ @AutoValue @JsonDeserialize(builder = Citation.Builder.class) public abstract class Citation extends JsonSerializable { @@ -54,6 +54,7 @@ public abstract class Citation extends JsonSerializable { public abstract Optional uri(); /** Instantiates a builder for Citation. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_Citation.Builder(); } @@ -131,6 +132,7 @@ public Builder publicationDate(GoogleTypeDate.Builder publicationDateBuilder) { } /** Deserializes a JSON string to a Citation object. */ + @ExcludeFromGeneratedCoverageReport public static Citation fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, Citation.class); } diff --git a/src/main/java/com/google/genai/types/CitationMetadata.java b/src/main/java/com/google/genai/types/CitationMetadata.java index 701e9e70554..d0ac71aa954 100644 --- a/src/main/java/com/google/genai/types/CitationMetadata.java +++ b/src/main/java/com/google/genai/types/CitationMetadata.java @@ -41,6 +41,7 @@ public abstract class CitationMetadata extends JsonSerializable { public abstract Optional> citations(); /** Instantiates a builder for CitationMetadata. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_CitationMetadata.Builder(); } @@ -93,6 +94,7 @@ public Builder citations(Citation.Builder... citationsBuilders) { } /** Deserializes a JSON string to a CitationMetadata object. */ + @ExcludeFromGeneratedCoverageReport public static CitationMetadata fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, CitationMetadata.class); } diff --git a/src/main/java/com/google/genai/types/ClientOptions.java b/src/main/java/com/google/genai/types/ClientOptions.java index 8157b162225..245d93d9d1a 100644 --- a/src/main/java/com/google/genai/types/ClientOptions.java +++ b/src/main/java/com/google/genai/types/ClientOptions.java @@ -38,6 +38,7 @@ public abstract class ClientOptions extends JsonSerializable { public abstract Optional maxConnectionsPerHost(); /** Instantiates a builder for ClientOptions. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_ClientOptions.Builder(); } @@ -74,6 +75,7 @@ private static Builder create() { } /** Deserializes a JSON string to a ClientOptions object. */ + @ExcludeFromGeneratedCoverageReport public static ClientOptions fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, ClientOptions.class); } diff --git a/src/main/java/com/google/genai/types/CodeExecutionResult.java b/src/main/java/com/google/genai/types/CodeExecutionResult.java index 2907684badd..433267c12e5 100644 --- a/src/main/java/com/google/genai/types/CodeExecutionResult.java +++ b/src/main/java/com/google/genai/types/CodeExecutionResult.java @@ -45,6 +45,7 @@ public abstract class CodeExecutionResult extends JsonSerializable { public abstract Optional output(); /** Instantiates a builder for CodeExecutionResult. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_CodeExecutionResult.Builder(); } @@ -102,6 +103,7 @@ public Builder outcome(String outcome) { } /** Deserializes a JSON string to a CodeExecutionResult object. */ + @ExcludeFromGeneratedCoverageReport public static CodeExecutionResult fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, CodeExecutionResult.class); } diff --git a/src/main/java/com/google/genai/types/ComputeTokensConfig.java b/src/main/java/com/google/genai/types/ComputeTokensConfig.java index 6db60ccd1d9..b27800d6c77 100644 --- a/src/main/java/com/google/genai/types/ComputeTokensConfig.java +++ b/src/main/java/com/google/genai/types/ComputeTokensConfig.java @@ -34,6 +34,7 @@ public abstract class ComputeTokensConfig extends JsonSerializable { public abstract Optional httpOptions(); /** Instantiates a builder for ComputeTokensConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_ComputeTokensConfig.Builder(); } @@ -71,6 +72,7 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { } /** Deserializes a JSON string to a ComputeTokensConfig object. */ + @ExcludeFromGeneratedCoverageReport public static ComputeTokensConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, ComputeTokensConfig.class); } diff --git a/src/main/java/com/google/genai/types/ComputeTokensParameters.java b/src/main/java/com/google/genai/types/ComputeTokensParameters.java index b0c02b9970a..ec789b07dc1 100644 --- a/src/main/java/com/google/genai/types/ComputeTokensParameters.java +++ b/src/main/java/com/google/genai/types/ComputeTokensParameters.java @@ -51,6 +51,7 @@ public abstract class ComputeTokensParameters extends JsonSerializable { public abstract Optional config(); /** Instantiates a builder for ComputeTokensParameters. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_ComputeTokensParameters.Builder(); } @@ -126,6 +127,7 @@ public Builder config(ComputeTokensConfig.Builder configBuilder) { } /** Deserializes a JSON string to a ComputeTokensParameters object. */ + @ExcludeFromGeneratedCoverageReport public static ComputeTokensParameters fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, ComputeTokensParameters.class); } diff --git a/src/main/java/com/google/genai/types/ComputeTokensResponse.java b/src/main/java/com/google/genai/types/ComputeTokensResponse.java index 60caed0e736..15efc470ec9 100644 --- a/src/main/java/com/google/genai/types/ComputeTokensResponse.java +++ b/src/main/java/com/google/genai/types/ComputeTokensResponse.java @@ -33,6 +33,10 @@ @AutoValue @JsonDeserialize(builder = ComputeTokensResponse.Builder.class) public abstract class ComputeTokensResponse extends JsonSerializable { + /** Used to retain the full HTTP response. */ + @JsonProperty("sdkHttpResponse") + public abstract Optional sdkHttpResponse(); + /** * Lists of tokens info from the input. A ComputeTokensRequest could have multiple instances with * a prompt in each instance. We also need to return lists of tokens info for the request with @@ -42,6 +46,7 @@ public abstract class ComputeTokensResponse extends JsonSerializable { public abstract Optional> tokensInfo(); /** Instantiates a builder for ComputeTokensResponse. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_ComputeTokensResponse.Builder(); } @@ -58,6 +63,23 @@ private static Builder create() { return new AutoValue_ComputeTokensResponse.Builder(); } + /** + * Setter for sdkHttpResponse. + * + *

sdkHttpResponse: Used to retain the full HTTP response. + */ + @JsonProperty("sdkHttpResponse") + public abstract Builder sdkHttpResponse(HttpResponse sdkHttpResponse); + + /** + * Setter for sdkHttpResponse builder. + * + *

sdkHttpResponse: Used to retain the full HTTP response. + */ + public Builder sdkHttpResponse(HttpResponse.Builder sdkHttpResponseBuilder) { + return sdkHttpResponse(sdkHttpResponseBuilder.build()); + } + /** * Setter for tokensInfo. * @@ -97,6 +119,7 @@ public Builder tokensInfo(TokensInfo.Builder... tokensInfoBuilders) { } /** Deserializes a JSON string to a ComputeTokensResponse object. */ + @ExcludeFromGeneratedCoverageReport public static ComputeTokensResponse fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, ComputeTokensResponse.class); } diff --git a/src/main/java/com/google/genai/types/ComputeTokensResult.java b/src/main/java/com/google/genai/types/ComputeTokensResult.java new file mode 100644 index 00000000000..90da17b86aa --- /dev/null +++ b/src/main/java/com/google/genai/types/ComputeTokensResult.java @@ -0,0 +1,95 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Auto-generated code. Do not edit. + +package com.google.genai.types; + +import static com.google.common.collect.ImmutableList.toImmutableList; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.google.auto.value.AutoValue; +import com.google.genai.JsonSerializable; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +/** Local tokenizer compute tokens result. */ +@AutoValue +@JsonDeserialize(builder = ComputeTokensResult.Builder.class) +public abstract class ComputeTokensResult extends JsonSerializable { + /** Lists of tokens info from the input. */ + @JsonProperty("tokensInfo") + public abstract Optional> tokensInfo(); + + /** Instantiates a builder for ComputeTokensResult. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_ComputeTokensResult.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for ComputeTokensResult. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `ComputeTokensResult.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_ComputeTokensResult.Builder(); + } + + /** + * Setter for tokensInfo. + * + *

tokensInfo: Lists of tokens info from the input. + */ + @JsonProperty("tokensInfo") + public abstract Builder tokensInfo(List tokensInfo); + + /** + * Setter for tokensInfo. + * + *

tokensInfo: Lists of tokens info from the input. + */ + public Builder tokensInfo(TokensInfo... tokensInfo) { + return tokensInfo(Arrays.asList(tokensInfo)); + } + + /** + * Setter for tokensInfo builder. + * + *

tokensInfo: Lists of tokens info from the input. + */ + public Builder tokensInfo(TokensInfo.Builder... tokensInfoBuilders) { + return tokensInfo( + Arrays.asList(tokensInfoBuilders).stream() + .map(TokensInfo.Builder::build) + .collect(toImmutableList())); + } + + public abstract ComputeTokensResult build(); + } + + /** Deserializes a JSON string to a ComputeTokensResult object. */ + @ExcludeFromGeneratedCoverageReport + public static ComputeTokensResult fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, ComputeTokensResult.class); + } +} diff --git a/src/main/java/com/google/genai/types/ComputerUse.java b/src/main/java/com/google/genai/types/ComputerUse.java new file mode 100644 index 00000000000..13e17fe5f23 --- /dev/null +++ b/src/main/java/com/google/genai/types/ComputerUse.java @@ -0,0 +1,125 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Auto-generated code. Do not edit. + +package com.google.genai.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.google.auto.value.AutoValue; +import com.google.errorprone.annotations.CanIgnoreReturnValue; +import com.google.genai.JsonSerializable; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +/** Tool to support computer use. */ +@AutoValue +@JsonDeserialize(builder = ComputerUse.Builder.class) +public abstract class ComputerUse extends JsonSerializable { + /** Required. The environment being operated. */ + @JsonProperty("environment") + public abstract Optional environment(); + + /** + * By default, predefined functions are included in the final model call. Some of them can be + * explicitly excluded from being automatically included. This can serve two purposes: 1. Using a + * more restricted / different action space. 2. Improving the definitions / instructions of + * predefined functions. + */ + @JsonProperty("excludedPredefinedFunctions") + public abstract Optional> excludedPredefinedFunctions(); + + /** Instantiates a builder for ComputerUse. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_ComputerUse.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for ComputerUse. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `ComputerUse.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_ComputerUse.Builder(); + } + + /** + * Setter for environment. + * + *

environment: Required. The environment being operated. + */ + @JsonProperty("environment") + public abstract Builder environment(Environment environment); + + /** + * Setter for environment given a known enum. + * + *

environment: Required. The environment being operated. + */ + @CanIgnoreReturnValue + public Builder environment(Environment.Known knownType) { + return environment(new Environment(knownType)); + } + + /** + * Setter for environment given a string. + * + *

environment: Required. The environment being operated. + */ + @CanIgnoreReturnValue + public Builder environment(String environment) { + return environment(new Environment(environment)); + } + + /** + * Setter for excludedPredefinedFunctions. + * + *

excludedPredefinedFunctions: By default, predefined functions are included in the final + * model call. Some of them can be explicitly excluded from being automatically included. This + * can serve two purposes: 1. Using a more restricted / different action space. 2. Improving the + * definitions / instructions of predefined functions. + */ + @JsonProperty("excludedPredefinedFunctions") + public abstract Builder excludedPredefinedFunctions(List excludedPredefinedFunctions); + + /** + * Setter for excludedPredefinedFunctions. + * + *

excludedPredefinedFunctions: By default, predefined functions are included in the final + * model call. Some of them can be explicitly excluded from being automatically included. This + * can serve two purposes: 1. Using a more restricted / different action space. 2. Improving the + * definitions / instructions of predefined functions. + */ + public Builder excludedPredefinedFunctions(String... excludedPredefinedFunctions) { + return excludedPredefinedFunctions(Arrays.asList(excludedPredefinedFunctions)); + } + + public abstract ComputerUse build(); + } + + /** Deserializes a JSON string to a ComputerUse object. */ + @ExcludeFromGeneratedCoverageReport + public static ComputerUse fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, ComputerUse.class); + } +} diff --git a/src/main/java/com/google/genai/types/Content.java b/src/main/java/com/google/genai/types/Content.java index 3e6229cb1bf..ec17c1d1286 100644 --- a/src/main/java/com/google/genai/types/Content.java +++ b/src/main/java/com/google/genai/types/Content.java @@ -44,13 +44,13 @@ public abstract class Content extends JsonSerializable { /** * Optional. The producer of the content. Must be either 'user' or 'model'. Useful to set for - * multi-turn conversations, otherwise can be empty. If role is not specified, SDK will determine - * the role. + * multi-turn conversations, otherwise can be left blank or unset. */ @JsonProperty("role") public abstract Optional role(); /** Instantiates a builder for Content. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_Content.Builder(); } @@ -103,8 +103,7 @@ public Builder parts(Part.Builder... partsBuilders) { * Setter for role. * *

role: Optional. The producer of the content. Must be either 'user' or 'model'. Useful to - * set for multi-turn conversations, otherwise can be empty. If role is not specified, SDK will - * determine the role. + * set for multi-turn conversations, otherwise can be left blank or unset. */ @JsonProperty("role") public abstract Builder role(String role); @@ -113,6 +112,7 @@ public Builder parts(Part.Builder... partsBuilders) { } /** Deserializes a JSON string to a Content object. */ + @ExcludeFromGeneratedCoverageReport public static Content fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, Content.class); } diff --git a/src/main/java/com/google/genai/types/ContentEmbedding.java b/src/main/java/com/google/genai/types/ContentEmbedding.java index 9dc43169795..be2bbd049c9 100644 --- a/src/main/java/com/google/genai/types/ContentEmbedding.java +++ b/src/main/java/com/google/genai/types/ContentEmbedding.java @@ -40,6 +40,7 @@ public abstract class ContentEmbedding extends JsonSerializable { public abstract Optional statistics(); /** Instantiates a builder for ContentEmbedding. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_ContentEmbedding.Builder(); } @@ -94,6 +95,7 @@ public Builder statistics(ContentEmbeddingStatistics.Builder statisticsBuilder) } /** Deserializes a JSON string to a ContentEmbedding object. */ + @ExcludeFromGeneratedCoverageReport public static ContentEmbedding fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, ContentEmbedding.class); } diff --git a/src/main/java/com/google/genai/types/ContentEmbeddingStatistics.java b/src/main/java/com/google/genai/types/ContentEmbeddingStatistics.java index 32e37344c02..6440a3eb4dc 100644 --- a/src/main/java/com/google/genai/types/ContentEmbeddingStatistics.java +++ b/src/main/java/com/google/genai/types/ContentEmbeddingStatistics.java @@ -41,6 +41,7 @@ public abstract class ContentEmbeddingStatistics extends JsonSerializable { public abstract Optional tokenCount(); /** Instantiates a builder for ContentEmbeddingStatistics. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_ContentEmbeddingStatistics.Builder(); } @@ -78,6 +79,7 @@ private static Builder create() { } /** Deserializes a JSON string to a ContentEmbeddingStatistics object. */ + @ExcludeFromGeneratedCoverageReport public static ContentEmbeddingStatistics fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, ContentEmbeddingStatistics.class); } diff --git a/src/main/java/com/google/genai/types/ContentReferenceImage.java b/src/main/java/com/google/genai/types/ContentReferenceImage.java new file mode 100644 index 00000000000..a5e7c0538d4 --- /dev/null +++ b/src/main/java/com/google/genai/types/ContentReferenceImage.java @@ -0,0 +1,118 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Auto-generated code. Do not edit. + +package com.google.genai.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.google.auto.value.AutoValue; +import com.google.genai.JsonSerializable; +import java.util.Optional; + +/** + * A content reference image. + * + *

A content reference image represents a subject to reference (ex. person, product, animal) + * provided by the user. It can optionally be provided in addition to a style reference image (ex. + * background, style reference). + */ +@AutoValue +@JsonDeserialize(builder = ContentReferenceImage.Builder.class) +public abstract class ContentReferenceImage extends JsonSerializable implements ReferenceImage { + /** The reference image for the editing operation. */ + @JsonProperty("referenceImage") + public abstract Optional referenceImage(); + + /** The id of the reference image. */ + @JsonProperty("referenceId") + public abstract Optional referenceId(); + + /** The type of the reference image. Only set by the SDK. */ + @JsonProperty("referenceType") + public abstract Optional referenceType(); + + /** Instantiates a builder for ContentReferenceImage. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_ContentReferenceImage.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for ContentReferenceImage. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `ContentReferenceImage.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_ContentReferenceImage.Builder(); + } + + /** + * Setter for referenceImage. + * + *

referenceImage: The reference image for the editing operation. + */ + @JsonProperty("referenceImage") + public abstract Builder referenceImage(Image referenceImage); + + /** + * Setter for referenceImage builder. + * + *

referenceImage: The reference image for the editing operation. + */ + public Builder referenceImage(Image.Builder referenceImageBuilder) { + return referenceImage(referenceImageBuilder.build()); + } + + /** + * Setter for referenceId. + * + *

referenceId: The id of the reference image. + */ + @JsonProperty("referenceId") + public abstract Builder referenceId(Integer referenceId); + + /** + * Setter for referenceType. + * + *

referenceType: The type of the reference image. Only set by the SDK. + */ + @JsonProperty("referenceType") + public abstract Builder referenceType(String referenceType); + + public abstract ContentReferenceImage build(); + } + + /** Deserializes a JSON string to a ContentReferenceImage object. */ + @ExcludeFromGeneratedCoverageReport + public static ContentReferenceImage fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, ContentReferenceImage.class); + } + + @Override + public ReferenceImageAPI toReferenceImageAPI() { + ReferenceImageAPI.Builder referenceImageAPIBuilder = ReferenceImageAPI.builder(); + referenceImage().ifPresent(referenceImageAPIBuilder::referenceImage); + referenceId().ifPresent(referenceImageAPIBuilder::referenceId); + referenceImageAPIBuilder.referenceType("REFERENCE_TYPE_CONTENT"); + return referenceImageAPIBuilder.build(); + } +} diff --git a/src/main/java/com/google/genai/types/ContextWindowCompressionConfig.java b/src/main/java/com/google/genai/types/ContextWindowCompressionConfig.java index 0534b206b5a..594aaf57518 100644 --- a/src/main/java/com/google/genai/types/ContextWindowCompressionConfig.java +++ b/src/main/java/com/google/genai/types/ContextWindowCompressionConfig.java @@ -41,6 +41,7 @@ public abstract class ContextWindowCompressionConfig extends JsonSerializable { public abstract Optional slidingWindow(); /** Instantiates a builder for ContextWindowCompressionConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_ContextWindowCompressionConfig.Builder(); } @@ -89,6 +90,7 @@ public Builder slidingWindow(SlidingWindow.Builder slidingWindowBuilder) { } /** Deserializes a JSON string to a ContextWindowCompressionConfig object. */ + @ExcludeFromGeneratedCoverageReport public static ContextWindowCompressionConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, ContextWindowCompressionConfig.class); } diff --git a/src/main/java/com/google/genai/types/ControlReferenceConfig.java b/src/main/java/com/google/genai/types/ControlReferenceConfig.java index 698999ca7c7..a8a00f545a7 100644 --- a/src/main/java/com/google/genai/types/ControlReferenceConfig.java +++ b/src/main/java/com/google/genai/types/ControlReferenceConfig.java @@ -42,6 +42,7 @@ public abstract class ControlReferenceConfig extends JsonSerializable { public abstract Optional enableControlImageComputation(); /** Instantiates a builder for ControlReferenceConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_ControlReferenceConfig.Builder(); } @@ -100,6 +101,7 @@ public Builder controlType(String controlType) { } /** Deserializes a JSON string to a ControlReferenceConfig object. */ + @ExcludeFromGeneratedCoverageReport public static ControlReferenceConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, ControlReferenceConfig.class); } diff --git a/src/main/java/com/google/genai/types/ControlReferenceImage.java b/src/main/java/com/google/genai/types/ControlReferenceImage.java index 9d3cdb920c9..0471d171bf4 100644 --- a/src/main/java/com/google/genai/types/ControlReferenceImage.java +++ b/src/main/java/com/google/genai/types/ControlReferenceImage.java @@ -55,6 +55,7 @@ public abstract class ControlReferenceImage extends JsonSerializable implements public abstract Optional config(); /** Instantiates a builder for ControlReferenceImage. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_ControlReferenceImage.Builder(); } @@ -125,6 +126,7 @@ public Builder config(ControlReferenceConfig.Builder configBuilder) { } /** Deserializes a JSON string to a ControlReferenceImage object. */ + @ExcludeFromGeneratedCoverageReport public static ControlReferenceImage fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, ControlReferenceImage.class); } diff --git a/src/main/java/com/google/genai/types/ControlReferenceType.java b/src/main/java/com/google/genai/types/ControlReferenceType.java index 6487868075f..ed0c86ebc53 100644 --- a/src/main/java/com/google/genai/types/ControlReferenceType.java +++ b/src/main/java/com/google/genai/types/ControlReferenceType.java @@ -61,12 +61,14 @@ public ControlReferenceType(Known knownValue) { this.value = knownValue.toString(); } + @ExcludeFromGeneratedCoverageReport @Override @JsonValue public String toString() { return this.value; } + @ExcludeFromGeneratedCoverageReport @SuppressWarnings("PatternMatchingInstanceof") @Override public boolean equals(Object o) { @@ -93,6 +95,7 @@ public boolean equals(Object o) { return false; } + @ExcludeFromGeneratedCoverageReport @Override public int hashCode() { if (this.controlReferenceTypeEnum != Known.CONTROL_REFERENCE_TYPE_UNSPECIFIED) { @@ -102,6 +105,7 @@ public int hashCode() { } } + @ExcludeFromGeneratedCoverageReport public Known knownEnum() { return this.controlReferenceTypeEnum; } diff --git a/src/main/java/com/google/genai/types/CountTokensConfig.java b/src/main/java/com/google/genai/types/CountTokensConfig.java index 2d24dce46d9..dab32e0f530 100644 --- a/src/main/java/com/google/genai/types/CountTokensConfig.java +++ b/src/main/java/com/google/genai/types/CountTokensConfig.java @@ -56,6 +56,7 @@ public abstract class CountTokensConfig extends JsonSerializable { public abstract Optional generationConfig(); /** Instantiates a builder for CountTokensConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_CountTokensConfig.Builder(); } @@ -161,6 +162,7 @@ public Builder generationConfig(GenerationConfig.Builder generationConfigBuilder } /** Deserializes a JSON string to a CountTokensConfig object. */ + @ExcludeFromGeneratedCoverageReport public static CountTokensConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, CountTokensConfig.class); } diff --git a/src/main/java/com/google/genai/types/CountTokensParameters.java b/src/main/java/com/google/genai/types/CountTokensParameters.java index 896796e5718..d21e0591958 100644 --- a/src/main/java/com/google/genai/types/CountTokensParameters.java +++ b/src/main/java/com/google/genai/types/CountTokensParameters.java @@ -51,6 +51,7 @@ public abstract class CountTokensParameters extends JsonSerializable { public abstract Optional config(); /** Instantiates a builder for CountTokensParameters. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_CountTokensParameters.Builder(); } @@ -126,6 +127,7 @@ public Builder config(CountTokensConfig.Builder configBuilder) { } /** Deserializes a JSON string to a CountTokensParameters object. */ + @ExcludeFromGeneratedCoverageReport public static CountTokensParameters fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, CountTokensParameters.class); } diff --git a/src/main/java/com/google/genai/types/CountTokensResponse.java b/src/main/java/com/google/genai/types/CountTokensResponse.java index 98c8c228844..8398b00cb09 100644 --- a/src/main/java/com/google/genai/types/CountTokensResponse.java +++ b/src/main/java/com/google/genai/types/CountTokensResponse.java @@ -29,6 +29,10 @@ @AutoValue @JsonDeserialize(builder = CountTokensResponse.Builder.class) public abstract class CountTokensResponse extends JsonSerializable { + /** Used to retain the full HTTP response. */ + @JsonProperty("sdkHttpResponse") + public abstract Optional sdkHttpResponse(); + /** Total number of tokens. */ @JsonProperty("totalTokens") public abstract Optional totalTokens(); @@ -38,6 +42,7 @@ public abstract class CountTokensResponse extends JsonSerializable { public abstract Optional cachedContentTokenCount(); /** Instantiates a builder for CountTokensResponse. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_CountTokensResponse.Builder(); } @@ -54,6 +59,23 @@ private static Builder create() { return new AutoValue_CountTokensResponse.Builder(); } + /** + * Setter for sdkHttpResponse. + * + *

sdkHttpResponse: Used to retain the full HTTP response. + */ + @JsonProperty("sdkHttpResponse") + public abstract Builder sdkHttpResponse(HttpResponse sdkHttpResponse); + + /** + * Setter for sdkHttpResponse builder. + * + *

sdkHttpResponse: Used to retain the full HTTP response. + */ + public Builder sdkHttpResponse(HttpResponse.Builder sdkHttpResponseBuilder) { + return sdkHttpResponse(sdkHttpResponseBuilder.build()); + } + /** * Setter for totalTokens. * @@ -75,6 +97,7 @@ private static Builder create() { } /** Deserializes a JSON string to a CountTokensResponse object. */ + @ExcludeFromGeneratedCoverageReport public static CountTokensResponse fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, CountTokensResponse.class); } diff --git a/src/main/java/com/google/genai/types/AuthToken.java b/src/main/java/com/google/genai/types/CountTokensResult.java similarity index 52% rename from src/main/java/com/google/genai/types/AuthToken.java rename to src/main/java/com/google/genai/types/CountTokensResult.java index 444f1d5e1d9..8666c61884e 100644 --- a/src/main/java/com/google/genai/types/AuthToken.java +++ b/src/main/java/com/google/genai/types/CountTokensResult.java @@ -25,39 +25,46 @@ import com.google.genai.JsonSerializable; import java.util.Optional; -/** Config for auth_tokens.create parameters. */ +/** Local tokenizer count tokens result. */ @AutoValue -@JsonDeserialize(builder = AuthToken.Builder.class) -public abstract class AuthToken extends JsonSerializable { - /** The name of the auth token. */ - @JsonProperty("name") - public abstract Optional name(); +@JsonDeserialize(builder = CountTokensResult.Builder.class) +public abstract class CountTokensResult extends JsonSerializable { + /** The total number of tokens. */ + @JsonProperty("totalTokens") + public abstract Optional totalTokens(); - /** Instantiates a builder for AuthToken. */ + /** Instantiates a builder for CountTokensResult. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { - return new AutoValue_AuthToken.Builder(); + return new AutoValue_CountTokensResult.Builder(); } /** Creates a builder with the same values as this instance. */ public abstract Builder toBuilder(); - /** Builder for AuthToken. */ + /** Builder for CountTokensResult. */ @AutoValue.Builder public abstract static class Builder { - /** For internal usage. Please use `AuthToken.builder()` for instantiation. */ + /** For internal usage. Please use `CountTokensResult.builder()` for instantiation. */ @JsonCreator private static Builder create() { - return new AutoValue_AuthToken.Builder(); + return new AutoValue_CountTokensResult.Builder(); } - @JsonProperty("name") - public abstract Builder name(String name); + /** + * Setter for totalTokens. + * + *

totalTokens: The total number of tokens. + */ + @JsonProperty("totalTokens") + public abstract Builder totalTokens(Integer totalTokens); - public abstract AuthToken build(); + public abstract CountTokensResult build(); } - /** Deserializes a JSON string to a AuthToken object. */ - public static AuthToken fromJson(String jsonString) { - return JsonSerializable.fromJsonString(jsonString, AuthToken.class); + /** Deserializes a JSON string to a CountTokensResult object. */ + @ExcludeFromGeneratedCoverageReport + public static CountTokensResult fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, CountTokensResult.class); } } diff --git a/src/main/java/com/google/genai/types/CreateAuthTokenConfig.java b/src/main/java/com/google/genai/types/CreateAuthTokenConfig.java deleted file mode 100644 index ec3e81c854c..00000000000 --- a/src/main/java/com/google/genai/types/CreateAuthTokenConfig.java +++ /dev/null @@ -1,185 +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 - * - * 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. - */ - -// Auto-generated code. Do not edit. - -package com.google.genai.types; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.google.auto.value.AutoValue; -import com.google.genai.JsonSerializable; -import java.time.Instant; -import java.util.Arrays; -import java.util.List; -import java.util.Optional; - -/** Optional parameters. */ -@AutoValue -@JsonDeserialize(builder = CreateAuthTokenConfig.Builder.class) -public abstract class CreateAuthTokenConfig extends JsonSerializable { - /** Used to override HTTP request options. */ - @JsonProperty("httpOptions") - public abstract Optional httpOptions(); - - /** - * An optional time after which, when using the resulting token, messages in Live API sessions - * will be rejected. (Gemini may preemptively close the session after this time.) - * - *

If not set then this defaults to 30 minutes in the future. If set, this value must be less - * than 20 hours in the future. - */ - @JsonProperty("expireTime") - public abstract Optional expireTime(); - - /** - * The time after which new Live API sessions using the token resulting from this request will be - * rejected. - * - *

If not set this defaults to 60 seconds in the future. If set, this value must be less than - * 20 hours in the future. - */ - @JsonProperty("newSessionExpireTime") - public abstract Optional newSessionExpireTime(); - - /** - * The number of times the token can be used. If this value is zero then no limit is applied. - * Default is 1. Resuming a Live API session does not count as a use. - */ - @JsonProperty("uses") - public abstract Optional uses(); - - /** Configuration specific to Live API connections created using this token. */ - @JsonProperty("liveConnectConstraints") - public abstract Optional liveConnectConstraints(); - - /** Additional fields to lock in the effective LiveConnectParameters. */ - @JsonProperty("lockAdditionalFields") - public abstract Optional> lockAdditionalFields(); - - /** Instantiates a builder for CreateAuthTokenConfig. */ - public static Builder builder() { - return new AutoValue_CreateAuthTokenConfig.Builder(); - } - - /** Creates a builder with the same values as this instance. */ - public abstract Builder toBuilder(); - - /** Builder for CreateAuthTokenConfig. */ - @AutoValue.Builder - public abstract static class Builder { - /** For internal usage. Please use `CreateAuthTokenConfig.builder()` for instantiation. */ - @JsonCreator - private static Builder create() { - return new AutoValue_CreateAuthTokenConfig.Builder(); - } - - /** - * Setter for httpOptions. - * - *

httpOptions: Used to override HTTP request options. - */ - @JsonProperty("httpOptions") - public abstract Builder httpOptions(HttpOptions httpOptions); - - /** - * Setter for httpOptions builder. - * - *

httpOptions: Used to override HTTP request options. - */ - public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { - return httpOptions(httpOptionsBuilder.build()); - } - - /** - * Setter for expireTime. - * - *

expireTime: An optional time after which, when using the resulting token, messages in Live - * API sessions will be rejected. (Gemini may preemptively close the session after this time.) - * - *

If not set then this defaults to 30 minutes in the future. If set, this value must be less - * than 20 hours in the future. - */ - @JsonProperty("expireTime") - public abstract Builder expireTime(Instant expireTime); - - /** - * Setter for newSessionExpireTime. - * - *

newSessionExpireTime: The time after which new Live API sessions using the token resulting - * from this request will be rejected. - * - *

If not set this defaults to 60 seconds in the future. If set, this value must be less than - * 20 hours in the future. - */ - @JsonProperty("newSessionExpireTime") - public abstract Builder newSessionExpireTime(Instant newSessionExpireTime); - - /** - * Setter for uses. - * - *

uses: The number of times the token can be used. If this value is zero then no limit is - * applied. Default is 1. Resuming a Live API session does not count as a use. - */ - @JsonProperty("uses") - public abstract Builder uses(Integer uses); - - /** - * Setter for liveConnectConstraints. - * - *

liveConnectConstraints: Configuration specific to Live API connections created using this - * token. - */ - @JsonProperty("liveConnectConstraints") - public abstract Builder liveConnectConstraints(LiveConnectConstraints liveConnectConstraints); - - /** - * Setter for liveConnectConstraints builder. - * - *

liveConnectConstraints: Configuration specific to Live API connections created using this - * token. - */ - public Builder liveConnectConstraints( - LiveConnectConstraints.Builder liveConnectConstraintsBuilder) { - return liveConnectConstraints(liveConnectConstraintsBuilder.build()); - } - - /** - * Setter for lockAdditionalFields. - * - *

lockAdditionalFields: Additional fields to lock in the effective LiveConnectParameters. - */ - @JsonProperty("lockAdditionalFields") - public abstract Builder lockAdditionalFields(List lockAdditionalFields); - - /** - * Setter for lockAdditionalFields. - * - *

lockAdditionalFields: Additional fields to lock in the effective LiveConnectParameters. - */ - public Builder lockAdditionalFields(String... lockAdditionalFields) { - return lockAdditionalFields(Arrays.asList(lockAdditionalFields)); - } - - public abstract CreateAuthTokenConfig build(); - } - - /** Deserializes a JSON string to a CreateAuthTokenConfig object. */ - public static CreateAuthTokenConfig fromJson(String jsonString) { - return JsonSerializable.fromJsonString(jsonString, CreateAuthTokenConfig.class); - } -} diff --git a/src/main/java/com/google/genai/types/CreateAuthTokenParameters.java b/src/main/java/com/google/genai/types/CreateAuthTokenParameters.java deleted file mode 100644 index e370fc951ff..00000000000 --- a/src/main/java/com/google/genai/types/CreateAuthTokenParameters.java +++ /dev/null @@ -1,65 +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 - * - * 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. - */ - -// Auto-generated code. Do not edit. - -package com.google.genai.types; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.google.api.core.InternalApi; -import com.google.auto.value.AutoValue; -import com.google.genai.JsonSerializable; -import java.util.Optional; - -/** Config for auth_tokens.create parameters. */ -@AutoValue -@InternalApi -@JsonDeserialize(builder = CreateAuthTokenParameters.Builder.class) -public abstract class CreateAuthTokenParameters extends JsonSerializable { - /** Optional parameters for the request. */ - @JsonProperty("config") - public abstract Optional config(); - - /** Instantiates a builder for CreateAuthTokenParameters. */ - public static Builder builder() { - return new AutoValue_CreateAuthTokenParameters.Builder(); - } - - /** Creates a builder with the same values as this instance. */ - public abstract Builder toBuilder(); - - /** Builder for CreateAuthTokenParameters. */ - @AutoValue.Builder - public abstract static class Builder { - /** For internal usage. Please use `CreateAuthTokenParameters.builder()` for instantiation. */ - @JsonCreator - private static Builder create() { - return new AutoValue_CreateAuthTokenParameters.Builder(); - } - - @JsonProperty("config") - public abstract Builder config(CreateAuthTokenConfig config); - - public abstract CreateAuthTokenParameters build(); - } - - /** Deserializes a JSON string to a CreateAuthTokenParameters object. */ - public static CreateAuthTokenParameters fromJson(String jsonString) { - return JsonSerializable.fromJsonString(jsonString, CreateAuthTokenParameters.class); - } -} diff --git a/src/main/java/com/google/genai/types/CreateBatchJobConfig.java b/src/main/java/com/google/genai/types/CreateBatchJobConfig.java index 505ecda5e47..5e8a1fcc141 100644 --- a/src/main/java/com/google/genai/types/CreateBatchJobConfig.java +++ b/src/main/java/com/google/genai/types/CreateBatchJobConfig.java @@ -45,6 +45,7 @@ public abstract class CreateBatchJobConfig extends JsonSerializable { public abstract Optional dest(); /** Instantiates a builder for CreateBatchJobConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_CreateBatchJobConfig.Builder(); } @@ -109,6 +110,7 @@ public Builder dest(BatchJobDestination.Builder destBuilder) { } /** Deserializes a JSON string to a CreateBatchJobConfig object. */ + @ExcludeFromGeneratedCoverageReport public static CreateBatchJobConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, CreateBatchJobConfig.class); } diff --git a/src/main/java/com/google/genai/types/CreateBatchJobParameters.java b/src/main/java/com/google/genai/types/CreateBatchJobParameters.java index e5348a0a460..445213a1715 100644 --- a/src/main/java/com/google/genai/types/CreateBatchJobParameters.java +++ b/src/main/java/com/google/genai/types/CreateBatchJobParameters.java @@ -47,6 +47,7 @@ public abstract class CreateBatchJobParameters extends JsonSerializable { public abstract Optional config(); /** Instantiates a builder for CreateBatchJobParameters. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_CreateBatchJobParameters.Builder(); } @@ -111,6 +112,7 @@ public Builder config(CreateBatchJobConfig.Builder configBuilder) { } /** Deserializes a JSON string to a CreateBatchJobParameters object. */ + @ExcludeFromGeneratedCoverageReport public static CreateBatchJobParameters fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, CreateBatchJobParameters.class); } diff --git a/src/main/java/com/google/genai/types/CreateCachedContentConfig.java b/src/main/java/com/google/genai/types/CreateCachedContentConfig.java index a161571e3b9..d766c78d906 100644 --- a/src/main/java/com/google/genai/types/CreateCachedContentConfig.java +++ b/src/main/java/com/google/genai/types/CreateCachedContentConfig.java @@ -84,6 +84,7 @@ public abstract class CreateCachedContentConfig extends JsonSerializable { public abstract Optional kmsKeyName(); /** Instantiates a builder for CreateCachedContentConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_CreateCachedContentConfig.Builder(); } @@ -252,6 +253,7 @@ public Builder toolConfig(ToolConfig.Builder toolConfigBuilder) { } /** Deserializes a JSON string to a CreateCachedContentConfig object. */ + @ExcludeFromGeneratedCoverageReport public static CreateCachedContentConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, CreateCachedContentConfig.class); } diff --git a/src/main/java/com/google/genai/types/CreateCachedContentParameters.java b/src/main/java/com/google/genai/types/CreateCachedContentParameters.java index afa0b4bc86e..70ae0d868f9 100644 --- a/src/main/java/com/google/genai/types/CreateCachedContentParameters.java +++ b/src/main/java/com/google/genai/types/CreateCachedContentParameters.java @@ -40,6 +40,7 @@ public abstract class CreateCachedContentParameters extends JsonSerializable { public abstract Optional config(); /** Instantiates a builder for CreateCachedContentParameters. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_CreateCachedContentParameters.Builder(); } @@ -87,6 +88,7 @@ public Builder config(CreateCachedContentConfig.Builder configBuilder) { } /** Deserializes a JSON string to a CreateCachedContentParameters object. */ + @ExcludeFromGeneratedCoverageReport public static CreateCachedContentParameters fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, CreateCachedContentParameters.class); } diff --git a/src/main/java/com/google/genai/types/CreateEmbeddingsBatchJobConfig.java b/src/main/java/com/google/genai/types/CreateEmbeddingsBatchJobConfig.java new file mode 100644 index 00000000000..af4f9080dd5 --- /dev/null +++ b/src/main/java/com/google/genai/types/CreateEmbeddingsBatchJobConfig.java @@ -0,0 +1,93 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Auto-generated code. Do not edit. + +package com.google.genai.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.google.auto.value.AutoValue; +import com.google.genai.JsonSerializable; +import java.util.Optional; + +/** Config for optional parameters. */ +@AutoValue +@JsonDeserialize(builder = CreateEmbeddingsBatchJobConfig.Builder.class) +public abstract class CreateEmbeddingsBatchJobConfig extends JsonSerializable { + /** Used to override HTTP request options. */ + @JsonProperty("httpOptions") + public abstract Optional httpOptions(); + + /** The user-defined name of this BatchJob. */ + @JsonProperty("displayName") + public abstract Optional displayName(); + + /** Instantiates a builder for CreateEmbeddingsBatchJobConfig. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_CreateEmbeddingsBatchJobConfig.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for CreateEmbeddingsBatchJobConfig. */ + @AutoValue.Builder + public abstract static class Builder { + /** + * For internal usage. Please use `CreateEmbeddingsBatchJobConfig.builder()` for instantiation. + */ + @JsonCreator + private static Builder create() { + return new AutoValue_CreateEmbeddingsBatchJobConfig.Builder(); + } + + /** + * Setter for httpOptions. + * + *

httpOptions: Used to override HTTP request options. + */ + @JsonProperty("httpOptions") + public abstract Builder httpOptions(HttpOptions httpOptions); + + /** + * Setter for httpOptions builder. + * + *

httpOptions: Used to override HTTP request options. + */ + public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { + return httpOptions(httpOptionsBuilder.build()); + } + + /** + * Setter for displayName. + * + *

displayName: The user-defined name of this BatchJob. + */ + @JsonProperty("displayName") + public abstract Builder displayName(String displayName); + + public abstract CreateEmbeddingsBatchJobConfig build(); + } + + /** Deserializes a JSON string to a CreateEmbeddingsBatchJobConfig object. */ + @ExcludeFromGeneratedCoverageReport + public static CreateEmbeddingsBatchJobConfig fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, CreateEmbeddingsBatchJobConfig.class); + } +} diff --git a/src/main/java/com/google/genai/types/CreateEmbeddingsBatchJobParameters.java b/src/main/java/com/google/genai/types/CreateEmbeddingsBatchJobParameters.java new file mode 100644 index 00000000000..39b033808a0 --- /dev/null +++ b/src/main/java/com/google/genai/types/CreateEmbeddingsBatchJobParameters.java @@ -0,0 +1,117 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Auto-generated code. Do not edit. + +package com.google.genai.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.google.api.core.InternalApi; +import com.google.auto.value.AutoValue; +import com.google.genai.JsonSerializable; +import java.util.Optional; + +/** Config for batches.create parameters. */ +@AutoValue +@InternalApi +@JsonDeserialize(builder = CreateEmbeddingsBatchJobParameters.Builder.class) +public abstract class CreateEmbeddingsBatchJobParameters extends JsonSerializable { + /** The name of the model to produces the predictions via the BatchJob. */ + @JsonProperty("model") + public abstract Optional model(); + + /** input data to run batch job". */ + @JsonProperty("src") + public abstract Optional src(); + + /** Optional parameters for creating a BatchJob. */ + @JsonProperty("config") + public abstract Optional config(); + + /** Instantiates a builder for CreateEmbeddingsBatchJobParameters. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_CreateEmbeddingsBatchJobParameters.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for CreateEmbeddingsBatchJobParameters. */ + @AutoValue.Builder + public abstract static class Builder { + /** + * For internal usage. Please use `CreateEmbeddingsBatchJobParameters.builder()` for + * instantiation. + */ + @JsonCreator + private static Builder create() { + return new AutoValue_CreateEmbeddingsBatchJobParameters.Builder(); + } + + /** + * Setter for model. + * + *

model: The name of the model to produces the predictions via the BatchJob. + */ + @JsonProperty("model") + public abstract Builder model(String model); + + /** + * Setter for src. + * + *

src: input data to run batch job". + */ + @JsonProperty("src") + public abstract Builder src(EmbeddingsBatchJobSource src); + + /** + * Setter for src builder. + * + *

src: input data to run batch job". + */ + public Builder src(EmbeddingsBatchJobSource.Builder srcBuilder) { + return src(srcBuilder.build()); + } + + /** + * Setter for config. + * + *

config: Optional parameters for creating a BatchJob. + */ + @JsonProperty("config") + public abstract Builder config(CreateEmbeddingsBatchJobConfig config); + + /** + * Setter for config builder. + * + *

config: Optional parameters for creating a BatchJob. + */ + public Builder config(CreateEmbeddingsBatchJobConfig.Builder configBuilder) { + return config(configBuilder.build()); + } + + public abstract CreateEmbeddingsBatchJobParameters build(); + } + + /** Deserializes a JSON string to a CreateEmbeddingsBatchJobParameters object. */ + @ExcludeFromGeneratedCoverageReport + public static CreateEmbeddingsBatchJobParameters fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, CreateEmbeddingsBatchJobParameters.class); + } +} diff --git a/src/main/java/com/google/genai/types/CreateFileConfig.java b/src/main/java/com/google/genai/types/CreateFileConfig.java index 0202c9f4a7b..13b998624fb 100644 --- a/src/main/java/com/google/genai/types/CreateFileConfig.java +++ b/src/main/java/com/google/genai/types/CreateFileConfig.java @@ -38,6 +38,7 @@ public abstract class CreateFileConfig extends JsonSerializable { public abstract Optional shouldReturnHttpResponse(); /** Instantiates a builder for CreateFileConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_CreateFileConfig.Builder(); } @@ -84,6 +85,7 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { } /** Deserializes a JSON string to a CreateFileConfig object. */ + @ExcludeFromGeneratedCoverageReport public static CreateFileConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, CreateFileConfig.class); } diff --git a/src/main/java/com/google/genai/types/CreateFileParameters.java b/src/main/java/com/google/genai/types/CreateFileParameters.java index 027f2c05596..4e7c0202097 100644 --- a/src/main/java/com/google/genai/types/CreateFileParameters.java +++ b/src/main/java/com/google/genai/types/CreateFileParameters.java @@ -44,6 +44,7 @@ public abstract class CreateFileParameters extends JsonSerializable { public abstract Optional config(); /** Instantiates a builder for CreateFileParameters. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_CreateFileParameters.Builder(); } @@ -102,6 +103,7 @@ public Builder config(CreateFileConfig.Builder configBuilder) { } /** Deserializes a JSON string to a CreateFileParameters object. */ + @ExcludeFromGeneratedCoverageReport public static CreateFileParameters fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, CreateFileParameters.class); } diff --git a/src/main/java/com/google/genai/types/CreateFileResponse.java b/src/main/java/com/google/genai/types/CreateFileResponse.java index f78b822fcbf..da9305682bd 100644 --- a/src/main/java/com/google/genai/types/CreateFileResponse.java +++ b/src/main/java/com/google/genai/types/CreateFileResponse.java @@ -34,6 +34,7 @@ public abstract class CreateFileResponse extends JsonSerializable { public abstract Optional sdkHttpResponse(); /** Instantiates a builder for CreateFileResponse. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_CreateFileResponse.Builder(); } @@ -71,6 +72,7 @@ public Builder sdkHttpResponse(HttpResponse.Builder sdkHttpResponseBuilder) { } /** Deserializes a JSON string to a CreateFileResponse object. */ + @ExcludeFromGeneratedCoverageReport public static CreateFileResponse fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, CreateFileResponse.class); } diff --git a/src/main/java/com/google/genai/types/CreateTuningJobConfig.java b/src/main/java/com/google/genai/types/CreateTuningJobConfig.java index 151fcfd4a35..a5b20155c39 100644 --- a/src/main/java/com/google/genai/types/CreateTuningJobConfig.java +++ b/src/main/java/com/google/genai/types/CreateTuningJobConfig.java @@ -24,9 +24,10 @@ import com.google.auto.value.AutoValue; import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.genai.JsonSerializable; +import java.util.Map; import java.util.Optional; -/** Supervised fine-tuning job creation request - optional fields. */ +/** Fine-tuning job creation request - optional fields. */ @AutoValue @JsonDeserialize(builder = CreateTuningJobConfig.Builder.class) public abstract class CreateTuningJobConfig extends JsonSerializable { @@ -35,9 +36,13 @@ public abstract class CreateTuningJobConfig extends JsonSerializable { public abstract Optional httpOptions(); /** - * Cloud Storage path to file containing training dataset for tuning. The dataset must be - * formatted as a JSONL file. + * The method to use for tuning (SUPERVISED_FINE_TUNING or PREFERENCE_TUNING). If not set, the + * default method (SFT) will be used. */ + @JsonProperty("method") + public abstract Optional method(); + + /** Validation dataset for tuning. The dataset must be formatted as a JSONL file. */ @JsonProperty("validationDataset") public abstract Optional validationDataset(); @@ -61,12 +66,16 @@ public abstract class CreateTuningJobConfig extends JsonSerializable { public abstract Optional learningRateMultiplier(); /** - * If set to true, disable intermediate checkpoints for SFT and only the last checkpoint will be - * exported. Otherwise, enable intermediate checkpoints for SFT. + * If set to true, disable intermediate checkpoints and only the last checkpoint will be exported. + * Otherwise, enable intermediate checkpoints. */ @JsonProperty("exportLastCheckpointOnly") public abstract Optional exportLastCheckpointOnly(); + /** The optional checkpoint id of the pre-tuned model to use for tuning, if applicable. */ + @JsonProperty("preTunedModelCheckpointId") + public abstract Optional preTunedModelCheckpointId(); + /** Adapter size for tuning. */ @JsonProperty("adapterSize") public abstract Optional adapterSize(); @@ -85,7 +94,22 @@ public abstract class CreateTuningJobConfig extends JsonSerializable { @JsonProperty("learningRate") public abstract Optional learningRate(); + /** + * Optional. The labels with user-defined metadata to organize TuningJob and generated resources + * such as Model and Endpoint. Label keys and values can be no longer than 64 characters (Unicode + * codepoints), can only contain lowercase letters, numeric characters, underscores and dashes. + * International characters are allowed. See https://goo.gl/xmQnxf for more information and + * examples of labels. + */ + @JsonProperty("labels") + public abstract Optional> labels(); + + /** Weight for KL Divergence regularization, Preference Optimization tuning only. */ + @JsonProperty("beta") + public abstract Optional beta(); + /** Instantiates a builder for CreateTuningJobConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_CreateTuningJobConfig.Builder(); } @@ -119,11 +143,42 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { return httpOptions(httpOptionsBuilder.build()); } + /** + * Setter for method. + * + *

method: The method to use for tuning (SUPERVISED_FINE_TUNING or PREFERENCE_TUNING). If not + * set, the default method (SFT) will be used. + */ + @JsonProperty("method") + public abstract Builder method(TuningMethod method); + + /** + * Setter for method given a known enum. + * + *

method: The method to use for tuning (SUPERVISED_FINE_TUNING or PREFERENCE_TUNING). If not + * set, the default method (SFT) will be used. + */ + @CanIgnoreReturnValue + public Builder method(TuningMethod.Known knownType) { + return method(new TuningMethod(knownType)); + } + + /** + * Setter for method given a string. + * + *

method: The method to use for tuning (SUPERVISED_FINE_TUNING or PREFERENCE_TUNING). If not + * set, the default method (SFT) will be used. + */ + @CanIgnoreReturnValue + public Builder method(String method) { + return method(new TuningMethod(method)); + } + /** * Setter for validationDataset. * - *

validationDataset: Cloud Storage path to file containing training dataset for tuning. The - * dataset must be formatted as a JSONL file. + *

validationDataset: Validation dataset for tuning. The dataset must be formatted as a JSONL + * file. */ @JsonProperty("validationDataset") public abstract Builder validationDataset(TuningValidationDataset validationDataset); @@ -131,8 +186,8 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { /** * Setter for validationDataset builder. * - *

validationDataset: Cloud Storage path to file containing training dataset for tuning. The - * dataset must be formatted as a JSONL file. + *

validationDataset: Validation dataset for tuning. The dataset must be formatted as a JSONL + * file. */ public Builder validationDataset(TuningValidationDataset.Builder validationDatasetBuilder) { return validationDataset(validationDatasetBuilder.build()); @@ -175,13 +230,21 @@ public Builder validationDataset(TuningValidationDataset.Builder validationDatas /** * Setter for exportLastCheckpointOnly. * - *

exportLastCheckpointOnly: If set to true, disable intermediate checkpoints for SFT and - * only the last checkpoint will be exported. Otherwise, enable intermediate checkpoints for - * SFT. + *

exportLastCheckpointOnly: If set to true, disable intermediate checkpoints and only the + * last checkpoint will be exported. Otherwise, enable intermediate checkpoints. */ @JsonProperty("exportLastCheckpointOnly") public abstract Builder exportLastCheckpointOnly(boolean exportLastCheckpointOnly); + /** + * Setter for preTunedModelCheckpointId. + * + *

preTunedModelCheckpointId: The optional checkpoint id of the pre-tuned model to use for + * tuning, if applicable. + */ + @JsonProperty("preTunedModelCheckpointId") + public abstract Builder preTunedModelCheckpointId(String preTunedModelCheckpointId); + /** * Setter for adapterSize. * @@ -228,10 +291,31 @@ public Builder adapterSize(String adapterSize) { @JsonProperty("learningRate") public abstract Builder learningRate(Float learningRate); + /** + * Setter for labels. + * + *

labels: Optional. The labels with user-defined metadata to organize TuningJob and + * generated resources such as Model and Endpoint. Label keys and values can be no longer than + * 64 characters (Unicode codepoints), can only contain lowercase letters, numeric characters, + * underscores and dashes. International characters are allowed. See https://goo.gl/xmQnxf for + * more information and examples of labels. + */ + @JsonProperty("labels") + public abstract Builder labels(Map labels); + + /** + * Setter for beta. + * + *

beta: Weight for KL Divergence regularization, Preference Optimization tuning only. + */ + @JsonProperty("beta") + public abstract Builder beta(Float beta); + public abstract CreateTuningJobConfig build(); } /** Deserializes a JSON string to a CreateTuningJobConfig object. */ + @ExcludeFromGeneratedCoverageReport public static CreateTuningJobConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, CreateTuningJobConfig.class); } diff --git a/src/main/java/com/google/genai/types/CreateTuningJobParameters.java b/src/main/java/com/google/genai/types/CreateTuningJobParameters.java index 30683c0ae15..4c95675332e 100644 --- a/src/main/java/com/google/genai/types/CreateTuningJobParameters.java +++ b/src/main/java/com/google/genai/types/CreateTuningJobParameters.java @@ -26,12 +26,12 @@ import com.google.genai.JsonSerializable; import java.util.Optional; -/** Supervised fine-tuning job creation parameters - optional fields. */ +/** Fine-tuning job creation parameters - optional fields. */ @AutoValue @InternalApi @JsonDeserialize(builder = CreateTuningJobParameters.Builder.class) public abstract class CreateTuningJobParameters extends JsonSerializable { - /** The base model that is being tuned, e.g., "gemini-1.0-pro-002". */ + /** The base model that is being tuned, e.g., "gemini-2.5-flash". */ @JsonProperty("baseModel") public abstract Optional baseModel(); @@ -47,6 +47,7 @@ public abstract class CreateTuningJobParameters extends JsonSerializable { public abstract Optional config(); /** Instantiates a builder for CreateTuningJobParameters. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_CreateTuningJobParameters.Builder(); } @@ -66,7 +67,7 @@ private static Builder create() { /** * Setter for baseModel. * - *

baseModel: The base model that is being tuned, e.g., "gemini-1.0-pro-002". + *

baseModel: The base model that is being tuned, e.g., "gemini-2.5-flash". */ @JsonProperty("baseModel") public abstract Builder baseModel(String baseModel); @@ -111,6 +112,7 @@ public Builder config(CreateTuningJobConfig.Builder configBuilder) { } /** Deserializes a JSON string to a CreateTuningJobParameters object. */ + @ExcludeFromGeneratedCoverageReport public static CreateTuningJobParameters fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, CreateTuningJobParameters.class); } diff --git a/src/main/java/com/google/genai/types/CreateTuningJobParametersPrivate.java b/src/main/java/com/google/genai/types/CreateTuningJobParametersPrivate.java new file mode 100644 index 00000000000..5f9786ade45 --- /dev/null +++ b/src/main/java/com/google/genai/types/CreateTuningJobParametersPrivate.java @@ -0,0 +1,143 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Auto-generated code. Do not edit. + +package com.google.genai.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.google.api.core.InternalApi; +import com.google.auto.value.AutoValue; +import com.google.genai.JsonSerializable; +import java.util.Optional; + +/** Fine-tuning job creation parameters - optional fields. */ +@AutoValue +@InternalApi +@JsonDeserialize(builder = CreateTuningJobParametersPrivate.Builder.class) +public abstract class CreateTuningJobParametersPrivate extends JsonSerializable { + /** The base model that is being tuned, e.g., "gemini-2.5-flash". */ + @JsonProperty("baseModel") + public abstract Optional baseModel(); + + /** The PreTunedModel that is being tuned. */ + @JsonProperty("preTunedModel") + public abstract Optional preTunedModel(); + + /** + * Cloud Storage path to file containing training dataset for tuning. The dataset must be + * formatted as a JSONL file. + */ + @JsonProperty("trainingDataset") + public abstract Optional trainingDataset(); + + /** Configuration for the tuning job. */ + @JsonProperty("config") + public abstract Optional config(); + + /** Instantiates a builder for CreateTuningJobParametersPrivate. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_CreateTuningJobParametersPrivate.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for CreateTuningJobParametersPrivate. */ + @AutoValue.Builder + public abstract static class Builder { + /** + * For internal usage. Please use `CreateTuningJobParametersPrivate.builder()` for + * instantiation. + */ + @JsonCreator + private static Builder create() { + return new AutoValue_CreateTuningJobParametersPrivate.Builder(); + } + + /** + * Setter for baseModel. + * + *

baseModel: The base model that is being tuned, e.g., "gemini-2.5-flash". + */ + @JsonProperty("baseModel") + public abstract Builder baseModel(String baseModel); + + /** + * Setter for preTunedModel. + * + *

preTunedModel: The PreTunedModel that is being tuned. + */ + @JsonProperty("preTunedModel") + public abstract Builder preTunedModel(PreTunedModel preTunedModel); + + /** + * Setter for preTunedModel builder. + * + *

preTunedModel: The PreTunedModel that is being tuned. + */ + public Builder preTunedModel(PreTunedModel.Builder preTunedModelBuilder) { + return preTunedModel(preTunedModelBuilder.build()); + } + + /** + * Setter for trainingDataset. + * + *

trainingDataset: Cloud Storage path to file containing training dataset for tuning. The + * dataset must be formatted as a JSONL file. + */ + @JsonProperty("trainingDataset") + public abstract Builder trainingDataset(TuningDataset trainingDataset); + + /** + * Setter for trainingDataset builder. + * + *

trainingDataset: Cloud Storage path to file containing training dataset for tuning. The + * dataset must be formatted as a JSONL file. + */ + public Builder trainingDataset(TuningDataset.Builder trainingDatasetBuilder) { + return trainingDataset(trainingDatasetBuilder.build()); + } + + /** + * Setter for config. + * + *

config: Configuration for the tuning job. + */ + @JsonProperty("config") + public abstract Builder config(CreateTuningJobConfig config); + + /** + * Setter for config builder. + * + *

config: Configuration for the tuning job. + */ + public Builder config(CreateTuningJobConfig.Builder configBuilder) { + return config(configBuilder.build()); + } + + public abstract CreateTuningJobParametersPrivate build(); + } + + /** Deserializes a JSON string to a CreateTuningJobParametersPrivate object. */ + @ExcludeFromGeneratedCoverageReport + public static CreateTuningJobParametersPrivate fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, CreateTuningJobParametersPrivate.class); + } +} diff --git a/src/main/java/com/google/genai/types/DatasetDistribution.java b/src/main/java/com/google/genai/types/DatasetDistribution.java index f70b89330ee..5b86653a1e1 100644 --- a/src/main/java/com/google/genai/types/DatasetDistribution.java +++ b/src/main/java/com/google/genai/types/DatasetDistribution.java @@ -29,7 +29,7 @@ import java.util.List; import java.util.Optional; -/** Distribution computed over a tuning dataset. */ +/** Distribution computed over a tuning dataset. This data type is not supported in Gemini API. */ @AutoValue @JsonDeserialize(builder = DatasetDistribution.Builder.class) public abstract class DatasetDistribution extends JsonSerializable { @@ -66,6 +66,7 @@ public abstract class DatasetDistribution extends JsonSerializable { public abstract Optional sum(); /** Instantiates a builder for DatasetDistribution. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_DatasetDistribution.Builder(); } @@ -171,6 +172,7 @@ public Builder buckets(DatasetDistributionDistributionBucket.Builder... bucketsB } /** Deserializes a JSON string to a DatasetDistribution object. */ + @ExcludeFromGeneratedCoverageReport public static DatasetDistribution fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, DatasetDistribution.class); } diff --git a/src/main/java/com/google/genai/types/DatasetDistributionDistributionBucket.java b/src/main/java/com/google/genai/types/DatasetDistributionDistributionBucket.java index adf61aa69ce..131d52715f6 100644 --- a/src/main/java/com/google/genai/types/DatasetDistributionDistributionBucket.java +++ b/src/main/java/com/google/genai/types/DatasetDistributionDistributionBucket.java @@ -25,7 +25,10 @@ import com.google.genai.JsonSerializable; import java.util.Optional; -/** Dataset bucket used to create a histogram for the distribution given a population of values. */ +/** + * Dataset bucket used to create a histogram for the distribution given a population of values. This + * data type is not supported in Gemini API. + */ @AutoValue @JsonDeserialize(builder = DatasetDistributionDistributionBucket.Builder.class) public abstract class DatasetDistributionDistributionBucket extends JsonSerializable { @@ -42,6 +45,7 @@ public abstract class DatasetDistributionDistributionBucket extends JsonSerializ public abstract Optional right(); /** Instantiates a builder for DatasetDistributionDistributionBucket. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_DatasetDistributionDistributionBucket.Builder(); } @@ -89,6 +93,7 @@ private static Builder create() { } /** Deserializes a JSON string to a DatasetDistributionDistributionBucket object. */ + @ExcludeFromGeneratedCoverageReport public static DatasetDistributionDistributionBucket fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, DatasetDistributionDistributionBucket.class); } diff --git a/src/main/java/com/google/genai/types/DatasetStats.java b/src/main/java/com/google/genai/types/DatasetStats.java index dcc839becb7..f322c97abcf 100644 --- a/src/main/java/com/google/genai/types/DatasetStats.java +++ b/src/main/java/com/google/genai/types/DatasetStats.java @@ -29,7 +29,7 @@ import java.util.List; import java.util.Optional; -/** Statistics computed over a tuning dataset. */ +/** Statistics computed over a tuning dataset. This data type is not supported in Gemini API. */ @AutoValue @JsonDeserialize(builder = DatasetStats.Builder.class) public abstract class DatasetStats extends JsonSerializable { @@ -66,6 +66,7 @@ public abstract class DatasetStats extends JsonSerializable { public abstract Optional userOutputTokenDistribution(); /** Instantiates a builder for DatasetStats. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_DatasetStats.Builder(); } @@ -209,6 +210,7 @@ public Builder userOutputTokenDistribution( } /** Deserializes a JSON string to a DatasetStats object. */ + @ExcludeFromGeneratedCoverageReport public static DatasetStats fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, DatasetStats.class); } diff --git a/src/main/java/com/google/genai/types/DeleteBatchJobConfig.java b/src/main/java/com/google/genai/types/DeleteBatchJobConfig.java index 638197ccef4..3717e3d14c6 100644 --- a/src/main/java/com/google/genai/types/DeleteBatchJobConfig.java +++ b/src/main/java/com/google/genai/types/DeleteBatchJobConfig.java @@ -34,6 +34,7 @@ public abstract class DeleteBatchJobConfig extends JsonSerializable { public abstract Optional httpOptions(); /** Instantiates a builder for DeleteBatchJobConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_DeleteBatchJobConfig.Builder(); } @@ -71,6 +72,7 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { } /** Deserializes a JSON string to a DeleteBatchJobConfig object. */ + @ExcludeFromGeneratedCoverageReport public static DeleteBatchJobConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, DeleteBatchJobConfig.class); } diff --git a/src/main/java/com/google/genai/types/DeleteBatchJobParameters.java b/src/main/java/com/google/genai/types/DeleteBatchJobParameters.java index 27807fea35a..c72c66bc6fd 100644 --- a/src/main/java/com/google/genai/types/DeleteBatchJobParameters.java +++ b/src/main/java/com/google/genai/types/DeleteBatchJobParameters.java @@ -44,6 +44,7 @@ public abstract class DeleteBatchJobParameters extends JsonSerializable { public abstract Optional config(); /** Instantiates a builder for DeleteBatchJobParameters. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_DeleteBatchJobParameters.Builder(); } @@ -91,6 +92,7 @@ public Builder config(DeleteBatchJobConfig.Builder configBuilder) { } /** Deserializes a JSON string to a DeleteBatchJobParameters object. */ + @ExcludeFromGeneratedCoverageReport public static DeleteBatchJobParameters fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, DeleteBatchJobParameters.class); } diff --git a/src/main/java/com/google/genai/types/DeleteCachedContentConfig.java b/src/main/java/com/google/genai/types/DeleteCachedContentConfig.java index b30bd2724b8..9343df3f57b 100644 --- a/src/main/java/com/google/genai/types/DeleteCachedContentConfig.java +++ b/src/main/java/com/google/genai/types/DeleteCachedContentConfig.java @@ -34,6 +34,7 @@ public abstract class DeleteCachedContentConfig extends JsonSerializable { public abstract Optional httpOptions(); /** Instantiates a builder for DeleteCachedContentConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_DeleteCachedContentConfig.Builder(); } @@ -71,6 +72,7 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { } /** Deserializes a JSON string to a DeleteCachedContentConfig object. */ + @ExcludeFromGeneratedCoverageReport public static DeleteCachedContentConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, DeleteCachedContentConfig.class); } diff --git a/src/main/java/com/google/genai/types/DeleteCachedContentParameters.java b/src/main/java/com/google/genai/types/DeleteCachedContentParameters.java index ff4794ece9d..536d1ab11a3 100644 --- a/src/main/java/com/google/genai/types/DeleteCachedContentParameters.java +++ b/src/main/java/com/google/genai/types/DeleteCachedContentParameters.java @@ -40,6 +40,7 @@ public abstract class DeleteCachedContentParameters extends JsonSerializable { public abstract Optional config(); /** Instantiates a builder for DeleteCachedContentParameters. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_DeleteCachedContentParameters.Builder(); } @@ -87,6 +88,7 @@ public Builder config(DeleteCachedContentConfig.Builder configBuilder) { } /** Deserializes a JSON string to a DeleteCachedContentParameters object. */ + @ExcludeFromGeneratedCoverageReport public static DeleteCachedContentParameters fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, DeleteCachedContentParameters.class); } diff --git a/src/main/java/com/google/genai/types/DeleteCachedContentResponse.java b/src/main/java/com/google/genai/types/DeleteCachedContentResponse.java index 339d4b6ef97..339ea6bd49d 100644 --- a/src/main/java/com/google/genai/types/DeleteCachedContentResponse.java +++ b/src/main/java/com/google/genai/types/DeleteCachedContentResponse.java @@ -19,15 +19,22 @@ package com.google.genai.types; import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.google.auto.value.AutoValue; import com.google.genai.JsonSerializable; +import java.util.Optional; /** Empty response for caches.delete method. */ @AutoValue @JsonDeserialize(builder = DeleteCachedContentResponse.Builder.class) public abstract class DeleteCachedContentResponse extends JsonSerializable { + /** Used to retain the full HTTP response. */ + @JsonProperty("sdkHttpResponse") + public abstract Optional sdkHttpResponse(); + /** Instantiates a builder for DeleteCachedContentResponse. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_DeleteCachedContentResponse.Builder(); } @@ -44,10 +51,28 @@ private static Builder create() { return new AutoValue_DeleteCachedContentResponse.Builder(); } + /** + * Setter for sdkHttpResponse. + * + *

sdkHttpResponse: Used to retain the full HTTP response. + */ + @JsonProperty("sdkHttpResponse") + public abstract Builder sdkHttpResponse(HttpResponse sdkHttpResponse); + + /** + * Setter for sdkHttpResponse builder. + * + *

sdkHttpResponse: Used to retain the full HTTP response. + */ + public Builder sdkHttpResponse(HttpResponse.Builder sdkHttpResponseBuilder) { + return sdkHttpResponse(sdkHttpResponseBuilder.build()); + } + public abstract DeleteCachedContentResponse build(); } /** Deserializes a JSON string to a DeleteCachedContentResponse object. */ + @ExcludeFromGeneratedCoverageReport public static DeleteCachedContentResponse fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, DeleteCachedContentResponse.class); } diff --git a/src/main/java/com/google/genai/types/DeleteFileConfig.java b/src/main/java/com/google/genai/types/DeleteFileConfig.java index 530b22e25ab..1059f2b3715 100644 --- a/src/main/java/com/google/genai/types/DeleteFileConfig.java +++ b/src/main/java/com/google/genai/types/DeleteFileConfig.java @@ -34,6 +34,7 @@ public abstract class DeleteFileConfig extends JsonSerializable { public abstract Optional httpOptions(); /** Instantiates a builder for DeleteFileConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_DeleteFileConfig.Builder(); } @@ -71,6 +72,7 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { } /** Deserializes a JSON string to a DeleteFileConfig object. */ + @ExcludeFromGeneratedCoverageReport public static DeleteFileConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, DeleteFileConfig.class); } diff --git a/src/main/java/com/google/genai/types/DeleteFileParameters.java b/src/main/java/com/google/genai/types/DeleteFileParameters.java index a4a18770a39..cb4d5ed6707 100644 --- a/src/main/java/com/google/genai/types/DeleteFileParameters.java +++ b/src/main/java/com/google/genai/types/DeleteFileParameters.java @@ -40,6 +40,7 @@ public abstract class DeleteFileParameters extends JsonSerializable { public abstract Optional config(); /** Instantiates a builder for DeleteFileParameters. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_DeleteFileParameters.Builder(); } @@ -85,6 +86,7 @@ public Builder config(DeleteFileConfig.Builder configBuilder) { } /** Deserializes a JSON string to a DeleteFileParameters object. */ + @ExcludeFromGeneratedCoverageReport public static DeleteFileParameters fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, DeleteFileParameters.class); } diff --git a/src/main/java/com/google/genai/types/DeleteFileResponse.java b/src/main/java/com/google/genai/types/DeleteFileResponse.java index c1b34814310..72b5ab8bb68 100644 --- a/src/main/java/com/google/genai/types/DeleteFileResponse.java +++ b/src/main/java/com/google/genai/types/DeleteFileResponse.java @@ -19,15 +19,22 @@ package com.google.genai.types; import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.google.auto.value.AutoValue; import com.google.genai.JsonSerializable; +import java.util.Optional; /** Response for the delete file method. */ @AutoValue @JsonDeserialize(builder = DeleteFileResponse.Builder.class) public abstract class DeleteFileResponse extends JsonSerializable { + /** Used to retain the full HTTP response. */ + @JsonProperty("sdkHttpResponse") + public abstract Optional sdkHttpResponse(); + /** Instantiates a builder for DeleteFileResponse. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_DeleteFileResponse.Builder(); } @@ -44,10 +51,28 @@ private static Builder create() { return new AutoValue_DeleteFileResponse.Builder(); } + /** + * Setter for sdkHttpResponse. + * + *

sdkHttpResponse: Used to retain the full HTTP response. + */ + @JsonProperty("sdkHttpResponse") + public abstract Builder sdkHttpResponse(HttpResponse sdkHttpResponse); + + /** + * Setter for sdkHttpResponse builder. + * + *

sdkHttpResponse: Used to retain the full HTTP response. + */ + public Builder sdkHttpResponse(HttpResponse.Builder sdkHttpResponseBuilder) { + return sdkHttpResponse(sdkHttpResponseBuilder.build()); + } + public abstract DeleteFileResponse build(); } /** Deserializes a JSON string to a DeleteFileResponse object. */ + @ExcludeFromGeneratedCoverageReport public static DeleteFileResponse fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, DeleteFileResponse.class); } diff --git a/src/main/java/com/google/genai/types/DeleteModelConfig.java b/src/main/java/com/google/genai/types/DeleteModelConfig.java index cc1b8543833..04f9528dde1 100644 --- a/src/main/java/com/google/genai/types/DeleteModelConfig.java +++ b/src/main/java/com/google/genai/types/DeleteModelConfig.java @@ -34,6 +34,7 @@ public abstract class DeleteModelConfig extends JsonSerializable { public abstract Optional httpOptions(); /** Instantiates a builder for DeleteModelConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_DeleteModelConfig.Builder(); } @@ -71,6 +72,7 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { } /** Deserializes a JSON string to a DeleteModelConfig object. */ + @ExcludeFromGeneratedCoverageReport public static DeleteModelConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, DeleteModelConfig.class); } diff --git a/src/main/java/com/google/genai/types/DeleteModelParameters.java b/src/main/java/com/google/genai/types/DeleteModelParameters.java index 383e43ea7f5..8e5d9a7e143 100644 --- a/src/main/java/com/google/genai/types/DeleteModelParameters.java +++ b/src/main/java/com/google/genai/types/DeleteModelParameters.java @@ -40,6 +40,7 @@ public abstract class DeleteModelParameters extends JsonSerializable { public abstract Optional config(); /** Instantiates a builder for DeleteModelParameters. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_DeleteModelParameters.Builder(); } @@ -85,6 +86,7 @@ public Builder config(DeleteModelConfig.Builder configBuilder) { } /** Deserializes a JSON string to a DeleteModelParameters object. */ + @ExcludeFromGeneratedCoverageReport public static DeleteModelParameters fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, DeleteModelParameters.class); } diff --git a/src/main/java/com/google/genai/types/DeleteModelResponse.java b/src/main/java/com/google/genai/types/DeleteModelResponse.java index 5a7d3c90794..e780e9b4202 100644 --- a/src/main/java/com/google/genai/types/DeleteModelResponse.java +++ b/src/main/java/com/google/genai/types/DeleteModelResponse.java @@ -19,15 +19,22 @@ package com.google.genai.types; import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.google.auto.value.AutoValue; import com.google.genai.JsonSerializable; +import java.util.Optional; /** None */ @AutoValue @JsonDeserialize(builder = DeleteModelResponse.Builder.class) public abstract class DeleteModelResponse extends JsonSerializable { + /** Used to retain the full HTTP response. */ + @JsonProperty("sdkHttpResponse") + public abstract Optional sdkHttpResponse(); + /** Instantiates a builder for DeleteModelResponse. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_DeleteModelResponse.Builder(); } @@ -44,10 +51,28 @@ private static Builder create() { return new AutoValue_DeleteModelResponse.Builder(); } + /** + * Setter for sdkHttpResponse. + * + *

sdkHttpResponse: Used to retain the full HTTP response. + */ + @JsonProperty("sdkHttpResponse") + public abstract Builder sdkHttpResponse(HttpResponse sdkHttpResponse); + + /** + * Setter for sdkHttpResponse builder. + * + *

sdkHttpResponse: Used to retain the full HTTP response. + */ + public Builder sdkHttpResponse(HttpResponse.Builder sdkHttpResponseBuilder) { + return sdkHttpResponse(sdkHttpResponseBuilder.build()); + } + public abstract DeleteModelResponse build(); } /** Deserializes a JSON string to a DeleteModelResponse object. */ + @ExcludeFromGeneratedCoverageReport public static DeleteModelResponse fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, DeleteModelResponse.class); } diff --git a/src/main/java/com/google/genai/types/DeleteResourceJob.java b/src/main/java/com/google/genai/types/DeleteResourceJob.java index e3bc5e40fc9..150360ef43a 100644 --- a/src/main/java/com/google/genai/types/DeleteResourceJob.java +++ b/src/main/java/com/google/genai/types/DeleteResourceJob.java @@ -29,6 +29,10 @@ @AutoValue @JsonDeserialize(builder = DeleteResourceJob.Builder.class) public abstract class DeleteResourceJob extends JsonSerializable { + /** Used to retain the full HTTP response. */ + @JsonProperty("sdkHttpResponse") + public abstract Optional sdkHttpResponse(); + /** */ @JsonProperty("name") public abstract Optional name(); @@ -42,6 +46,7 @@ public abstract class DeleteResourceJob extends JsonSerializable { public abstract Optional error(); /** Instantiates a builder for DeleteResourceJob. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_DeleteResourceJob.Builder(); } @@ -58,6 +63,23 @@ private static Builder create() { return new AutoValue_DeleteResourceJob.Builder(); } + /** + * Setter for sdkHttpResponse. + * + *

sdkHttpResponse: Used to retain the full HTTP response. + */ + @JsonProperty("sdkHttpResponse") + public abstract Builder sdkHttpResponse(HttpResponse sdkHttpResponse); + + /** + * Setter for sdkHttpResponse builder. + * + *

sdkHttpResponse: Used to retain the full HTTP response. + */ + public Builder sdkHttpResponse(HttpResponse.Builder sdkHttpResponseBuilder) { + return sdkHttpResponse(sdkHttpResponseBuilder.build()); + } + /** * Setter for name. * @@ -95,6 +117,7 @@ public Builder error(JobError.Builder errorBuilder) { } /** Deserializes a JSON string to a DeleteResourceJob object. */ + @ExcludeFromGeneratedCoverageReport public static DeleteResourceJob fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, DeleteResourceJob.class); } diff --git a/src/main/java/com/google/genai/types/DistillationDataStats.java b/src/main/java/com/google/genai/types/DistillationDataStats.java index 68c608529f5..686475831cd 100644 --- a/src/main/java/com/google/genai/types/DistillationDataStats.java +++ b/src/main/java/com/google/genai/types/DistillationDataStats.java @@ -25,7 +25,10 @@ import com.google.genai.JsonSerializable; import java.util.Optional; -/** Statistics computed for datasets used for distillation. */ +/** + * Statistics computed for datasets used for distillation. This data type is not supported in Gemini + * API. + */ @AutoValue @JsonDeserialize(builder = DistillationDataStats.Builder.class) public abstract class DistillationDataStats extends JsonSerializable { @@ -34,6 +37,7 @@ public abstract class DistillationDataStats extends JsonSerializable { public abstract Optional trainingDatasetStats(); /** Instantiates a builder for DistillationDataStats. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_DistillationDataStats.Builder(); } @@ -71,6 +75,7 @@ public Builder trainingDatasetStats(DatasetStats.Builder trainingDatasetStatsBui } /** Deserializes a JSON string to a DistillationDataStats object. */ + @ExcludeFromGeneratedCoverageReport public static DistillationDataStats fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, DistillationDataStats.class); } diff --git a/src/main/java/com/google/genai/types/DistillationSpec.java b/src/main/java/com/google/genai/types/DistillationSpec.java deleted file mode 100644 index 638b6450620..00000000000 --- a/src/main/java/com/google/genai/types/DistillationSpec.java +++ /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 - * - * 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. - */ - -// Auto-generated code. Do not edit. - -package com.google.genai.types; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.google.auto.value.AutoValue; -import com.google.genai.JsonSerializable; -import java.util.Optional; - -/** Tuning Spec for Distillation. */ -@AutoValue -@JsonDeserialize(builder = DistillationSpec.Builder.class) -public abstract class DistillationSpec extends JsonSerializable { - /** - * The base teacher model that is being distilled. See [Supported - * models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/tuning#supported_models). - */ - @JsonProperty("baseTeacherModel") - public abstract Optional baseTeacherModel(); - - /** Optional. Hyperparameters for Distillation. */ - @JsonProperty("hyperParameters") - public abstract Optional hyperParameters(); - - /** - * Deprecated. A path in a Cloud Storage bucket, which will be treated as the root output - * directory of the distillation pipeline. It is used by the system to generate the paths of - * output artifacts. - */ - @JsonProperty("pipelineRootDirectory") - public abstract Optional pipelineRootDirectory(); - - /** - * The student model that is being tuned, e.g., "google/gemma-2b-1.1-it". Deprecated. Use - * base_model instead. - */ - @JsonProperty("studentModel") - public abstract Optional studentModel(); - - /** - * Deprecated. Cloud Storage path to file containing training dataset for tuning. The dataset must - * be formatted as a JSONL file. - */ - @JsonProperty("trainingDatasetUri") - public abstract Optional trainingDatasetUri(); - - /** - * The resource name of the Tuned teacher model. Format: - * `projects/{project}/locations/{location}/models/{model}`. - */ - @JsonProperty("tunedTeacherModelSource") - public abstract Optional tunedTeacherModelSource(); - - /** - * Optional. Cloud Storage path to file containing validation dataset for tuning. The dataset must - * be formatted as a JSONL file. - */ - @JsonProperty("validationDatasetUri") - public abstract Optional validationDatasetUri(); - - /** Instantiates a builder for DistillationSpec. */ - public static Builder builder() { - return new AutoValue_DistillationSpec.Builder(); - } - - /** Creates a builder with the same values as this instance. */ - public abstract Builder toBuilder(); - - /** Builder for DistillationSpec. */ - @AutoValue.Builder - public abstract static class Builder { - /** For internal usage. Please use `DistillationSpec.builder()` for instantiation. */ - @JsonCreator - private static Builder create() { - return new AutoValue_DistillationSpec.Builder(); - } - - /** - * Setter for baseTeacherModel. - * - *

baseTeacherModel: The base teacher model that is being distilled. See [Supported - * models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/tuning#supported_models). - */ - @JsonProperty("baseTeacherModel") - public abstract Builder baseTeacherModel(String baseTeacherModel); - - /** - * Setter for hyperParameters. - * - *

hyperParameters: Optional. Hyperparameters for Distillation. - */ - @JsonProperty("hyperParameters") - public abstract Builder hyperParameters(DistillationHyperParameters hyperParameters); - - /** - * Setter for hyperParameters builder. - * - *

hyperParameters: Optional. Hyperparameters for Distillation. - */ - public Builder hyperParameters(DistillationHyperParameters.Builder hyperParametersBuilder) { - return hyperParameters(hyperParametersBuilder.build()); - } - - /** - * Setter for pipelineRootDirectory. - * - *

pipelineRootDirectory: Deprecated. A path in a Cloud Storage bucket, which will be treated - * as the root output directory of the distillation pipeline. It is used by the system to - * generate the paths of output artifacts. - */ - @JsonProperty("pipelineRootDirectory") - public abstract Builder pipelineRootDirectory(String pipelineRootDirectory); - - /** - * Setter for studentModel. - * - *

studentModel: The student model that is being tuned, e.g., "google/gemma-2b-1.1-it". - * Deprecated. Use base_model instead. - */ - @JsonProperty("studentModel") - public abstract Builder studentModel(String studentModel); - - /** - * Setter for trainingDatasetUri. - * - *

trainingDatasetUri: Deprecated. Cloud Storage path to file containing training dataset for - * tuning. The dataset must be formatted as a JSONL file. - */ - @JsonProperty("trainingDatasetUri") - public abstract Builder trainingDatasetUri(String trainingDatasetUri); - - /** - * Setter for tunedTeacherModelSource. - * - *

tunedTeacherModelSource: The resource name of the Tuned teacher model. Format: - * `projects/{project}/locations/{location}/models/{model}`. - */ - @JsonProperty("tunedTeacherModelSource") - public abstract Builder tunedTeacherModelSource(String tunedTeacherModelSource); - - /** - * Setter for validationDatasetUri. - * - *

validationDatasetUri: Optional. Cloud Storage path to file containing validation dataset - * for tuning. The dataset must be formatted as a JSONL file. - */ - @JsonProperty("validationDatasetUri") - public abstract Builder validationDatasetUri(String validationDatasetUri); - - public abstract DistillationSpec build(); - } - - /** Deserializes a JSON string to a DistillationSpec object. */ - public static DistillationSpec fromJson(String jsonString) { - return JsonSerializable.fromJsonString(jsonString, DistillationSpec.class); - } -} diff --git a/src/main/java/com/google/genai/types/DownloadFileConfig.java b/src/main/java/com/google/genai/types/DownloadFileConfig.java index ec8e6aa6ccd..2a23c62a0e1 100644 --- a/src/main/java/com/google/genai/types/DownloadFileConfig.java +++ b/src/main/java/com/google/genai/types/DownloadFileConfig.java @@ -34,6 +34,7 @@ public abstract class DownloadFileConfig extends JsonSerializable { public abstract Optional httpOptions(); /** Instantiates a builder for DownloadFileConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_DownloadFileConfig.Builder(); } @@ -71,6 +72,7 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { } /** Deserializes a JSON string to a DownloadFileConfig object. */ + @ExcludeFromGeneratedCoverageReport public static DownloadFileConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, DownloadFileConfig.class); } diff --git a/src/main/java/com/google/genai/types/DynamicRetrievalConfig.java b/src/main/java/com/google/genai/types/DynamicRetrievalConfig.java index efc4f87949d..97089b82cce 100644 --- a/src/main/java/com/google/genai/types/DynamicRetrievalConfig.java +++ b/src/main/java/com/google/genai/types/DynamicRetrievalConfig.java @@ -42,6 +42,7 @@ public abstract class DynamicRetrievalConfig extends JsonSerializable { public abstract Optional dynamicThreshold(); /** Instantiates a builder for DynamicRetrievalConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_DynamicRetrievalConfig.Builder(); } @@ -99,6 +100,7 @@ public Builder mode(String mode) { } /** Deserializes a JSON string to a DynamicRetrievalConfig object. */ + @ExcludeFromGeneratedCoverageReport public static DynamicRetrievalConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, DynamicRetrievalConfig.class); } diff --git a/src/main/java/com/google/genai/types/DynamicRetrievalConfigMode.java b/src/main/java/com/google/genai/types/DynamicRetrievalConfigMode.java index 0af252eea2f..515b5ff89af 100644 --- a/src/main/java/com/google/genai/types/DynamicRetrievalConfigMode.java +++ b/src/main/java/com/google/genai/types/DynamicRetrievalConfigMode.java @@ -59,12 +59,14 @@ public DynamicRetrievalConfigMode(Known knownValue) { this.value = knownValue.toString(); } + @ExcludeFromGeneratedCoverageReport @Override @JsonValue public String toString() { return this.value; } + @ExcludeFromGeneratedCoverageReport @SuppressWarnings("PatternMatchingInstanceof") @Override public boolean equals(Object o) { @@ -94,6 +96,7 @@ public boolean equals(Object o) { return false; } + @ExcludeFromGeneratedCoverageReport @Override public int hashCode() { if (this.dynamicRetrievalConfigModeEnum != Known.DYNAMIC_RETRIEVAL_CONFIG_MODE_UNSPECIFIED) { @@ -103,6 +106,7 @@ public int hashCode() { } } + @ExcludeFromGeneratedCoverageReport public Known knownEnum() { return this.dynamicRetrievalConfigModeEnum; } diff --git a/src/main/java/com/google/genai/types/EditImageConfig.java b/src/main/java/com/google/genai/types/EditImageConfig.java index 0f0c7f6e539..a5a0e36c1cb 100644 --- a/src/main/java/com/google/genai/types/EditImageConfig.java +++ b/src/main/java/com/google/genai/types/EditImageConfig.java @@ -24,6 +24,7 @@ import com.google.auto.value.AutoValue; import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.genai.JsonSerializable; +import java.util.Map; import java.util.Optional; /** Configuration for editing an image. */ @@ -104,6 +105,10 @@ public abstract class EditImageConfig extends JsonSerializable { @JsonProperty("addWatermark") public abstract Optional addWatermark(); + /** User specified labels to track billing usage. */ + @JsonProperty("labels") + public abstract Optional> labels(); + /** Describes the editing mode for the request. */ @JsonProperty("editMode") public abstract Optional editMode(); @@ -116,6 +121,7 @@ public abstract class EditImageConfig extends JsonSerializable { public abstract Optional baseSteps(); /** Instantiates a builder for EditImageConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_EditImageConfig.Builder(); } @@ -327,6 +333,14 @@ public Builder language(String language) { @JsonProperty("addWatermark") public abstract Builder addWatermark(boolean addWatermark); + /** + * Setter for labels. + * + *

labels: User specified labels to track billing usage. + */ + @JsonProperty("labels") + public abstract Builder labels(Map labels); + /** * Setter for editMode. * @@ -368,6 +382,7 @@ public Builder editMode(String editMode) { } /** Deserializes a JSON string to a EditImageConfig object. */ + @ExcludeFromGeneratedCoverageReport public static EditImageConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, EditImageConfig.class); } diff --git a/src/main/java/com/google/genai/types/EditImageParameters.java b/src/main/java/com/google/genai/types/EditImageParameters.java index df0568abec0..c5e580b4074 100644 --- a/src/main/java/com/google/genai/types/EditImageParameters.java +++ b/src/main/java/com/google/genai/types/EditImageParameters.java @@ -41,7 +41,7 @@ public abstract class EditImageParameters extends JsonSerializable { @JsonProperty("prompt") public abstract Optional prompt(); - /** The reference images for Imagen 3 editing. */ + /** The reference images for editing. */ @JsonProperty("referenceImages") public abstract Optional> referenceImages(); @@ -50,6 +50,7 @@ public abstract class EditImageParameters extends JsonSerializable { public abstract Optional config(); /** Instantiates a builder for EditImageParameters. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_EditImageParameters.Builder(); } @@ -85,7 +86,7 @@ private static Builder create() { /** * Setter for referenceImages. * - *

referenceImages: The reference images for Imagen 3 editing. + *

referenceImages: The reference images for editing. */ @JsonProperty("referenceImages") public abstract Builder referenceImages(List referenceImages); @@ -93,7 +94,7 @@ private static Builder create() { /** * Setter for referenceImages. * - *

referenceImages: The reference images for Imagen 3 editing. + *

referenceImages: The reference images for editing. */ public Builder referenceImages(ReferenceImageAPI... referenceImages) { return referenceImages(Arrays.asList(referenceImages)); @@ -120,6 +121,7 @@ public Builder config(EditImageConfig.Builder configBuilder) { } /** Deserializes a JSON string to a EditImageParameters object. */ + @ExcludeFromGeneratedCoverageReport public static EditImageParameters fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, EditImageParameters.class); } diff --git a/src/main/java/com/google/genai/types/EditImageResponse.java b/src/main/java/com/google/genai/types/EditImageResponse.java index 7aee310938b..ccfdf61148c 100644 --- a/src/main/java/com/google/genai/types/EditImageResponse.java +++ b/src/main/java/com/google/genai/types/EditImageResponse.java @@ -33,11 +33,16 @@ @AutoValue @JsonDeserialize(builder = EditImageResponse.Builder.class) public abstract class EditImageResponse extends JsonSerializable { + /** Used to retain the full HTTP response. */ + @JsonProperty("sdkHttpResponse") + public abstract Optional sdkHttpResponse(); + /** Generated images. */ @JsonProperty("generatedImages") public abstract Optional> generatedImages(); /** Instantiates a builder for EditImageResponse. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_EditImageResponse.Builder(); } @@ -54,6 +59,23 @@ private static Builder create() { return new AutoValue_EditImageResponse.Builder(); } + /** + * Setter for sdkHttpResponse. + * + *

sdkHttpResponse: Used to retain the full HTTP response. + */ + @JsonProperty("sdkHttpResponse") + public abstract Builder sdkHttpResponse(HttpResponse sdkHttpResponse); + + /** + * Setter for sdkHttpResponse builder. + * + *

sdkHttpResponse: Used to retain the full HTTP response. + */ + public Builder sdkHttpResponse(HttpResponse.Builder sdkHttpResponseBuilder) { + return sdkHttpResponse(sdkHttpResponseBuilder.build()); + } + /** * Setter for generatedImages. * @@ -87,6 +109,7 @@ public Builder generatedImages(GeneratedImage.Builder... generatedImagesBuilders } /** Deserializes a JSON string to a EditImageResponse object. */ + @ExcludeFromGeneratedCoverageReport public static EditImageResponse fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, EditImageResponse.class); } diff --git a/src/main/java/com/google/genai/types/EditMode.java b/src/main/java/com/google/genai/types/EditMode.java index 1e7d6fb70f7..9d1de02603c 100644 --- a/src/main/java/com/google/genai/types/EditMode.java +++ b/src/main/java/com/google/genai/types/EditMode.java @@ -23,7 +23,7 @@ import com.google.common.base.Ascii; import java.util.Objects; -/** Enum representing the Imagen 3 Edit mode. */ +/** Enum representing the editing mode. */ public class EditMode { /** Enum representing the known values for EditMode. */ @@ -69,12 +69,14 @@ public EditMode(Known knownValue) { this.value = knownValue.toString(); } + @ExcludeFromGeneratedCoverageReport @Override @JsonValue public String toString() { return this.value; } + @ExcludeFromGeneratedCoverageReport @SuppressWarnings("PatternMatchingInstanceof") @Override public boolean equals(Object o) { @@ -101,6 +103,7 @@ public boolean equals(Object o) { return false; } + @ExcludeFromGeneratedCoverageReport @Override public int hashCode() { if (this.editModeEnum != Known.EDIT_MODE_UNSPECIFIED) { @@ -110,6 +113,7 @@ public int hashCode() { } } + @ExcludeFromGeneratedCoverageReport public Known knownEnum() { return this.editModeEnum; } diff --git a/src/main/java/com/google/genai/types/EmbedContentBatch.java b/src/main/java/com/google/genai/types/EmbedContentBatch.java new file mode 100644 index 00000000000..c6fab636605 --- /dev/null +++ b/src/main/java/com/google/genai/types/EmbedContentBatch.java @@ -0,0 +1,116 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Auto-generated code. Do not edit. + +package com.google.genai.types; + +import static com.google.common.collect.ImmutableList.toImmutableList; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.google.auto.value.AutoValue; +import com.google.genai.JsonSerializable; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +/** Parameters for the embed_content method. */ +@AutoValue +@JsonDeserialize(builder = EmbedContentBatch.Builder.class) +public abstract class EmbedContentBatch extends JsonSerializable { + /** The content to embed. Only the `parts.text` fields will be counted. */ + @JsonProperty("contents") + public abstract Optional> contents(); + + /** Configuration that contains optional parameters. */ + @JsonProperty("config") + public abstract Optional config(); + + /** Instantiates a builder for EmbedContentBatch. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_EmbedContentBatch.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for EmbedContentBatch. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `EmbedContentBatch.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_EmbedContentBatch.Builder(); + } + + /** + * Setter for contents. + * + *

contents: The content to embed. Only the `parts.text` fields will be counted. + */ + @JsonProperty("contents") + public abstract Builder contents(List contents); + + /** + * Setter for contents. + * + *

contents: The content to embed. Only the `parts.text` fields will be counted. + */ + public Builder contents(Content... contents) { + return contents(Arrays.asList(contents)); + } + + /** + * Setter for contents builder. + * + *

contents: The content to embed. Only the `parts.text` fields will be counted. + */ + public Builder contents(Content.Builder... contentsBuilders) { + return contents( + Arrays.asList(contentsBuilders).stream() + .map(Content.Builder::build) + .collect(toImmutableList())); + } + + /** + * Setter for config. + * + *

config: Configuration that contains optional parameters. + */ + @JsonProperty("config") + public abstract Builder config(EmbedContentConfig config); + + /** + * Setter for config builder. + * + *

config: Configuration that contains optional parameters. + */ + public Builder config(EmbedContentConfig.Builder configBuilder) { + return config(configBuilder.build()); + } + + public abstract EmbedContentBatch build(); + } + + /** Deserializes a JSON string to a EmbedContentBatch object. */ + @ExcludeFromGeneratedCoverageReport + public static EmbedContentBatch fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, EmbedContentBatch.class); + } +} diff --git a/src/main/java/com/google/genai/types/EmbedContentConfig.java b/src/main/java/com/google/genai/types/EmbedContentConfig.java index ccef31e056f..88bc9c824c6 100644 --- a/src/main/java/com/google/genai/types/EmbedContentConfig.java +++ b/src/main/java/com/google/genai/types/EmbedContentConfig.java @@ -62,6 +62,7 @@ public abstract class EmbedContentConfig extends JsonSerializable { public abstract Optional autoTruncate(); /** Instantiates a builder for EmbedContentConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_EmbedContentConfig.Builder(); } @@ -143,6 +144,7 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { } /** Deserializes a JSON string to a EmbedContentConfig object. */ + @ExcludeFromGeneratedCoverageReport public static EmbedContentConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, EmbedContentConfig.class); } diff --git a/src/main/java/com/google/genai/types/EmbedContentMetadata.java b/src/main/java/com/google/genai/types/EmbedContentMetadata.java index 816bb9d11c4..baadebbdb88 100644 --- a/src/main/java/com/google/genai/types/EmbedContentMetadata.java +++ b/src/main/java/com/google/genai/types/EmbedContentMetadata.java @@ -34,6 +34,7 @@ public abstract class EmbedContentMetadata extends JsonSerializable { public abstract Optional billableCharacterCount(); /** Instantiates a builder for EmbedContentMetadata. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_EmbedContentMetadata.Builder(); } @@ -63,6 +64,7 @@ private static Builder create() { } /** Deserializes a JSON string to a EmbedContentMetadata object. */ + @ExcludeFromGeneratedCoverageReport public static EmbedContentMetadata fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, EmbedContentMetadata.class); } diff --git a/src/main/java/com/google/genai/types/EmbedContentParameters.java b/src/main/java/com/google/genai/types/EmbedContentParameters.java index 4ae02be1959..6a52239f7dc 100644 --- a/src/main/java/com/google/genai/types/EmbedContentParameters.java +++ b/src/main/java/com/google/genai/types/EmbedContentParameters.java @@ -51,6 +51,7 @@ public abstract class EmbedContentParameters extends JsonSerializable { public abstract Optional config(); /** Instantiates a builder for EmbedContentParameters. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_EmbedContentParameters.Builder(); } @@ -126,6 +127,7 @@ public Builder config(EmbedContentConfig.Builder configBuilder) { } /** Deserializes a JSON string to a EmbedContentParameters object. */ + @ExcludeFromGeneratedCoverageReport public static EmbedContentParameters fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, EmbedContentParameters.class); } diff --git a/src/main/java/com/google/genai/types/EmbedContentResponse.java b/src/main/java/com/google/genai/types/EmbedContentResponse.java index 2f35dd4a307..d32055eb817 100644 --- a/src/main/java/com/google/genai/types/EmbedContentResponse.java +++ b/src/main/java/com/google/genai/types/EmbedContentResponse.java @@ -33,6 +33,10 @@ @AutoValue @JsonDeserialize(builder = EmbedContentResponse.Builder.class) public abstract class EmbedContentResponse extends JsonSerializable { + /** Used to retain the full HTTP response. */ + @JsonProperty("sdkHttpResponse") + public abstract Optional sdkHttpResponse(); + /** The embeddings for each request, in the same order as provided in the batch request. */ @JsonProperty("embeddings") public abstract Optional> embeddings(); @@ -42,6 +46,7 @@ public abstract class EmbedContentResponse extends JsonSerializable { public abstract Optional metadata(); /** Instantiates a builder for EmbedContentResponse. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_EmbedContentResponse.Builder(); } @@ -58,6 +63,23 @@ private static Builder create() { return new AutoValue_EmbedContentResponse.Builder(); } + /** + * Setter for sdkHttpResponse. + * + *

sdkHttpResponse: Used to retain the full HTTP response. + */ + @JsonProperty("sdkHttpResponse") + public abstract Builder sdkHttpResponse(HttpResponse sdkHttpResponse); + + /** + * Setter for sdkHttpResponse builder. + * + *

sdkHttpResponse: Used to retain the full HTTP response. + */ + public Builder sdkHttpResponse(HttpResponse.Builder sdkHttpResponseBuilder) { + return sdkHttpResponse(sdkHttpResponseBuilder.build()); + } + /** * Setter for embeddings. * @@ -111,6 +133,7 @@ public Builder metadata(EmbedContentMetadata.Builder metadataBuilder) { } /** Deserializes a JSON string to a EmbedContentResponse object. */ + @ExcludeFromGeneratedCoverageReport public static EmbedContentResponse fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, EmbedContentResponse.class); } diff --git a/src/main/java/com/google/genai/types/EmbeddingsBatchJobSource.java b/src/main/java/com/google/genai/types/EmbeddingsBatchJobSource.java new file mode 100644 index 00000000000..03d1a18eda5 --- /dev/null +++ b/src/main/java/com/google/genai/types/EmbeddingsBatchJobSource.java @@ -0,0 +1,92 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Auto-generated code. Do not edit. + +package com.google.genai.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.google.auto.value.AutoValue; +import com.google.genai.JsonSerializable; +import java.util.Optional; + +/** None */ +@AutoValue +@JsonDeserialize(builder = EmbeddingsBatchJobSource.Builder.class) +public abstract class EmbeddingsBatchJobSource extends JsonSerializable { + /** The Gemini Developer API's file resource name of the input data (e.g. "files/12345"). */ + @JsonProperty("fileName") + public abstract Optional fileName(); + + /** The Gemini Developer API's inlined input data to run batch job. */ + @JsonProperty("inlinedRequests") + public abstract Optional inlinedRequests(); + + /** Instantiates a builder for EmbeddingsBatchJobSource. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_EmbeddingsBatchJobSource.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for EmbeddingsBatchJobSource. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `EmbeddingsBatchJobSource.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_EmbeddingsBatchJobSource.Builder(); + } + + /** + * Setter for fileName. + * + *

fileName: The Gemini Developer API's file resource name of the input data (e.g. + * "files/12345"). + */ + @JsonProperty("fileName") + public abstract Builder fileName(String fileName); + + /** + * Setter for inlinedRequests. + * + *

inlinedRequests: The Gemini Developer API's inlined input data to run batch job. + */ + @JsonProperty("inlinedRequests") + public abstract Builder inlinedRequests(EmbedContentBatch inlinedRequests); + + /** + * Setter for inlinedRequests builder. + * + *

inlinedRequests: The Gemini Developer API's inlined input data to run batch job. + */ + public Builder inlinedRequests(EmbedContentBatch.Builder inlinedRequestsBuilder) { + return inlinedRequests(inlinedRequestsBuilder.build()); + } + + public abstract EmbeddingsBatchJobSource build(); + } + + /** Deserializes a JSON string to a EmbeddingsBatchJobSource object. */ + @ExcludeFromGeneratedCoverageReport + public static EmbeddingsBatchJobSource fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, EmbeddingsBatchJobSource.class); + } +} diff --git a/src/main/java/com/google/genai/types/EncryptionSpec.java b/src/main/java/com/google/genai/types/EncryptionSpec.java index ea39c7c341a..024f865cb0f 100644 --- a/src/main/java/com/google/genai/types/EncryptionSpec.java +++ b/src/main/java/com/google/genai/types/EncryptionSpec.java @@ -27,6 +27,7 @@ /** * Represents a customer-managed encryption key spec that can be applied to a top-level resource. + * This data type is not supported in Gemini API. */ @AutoValue @JsonDeserialize(builder = EncryptionSpec.Builder.class) @@ -41,6 +42,7 @@ public abstract class EncryptionSpec extends JsonSerializable { public abstract Optional kmsKeyName(); /** Instantiates a builder for EncryptionSpec. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_EncryptionSpec.Builder(); } @@ -72,6 +74,7 @@ private static Builder create() { } /** Deserializes a JSON string to a EncryptionSpec object. */ + @ExcludeFromGeneratedCoverageReport public static EncryptionSpec fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, EncryptionSpec.class); } diff --git a/src/main/java/com/google/genai/types/EndSensitivity.java b/src/main/java/com/google/genai/types/EndSensitivity.java index 35641b466bb..3cf231dba11 100644 --- a/src/main/java/com/google/genai/types/EndSensitivity.java +++ b/src/main/java/com/google/genai/types/EndSensitivity.java @@ -60,12 +60,14 @@ public EndSensitivity(Known knownValue) { this.value = knownValue.toString(); } + @ExcludeFromGeneratedCoverageReport @Override @JsonValue public String toString() { return this.value; } + @ExcludeFromGeneratedCoverageReport @SuppressWarnings("PatternMatchingInstanceof") @Override public boolean equals(Object o) { @@ -92,6 +94,7 @@ public boolean equals(Object o) { return false; } + @ExcludeFromGeneratedCoverageReport @Override public int hashCode() { if (this.endSensitivityEnum != Known.END_SENSITIVITY_UNSPECIFIED) { @@ -101,6 +104,7 @@ public int hashCode() { } } + @ExcludeFromGeneratedCoverageReport public Known knownEnum() { return this.endSensitivityEnum; } diff --git a/src/main/java/com/google/genai/types/Endpoint.java b/src/main/java/com/google/genai/types/Endpoint.java index 85a19fb8a39..78d1991b5c3 100644 --- a/src/main/java/com/google/genai/types/Endpoint.java +++ b/src/main/java/com/google/genai/types/Endpoint.java @@ -38,6 +38,7 @@ public abstract class Endpoint extends JsonSerializable { public abstract Optional deployedModelId(); /** Instantiates a builder for Endpoint. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_Endpoint.Builder(); } @@ -74,6 +75,7 @@ private static Builder create() { } /** Deserializes a JSON string to a Endpoint object. */ + @ExcludeFromGeneratedCoverageReport public static Endpoint fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, Endpoint.class); } diff --git a/src/main/java/com/google/genai/types/EnterpriseWebSearch.java b/src/main/java/com/google/genai/types/EnterpriseWebSearch.java index 29543cfc27f..1b70a5862f0 100644 --- a/src/main/java/com/google/genai/types/EnterpriseWebSearch.java +++ b/src/main/java/com/google/genai/types/EnterpriseWebSearch.java @@ -19,15 +19,30 @@ package com.google.genai.types; import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.google.auto.value.AutoValue; import com.google.genai.JsonSerializable; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; -/** Tool to search public web data, powered by Vertex AI Search and Sec4 compliance. */ +/** + * Tool to search public web data, powered by Vertex AI Search and Sec4 compliance. This data type + * is not supported in Gemini API. + */ @AutoValue @JsonDeserialize(builder = EnterpriseWebSearch.Builder.class) public abstract class EnterpriseWebSearch extends JsonSerializable { + /** + * Optional. List of domains to be excluded from the search results. The default limit is 2000 + * domains. + */ + @JsonProperty("excludeDomains") + public abstract Optional> excludeDomains(); + /** Instantiates a builder for EnterpriseWebSearch. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_EnterpriseWebSearch.Builder(); } @@ -44,10 +59,30 @@ private static Builder create() { return new AutoValue_EnterpriseWebSearch.Builder(); } + /** + * Setter for excludeDomains. + * + *

excludeDomains: Optional. List of domains to be excluded from the search results. The + * default limit is 2000 domains. + */ + @JsonProperty("excludeDomains") + public abstract Builder excludeDomains(List excludeDomains); + + /** + * Setter for excludeDomains. + * + *

excludeDomains: Optional. List of domains to be excluded from the search results. The + * default limit is 2000 domains. + */ + public Builder excludeDomains(String... excludeDomains) { + return excludeDomains(Arrays.asList(excludeDomains)); + } + public abstract EnterpriseWebSearch build(); } /** Deserializes a JSON string to a EnterpriseWebSearch object. */ + @ExcludeFromGeneratedCoverageReport public static EnterpriseWebSearch fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, EnterpriseWebSearch.class); } diff --git a/src/main/java/com/google/genai/types/EntityLabel.java b/src/main/java/com/google/genai/types/EntityLabel.java new file mode 100644 index 00000000000..bc2cdb87037 --- /dev/null +++ b/src/main/java/com/google/genai/types/EntityLabel.java @@ -0,0 +1,82 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Auto-generated code. Do not edit. + +package com.google.genai.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.google.auto.value.AutoValue; +import com.google.genai.JsonSerializable; +import java.util.Optional; + +/** An entity representing the segmented area. */ +@AutoValue +@JsonDeserialize(builder = EntityLabel.Builder.class) +public abstract class EntityLabel extends JsonSerializable { + /** The label of the segmented entity. */ + @JsonProperty("label") + public abstract Optional label(); + + /** The confidence score of the detected label. */ + @JsonProperty("score") + public abstract Optional score(); + + /** Instantiates a builder for EntityLabel. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_EntityLabel.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for EntityLabel. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `EntityLabel.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_EntityLabel.Builder(); + } + + /** + * Setter for label. + * + *

label: The label of the segmented entity. + */ + @JsonProperty("label") + public abstract Builder label(String label); + + /** + * Setter for score. + * + *

score: The confidence score of the detected label. + */ + @JsonProperty("score") + public abstract Builder score(Float score); + + public abstract EntityLabel build(); + } + + /** Deserializes a JSON string to a EntityLabel object. */ + @ExcludeFromGeneratedCoverageReport + public static EntityLabel fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, EntityLabel.class); + } +} diff --git a/src/main/java/com/google/genai/types/Environment.java b/src/main/java/com/google/genai/types/Environment.java index 4347d593cfd..4fefd958a0a 100644 --- a/src/main/java/com/google/genai/types/Environment.java +++ b/src/main/java/com/google/genai/types/Environment.java @@ -23,7 +23,7 @@ import com.google.common.base.Ascii; import java.util.Objects; -/** Required. The environment being operated. */ +/** The environment being operated. */ public class Environment { /** Enum representing the known values for Environment. */ @@ -57,12 +57,14 @@ public Environment(Known knownValue) { this.value = knownValue.toString(); } + @ExcludeFromGeneratedCoverageReport @Override @JsonValue public String toString() { return this.value; } + @ExcludeFromGeneratedCoverageReport @SuppressWarnings("PatternMatchingInstanceof") @Override public boolean equals(Object o) { @@ -89,6 +91,7 @@ public boolean equals(Object o) { return false; } + @ExcludeFromGeneratedCoverageReport @Override public int hashCode() { if (this.environmentEnum != Known.ENVIRONMENT_UNSPECIFIED) { @@ -98,6 +101,7 @@ public int hashCode() { } } + @ExcludeFromGeneratedCoverageReport public Known knownEnum() { return this.environmentEnum; } diff --git a/src/main/java/com/google/genai/types/ExcludeFromGeneratedCoverageReport.java b/src/main/java/com/google/genai/types/ExcludeFromGeneratedCoverageReport.java new file mode 100644 index 00000000000..73d98f6f869 --- /dev/null +++ b/src/main/java/com/google/genai/types/ExcludeFromGeneratedCoverageReport.java @@ -0,0 +1,31 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.genai.types; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Annotation to exclude a method or constructor from the Jacoco coverage report. + * + *

Jacoco will exclude methods that have an annotation with the word "generated" in it. + */ +@Retention(RetentionPolicy.CLASS) +@Target({ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.TYPE}) +@interface ExcludeFromGeneratedCoverageReport {} diff --git a/src/main/java/com/google/genai/types/ExecutableCode.java b/src/main/java/com/google/genai/types/ExecutableCode.java index 96779f55a4b..f017751d847 100644 --- a/src/main/java/com/google/genai/types/ExecutableCode.java +++ b/src/main/java/com/google/genai/types/ExecutableCode.java @@ -43,6 +43,7 @@ public abstract class ExecutableCode extends JsonSerializable { public abstract Optional language(); /** Instantiates a builder for ExecutableCode. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_ExecutableCode.Builder(); } @@ -99,6 +100,7 @@ public Builder language(String language) { } /** Deserializes a JSON string to a ExecutableCode object. */ + @ExcludeFromGeneratedCoverageReport public static ExecutableCode fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, ExecutableCode.class); } diff --git a/src/main/java/com/google/genai/types/ExternalApi.java b/src/main/java/com/google/genai/types/ExternalApi.java index 69a7ecb26e8..472c59966f8 100644 --- a/src/main/java/com/google/genai/types/ExternalApi.java +++ b/src/main/java/com/google/genai/types/ExternalApi.java @@ -28,7 +28,8 @@ /** * Retrieve from data source powered by external API for grounding. The external API is not owned by - * Google, but need to follow the pre-defined API spec. + * Google, but need to follow the pre-defined API spec. This data type is not supported in Gemini + * API. */ @AutoValue @JsonDeserialize(builder = ExternalApi.Builder.class) @@ -61,6 +62,7 @@ public abstract class ExternalApi extends JsonSerializable { public abstract Optional simpleSearchParams(); /** Instantiates a builder for ExternalApi. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_ExternalApi.Builder(); } @@ -190,6 +192,7 @@ public Builder simpleSearchParams( } /** Deserializes a JSON string to a ExternalApi object. */ + @ExcludeFromGeneratedCoverageReport public static ExternalApi fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, ExternalApi.class); } diff --git a/src/main/java/com/google/genai/types/ExternalApiElasticSearchParams.java b/src/main/java/com/google/genai/types/ExternalApiElasticSearchParams.java index 5ec0a623ec5..5db0372cd92 100644 --- a/src/main/java/com/google/genai/types/ExternalApiElasticSearchParams.java +++ b/src/main/java/com/google/genai/types/ExternalApiElasticSearchParams.java @@ -25,7 +25,10 @@ import com.google.genai.JsonSerializable; import java.util.Optional; -/** The search parameters to use for the ELASTIC_SEARCH spec. */ +/** + * The search parameters to use for the ELASTIC_SEARCH spec. This data type is not supported in + * Gemini API. + */ @AutoValue @JsonDeserialize(builder = ExternalApiElasticSearchParams.Builder.class) public abstract class ExternalApiElasticSearchParams extends JsonSerializable { @@ -45,6 +48,7 @@ public abstract class ExternalApiElasticSearchParams extends JsonSerializable { public abstract Optional searchTemplate(); /** Instantiates a builder for ExternalApiElasticSearchParams. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_ExternalApiElasticSearchParams.Builder(); } @@ -92,6 +96,7 @@ private static Builder create() { } /** Deserializes a JSON string to a ExternalApiElasticSearchParams object. */ + @ExcludeFromGeneratedCoverageReport public static ExternalApiElasticSearchParams fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, ExternalApiElasticSearchParams.class); } diff --git a/src/main/java/com/google/genai/types/ExternalApiSimpleSearchParams.java b/src/main/java/com/google/genai/types/ExternalApiSimpleSearchParams.java index 39314fe765f..b82a413cd90 100644 --- a/src/main/java/com/google/genai/types/ExternalApiSimpleSearchParams.java +++ b/src/main/java/com/google/genai/types/ExternalApiSimpleSearchParams.java @@ -23,11 +23,15 @@ import com.google.auto.value.AutoValue; import com.google.genai.JsonSerializable; -/** The search parameters to use for SIMPLE_SEARCH spec. */ +/** + * The search parameters to use for SIMPLE_SEARCH spec. This data type is not supported in Gemini + * API. + */ @AutoValue @JsonDeserialize(builder = ExternalApiSimpleSearchParams.Builder.class) public abstract class ExternalApiSimpleSearchParams extends JsonSerializable { /** Instantiates a builder for ExternalApiSimpleSearchParams. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_ExternalApiSimpleSearchParams.Builder(); } @@ -50,6 +54,7 @@ private static Builder create() { } /** Deserializes a JSON string to a ExternalApiSimpleSearchParams object. */ + @ExcludeFromGeneratedCoverageReport public static ExternalApiSimpleSearchParams fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, ExternalApiSimpleSearchParams.class); } diff --git a/src/main/java/com/google/genai/types/FeatureSelectionPreference.java b/src/main/java/com/google/genai/types/FeatureSelectionPreference.java index 5a1815d0128..7976dff966d 100644 --- a/src/main/java/com/google/genai/types/FeatureSelectionPreference.java +++ b/src/main/java/com/google/genai/types/FeatureSelectionPreference.java @@ -59,12 +59,14 @@ public FeatureSelectionPreference(Known knownValue) { this.value = knownValue.toString(); } + @ExcludeFromGeneratedCoverageReport @Override @JsonValue public String toString() { return this.value; } + @ExcludeFromGeneratedCoverageReport @SuppressWarnings("PatternMatchingInstanceof") @Override public boolean equals(Object o) { @@ -91,6 +93,7 @@ public boolean equals(Object o) { return false; } + @ExcludeFromGeneratedCoverageReport @Override public int hashCode() { if (this.featureSelectionPreferenceEnum != Known.FEATURE_SELECTION_PREFERENCE_UNSPECIFIED) { @@ -100,6 +103,7 @@ public int hashCode() { } } + @ExcludeFromGeneratedCoverageReport public Known knownEnum() { return this.featureSelectionPreferenceEnum; } diff --git a/src/main/java/com/google/genai/types/FetchPredictOperationConfig.java b/src/main/java/com/google/genai/types/FetchPredictOperationConfig.java index 006f2f9489f..f8ea69c8315 100644 --- a/src/main/java/com/google/genai/types/FetchPredictOperationConfig.java +++ b/src/main/java/com/google/genai/types/FetchPredictOperationConfig.java @@ -34,6 +34,7 @@ public abstract class FetchPredictOperationConfig extends JsonSerializable { public abstract Optional httpOptions(); /** Instantiates a builder for FetchPredictOperationConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_FetchPredictOperationConfig.Builder(); } @@ -71,6 +72,7 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { } /** Deserializes a JSON string to a FetchPredictOperationConfig object. */ + @ExcludeFromGeneratedCoverageReport public static FetchPredictOperationConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, FetchPredictOperationConfig.class); } diff --git a/src/main/java/com/google/genai/types/FetchPredictOperationParameters.java b/src/main/java/com/google/genai/types/FetchPredictOperationParameters.java index 4a3eae13eae..acb9eb36b59 100644 --- a/src/main/java/com/google/genai/types/FetchPredictOperationParameters.java +++ b/src/main/java/com/google/genai/types/FetchPredictOperationParameters.java @@ -44,6 +44,7 @@ public abstract class FetchPredictOperationParameters extends JsonSerializable { public abstract Optional config(); /** Instantiates a builder for FetchPredictOperationParameters. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_FetchPredictOperationParameters.Builder(); } @@ -99,6 +100,7 @@ public Builder config(FetchPredictOperationConfig.Builder configBuilder) { } /** Deserializes a JSON string to a FetchPredictOperationParameters object. */ + @ExcludeFromGeneratedCoverageReport public static FetchPredictOperationParameters fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, FetchPredictOperationParameters.class); } diff --git a/src/main/java/com/google/genai/types/File.java b/src/main/java/com/google/genai/types/File.java index 34ecb1e76d9..bbf979d72c2 100644 --- a/src/main/java/com/google/genai/types/File.java +++ b/src/main/java/com/google/genai/types/File.java @@ -101,6 +101,7 @@ public abstract class File extends JsonSerializable { public abstract Optional error(); /** Instantiates a builder for File. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_File.Builder(); } @@ -289,6 +290,7 @@ public Builder error(FileStatus.Builder errorBuilder) { } /** Deserializes a JSON string to a File object. */ + @ExcludeFromGeneratedCoverageReport public static File fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, File.class); } diff --git a/src/main/java/com/google/genai/types/FileData.java b/src/main/java/com/google/genai/types/FileData.java index d36aa3b8157..9a794ba5854 100644 --- a/src/main/java/com/google/genai/types/FileData.java +++ b/src/main/java/com/google/genai/types/FileData.java @@ -31,7 +31,9 @@ public abstract class FileData extends JsonSerializable { /** * Optional. Display name of the file data. Used to provide a label or filename to distinguish - * file datas. It is not currently used in the Gemini GenerateContent calls. + * file datas. This field is only returned in PromptMessage for prompt management. It is currently + * used in the Gemini GenerateContent calls only when server side tools (code_execution, + * google_search, and url_context) are enabled. This field is not supported in Gemini API. */ @JsonProperty("displayName") public abstract Optional displayName(); @@ -45,6 +47,7 @@ public abstract class FileData extends JsonSerializable { public abstract Optional mimeType(); /** Instantiates a builder for FileData. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_FileData.Builder(); } @@ -65,7 +68,10 @@ private static Builder create() { * Setter for displayName. * *

displayName: Optional. Display name of the file data. Used to provide a label or filename - * to distinguish file datas. It is not currently used in the Gemini GenerateContent calls. + * to distinguish file datas. This field is only returned in PromptMessage for prompt + * management. It is currently used in the Gemini GenerateContent calls only when server side + * tools (code_execution, google_search, and url_context) are enabled. This field is not + * supported in Gemini API. */ @JsonProperty("displayName") public abstract Builder displayName(String displayName); @@ -90,6 +96,7 @@ private static Builder create() { } /** Deserializes a JSON string to a FileData object. */ + @ExcludeFromGeneratedCoverageReport public static FileData fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, FileData.class); } diff --git a/src/main/java/com/google/genai/types/FileSource.java b/src/main/java/com/google/genai/types/FileSource.java index fa360c5fda9..1763c1c4d78 100644 --- a/src/main/java/com/google/genai/types/FileSource.java +++ b/src/main/java/com/google/genai/types/FileSource.java @@ -59,12 +59,14 @@ public FileSource(Known knownValue) { this.value = knownValue.toString(); } + @ExcludeFromGeneratedCoverageReport @Override @JsonValue public String toString() { return this.value; } + @ExcludeFromGeneratedCoverageReport @SuppressWarnings("PatternMatchingInstanceof") @Override public boolean equals(Object o) { @@ -91,6 +93,7 @@ public boolean equals(Object o) { return false; } + @ExcludeFromGeneratedCoverageReport @Override public int hashCode() { if (this.fileSourceEnum != Known.FILE_SOURCE_UNSPECIFIED) { @@ -100,6 +103,7 @@ public int hashCode() { } } + @ExcludeFromGeneratedCoverageReport public Known knownEnum() { return this.fileSourceEnum; } diff --git a/src/main/java/com/google/genai/types/FileState.java b/src/main/java/com/google/genai/types/FileState.java index a4f74872b85..af9e2ae68f7 100644 --- a/src/main/java/com/google/genai/types/FileState.java +++ b/src/main/java/com/google/genai/types/FileState.java @@ -61,12 +61,14 @@ public FileState(Known knownValue) { this.value = knownValue.toString(); } + @ExcludeFromGeneratedCoverageReport @Override @JsonValue public String toString() { return this.value; } + @ExcludeFromGeneratedCoverageReport @SuppressWarnings("PatternMatchingInstanceof") @Override public boolean equals(Object o) { @@ -93,6 +95,7 @@ public boolean equals(Object o) { return false; } + @ExcludeFromGeneratedCoverageReport @Override public int hashCode() { if (this.fileStateEnum != Known.FILE_STATE_UNSPECIFIED) { @@ -102,6 +105,7 @@ public int hashCode() { } } + @ExcludeFromGeneratedCoverageReport public Known knownEnum() { return this.fileStateEnum; } diff --git a/src/main/java/com/google/genai/types/FileStatus.java b/src/main/java/com/google/genai/types/FileStatus.java index 5c69faa3292..d3c190a2b50 100644 --- a/src/main/java/com/google/genai/types/FileStatus.java +++ b/src/main/java/com/google/genai/types/FileStatus.java @@ -51,6 +51,7 @@ public abstract class FileStatus extends JsonSerializable { public abstract Optional code(); /** Instantiates a builder for FileStatus. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_FileStatus.Builder(); } @@ -107,6 +108,7 @@ public Builder details(Map... details) { } /** Deserializes a JSON string to a FileStatus object. */ + @ExcludeFromGeneratedCoverageReport public static FileStatus fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, FileStatus.class); } diff --git a/src/main/java/com/google/genai/types/FinishReason.java b/src/main/java/com/google/genai/types/FinishReason.java index 6df7ea34964..4f2a8f9b4a0 100644 --- a/src/main/java/com/google/genai/types/FinishReason.java +++ b/src/main/java/com/google/genai/types/FinishReason.java @@ -75,7 +75,13 @@ public enum Known { IMAGE_SAFETY, /** The tool call generated by the model is invalid. */ - UNEXPECTED_TOOL_CALL + UNEXPECTED_TOOL_CALL, + + /** Image generation stopped because the generated images have prohibited content. */ + IMAGE_PROHIBITED_CONTENT, + + /** The model was expected to generate an image, but none was generated. */ + NO_IMAGE } private Known finishReasonEnum; @@ -100,12 +106,14 @@ public FinishReason(Known knownValue) { this.value = knownValue.toString(); } + @ExcludeFromGeneratedCoverageReport @Override @JsonValue public String toString() { return this.value; } + @ExcludeFromGeneratedCoverageReport @SuppressWarnings("PatternMatchingInstanceof") @Override public boolean equals(Object o) { @@ -132,6 +140,7 @@ public boolean equals(Object o) { return false; } + @ExcludeFromGeneratedCoverageReport @Override public int hashCode() { if (this.finishReasonEnum != Known.FINISH_REASON_UNSPECIFIED) { @@ -141,6 +150,7 @@ public int hashCode() { } } + @ExcludeFromGeneratedCoverageReport public Known knownEnum() { return this.finishReasonEnum; } diff --git a/src/main/java/com/google/genai/types/FunctionCall.java b/src/main/java/com/google/genai/types/FunctionCall.java index ca0a88af924..ebadb56c076 100644 --- a/src/main/java/com/google/genai/types/FunctionCall.java +++ b/src/main/java/com/google/genai/types/FunctionCall.java @@ -49,6 +49,7 @@ public abstract class FunctionCall extends JsonSerializable { public abstract Optional name(); /** Instantiates a builder for FunctionCall. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_FunctionCall.Builder(); } @@ -95,6 +96,7 @@ private static Builder create() { } /** Deserializes a JSON string to a FunctionCall object. */ + @ExcludeFromGeneratedCoverageReport public static FunctionCall fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, FunctionCall.class); } diff --git a/src/main/java/com/google/genai/types/FunctionCallingConfig.java b/src/main/java/com/google/genai/types/FunctionCallingConfig.java index cd64b08f89d..5d280e4642a 100644 --- a/src/main/java/com/google/genai/types/FunctionCallingConfig.java +++ b/src/main/java/com/google/genai/types/FunctionCallingConfig.java @@ -45,6 +45,7 @@ public abstract class FunctionCallingConfig extends JsonSerializable { public abstract Optional> allowedFunctionNames(); /** Instantiates a builder for FunctionCallingConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_FunctionCallingConfig.Builder(); } @@ -114,6 +115,7 @@ public Builder allowedFunctionNames(String... allowedFunctionNames) { } /** Deserializes a JSON string to a FunctionCallingConfig object. */ + @ExcludeFromGeneratedCoverageReport public static FunctionCallingConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, FunctionCallingConfig.class); } diff --git a/src/main/java/com/google/genai/types/FunctionCallingConfigMode.java b/src/main/java/com/google/genai/types/FunctionCallingConfigMode.java index 6d6ff9c675d..8c86c3c3cfa 100644 --- a/src/main/java/com/google/genai/types/FunctionCallingConfigMode.java +++ b/src/main/java/com/google/genai/types/FunctionCallingConfigMode.java @@ -50,6 +50,14 @@ public enum Known { */ NONE, + /** + * Model decides to predict either a function call or a natural language response, but will + * validate function calls with constrained decoding. If "allowed_function_names" are set, the + * predicted function call will be limited to any one of "allowed_function_names", else the + * predicted function call will be any one of the provided "function_declarations". + */ + VALIDATED, + FUNCTION_CALLING_CONFIG_MODE_UNSPECIFIED } @@ -75,12 +83,14 @@ public FunctionCallingConfigMode(Known knownValue) { this.value = knownValue.toString(); } + @ExcludeFromGeneratedCoverageReport @Override @JsonValue public String toString() { return this.value; } + @ExcludeFromGeneratedCoverageReport @SuppressWarnings("PatternMatchingInstanceof") @Override public boolean equals(Object o) { @@ -107,6 +117,7 @@ public boolean equals(Object o) { return false; } + @ExcludeFromGeneratedCoverageReport @Override public int hashCode() { if (this.functionCallingConfigModeEnum != Known.FUNCTION_CALLING_CONFIG_MODE_UNSPECIFIED) { @@ -116,6 +127,7 @@ public int hashCode() { } } + @ExcludeFromGeneratedCoverageReport public Known knownEnum() { return this.functionCallingConfigModeEnum; } diff --git a/src/main/java/com/google/genai/types/FunctionDeclaration.java b/src/main/java/com/google/genai/types/FunctionDeclaration.java index 7e02cc508ea..78801843a0f 100644 --- a/src/main/java/com/google/genai/types/FunctionDeclaration.java +++ b/src/main/java/com/google/genai/types/FunctionDeclaration.java @@ -97,6 +97,7 @@ public abstract class FunctionDeclaration extends JsonSerializable { public abstract Optional responseJsonSchema(); /** Instantiates a builder for FunctionDeclaration. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_FunctionDeclaration.Builder(); } @@ -236,6 +237,7 @@ public Builder response(Schema.Builder responseBuilder) { } /** Deserializes a JSON string to a FunctionDeclaration object. */ + @ExcludeFromGeneratedCoverageReport public static FunctionDeclaration fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, FunctionDeclaration.class); } diff --git a/src/main/java/com/google/genai/types/FunctionResponse.java b/src/main/java/com/google/genai/types/FunctionResponse.java index a3cdc1ecdea..e5f11e8438d 100644 --- a/src/main/java/com/google/genai/types/FunctionResponse.java +++ b/src/main/java/com/google/genai/types/FunctionResponse.java @@ -18,12 +18,16 @@ package com.google.genai.types; +import static com.google.common.collect.ImmutableList.toImmutableList; + import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.google.auto.value.AutoValue; import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.genai.JsonSerializable; +import java.util.Arrays; +import java.util.List; import java.util.Map; import java.util.Optional; @@ -49,6 +53,13 @@ public abstract class FunctionResponse extends JsonSerializable { @JsonProperty("scheduling") public abstract Optional scheduling(); + /** + * List of parts that constitute a function response. Each part may have a different IANA MIME + * type. + */ + @JsonProperty("parts") + public abstract Optional> parts(); + /** * Optional. The id of the function call this response is for. Populated by the client to match * the corresponding function call `id`. @@ -72,6 +83,7 @@ public abstract class FunctionResponse extends JsonSerializable { public abstract Optional> response(); /** Instantiates a builder for FunctionResponse. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_FunctionResponse.Builder(); } @@ -133,6 +145,38 @@ public Builder scheduling(String scheduling) { return scheduling(new FunctionResponseScheduling(scheduling)); } + /** + * Setter for parts. + * + *

parts: List of parts that constitute a function response. Each part may have a different + * IANA MIME type. + */ + @JsonProperty("parts") + public abstract Builder parts(List parts); + + /** + * Setter for parts. + * + *

parts: List of parts that constitute a function response. Each part may have a different + * IANA MIME type. + */ + public Builder parts(FunctionResponsePart... parts) { + return parts(Arrays.asList(parts)); + } + + /** + * Setter for parts builder. + * + *

parts: List of parts that constitute a function response. Each part may have a different + * IANA MIME type. + */ + public Builder parts(FunctionResponsePart.Builder... partsBuilders) { + return parts( + Arrays.asList(partsBuilders).stream() + .map(FunctionResponsePart.Builder::build) + .collect(toImmutableList())); + } + /** * Setter for id. * @@ -165,6 +209,7 @@ public Builder scheduling(String scheduling) { } /** Deserializes a JSON string to a FunctionResponse object. */ + @ExcludeFromGeneratedCoverageReport public static FunctionResponse fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, FunctionResponse.class); } diff --git a/src/main/java/com/google/genai/types/FunctionResponseBlob.java b/src/main/java/com/google/genai/types/FunctionResponseBlob.java new file mode 100644 index 00000000000..4da5207fad0 --- /dev/null +++ b/src/main/java/com/google/genai/types/FunctionResponseBlob.java @@ -0,0 +1,86 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Auto-generated code. Do not edit. + +package com.google.genai.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.google.auto.value.AutoValue; +import com.google.genai.JsonSerializable; +import java.util.Optional; + +/** + * Raw media bytes for function response. + * + *

Text should not be sent as raw bytes, use the FunctionResponse.response field. + */ +@AutoValue +@JsonDeserialize(builder = FunctionResponseBlob.Builder.class) +public abstract class FunctionResponseBlob extends JsonSerializable { + /** Required. The IANA standard MIME type of the source data. */ + @JsonProperty("mimeType") + public abstract Optional mimeType(); + + /** Required. Inline media bytes. */ + @JsonProperty("data") + public abstract Optional data(); + + /** Instantiates a builder for FunctionResponseBlob. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_FunctionResponseBlob.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for FunctionResponseBlob. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `FunctionResponseBlob.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_FunctionResponseBlob.Builder(); + } + + /** + * Setter for mimeType. + * + *

mimeType: Required. The IANA standard MIME type of the source data. + */ + @JsonProperty("mimeType") + public abstract Builder mimeType(String mimeType); + + /** + * Setter for data. + * + *

data: Required. Inline media bytes. + */ + @JsonProperty("data") + public abstract Builder data(byte[] data); + + public abstract FunctionResponseBlob build(); + } + + /** Deserializes a JSON string to a FunctionResponseBlob object. */ + @ExcludeFromGeneratedCoverageReport + public static FunctionResponseBlob fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, FunctionResponseBlob.class); + } +} diff --git a/src/main/java/com/google/genai/types/FunctionResponseFileData.java b/src/main/java/com/google/genai/types/FunctionResponseFileData.java new file mode 100644 index 00000000000..5b4de4a8a8e --- /dev/null +++ b/src/main/java/com/google/genai/types/FunctionResponseFileData.java @@ -0,0 +1,82 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Auto-generated code. Do not edit. + +package com.google.genai.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.google.auto.value.AutoValue; +import com.google.genai.JsonSerializable; +import java.util.Optional; + +/** URI based data for function response. */ +@AutoValue +@JsonDeserialize(builder = FunctionResponseFileData.Builder.class) +public abstract class FunctionResponseFileData extends JsonSerializable { + /** Required. URI. */ + @JsonProperty("fileUri") + public abstract Optional fileUri(); + + /** Required. The IANA standard MIME type of the source data. */ + @JsonProperty("mimeType") + public abstract Optional mimeType(); + + /** Instantiates a builder for FunctionResponseFileData. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_FunctionResponseFileData.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for FunctionResponseFileData. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `FunctionResponseFileData.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_FunctionResponseFileData.Builder(); + } + + /** + * Setter for fileUri. + * + *

fileUri: Required. URI. + */ + @JsonProperty("fileUri") + public abstract Builder fileUri(String fileUri); + + /** + * Setter for mimeType. + * + *

mimeType: Required. The IANA standard MIME type of the source data. + */ + @JsonProperty("mimeType") + public abstract Builder mimeType(String mimeType); + + public abstract FunctionResponseFileData build(); + } + + /** Deserializes a JSON string to a FunctionResponseFileData object. */ + @ExcludeFromGeneratedCoverageReport + public static FunctionResponseFileData fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, FunctionResponseFileData.class); + } +} diff --git a/src/main/java/com/google/genai/types/FunctionResponsePart.java b/src/main/java/com/google/genai/types/FunctionResponsePart.java new file mode 100644 index 00000000000..a01091029b8 --- /dev/null +++ b/src/main/java/com/google/genai/types/FunctionResponsePart.java @@ -0,0 +1,126 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Auto-generated code. Do not edit. + +package com.google.genai.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.google.auto.value.AutoValue; +import com.google.genai.JsonSerializable; +import java.util.Optional; + +/** + * A datatype containing media that is part of a `FunctionResponse` message. + * + *

A `FunctionResponsePart` consists of data which has an associated datatype. A + * `FunctionResponsePart` can only contain one of the accepted types in `FunctionResponsePart.data`. + * + *

A `FunctionResponsePart` must have a fixed IANA MIME type identifying the type and subtype of + * the media if the `inline_data` field is filled with raw bytes. + */ +@AutoValue +@JsonDeserialize(builder = FunctionResponsePart.Builder.class) +public abstract class FunctionResponsePart extends JsonSerializable { + /** Optional. Inline media bytes. */ + @JsonProperty("inlineData") + public abstract Optional inlineData(); + + /** Optional. URI based data. */ + @JsonProperty("fileData") + public abstract Optional fileData(); + + /** Instantiates a builder for FunctionResponsePart. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_FunctionResponsePart.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for FunctionResponsePart. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `FunctionResponsePart.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_FunctionResponsePart.Builder(); + } + + /** + * Setter for inlineData. + * + *

inlineData: Optional. Inline media bytes. + */ + @JsonProperty("inlineData") + public abstract Builder inlineData(FunctionResponseBlob inlineData); + + /** + * Setter for inlineData builder. + * + *

inlineData: Optional. Inline media bytes. + */ + public Builder inlineData(FunctionResponseBlob.Builder inlineDataBuilder) { + return inlineData(inlineDataBuilder.build()); + } + + /** + * Setter for fileData. + * + *

fileData: Optional. URI based data. + */ + @JsonProperty("fileData") + public abstract Builder fileData(FunctionResponseFileData fileData); + + /** + * Setter for fileData builder. + * + *

fileData: Optional. URI based data. + */ + public Builder fileData(FunctionResponseFileData.Builder fileDataBuilder) { + return fileData(fileDataBuilder.build()); + } + + public abstract FunctionResponsePart build(); + } + + /** Deserializes a JSON string to a FunctionResponsePart object. */ + @ExcludeFromGeneratedCoverageReport + public static FunctionResponsePart fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, FunctionResponsePart.class); + } + + /** + * Constructs a FunctionResponsePart with FunctionResponseBlob from a byte array and MIME type. + */ + public static FunctionResponsePart fromBytes(byte[] bytes, String mimeType) { + return builder() + .inlineData(FunctionResponseBlob.builder().data(bytes).mimeType(mimeType)) + .build(); + } + + /** + * Constructs a FunctionResponsePart with FunctionResponseFileData from a file URI and MIME type. + */ + public static FunctionResponsePart fromUri(String fileUri, String mimeType) { + return builder() + .fileData(FunctionResponseFileData.builder().fileUri(fileUri).mimeType(mimeType)) + .build(); + } +} diff --git a/src/main/java/com/google/genai/types/FunctionResponseScheduling.java b/src/main/java/com/google/genai/types/FunctionResponseScheduling.java index 527afa0a418..cd22370f049 100644 --- a/src/main/java/com/google/genai/types/FunctionResponseScheduling.java +++ b/src/main/java/com/google/genai/types/FunctionResponseScheduling.java @@ -71,12 +71,14 @@ public FunctionResponseScheduling(Known knownValue) { this.value = knownValue.toString(); } + @ExcludeFromGeneratedCoverageReport @Override @JsonValue public String toString() { return this.value; } + @ExcludeFromGeneratedCoverageReport @SuppressWarnings("PatternMatchingInstanceof") @Override public boolean equals(Object o) { @@ -103,6 +105,7 @@ public boolean equals(Object o) { return false; } + @ExcludeFromGeneratedCoverageReport @Override public int hashCode() { if (this.functionResponseSchedulingEnum != Known.FUNCTION_RESPONSE_SCHEDULING_UNSPECIFIED) { @@ -112,6 +115,7 @@ public int hashCode() { } } + @ExcludeFromGeneratedCoverageReport public Known knownEnum() { return this.functionResponseSchedulingEnum; } diff --git a/src/main/java/com/google/genai/types/GeminiPreferenceExample.java b/src/main/java/com/google/genai/types/GeminiPreferenceExample.java new file mode 100644 index 00000000000..fb821207125 --- /dev/null +++ b/src/main/java/com/google/genai/types/GeminiPreferenceExample.java @@ -0,0 +1,128 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Auto-generated code. Do not edit. + +package com.google.genai.types; + +import static com.google.common.collect.ImmutableList.toImmutableList; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.google.auto.value.AutoValue; +import com.google.genai.JsonSerializable; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +/** Input example for preference optimization. This data type is not supported in Gemini API. */ +@AutoValue +@JsonDeserialize(builder = GeminiPreferenceExample.Builder.class) +public abstract class GeminiPreferenceExample extends JsonSerializable { + /** List of completions for a given prompt. */ + @JsonProperty("completions") + public abstract Optional> completions(); + + /** Multi-turn contents that represents the Prompt. */ + @JsonProperty("contents") + public abstract Optional> contents(); + + /** Instantiates a builder for GeminiPreferenceExample. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_GeminiPreferenceExample.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for GeminiPreferenceExample. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `GeminiPreferenceExample.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_GeminiPreferenceExample.Builder(); + } + + /** + * Setter for completions. + * + *

completions: List of completions for a given prompt. + */ + @JsonProperty("completions") + public abstract Builder completions(List completions); + + /** + * Setter for completions. + * + *

completions: List of completions for a given prompt. + */ + public Builder completions(GeminiPreferenceExampleCompletion... completions) { + return completions(Arrays.asList(completions)); + } + + /** + * Setter for completions builder. + * + *

completions: List of completions for a given prompt. + */ + public Builder completions(GeminiPreferenceExampleCompletion.Builder... completionsBuilders) { + return completions( + Arrays.asList(completionsBuilders).stream() + .map(GeminiPreferenceExampleCompletion.Builder::build) + .collect(toImmutableList())); + } + + /** + * Setter for contents. + * + *

contents: Multi-turn contents that represents the Prompt. + */ + @JsonProperty("contents") + public abstract Builder contents(List contents); + + /** + * Setter for contents. + * + *

contents: Multi-turn contents that represents the Prompt. + */ + public Builder contents(Content... contents) { + return contents(Arrays.asList(contents)); + } + + /** + * Setter for contents builder. + * + *

contents: Multi-turn contents that represents the Prompt. + */ + public Builder contents(Content.Builder... contentsBuilders) { + return contents( + Arrays.asList(contentsBuilders).stream() + .map(Content.Builder::build) + .collect(toImmutableList())); + } + + public abstract GeminiPreferenceExample build(); + } + + /** Deserializes a JSON string to a GeminiPreferenceExample object. */ + @ExcludeFromGeneratedCoverageReport + public static GeminiPreferenceExample fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, GeminiPreferenceExample.class); + } +} diff --git a/src/main/java/com/google/genai/types/GeminiPreferenceExampleCompletion.java b/src/main/java/com/google/genai/types/GeminiPreferenceExampleCompletion.java new file mode 100644 index 00000000000..4ad1a017a67 --- /dev/null +++ b/src/main/java/com/google/genai/types/GeminiPreferenceExampleCompletion.java @@ -0,0 +1,94 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Auto-generated code. Do not edit. + +package com.google.genai.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.google.auto.value.AutoValue; +import com.google.genai.JsonSerializable; +import java.util.Optional; + +/** Completion and its preference score. This data type is not supported in Gemini API. */ +@AutoValue +@JsonDeserialize(builder = GeminiPreferenceExampleCompletion.Builder.class) +public abstract class GeminiPreferenceExampleCompletion extends JsonSerializable { + /** Single turn completion for the given prompt. */ + @JsonProperty("completion") + public abstract Optional completion(); + + /** The score for the given completion. */ + @JsonProperty("score") + public abstract Optional score(); + + /** Instantiates a builder for GeminiPreferenceExampleCompletion. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_GeminiPreferenceExampleCompletion.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for GeminiPreferenceExampleCompletion. */ + @AutoValue.Builder + public abstract static class Builder { + /** + * For internal usage. Please use `GeminiPreferenceExampleCompletion.builder()` for + * instantiation. + */ + @JsonCreator + private static Builder create() { + return new AutoValue_GeminiPreferenceExampleCompletion.Builder(); + } + + /** + * Setter for completion. + * + *

completion: Single turn completion for the given prompt. + */ + @JsonProperty("completion") + public abstract Builder completion(Content completion); + + /** + * Setter for completion builder. + * + *

completion: Single turn completion for the given prompt. + */ + public Builder completion(Content.Builder completionBuilder) { + return completion(completionBuilder.build()); + } + + /** + * Setter for score. + * + *

score: The score for the given completion. + */ + @JsonProperty("score") + public abstract Builder score(Float score); + + public abstract GeminiPreferenceExampleCompletion build(); + } + + /** Deserializes a JSON string to a GeminiPreferenceExampleCompletion object. */ + @ExcludeFromGeneratedCoverageReport + public static GeminiPreferenceExampleCompletion fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, GeminiPreferenceExampleCompletion.class); + } +} diff --git a/src/main/java/com/google/genai/types/GenerateContentConfig.java b/src/main/java/com/google/genai/types/GenerateContentConfig.java index ed28f450e84..bfd582b3f7f 100644 --- a/src/main/java/com/google/genai/types/GenerateContentConfig.java +++ b/src/main/java/com/google/genai/types/GenerateContentConfig.java @@ -44,6 +44,10 @@ public abstract class GenerateContentConfig extends JsonSerializable { @JsonProperty("httpOptions") public abstract Optional httpOptions(); + /** If true, the raw HTTP response will be returned in the 'sdk_http_response' field. */ + @JsonProperty("shouldReturnHttpResponse") + public abstract Optional shouldReturnHttpResponse(); + /** * Instructions for the model to steer it toward better performance. For example, "Answer as * concisely as possible" or "Don't use technical terms in your response". @@ -215,7 +219,12 @@ public abstract class GenerateContentConfig extends JsonSerializable { @JsonProperty("thinkingConfig") public abstract Optional thinkingConfig(); + /** The image generation configuration. */ + @JsonProperty("imageConfig") + public abstract Optional imageConfig(); + /** Instantiates a builder for GenerateContentConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_GenerateContentConfig.Builder(); } @@ -249,6 +258,15 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { return httpOptions(httpOptionsBuilder.build()); } + /** + * Setter for shouldReturnHttpResponse. + * + *

shouldReturnHttpResponse: If true, the raw HTTP response will be returned in the + * 'sdk_http_response' field. + */ + @JsonProperty("shouldReturnHttpResponse") + public abstract Builder shouldReturnHttpResponse(boolean shouldReturnHttpResponse); + /** * Setter for systemInstruction. * @@ -670,10 +688,28 @@ public Builder thinkingConfig(ThinkingConfig.Builder thinkingConfigBuilder) { return thinkingConfig(thinkingConfigBuilder.build()); } + /** + * Setter for imageConfig. + * + *

imageConfig: The image generation configuration. + */ + @JsonProperty("imageConfig") + public abstract Builder imageConfig(ImageConfig imageConfig); + + /** + * Setter for imageConfig builder. + * + *

imageConfig: The image generation configuration. + */ + public Builder imageConfig(ImageConfig.Builder imageConfigBuilder) { + return imageConfig(imageConfigBuilder.build()); + } + public abstract GenerateContentConfig build(); } /** Deserializes a JSON string to a GenerateContentConfig object. */ + @ExcludeFromGeneratedCoverageReport public static GenerateContentConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, GenerateContentConfig.class); } diff --git a/src/main/java/com/google/genai/types/GenerateContentParameters.java b/src/main/java/com/google/genai/types/GenerateContentParameters.java index 43f2ca07ed5..be550b56b61 100644 --- a/src/main/java/com/google/genai/types/GenerateContentParameters.java +++ b/src/main/java/com/google/genai/types/GenerateContentParameters.java @@ -51,6 +51,7 @@ public abstract class GenerateContentParameters extends JsonSerializable { public abstract Optional config(); /** Instantiates a builder for GenerateContentParameters. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_GenerateContentParameters.Builder(); } @@ -126,6 +127,7 @@ public Builder config(GenerateContentConfig.Builder configBuilder) { } /** Deserializes a JSON string to a GenerateContentParameters object. */ + @ExcludeFromGeneratedCoverageReport public static GenerateContentParameters fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, GenerateContentParameters.class); } diff --git a/src/main/java/com/google/genai/types/GenerateContentResponse.java b/src/main/java/com/google/genai/types/GenerateContentResponse.java index c00a72a4b02..33603df317b 100644 --- a/src/main/java/com/google/genai/types/GenerateContentResponse.java +++ b/src/main/java/com/google/genai/types/GenerateContentResponse.java @@ -53,10 +53,6 @@ public abstract class GenerateContentResponse extends JsonSerializable { @JsonProperty("createTime") public abstract Optional createTime(); - /** Identifier for each response. */ - @JsonProperty("responseId") - public abstract Optional responseId(); - /** The history of automatic function calling. */ @JsonProperty("automaticFunctionCallingHistory") public abstract Optional> automaticFunctionCallingHistory(); @@ -72,11 +68,18 @@ public abstract class GenerateContentResponse extends JsonSerializable { @JsonProperty("promptFeedback") public abstract Optional promptFeedback(); + /** + * Output only. response_id is used to identify each response. It is the encoding of the event_id. + */ + @JsonProperty("responseId") + public abstract Optional responseId(); + /** Usage metadata about the response(s). */ @JsonProperty("usageMetadata") public abstract Optional usageMetadata(); /** Instantiates a builder for GenerateContentResponse. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_GenerateContentResponse.Builder(); } @@ -147,14 +150,6 @@ public Builder candidates(Candidate.Builder... candidatesBuilders) { @JsonProperty("createTime") public abstract Builder createTime(Instant createTime); - /** - * Setter for responseId. - * - *

responseId: Identifier for each response. - */ - @JsonProperty("responseId") - public abstract Builder responseId(String responseId); - /** * Setter for automaticFunctionCallingHistory. * @@ -216,6 +211,15 @@ public Builder promptFeedback( return promptFeedback(promptFeedbackBuilder.build()); } + /** + * Setter for responseId. + * + *

responseId: Output only. response_id is used to identify each response. It is the encoding + * of the event_id. + */ + @JsonProperty("responseId") + public abstract Builder responseId(String responseId); + /** * Setter for usageMetadata. * @@ -238,6 +242,7 @@ public Builder usageMetadata( } /** Deserializes a JSON string to a GenerateContentResponse object. */ + @ExcludeFromGeneratedCoverageReport public static GenerateContentResponse fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, GenerateContentResponse.class); } diff --git a/src/main/java/com/google/genai/types/GenerateContentResponsePromptFeedback.java b/src/main/java/com/google/genai/types/GenerateContentResponsePromptFeedback.java index 08be365950f..0211ac8af21 100644 --- a/src/main/java/com/google/genai/types/GenerateContentResponsePromptFeedback.java +++ b/src/main/java/com/google/genai/types/GenerateContentResponsePromptFeedback.java @@ -30,23 +30,30 @@ import java.util.List; import java.util.Optional; -/** Content filter results for a prompt sent in the request. */ +/** + * Content filter results for a prompt sent in the request. Note: This is sent only in the first + * stream chunk and only if no candidates were generated due to content violations. + */ @AutoValue @JsonDeserialize(builder = GenerateContentResponsePromptFeedback.Builder.class) public abstract class GenerateContentResponsePromptFeedback extends JsonSerializable { - /** Output only. Blocked reason. */ + /** Output only. The reason why the prompt was blocked. */ @JsonProperty("blockReason") public abstract Optional blockReason(); - /** Output only. A readable block reason message. */ + /** + * Output only. A readable message that explains the reason why the prompt was blocked. This field + * is not supported in Gemini API. + */ @JsonProperty("blockReasonMessage") public abstract Optional blockReasonMessage(); - /** Output only. Safety ratings. */ + /** Output only. A list of safety ratings for the prompt. There is one rating per category. */ @JsonProperty("safetyRatings") public abstract Optional> safetyRatings(); /** Instantiates a builder for GenerateContentResponsePromptFeedback. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_GenerateContentResponsePromptFeedback.Builder(); } @@ -69,7 +76,7 @@ private static Builder create() { /** * Setter for blockReason. * - *

blockReason: Output only. Blocked reason. + *

blockReason: Output only. The reason why the prompt was blocked. */ @JsonProperty("blockReason") public abstract Builder blockReason(BlockedReason blockReason); @@ -77,7 +84,7 @@ private static Builder create() { /** * Setter for blockReason given a known enum. * - *

blockReason: Output only. Blocked reason. + *

blockReason: Output only. The reason why the prompt was blocked. */ @CanIgnoreReturnValue public Builder blockReason(BlockedReason.Known knownType) { @@ -87,7 +94,7 @@ public Builder blockReason(BlockedReason.Known knownType) { /** * Setter for blockReason given a string. * - *

blockReason: Output only. Blocked reason. + *

blockReason: Output only. The reason why the prompt was blocked. */ @CanIgnoreReturnValue public Builder blockReason(String blockReason) { @@ -97,7 +104,8 @@ public Builder blockReason(String blockReason) { /** * Setter for blockReasonMessage. * - *

blockReasonMessage: Output only. A readable block reason message. + *

blockReasonMessage: Output only. A readable message that explains the reason why the + * prompt was blocked. This field is not supported in Gemini API. */ @JsonProperty("blockReasonMessage") public abstract Builder blockReasonMessage(String blockReasonMessage); @@ -105,7 +113,8 @@ public Builder blockReason(String blockReason) { /** * Setter for safetyRatings. * - *

safetyRatings: Output only. Safety ratings. + *

safetyRatings: Output only. A list of safety ratings for the prompt. There is one rating + * per category. */ @JsonProperty("safetyRatings") public abstract Builder safetyRatings(List safetyRatings); @@ -113,7 +122,8 @@ public Builder blockReason(String blockReason) { /** * Setter for safetyRatings. * - *

safetyRatings: Output only. Safety ratings. + *

safetyRatings: Output only. A list of safety ratings for the prompt. There is one rating + * per category. */ public Builder safetyRatings(SafetyRating... safetyRatings) { return safetyRatings(Arrays.asList(safetyRatings)); @@ -122,7 +132,8 @@ public Builder safetyRatings(SafetyRating... safetyRatings) { /** * Setter for safetyRatings builder. * - *

safetyRatings: Output only. Safety ratings. + *

safetyRatings: Output only. A list of safety ratings for the prompt. There is one rating + * per category. */ public Builder safetyRatings(SafetyRating.Builder... safetyRatingsBuilders) { return safetyRatings( @@ -135,6 +146,7 @@ public Builder safetyRatings(SafetyRating.Builder... safetyRatingsBuilders) { } /** Deserializes a JSON string to a GenerateContentResponsePromptFeedback object. */ + @ExcludeFromGeneratedCoverageReport public static GenerateContentResponsePromptFeedback fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, GenerateContentResponsePromptFeedback.class); } diff --git a/src/main/java/com/google/genai/types/GenerateContentResponseUsageMetadata.java b/src/main/java/com/google/genai/types/GenerateContentResponseUsageMetadata.java index a268283e132..2a008442e5d 100644 --- a/src/main/java/com/google/genai/types/GenerateContentResponseUsageMetadata.java +++ b/src/main/java/com/google/genai/types/GenerateContentResponseUsageMetadata.java @@ -30,7 +30,7 @@ import java.util.List; import java.util.Optional; -/** Usage metadata about response(s). */ +/** Usage metadata about response(s). This data type is not supported in Gemini API. */ @AutoValue @JsonDeserialize(builder = GenerateContentResponseUsageMetadata.Builder.class) public abstract class GenerateContentResponseUsageMetadata extends JsonSerializable { @@ -85,6 +85,7 @@ public abstract class GenerateContentResponseUsageMetadata extends JsonSerializa public abstract Optional trafficType(); /** Instantiates a builder for GenerateContentResponseUsageMetadata. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_GenerateContentResponseUsageMetadata.Builder(); } @@ -323,6 +324,7 @@ public Builder trafficType(String trafficType) { } /** Deserializes a JSON string to a GenerateContentResponseUsageMetadata object. */ + @ExcludeFromGeneratedCoverageReport public static GenerateContentResponseUsageMetadata fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, GenerateContentResponseUsageMetadata.class); } diff --git a/src/main/java/com/google/genai/types/GenerateImagesConfig.java b/src/main/java/com/google/genai/types/GenerateImagesConfig.java index eda36d1880c..0a743f91fd5 100644 --- a/src/main/java/com/google/genai/types/GenerateImagesConfig.java +++ b/src/main/java/com/google/genai/types/GenerateImagesConfig.java @@ -24,6 +24,7 @@ import com.google.auto.value.AutoValue; import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.genai.JsonSerializable; +import java.util.Map; import java.util.Optional; /** The config for generating an images. */ @@ -104,6 +105,10 @@ public abstract class GenerateImagesConfig extends JsonSerializable { @JsonProperty("addWatermark") public abstract Optional addWatermark(); + /** User specified labels to track billing usage. */ + @JsonProperty("labels") + public abstract Optional> labels(); + /** * The size of the largest dimension of the generated image. Supported sizes are 1K and 2K (not * supported for Imagen 3 models). @@ -116,6 +121,7 @@ public abstract class GenerateImagesConfig extends JsonSerializable { public abstract Optional enhancePrompt(); /** Instantiates a builder for GenerateImagesConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_GenerateImagesConfig.Builder(); } @@ -327,6 +333,14 @@ public Builder language(String language) { @JsonProperty("addWatermark") public abstract Builder addWatermark(boolean addWatermark); + /** + * Setter for labels. + * + *

labels: User specified labels to track billing usage. + */ + @JsonProperty("labels") + public abstract Builder labels(Map labels); + /** * Setter for imageSize. * @@ -348,6 +362,7 @@ public Builder language(String language) { } /** Deserializes a JSON string to a GenerateImagesConfig object. */ + @ExcludeFromGeneratedCoverageReport public static GenerateImagesConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, GenerateImagesConfig.class); } diff --git a/src/main/java/com/google/genai/types/GenerateImagesParameters.java b/src/main/java/com/google/genai/types/GenerateImagesParameters.java index 4810d5c730e..80fef944455 100644 --- a/src/main/java/com/google/genai/types/GenerateImagesParameters.java +++ b/src/main/java/com/google/genai/types/GenerateImagesParameters.java @@ -47,6 +47,7 @@ public abstract class GenerateImagesParameters extends JsonSerializable { public abstract Optional config(); /** Instantiates a builder for GenerateImagesParameters. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_GenerateImagesParameters.Builder(); } @@ -101,6 +102,7 @@ public Builder config(GenerateImagesConfig.Builder configBuilder) { } /** Deserializes a JSON string to a GenerateImagesParameters object. */ + @ExcludeFromGeneratedCoverageReport public static GenerateImagesParameters fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, GenerateImagesParameters.class); } diff --git a/src/main/java/com/google/genai/types/GenerateImagesResponse.java b/src/main/java/com/google/genai/types/GenerateImagesResponse.java index 0cb23e2888e..f3126641b40 100644 --- a/src/main/java/com/google/genai/types/GenerateImagesResponse.java +++ b/src/main/java/com/google/genai/types/GenerateImagesResponse.java @@ -33,6 +33,10 @@ @AutoValue @JsonDeserialize(builder = GenerateImagesResponse.Builder.class) public abstract class GenerateImagesResponse extends JsonSerializable { + /** Used to retain the full HTTP response. */ + @JsonProperty("sdkHttpResponse") + public abstract Optional sdkHttpResponse(); + /** List of generated images. */ @JsonProperty("generatedImages") public abstract Optional> generatedImages(); @@ -45,6 +49,7 @@ public abstract class GenerateImagesResponse extends JsonSerializable { public abstract Optional positivePromptSafetyAttributes(); /** Instantiates a builder for GenerateImagesResponse. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_GenerateImagesResponse.Builder(); } @@ -61,6 +66,23 @@ private static Builder create() { return new AutoValue_GenerateImagesResponse.Builder(); } + /** + * Setter for sdkHttpResponse. + * + *

sdkHttpResponse: Used to retain the full HTTP response. + */ + @JsonProperty("sdkHttpResponse") + public abstract Builder sdkHttpResponse(HttpResponse sdkHttpResponse); + + /** + * Setter for sdkHttpResponse builder. + * + *

sdkHttpResponse: Used to retain the full HTTP response. + */ + public Builder sdkHttpResponse(HttpResponse.Builder sdkHttpResponseBuilder) { + return sdkHttpResponse(sdkHttpResponseBuilder.build()); + } + /** * Setter for generatedImages. * @@ -115,6 +137,7 @@ public Builder positivePromptSafetyAttributes( } /** Deserializes a JSON string to a GenerateImagesResponse object. */ + @ExcludeFromGeneratedCoverageReport public static GenerateImagesResponse fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, GenerateImagesResponse.class); } diff --git a/src/main/java/com/google/genai/types/GenerateVideosConfig.java b/src/main/java/com/google/genai/types/GenerateVideosConfig.java index 950d8416889..618c1fcf298 100644 --- a/src/main/java/com/google/genai/types/GenerateVideosConfig.java +++ b/src/main/java/com/google/genai/types/GenerateVideosConfig.java @@ -18,12 +18,16 @@ package com.google.genai.types; +import static com.google.common.collect.ImmutableList.toImmutableList; + import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.google.auto.value.AutoValue; import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.genai.JsonSerializable; +import java.util.Arrays; +import java.util.List; import java.util.Optional; /** Configuration for generating videos. */ @@ -79,10 +83,7 @@ public abstract class GenerateVideosConfig extends JsonSerializable { @JsonProperty("pubsubTopic") public abstract Optional pubsubTopic(); - /** - * Optional field in addition to the text content. Negative prompts can be explicitly stated here - * to help generate the video. - */ + /** Explicitly state what should not be included in the generated videos. */ @JsonProperty("negativePrompt") public abstract Optional negativePrompt(); @@ -101,11 +102,25 @@ public abstract class GenerateVideosConfig extends JsonSerializable { @JsonProperty("lastFrame") public abstract Optional lastFrame(); + /** + * The images to use as the references to generate the videos. If this field is provided, the text + * prompt field must also be provided. The image, video, or last_frame field are not supported. + * Each image must be associated with a type. Veo 2 supports up to 3 asset images *or* 1 style + * image. + */ + @JsonProperty("referenceImages") + public abstract Optional> referenceImages(); + + /** The mask to use for generating videos. */ + @JsonProperty("mask") + public abstract Optional mask(); + /** Compression quality of the generated videos. */ @JsonProperty("compressionQuality") public abstract Optional compressionQuality(); /** Instantiates a builder for GenerateVideosConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_GenerateVideosConfig.Builder(); } @@ -218,8 +233,7 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { /** * Setter for negativePrompt. * - *

negativePrompt: Optional field in addition to the text content. Negative prompts can be - * explicitly stated here to help generate the video. + *

negativePrompt: Explicitly state what should not be included in the generated videos. */ @JsonProperty("negativePrompt") public abstract Builder negativePrompt(String negativePrompt); @@ -259,6 +273,62 @@ public Builder lastFrame(Image.Builder lastFrameBuilder) { return lastFrame(lastFrameBuilder.build()); } + /** + * Setter for referenceImages. + * + *

referenceImages: The images to use as the references to generate the videos. If this field + * is provided, the text prompt field must also be provided. The image, video, or last_frame + * field are not supported. Each image must be associated with a type. Veo 2 supports up to 3 + * asset images *or* 1 style image. + */ + @JsonProperty("referenceImages") + public abstract Builder referenceImages(List referenceImages); + + /** + * Setter for referenceImages. + * + *

referenceImages: The images to use as the references to generate the videos. If this field + * is provided, the text prompt field must also be provided. The image, video, or last_frame + * field are not supported. Each image must be associated with a type. Veo 2 supports up to 3 + * asset images *or* 1 style image. + */ + public Builder referenceImages(VideoGenerationReferenceImage... referenceImages) { + return referenceImages(Arrays.asList(referenceImages)); + } + + /** + * Setter for referenceImages builder. + * + *

referenceImages: The images to use as the references to generate the videos. If this field + * is provided, the text prompt field must also be provided. The image, video, or last_frame + * field are not supported. Each image must be associated with a type. Veo 2 supports up to 3 + * asset images *or* 1 style image. + */ + public Builder referenceImages( + VideoGenerationReferenceImage.Builder... referenceImagesBuilders) { + return referenceImages( + Arrays.asList(referenceImagesBuilders).stream() + .map(VideoGenerationReferenceImage.Builder::build) + .collect(toImmutableList())); + } + + /** + * Setter for mask. + * + *

mask: The mask to use for generating videos. + */ + @JsonProperty("mask") + public abstract Builder mask(VideoGenerationMask mask); + + /** + * Setter for mask builder. + * + *

mask: The mask to use for generating videos. + */ + public Builder mask(VideoGenerationMask.Builder maskBuilder) { + return mask(maskBuilder.build()); + } + /** * Setter for compressionQuality. * @@ -291,6 +361,7 @@ public Builder compressionQuality(String compressionQuality) { } /** Deserializes a JSON string to a GenerateVideosConfig object. */ + @ExcludeFromGeneratedCoverageReport public static GenerateVideosConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, GenerateVideosConfig.class); } diff --git a/src/main/java/com/google/genai/types/GenerateVideosOperation.java b/src/main/java/com/google/genai/types/GenerateVideosOperation.java index c042c79a6fe..cf93a00372a 100644 --- a/src/main/java/com/google/genai/types/GenerateVideosOperation.java +++ b/src/main/java/com/google/genai/types/GenerateVideosOperation.java @@ -20,49 +20,38 @@ import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.google.auto.value.AutoValue; import com.google.genai.JsonSerializable; +import com.google.genai.OperationsConverters; import java.util.Map; import java.util.Optional; /** A video generation operation. */ @AutoValue @JsonDeserialize(builder = GenerateVideosOperation.Builder.class) -public abstract class GenerateVideosOperation extends JsonSerializable { - /** - * The server-assigned name, which is only unique within the same service that originally returns - * it. If you use the default HTTP mapping, the `name` should be a resource name ending with - * `operations/{unique_id}`. - */ - @JsonProperty("name") - public abstract Optional name(); - - /** - * Service-specific metadata associated with the operation. It typically contains progress - * information and common metadata such as create time. Some services might not provide such - * metadata. Any method that returns a long-running operation should document the metadata type, - * if any. - */ - @JsonProperty("metadata") - public abstract Optional> metadata(); - - /** - * If the value is `false`, it means the operation is still in progress. If `true`, the operation - * is completed, and either `error` or `response` is available. - */ - @JsonProperty("done") - public abstract Optional done(); - - /** The error result of the operation in case of failure or cancellation. */ - @JsonProperty("error") - public abstract Optional> error(); - +public abstract class GenerateVideosOperation + extends Operation { /** The generated videos. */ @JsonProperty("response") + @Override public abstract Optional response(); + @Override + public GenerateVideosOperation fromApiResponse(JsonNode apiResponse, boolean isVertexAi) { + OperationsConverters converter = new OperationsConverters(null); + JsonNode response; + if (isVertexAi) { + response = converter.generateVideosOperationFromVertex(apiResponse, null); + } else { + response = converter.generateVideosOperationFromMldev(apiResponse, null); + } + return JsonSerializable.fromJsonNode(response, GenerateVideosOperation.class); + } + /** Instantiates a builder for GenerateVideosOperation. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_GenerateVideosOperation.Builder(); } @@ -138,6 +127,7 @@ public Builder response(GenerateVideosResponse.Builder responseBuilder) { } /** Deserializes a JSON string to a GenerateVideosOperation object. */ + @ExcludeFromGeneratedCoverageReport public static GenerateVideosOperation fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, GenerateVideosOperation.class); } diff --git a/src/main/java/com/google/genai/types/GenerateVideosParameters.java b/src/main/java/com/google/genai/types/GenerateVideosParameters.java index 3382b826425..56cbf22a145 100644 --- a/src/main/java/com/google/genai/types/GenerateVideosParameters.java +++ b/src/main/java/com/google/genai/types/GenerateVideosParameters.java @@ -38,23 +38,34 @@ public abstract class GenerateVideosParameters extends JsonSerializable { @JsonProperty("model") public abstract Optional model(); - /** The text prompt for generating the videos. Optional for image to video use cases. */ + /** The text prompt for generating the videos. Optional if image or video is provided. */ @JsonProperty("prompt") public abstract Optional prompt(); - /** The input image for generating the videos. Optional if prompt or video is provided. */ + /** + * The input image for generating the videos. Optional if prompt is provided. Not allowed if video + * is provided. + */ @JsonProperty("image") public abstract Optional image(); - /** The input video for video extension use cases. Optional if prompt or image is provided. */ + /** + * The input video for video extension use cases. Optional if prompt is provided. Not allowed if + * image is provided. + */ @JsonProperty("video") public abstract Optional

prompt: The text prompt for generating the videos. Optional for image to video use cases. + *

prompt: The text prompt for generating the videos. Optional if image or video is provided. */ @JsonProperty("prompt") public abstract Builder prompt(String prompt); @@ -91,7 +102,8 @@ private static Builder create() { /** * Setter for image. * - *

image: The input image for generating the videos. Optional if prompt or video is provided. + *

image: The input image for generating the videos. Optional if prompt is provided. Not + * allowed if video is provided. */ @JsonProperty("image") public abstract Builder image(Image image); @@ -99,7 +111,8 @@ private static Builder create() { /** * Setter for image builder. * - *

image: The input image for generating the videos. Optional if prompt or video is provided. + *

image: The input image for generating the videos. Optional if prompt is provided. Not + * allowed if video is provided. */ public Builder image(Image.Builder imageBuilder) { return image(imageBuilder.build()); @@ -108,8 +121,8 @@ public Builder image(Image.Builder imageBuilder) { /** * Setter for video. * - *

video: The input video for video extension use cases. Optional if prompt or image is - * provided. + *

video: The input video for video extension use cases. Optional if prompt is provided. Not + * allowed if image is provided. */ @JsonProperty("video") public abstract Builder video(Video video); @@ -117,13 +130,30 @@ public Builder image(Image.Builder imageBuilder) { /** * Setter for video builder. * - *

video: The input video for video extension use cases. Optional if prompt or image is - * provided. + *

video: The input video for video extension use cases. Optional if prompt is provided. Not + * allowed if image is provided. */ public Builder video(Video.Builder videoBuilder) { return video(videoBuilder.build()); } + /** + * Setter for source. + * + *

source: A set of source input(s) for video generation. + */ + @JsonProperty("source") + public abstract Builder source(GenerateVideosSource source); + + /** + * Setter for source builder. + * + *

source: A set of source input(s) for video generation. + */ + public Builder source(GenerateVideosSource.Builder sourceBuilder) { + return source(sourceBuilder.build()); + } + /** * Setter for config. * @@ -145,6 +175,7 @@ public Builder config(GenerateVideosConfig.Builder configBuilder) { } /** Deserializes a JSON string to a GenerateVideosParameters object. */ + @ExcludeFromGeneratedCoverageReport public static GenerateVideosParameters fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, GenerateVideosParameters.class); } diff --git a/src/main/java/com/google/genai/types/GenerateVideosResponse.java b/src/main/java/com/google/genai/types/GenerateVideosResponse.java index 69027d743da..258ed0a7603 100644 --- a/src/main/java/com/google/genai/types/GenerateVideosResponse.java +++ b/src/main/java/com/google/genai/types/GenerateVideosResponse.java @@ -46,6 +46,7 @@ public abstract class GenerateVideosResponse extends JsonSerializable { public abstract Optional> raiMediaFilteredReasons(); /** Instantiates a builder for GenerateVideosResponse. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_GenerateVideosResponse.Builder(); } @@ -120,6 +121,7 @@ public Builder raiMediaFilteredReasons(String... raiMediaFilteredReasons) { } /** Deserializes a JSON string to a GenerateVideosResponse object. */ + @ExcludeFromGeneratedCoverageReport public static GenerateVideosResponse fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, GenerateVideosResponse.class); } diff --git a/src/main/java/com/google/genai/types/GenerateVideosSource.java b/src/main/java/com/google/genai/types/GenerateVideosSource.java new file mode 100644 index 00000000000..659ce4ede36 --- /dev/null +++ b/src/main/java/com/google/genai/types/GenerateVideosSource.java @@ -0,0 +1,122 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Auto-generated code. Do not edit. + +package com.google.genai.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.google.auto.value.AutoValue; +import com.google.genai.JsonSerializable; +import java.util.Optional; + +/** A set of source input(s) for video generation. */ +@AutoValue +@JsonDeserialize(builder = GenerateVideosSource.Builder.class) +public abstract class GenerateVideosSource extends JsonSerializable { + /** The text prompt for generating the videos. Optional if image or video is provided. */ + @JsonProperty("prompt") + public abstract Optional prompt(); + + /** + * The input image for generating the videos. Optional if prompt is provided. Not allowed if video + * is provided. + */ + @JsonProperty("image") + public abstract Optional image(); + + /** + * The input video for video extension use cases. Optional if prompt is provided. Not allowed if + * image is provided. + */ + @JsonProperty("video") + public abstract Optional

prompt: The text prompt for generating the videos. Optional if image or video is provided. + */ + @JsonProperty("prompt") + public abstract Builder prompt(String prompt); + + /** + * Setter for image. + * + *

image: The input image for generating the videos. Optional if prompt is provided. Not + * allowed if video is provided. + */ + @JsonProperty("image") + public abstract Builder image(Image image); + + /** + * Setter for image builder. + * + *

image: The input image for generating the videos. Optional if prompt is provided. Not + * allowed if video is provided. + */ + public Builder image(Image.Builder imageBuilder) { + return image(imageBuilder.build()); + } + + /** + * Setter for video. + * + *

video: The input video for video extension use cases. Optional if prompt is provided. Not + * allowed if image is provided. + */ + @JsonProperty("video") + public abstract Builder video(Video video); + + /** + * Setter for video builder. + * + *

video: The input video for video extension use cases. Optional if prompt is provided. Not + * allowed if image is provided. + */ + public Builder video(Video.Builder videoBuilder) { + return video(videoBuilder.build()); + } + + public abstract GenerateVideosSource build(); + } + + /** Deserializes a JSON string to a GenerateVideosSource object. */ + @ExcludeFromGeneratedCoverageReport + public static GenerateVideosSource fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, GenerateVideosSource.class); + } +} diff --git a/src/main/java/com/google/genai/types/GeneratedImage.java b/src/main/java/com/google/genai/types/GeneratedImage.java index bef81420d64..07ac595b010 100644 --- a/src/main/java/com/google/genai/types/GeneratedImage.java +++ b/src/main/java/com/google/genai/types/GeneratedImage.java @@ -46,6 +46,7 @@ public abstract class GeneratedImage extends JsonSerializable { public abstract Optional enhancedPrompt(); /** Instantiates a builder for GeneratedImage. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_GeneratedImage.Builder(); } @@ -120,6 +121,7 @@ public Builder safetyAttributes(SafetyAttributes.Builder safetyAttributesBuilder } /** Deserializes a JSON string to a GeneratedImage object. */ + @ExcludeFromGeneratedCoverageReport public static GeneratedImage fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, GeneratedImage.class); } diff --git a/src/main/java/com/google/genai/types/GeneratedImageMask.java b/src/main/java/com/google/genai/types/GeneratedImageMask.java new file mode 100644 index 00000000000..3adce259be2 --- /dev/null +++ b/src/main/java/com/google/genai/types/GeneratedImageMask.java @@ -0,0 +1,116 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Auto-generated code. Do not edit. + +package com.google.genai.types; + +import static com.google.common.collect.ImmutableList.toImmutableList; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.google.auto.value.AutoValue; +import com.google.genai.JsonSerializable; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +/** A generated image mask. */ +@AutoValue +@JsonDeserialize(builder = GeneratedImageMask.Builder.class) +public abstract class GeneratedImageMask extends JsonSerializable { + /** The generated image mask. */ + @JsonProperty("mask") + public abstract Optional mask(); + + /** The detected entities on the segmented area. */ + @JsonProperty("labels") + public abstract Optional> labels(); + + /** Instantiates a builder for GeneratedImageMask. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_GeneratedImageMask.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for GeneratedImageMask. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `GeneratedImageMask.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_GeneratedImageMask.Builder(); + } + + /** + * Setter for mask. + * + *

mask: The generated image mask. + */ + @JsonProperty("mask") + public abstract Builder mask(Image mask); + + /** + * Setter for mask builder. + * + *

mask: The generated image mask. + */ + public Builder mask(Image.Builder maskBuilder) { + return mask(maskBuilder.build()); + } + + /** + * Setter for labels. + * + *

labels: The detected entities on the segmented area. + */ + @JsonProperty("labels") + public abstract Builder labels(List labels); + + /** + * Setter for labels. + * + *

labels: The detected entities on the segmented area. + */ + public Builder labels(EntityLabel... labels) { + return labels(Arrays.asList(labels)); + } + + /** + * Setter for labels builder. + * + *

labels: The detected entities on the segmented area. + */ + public Builder labels(EntityLabel.Builder... labelsBuilders) { + return labels( + Arrays.asList(labelsBuilders).stream() + .map(EntityLabel.Builder::build) + .collect(toImmutableList())); + } + + public abstract GeneratedImageMask build(); + } + + /** Deserializes a JSON string to a GeneratedImageMask object. */ + @ExcludeFromGeneratedCoverageReport + public static GeneratedImageMask fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, GeneratedImageMask.class); + } +} diff --git a/src/main/java/com/google/genai/types/GeneratedVideo.java b/src/main/java/com/google/genai/types/GeneratedVideo.java index 467d15efc77..ce45662c3d1 100644 --- a/src/main/java/com/google/genai/types/GeneratedVideo.java +++ b/src/main/java/com/google/genai/types/GeneratedVideo.java @@ -34,6 +34,7 @@ public abstract class GeneratedVideo extends JsonSerializable { public abstract Optional

audioTimestamp: Optional. If enabled, audio timestamp will be included in the request to - * the model. + * the model. This field is not supported in Gemini API. */ @JsonProperty("audioTimestamp") public abstract Builder audioTimestamp(boolean audioTimestamp); @@ -204,7 +218,7 @@ public Builder modelSelectionConfig(ModelSelectionConfig.Builder modelSelectionC * Setter for enableAffectiveDialog. * *

enableAffectiveDialog: Optional. If enabled, the model will detect emotions and adapt its - * responses accordingly. + * responses accordingly. This field is not supported in Gemini API. */ @JsonProperty("enableAffectiveDialog") public abstract Builder enableAffectiveDialog(boolean enableAffectiveDialog); @@ -396,7 +410,7 @@ public Builder responseSchema(Schema.Builder responseSchemaBuilder) { /** * Setter for routingConfig. * - *

routingConfig: Optional. Routing configuration. + *

routingConfig: Optional. Routing configuration. This field is not supported in Gemini API. */ @JsonProperty("routingConfig") public abstract Builder routingConfig(GenerationConfigRoutingConfig routingConfig); @@ -404,7 +418,7 @@ public Builder responseSchema(Schema.Builder responseSchemaBuilder) { /** * Setter for routingConfig builder. * - *

routingConfig: Optional. Routing configuration. + *

routingConfig: Optional. Routing configuration. This field is not supported in Gemini API. */ public Builder routingConfig(GenerationConfigRoutingConfig.Builder routingConfigBuilder) { return routingConfig(routingConfigBuilder.build()); @@ -467,7 +481,7 @@ public Builder stopSequences(String... stopSequences) { * field is set for models that don't support thinking. */ @JsonProperty("thinkingConfig") - public abstract Builder thinkingConfig(GenerationConfigThinkingConfig thinkingConfig); + public abstract Builder thinkingConfig(ThinkingConfig thinkingConfig); /** * Setter for thinkingConfig builder. @@ -475,7 +489,7 @@ public Builder stopSequences(String... stopSequences) { *

thinkingConfig: Optional. Config for thinking features. An error will be returned if this * field is set for models that don't support thinking. */ - public Builder thinkingConfig(GenerationConfigThinkingConfig.Builder thinkingConfigBuilder) { + public Builder thinkingConfig(ThinkingConfig.Builder thinkingConfigBuilder) { return thinkingConfig(thinkingConfigBuilder.build()); } @@ -495,10 +509,20 @@ public Builder thinkingConfig(GenerationConfigThinkingConfig.Builder thinkingCon @JsonProperty("topP") public abstract Builder topP(Float topP); + /** + * Setter for enableEnhancedCivicAnswers. + * + *

enableEnhancedCivicAnswers: Optional. Enables enhanced civic answers. It may not be + * available for all models. This field is not supported in Vertex AI. + */ + @JsonProperty("enableEnhancedCivicAnswers") + public abstract Builder enableEnhancedCivicAnswers(boolean enableEnhancedCivicAnswers); + public abstract GenerationConfig build(); } /** Deserializes a JSON string to a GenerationConfig object. */ + @ExcludeFromGeneratedCoverageReport public static GenerationConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, GenerationConfig.class); } diff --git a/src/main/java/com/google/genai/types/GenerationConfigRoutingConfig.java b/src/main/java/com/google/genai/types/GenerationConfigRoutingConfig.java index a147ab529a7..7faa31c31dc 100644 --- a/src/main/java/com/google/genai/types/GenerationConfigRoutingConfig.java +++ b/src/main/java/com/google/genai/types/GenerationConfigRoutingConfig.java @@ -25,7 +25,10 @@ import com.google.genai.JsonSerializable; import java.util.Optional; -/** The configuration for routing the request to a specific model. */ +/** + * The configuration for routing the request to a specific model. This data type is not supported in + * Gemini API. + */ @AutoValue @JsonDeserialize(builder = GenerationConfigRoutingConfig.Builder.class) public abstract class GenerationConfigRoutingConfig extends JsonSerializable { @@ -38,6 +41,7 @@ public abstract class GenerationConfigRoutingConfig extends JsonSerializable { public abstract Optional manualMode(); /** Instantiates a builder for GenerationConfigRoutingConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_GenerationConfigRoutingConfig.Builder(); } @@ -95,6 +99,7 @@ public Builder manualMode( } /** Deserializes a JSON string to a GenerationConfigRoutingConfig object. */ + @ExcludeFromGeneratedCoverageReport public static GenerationConfigRoutingConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, GenerationConfigRoutingConfig.class); } diff --git a/src/main/java/com/google/genai/types/GenerationConfigRoutingConfigAutoRoutingMode.java b/src/main/java/com/google/genai/types/GenerationConfigRoutingConfigAutoRoutingMode.java index 8031269346e..da4a3c419e6 100644 --- a/src/main/java/com/google/genai/types/GenerationConfigRoutingConfigAutoRoutingMode.java +++ b/src/main/java/com/google/genai/types/GenerationConfigRoutingConfigAutoRoutingMode.java @@ -28,7 +28,8 @@ /** * When automated routing is specified, the routing will be determined by the pretrained routing - * model and customer provided model routing preference. + * model and customer provided model routing preference. This data type is not supported in Gemini + * API. */ @AutoValue @JsonDeserialize(builder = GenerationConfigRoutingConfigAutoRoutingMode.Builder.class) @@ -38,6 +39,7 @@ public abstract class GenerationConfigRoutingConfigAutoRoutingMode extends JsonS public abstract Optional modelRoutingPreference(); /** Instantiates a builder for GenerationConfigRoutingConfigAutoRoutingMode. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_GenerationConfigRoutingConfigAutoRoutingMode.Builder(); } @@ -89,6 +91,7 @@ public Builder modelRoutingPreference(String modelRoutingPreference) { } /** Deserializes a JSON string to a GenerationConfigRoutingConfigAutoRoutingMode object. */ + @ExcludeFromGeneratedCoverageReport public static GenerationConfigRoutingConfigAutoRoutingMode fromJson(String jsonString) { return JsonSerializable.fromJsonString( jsonString, GenerationConfigRoutingConfigAutoRoutingMode.class); diff --git a/src/main/java/com/google/genai/types/GenerationConfigRoutingConfigManualRoutingMode.java b/src/main/java/com/google/genai/types/GenerationConfigRoutingConfigManualRoutingMode.java index ed09fb73e5b..0c08420fc00 100644 --- a/src/main/java/com/google/genai/types/GenerationConfigRoutingConfigManualRoutingMode.java +++ b/src/main/java/com/google/genai/types/GenerationConfigRoutingConfigManualRoutingMode.java @@ -25,7 +25,10 @@ import com.google.genai.JsonSerializable; import java.util.Optional; -/** When manual routing is set, the specified model will be used directly. */ +/** + * When manual routing is set, the specified model will be used directly. This data type is not + * supported in Gemini API. + */ @AutoValue @JsonDeserialize(builder = GenerationConfigRoutingConfigManualRoutingMode.Builder.class) public abstract class GenerationConfigRoutingConfigManualRoutingMode extends JsonSerializable { @@ -37,6 +40,7 @@ public abstract class GenerationConfigRoutingConfigManualRoutingMode extends Jso public abstract Optional modelName(); /** Instantiates a builder for GenerationConfigRoutingConfigManualRoutingMode. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_GenerationConfigRoutingConfigManualRoutingMode.Builder(); } @@ -69,6 +73,7 @@ private static Builder create() { } /** Deserializes a JSON string to a GenerationConfigRoutingConfigManualRoutingMode object. */ + @ExcludeFromGeneratedCoverageReport public static GenerationConfigRoutingConfigManualRoutingMode fromJson(String jsonString) { return JsonSerializable.fromJsonString( jsonString, GenerationConfigRoutingConfigManualRoutingMode.class); diff --git a/src/main/java/com/google/genai/types/GenerationConfigThinkingConfig.java b/src/main/java/com/google/genai/types/GenerationConfigThinkingConfig.java deleted file mode 100644 index 115bf7cfb76..00000000000 --- a/src/main/java/com/google/genai/types/GenerationConfigThinkingConfig.java +++ /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 - * - * 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. - */ - -// Auto-generated code. Do not edit. - -package com.google.genai.types; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.google.auto.value.AutoValue; -import com.google.genai.JsonSerializable; -import java.util.Optional; - -/** Config for thinking features. */ -@AutoValue -@JsonDeserialize(builder = GenerationConfigThinkingConfig.Builder.class) -public abstract class GenerationConfigThinkingConfig extends JsonSerializable { - /** - * Optional. Indicates whether to include thoughts in the response. If true, thoughts are returned - * only when available. - */ - @JsonProperty("includeThoughts") - public abstract Optional includeThoughts(); - - /** - * Optional. Indicates the thinking budget in tokens. This is only applied when enable_thinking is - * true. - */ - @JsonProperty("thinkingBudget") - public abstract Optional thinkingBudget(); - - /** Instantiates a builder for GenerationConfigThinkingConfig. */ - public static Builder builder() { - return new AutoValue_GenerationConfigThinkingConfig.Builder(); - } - - /** Creates a builder with the same values as this instance. */ - public abstract Builder toBuilder(); - - /** Builder for GenerationConfigThinkingConfig. */ - @AutoValue.Builder - public abstract static class Builder { - /** - * For internal usage. Please use `GenerationConfigThinkingConfig.builder()` for instantiation. - */ - @JsonCreator - private static Builder create() { - return new AutoValue_GenerationConfigThinkingConfig.Builder(); - } - - /** - * Setter for includeThoughts. - * - *

includeThoughts: Optional. Indicates whether to include thoughts in the response. If true, - * thoughts are returned only when available. - */ - @JsonProperty("includeThoughts") - public abstract Builder includeThoughts(boolean includeThoughts); - - /** - * Setter for thinkingBudget. - * - *

thinkingBudget: Optional. Indicates the thinking budget in tokens. This is only applied - * when enable_thinking is true. - */ - @JsonProperty("thinkingBudget") - public abstract Builder thinkingBudget(Integer thinkingBudget); - - public abstract GenerationConfigThinkingConfig build(); - } - - /** Deserializes a JSON string to a GenerationConfigThinkingConfig object. */ - public static GenerationConfigThinkingConfig fromJson(String jsonString) { - return JsonSerializable.fromJsonString(jsonString, GenerationConfigThinkingConfig.class); - } -} diff --git a/src/main/java/com/google/genai/types/GetBatchJobConfig.java b/src/main/java/com/google/genai/types/GetBatchJobConfig.java index 22245c5b2b3..b6c2898b467 100644 --- a/src/main/java/com/google/genai/types/GetBatchJobConfig.java +++ b/src/main/java/com/google/genai/types/GetBatchJobConfig.java @@ -34,6 +34,7 @@ public abstract class GetBatchJobConfig extends JsonSerializable { public abstract Optional httpOptions(); /** Instantiates a builder for GetBatchJobConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_GetBatchJobConfig.Builder(); } @@ -71,6 +72,7 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { } /** Deserializes a JSON string to a GetBatchJobConfig object. */ + @ExcludeFromGeneratedCoverageReport public static GetBatchJobConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, GetBatchJobConfig.class); } diff --git a/src/main/java/com/google/genai/types/GetBatchJobParameters.java b/src/main/java/com/google/genai/types/GetBatchJobParameters.java index 5da46bf67a9..5b03fabd91c 100644 --- a/src/main/java/com/google/genai/types/GetBatchJobParameters.java +++ b/src/main/java/com/google/genai/types/GetBatchJobParameters.java @@ -44,6 +44,7 @@ public abstract class GetBatchJobParameters extends JsonSerializable { public abstract Optional config(); /** Instantiates a builder for GetBatchJobParameters. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_GetBatchJobParameters.Builder(); } @@ -91,6 +92,7 @@ public Builder config(GetBatchJobConfig.Builder configBuilder) { } /** Deserializes a JSON string to a GetBatchJobParameters object. */ + @ExcludeFromGeneratedCoverageReport public static GetBatchJobParameters fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, GetBatchJobParameters.class); } diff --git a/src/main/java/com/google/genai/types/GetCachedContentConfig.java b/src/main/java/com/google/genai/types/GetCachedContentConfig.java index ddbb45b4192..2177442470f 100644 --- a/src/main/java/com/google/genai/types/GetCachedContentConfig.java +++ b/src/main/java/com/google/genai/types/GetCachedContentConfig.java @@ -34,6 +34,7 @@ public abstract class GetCachedContentConfig extends JsonSerializable { public abstract Optional httpOptions(); /** Instantiates a builder for GetCachedContentConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_GetCachedContentConfig.Builder(); } @@ -71,6 +72,7 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { } /** Deserializes a JSON string to a GetCachedContentConfig object. */ + @ExcludeFromGeneratedCoverageReport public static GetCachedContentConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, GetCachedContentConfig.class); } diff --git a/src/main/java/com/google/genai/types/GetCachedContentParameters.java b/src/main/java/com/google/genai/types/GetCachedContentParameters.java index 6c863c21c10..6111401c39d 100644 --- a/src/main/java/com/google/genai/types/GetCachedContentParameters.java +++ b/src/main/java/com/google/genai/types/GetCachedContentParameters.java @@ -40,6 +40,7 @@ public abstract class GetCachedContentParameters extends JsonSerializable { public abstract Optional config(); /** Instantiates a builder for GetCachedContentParameters. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_GetCachedContentParameters.Builder(); } @@ -85,6 +86,7 @@ public Builder config(GetCachedContentConfig.Builder configBuilder) { } /** Deserializes a JSON string to a GetCachedContentParameters object. */ + @ExcludeFromGeneratedCoverageReport public static GetCachedContentParameters fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, GetCachedContentParameters.class); } diff --git a/src/main/java/com/google/genai/types/GetFileConfig.java b/src/main/java/com/google/genai/types/GetFileConfig.java index 3b862ca4bdf..fca759df36e 100644 --- a/src/main/java/com/google/genai/types/GetFileConfig.java +++ b/src/main/java/com/google/genai/types/GetFileConfig.java @@ -34,6 +34,7 @@ public abstract class GetFileConfig extends JsonSerializable { public abstract Optional httpOptions(); /** Instantiates a builder for GetFileConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_GetFileConfig.Builder(); } @@ -71,6 +72,7 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { } /** Deserializes a JSON string to a GetFileConfig object. */ + @ExcludeFromGeneratedCoverageReport public static GetFileConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, GetFileConfig.class); } diff --git a/src/main/java/com/google/genai/types/GetFileParameters.java b/src/main/java/com/google/genai/types/GetFileParameters.java index ac5e79f9c11..459cbde93e0 100644 --- a/src/main/java/com/google/genai/types/GetFileParameters.java +++ b/src/main/java/com/google/genai/types/GetFileParameters.java @@ -40,6 +40,7 @@ public abstract class GetFileParameters extends JsonSerializable { public abstract Optional config(); /** Instantiates a builder for GetFileParameters. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_GetFileParameters.Builder(); } @@ -85,6 +86,7 @@ public Builder config(GetFileConfig.Builder configBuilder) { } /** Deserializes a JSON string to a GetFileParameters object. */ + @ExcludeFromGeneratedCoverageReport public static GetFileParameters fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, GetFileParameters.class); } diff --git a/src/main/java/com/google/genai/types/GetModelConfig.java b/src/main/java/com/google/genai/types/GetModelConfig.java index a3b1782bf67..e6a2c394202 100644 --- a/src/main/java/com/google/genai/types/GetModelConfig.java +++ b/src/main/java/com/google/genai/types/GetModelConfig.java @@ -34,6 +34,7 @@ public abstract class GetModelConfig extends JsonSerializable { public abstract Optional httpOptions(); /** Instantiates a builder for GetModelConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_GetModelConfig.Builder(); } @@ -71,6 +72,7 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { } /** Deserializes a JSON string to a GetModelConfig object. */ + @ExcludeFromGeneratedCoverageReport public static GetModelConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, GetModelConfig.class); } diff --git a/src/main/java/com/google/genai/types/GetModelParameters.java b/src/main/java/com/google/genai/types/GetModelParameters.java index ec5023eb780..3254b6d046e 100644 --- a/src/main/java/com/google/genai/types/GetModelParameters.java +++ b/src/main/java/com/google/genai/types/GetModelParameters.java @@ -40,6 +40,7 @@ public abstract class GetModelParameters extends JsonSerializable { public abstract Optional config(); /** Instantiates a builder for GetModelParameters. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_GetModelParameters.Builder(); } @@ -85,6 +86,7 @@ public Builder config(GetModelConfig.Builder configBuilder) { } /** Deserializes a JSON string to a GetModelParameters object. */ + @ExcludeFromGeneratedCoverageReport public static GetModelParameters fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, GetModelParameters.class); } diff --git a/src/main/java/com/google/genai/types/GetOperationConfig.java b/src/main/java/com/google/genai/types/GetOperationConfig.java index a4deb5b5e9f..9783d8bd0c4 100644 --- a/src/main/java/com/google/genai/types/GetOperationConfig.java +++ b/src/main/java/com/google/genai/types/GetOperationConfig.java @@ -34,6 +34,7 @@ public abstract class GetOperationConfig extends JsonSerializable { public abstract Optional httpOptions(); /** Instantiates a builder for GetOperationConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_GetOperationConfig.Builder(); } @@ -71,6 +72,7 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { } /** Deserializes a JSON string to a GetOperationConfig object. */ + @ExcludeFromGeneratedCoverageReport public static GetOperationConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, GetOperationConfig.class); } diff --git a/src/main/java/com/google/genai/types/GetOperationParameters.java b/src/main/java/com/google/genai/types/GetOperationParameters.java index d2f67f24815..46f1161d64d 100644 --- a/src/main/java/com/google/genai/types/GetOperationParameters.java +++ b/src/main/java/com/google/genai/types/GetOperationParameters.java @@ -40,6 +40,7 @@ public abstract class GetOperationParameters extends JsonSerializable { public abstract Optional config(); /** Instantiates a builder for GetOperationParameters. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_GetOperationParameters.Builder(); } @@ -85,6 +86,7 @@ public Builder config(GetOperationConfig.Builder configBuilder) { } /** Deserializes a JSON string to a GetOperationParameters object. */ + @ExcludeFromGeneratedCoverageReport public static GetOperationParameters fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, GetOperationParameters.class); } diff --git a/src/main/java/com/google/genai/types/GetTuningJobConfig.java b/src/main/java/com/google/genai/types/GetTuningJobConfig.java index 03981c4c9c3..a428ed86bea 100644 --- a/src/main/java/com/google/genai/types/GetTuningJobConfig.java +++ b/src/main/java/com/google/genai/types/GetTuningJobConfig.java @@ -34,6 +34,7 @@ public abstract class GetTuningJobConfig extends JsonSerializable { public abstract Optional httpOptions(); /** Instantiates a builder for GetTuningJobConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_GetTuningJobConfig.Builder(); } @@ -71,6 +72,7 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { } /** Deserializes a JSON string to a GetTuningJobConfig object. */ + @ExcludeFromGeneratedCoverageReport public static GetTuningJobConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, GetTuningJobConfig.class); } diff --git a/src/main/java/com/google/genai/types/GetTuningJobParameters.java b/src/main/java/com/google/genai/types/GetTuningJobParameters.java index 9890b40ccda..d23350bb6d8 100644 --- a/src/main/java/com/google/genai/types/GetTuningJobParameters.java +++ b/src/main/java/com/google/genai/types/GetTuningJobParameters.java @@ -40,6 +40,7 @@ public abstract class GetTuningJobParameters extends JsonSerializable { public abstract Optional config(); /** Instantiates a builder for GetTuningJobParameters. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_GetTuningJobParameters.Builder(); } @@ -85,6 +86,7 @@ public Builder config(GetTuningJobConfig.Builder configBuilder) { } /** Deserializes a JSON string to a GetTuningJobParameters object. */ + @ExcludeFromGeneratedCoverageReport public static GetTuningJobParameters fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, GetTuningJobParameters.class); } diff --git a/src/main/java/com/google/genai/types/GoogleMaps.java b/src/main/java/com/google/genai/types/GoogleMaps.java index 32db579761e..1a96cba400c 100644 --- a/src/main/java/com/google/genai/types/GoogleMaps.java +++ b/src/main/java/com/google/genai/types/GoogleMaps.java @@ -33,7 +33,12 @@ public abstract class GoogleMaps extends JsonSerializable { @JsonProperty("authConfig") public abstract Optional authConfig(); + /** Optional. If true, include the widget context token in the response. */ + @JsonProperty("enableWidget") + public abstract Optional enableWidget(); + /** Instantiates a builder for GoogleMaps. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_GoogleMaps.Builder(); } @@ -67,10 +72,19 @@ public Builder authConfig(AuthConfig.Builder authConfigBuilder) { return authConfig(authConfigBuilder.build()); } + /** + * Setter for enableWidget. + * + *

enableWidget: Optional. If true, include the widget context token in the response. + */ + @JsonProperty("enableWidget") + public abstract Builder enableWidget(boolean enableWidget); + public abstract GoogleMaps build(); } /** Deserializes a JSON string to a GoogleMaps object. */ + @ExcludeFromGeneratedCoverageReport public static GoogleMaps fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, GoogleMaps.class); } diff --git a/src/main/java/com/google/genai/types/GoogleRpcStatus.java b/src/main/java/com/google/genai/types/GoogleRpcStatus.java index 6672f496f51..18bc5b7dc15 100644 --- a/src/main/java/com/google/genai/types/GoogleRpcStatus.java +++ b/src/main/java/com/google/genai/types/GoogleRpcStatus.java @@ -33,7 +33,8 @@ * environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). * Each `Status` message contains three pieces of data: error code, error message, and error * details. You can find out more about this error model and how to work with it in the [API Design - * Guide](https://cloud.google.com/apis/design/errors). + * Guide](https://cloud.google.com/apis/design/errors). This data type is not supported in Gemini + * API. */ @AutoValue @JsonDeserialize(builder = GoogleRpcStatus.Builder.class) @@ -58,6 +59,7 @@ public abstract class GoogleRpcStatus extends JsonSerializable { public abstract Optional message(); /** Instantiates a builder for GoogleRpcStatus. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_GoogleRpcStatus.Builder(); } @@ -115,6 +117,7 @@ public Builder details(Map... details) { } /** Deserializes a JSON string to a GoogleRpcStatus object. */ + @ExcludeFromGeneratedCoverageReport public static GoogleRpcStatus fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, GoogleRpcStatus.class); } diff --git a/src/main/java/com/google/genai/types/GoogleSearch.java b/src/main/java/com/google/genai/types/GoogleSearch.java index 20551876923..506b437e19a 100644 --- a/src/main/java/com/google/genai/types/GoogleSearch.java +++ b/src/main/java/com/google/genai/types/GoogleSearch.java @@ -23,20 +23,30 @@ import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.google.auto.value.AutoValue; import com.google.genai.JsonSerializable; +import java.util.Arrays; +import java.util.List; import java.util.Optional; -/** Tool to support Google Search in Model. Powered by Google. */ +/** GoogleSearch tool type. Tool to support Google Search in Model. Powered by Google. */ @AutoValue @JsonDeserialize(builder = GoogleSearch.Builder.class) public abstract class GoogleSearch extends JsonSerializable { + /** + * Optional. List of domains to be excluded from the search results. The default limit is 2000 + * domains. Example: ["amazon.com", "facebook.com"]. This field is not supported in Gemini API. + */ + @JsonProperty("excludeDomains") + public abstract Optional> excludeDomains(); + /** * Optional. Filter search results to a specific time range. If customers set a start time, they - * must set an end time (and vice versa). + * must set an end time (and vice versa). This field is not supported in Vertex AI. */ @JsonProperty("timeRangeFilter") public abstract Optional timeRangeFilter(); /** Instantiates a builder for GoogleSearch. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_GoogleSearch.Builder(); } @@ -53,11 +63,33 @@ private static Builder create() { return new AutoValue_GoogleSearch.Builder(); } + /** + * Setter for excludeDomains. + * + *

excludeDomains: Optional. List of domains to be excluded from the search results. The + * default limit is 2000 domains. Example: ["amazon.com", "facebook.com"]. This field is not + * supported in Gemini API. + */ + @JsonProperty("excludeDomains") + public abstract Builder excludeDomains(List excludeDomains); + + /** + * Setter for excludeDomains. + * + *

excludeDomains: Optional. List of domains to be excluded from the search results. The + * default limit is 2000 domains. Example: ["amazon.com", "facebook.com"]. This field is not + * supported in Gemini API. + */ + public Builder excludeDomains(String... excludeDomains) { + return excludeDomains(Arrays.asList(excludeDomains)); + } + /** * Setter for timeRangeFilter. * *

timeRangeFilter: Optional. Filter search results to a specific time range. If customers - * set a start time, they must set an end time (and vice versa). + * set a start time, they must set an end time (and vice versa). This field is not supported in + * Vertex AI. */ @JsonProperty("timeRangeFilter") public abstract Builder timeRangeFilter(Interval timeRangeFilter); @@ -66,7 +98,8 @@ private static Builder create() { * Setter for timeRangeFilter builder. * *

timeRangeFilter: Optional. Filter search results to a specific time range. If customers - * set a start time, they must set an end time (and vice versa). + * set a start time, they must set an end time (and vice versa). This field is not supported in + * Vertex AI. */ public Builder timeRangeFilter(Interval.Builder timeRangeFilterBuilder) { return timeRangeFilter(timeRangeFilterBuilder.build()); @@ -76,6 +109,7 @@ public Builder timeRangeFilter(Interval.Builder timeRangeFilterBuilder) { } /** Deserializes a JSON string to a GoogleSearch object. */ + @ExcludeFromGeneratedCoverageReport public static GoogleSearch fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, GoogleSearch.class); } diff --git a/src/main/java/com/google/genai/types/GoogleSearchRetrieval.java b/src/main/java/com/google/genai/types/GoogleSearchRetrieval.java index 340db1046a8..019fd9c6794 100644 --- a/src/main/java/com/google/genai/types/GoogleSearchRetrieval.java +++ b/src/main/java/com/google/genai/types/GoogleSearchRetrieval.java @@ -34,6 +34,7 @@ public abstract class GoogleSearchRetrieval extends JsonSerializable { public abstract Optional dynamicRetrievalConfig(); /** Instantiates a builder for GoogleSearchRetrieval. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_GoogleSearchRetrieval.Builder(); } @@ -74,6 +75,7 @@ public Builder dynamicRetrievalConfig( } /** Deserializes a JSON string to a GoogleSearchRetrieval object. */ + @ExcludeFromGeneratedCoverageReport public static GoogleSearchRetrieval fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, GoogleSearchRetrieval.class); } diff --git a/src/main/java/com/google/genai/types/GoogleTypeDate.java b/src/main/java/com/google/genai/types/GoogleTypeDate.java index 30c45fd51b2..6acaadb531c 100644 --- a/src/main/java/com/google/genai/types/GoogleTypeDate.java +++ b/src/main/java/com/google/genai/types/GoogleTypeDate.java @@ -32,7 +32,7 @@ * day values. * A month and day, with a zero year (for example, an anniversary). * A year on its * own, with a zero month and a zero day. * A year and month, with a zero day (for example, a credit * card expiration date). Related types: * google.type.TimeOfDay * google.type.DateTime * - * google.protobuf.Timestamp + * google.protobuf.Timestamp. This data type is not supported in Gemini API. */ @AutoValue @JsonDeserialize(builder = GoogleTypeDate.Builder.class) @@ -53,6 +53,7 @@ public abstract class GoogleTypeDate extends JsonSerializable { public abstract Optional year(); /** Instantiates a builder for GoogleTypeDate. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_GoogleTypeDate.Builder(); } @@ -99,6 +100,7 @@ private static Builder create() { } /** Deserializes a JSON string to a GoogleTypeDate object. */ + @ExcludeFromGeneratedCoverageReport public static GoogleTypeDate fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, GoogleTypeDate.class); } diff --git a/src/main/java/com/google/genai/types/GroundingChunk.java b/src/main/java/com/google/genai/types/GroundingChunk.java index 2e6a2aa4c41..ff5e375cc67 100644 --- a/src/main/java/com/google/genai/types/GroundingChunk.java +++ b/src/main/java/com/google/genai/types/GroundingChunk.java @@ -29,7 +29,14 @@ @AutoValue @JsonDeserialize(builder = GroundingChunk.Builder.class) public abstract class GroundingChunk extends JsonSerializable { - /** Grounding chunk from context retrieved by the retrieval tools. */ + /** Grounding chunk from Google Maps. This field is not supported in Gemini API. */ + @JsonProperty("maps") + public abstract Optional maps(); + + /** + * Grounding chunk from context retrieved by the retrieval tools. This field is not supported in + * Gemini API. + */ @JsonProperty("retrievedContext") public abstract Optional retrievedContext(); @@ -38,6 +45,7 @@ public abstract class GroundingChunk extends JsonSerializable { public abstract Optional web(); /** Instantiates a builder for GroundingChunk. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_GroundingChunk.Builder(); } @@ -54,10 +62,28 @@ private static Builder create() { return new AutoValue_GroundingChunk.Builder(); } + /** + * Setter for maps. + * + *

maps: Grounding chunk from Google Maps. This field is not supported in Gemini API. + */ + @JsonProperty("maps") + public abstract Builder maps(GroundingChunkMaps maps); + + /** + * Setter for maps builder. + * + *

maps: Grounding chunk from Google Maps. This field is not supported in Gemini API. + */ + public Builder maps(GroundingChunkMaps.Builder mapsBuilder) { + return maps(mapsBuilder.build()); + } + /** * Setter for retrievedContext. * - *

retrievedContext: Grounding chunk from context retrieved by the retrieval tools. + *

retrievedContext: Grounding chunk from context retrieved by the retrieval tools. This + * field is not supported in Gemini API. */ @JsonProperty("retrievedContext") public abstract Builder retrievedContext(GroundingChunkRetrievedContext retrievedContext); @@ -65,7 +91,8 @@ private static Builder create() { /** * Setter for retrievedContext builder. * - *

retrievedContext: Grounding chunk from context retrieved by the retrieval tools. + *

retrievedContext: Grounding chunk from context retrieved by the retrieval tools. This + * field is not supported in Gemini API. */ public Builder retrievedContext( GroundingChunkRetrievedContext.Builder retrievedContextBuilder) { @@ -93,6 +120,7 @@ public Builder web(GroundingChunkWeb.Builder webBuilder) { } /** Deserializes a JSON string to a GroundingChunk object. */ + @ExcludeFromGeneratedCoverageReport public static GroundingChunk fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, GroundingChunk.class); } diff --git a/src/main/java/com/google/genai/types/GroundingChunkMaps.java b/src/main/java/com/google/genai/types/GroundingChunkMaps.java new file mode 100644 index 00000000000..09a6311ca09 --- /dev/null +++ b/src/main/java/com/google/genai/types/GroundingChunkMaps.java @@ -0,0 +1,137 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Auto-generated code. Do not edit. + +package com.google.genai.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.google.auto.value.AutoValue; +import com.google.genai.JsonSerializable; +import java.util.Optional; + +/** Chunk from Google Maps. This data type is not supported in Gemini API. */ +@AutoValue +@JsonDeserialize(builder = GroundingChunkMaps.Builder.class) +public abstract class GroundingChunkMaps extends JsonSerializable { + /** + * Sources used to generate the place answer. This includes review snippets and photos that were + * used to generate the answer, as well as uris to flag content. + */ + @JsonProperty("placeAnswerSources") + public abstract Optional placeAnswerSources(); + + /** + * This Place's resource name, in `places/{place_id}` format. Can be used to look up the Place. + */ + @JsonProperty("placeId") + public abstract Optional placeId(); + + /** Text of the chunk. */ + @JsonProperty("text") + public abstract Optional text(); + + /** Title of the chunk. */ + @JsonProperty("title") + public abstract Optional title(); + + /** URI reference of the chunk. */ + @JsonProperty("uri") + public abstract Optional uri(); + + /** Instantiates a builder for GroundingChunkMaps. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_GroundingChunkMaps.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for GroundingChunkMaps. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `GroundingChunkMaps.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_GroundingChunkMaps.Builder(); + } + + /** + * Setter for placeAnswerSources. + * + *

placeAnswerSources: Sources used to generate the place answer. This includes review + * snippets and photos that were used to generate the answer, as well as uris to flag content. + */ + @JsonProperty("placeAnswerSources") + public abstract Builder placeAnswerSources( + GroundingChunkMapsPlaceAnswerSources placeAnswerSources); + + /** + * Setter for placeAnswerSources builder. + * + *

placeAnswerSources: Sources used to generate the place answer. This includes review + * snippets and photos that were used to generate the answer, as well as uris to flag content. + */ + public Builder placeAnswerSources( + GroundingChunkMapsPlaceAnswerSources.Builder placeAnswerSourcesBuilder) { + return placeAnswerSources(placeAnswerSourcesBuilder.build()); + } + + /** + * Setter for placeId. + * + *

placeId: This Place's resource name, in `places/{place_id}` format. Can be used to look up + * the Place. + */ + @JsonProperty("placeId") + public abstract Builder placeId(String placeId); + + /** + * Setter for text. + * + *

text: Text of the chunk. + */ + @JsonProperty("text") + public abstract Builder text(String text); + + /** + * Setter for title. + * + *

title: Title of the chunk. + */ + @JsonProperty("title") + public abstract Builder title(String title); + + /** + * Setter for uri. + * + *

uri: URI reference of the chunk. + */ + @JsonProperty("uri") + public abstract Builder uri(String uri); + + public abstract GroundingChunkMaps build(); + } + + /** Deserializes a JSON string to a GroundingChunkMaps object. */ + @ExcludeFromGeneratedCoverageReport + public static GroundingChunkMaps fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, GroundingChunkMaps.class); + } +} diff --git a/src/main/java/com/google/genai/types/GroundingChunkMapsPlaceAnswerSources.java b/src/main/java/com/google/genai/types/GroundingChunkMapsPlaceAnswerSources.java new file mode 100644 index 00000000000..f794d456b76 --- /dev/null +++ b/src/main/java/com/google/genai/types/GroundingChunkMapsPlaceAnswerSources.java @@ -0,0 +1,114 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Auto-generated code. Do not edit. + +package com.google.genai.types; + +import static com.google.common.collect.ImmutableList.toImmutableList; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.google.auto.value.AutoValue; +import com.google.genai.JsonSerializable; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +/** Sources used to generate the place answer. This data type is not supported in Gemini API. */ +@AutoValue +@JsonDeserialize(builder = GroundingChunkMapsPlaceAnswerSources.Builder.class) +public abstract class GroundingChunkMapsPlaceAnswerSources extends JsonSerializable { + /** A link where users can flag a problem with the generated answer. */ + @JsonProperty("flagContentUri") + public abstract Optional flagContentUri(); + + /** Snippets of reviews that are used to generate the answer. */ + @JsonProperty("reviewSnippets") + public abstract Optional> + reviewSnippets(); + + /** Instantiates a builder for GroundingChunkMapsPlaceAnswerSources. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_GroundingChunkMapsPlaceAnswerSources.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for GroundingChunkMapsPlaceAnswerSources. */ + @AutoValue.Builder + public abstract static class Builder { + /** + * For internal usage. Please use `GroundingChunkMapsPlaceAnswerSources.builder()` for + * instantiation. + */ + @JsonCreator + private static Builder create() { + return new AutoValue_GroundingChunkMapsPlaceAnswerSources.Builder(); + } + + /** + * Setter for flagContentUri. + * + *

flagContentUri: A link where users can flag a problem with the generated answer. + */ + @JsonProperty("flagContentUri") + public abstract Builder flagContentUri(String flagContentUri); + + /** + * Setter for reviewSnippets. + * + *

reviewSnippets: Snippets of reviews that are used to generate the answer. + */ + @JsonProperty("reviewSnippets") + public abstract Builder reviewSnippets( + List reviewSnippets); + + /** + * Setter for reviewSnippets. + * + *

reviewSnippets: Snippets of reviews that are used to generate the answer. + */ + public Builder reviewSnippets( + GroundingChunkMapsPlaceAnswerSourcesReviewSnippet... reviewSnippets) { + return reviewSnippets(Arrays.asList(reviewSnippets)); + } + + /** + * Setter for reviewSnippets builder. + * + *

reviewSnippets: Snippets of reviews that are used to generate the answer. + */ + public Builder reviewSnippets( + GroundingChunkMapsPlaceAnswerSourcesReviewSnippet.Builder... reviewSnippetsBuilders) { + return reviewSnippets( + Arrays.asList(reviewSnippetsBuilders).stream() + .map(GroundingChunkMapsPlaceAnswerSourcesReviewSnippet.Builder::build) + .collect(toImmutableList())); + } + + public abstract GroundingChunkMapsPlaceAnswerSources build(); + } + + /** Deserializes a JSON string to a GroundingChunkMapsPlaceAnswerSources object. */ + @ExcludeFromGeneratedCoverageReport + public static GroundingChunkMapsPlaceAnswerSources fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, GroundingChunkMapsPlaceAnswerSources.class); + } +} diff --git a/src/main/java/com/google/genai/types/GroundingChunkMapsPlaceAnswerSourcesAuthorAttribution.java b/src/main/java/com/google/genai/types/GroundingChunkMapsPlaceAnswerSourcesAuthorAttribution.java new file mode 100644 index 00000000000..7fb42316020 --- /dev/null +++ b/src/main/java/com/google/genai/types/GroundingChunkMapsPlaceAnswerSourcesAuthorAttribution.java @@ -0,0 +1,101 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Auto-generated code. Do not edit. + +package com.google.genai.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.google.auto.value.AutoValue; +import com.google.genai.JsonSerializable; +import java.util.Optional; + +/** Author attribution for a photo or review. This data type is not supported in Gemini API. */ +@AutoValue +@JsonDeserialize(builder = GroundingChunkMapsPlaceAnswerSourcesAuthorAttribution.Builder.class) +public abstract class GroundingChunkMapsPlaceAnswerSourcesAuthorAttribution + extends JsonSerializable { + /** Name of the author of the Photo or Review. */ + @JsonProperty("displayName") + public abstract Optional displayName(); + + /** Profile photo URI of the author of the Photo or Review. */ + @JsonProperty("photoUri") + public abstract Optional photoUri(); + + /** URI of the author of the Photo or Review. */ + @JsonProperty("uri") + public abstract Optional uri(); + + /** Instantiates a builder for GroundingChunkMapsPlaceAnswerSourcesAuthorAttribution. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_GroundingChunkMapsPlaceAnswerSourcesAuthorAttribution.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for GroundingChunkMapsPlaceAnswerSourcesAuthorAttribution. */ + @AutoValue.Builder + public abstract static class Builder { + /** + * For internal usage. Please use + * `GroundingChunkMapsPlaceAnswerSourcesAuthorAttribution.builder()` for instantiation. + */ + @JsonCreator + private static Builder create() { + return new AutoValue_GroundingChunkMapsPlaceAnswerSourcesAuthorAttribution.Builder(); + } + + /** + * Setter for displayName. + * + *

displayName: Name of the author of the Photo or Review. + */ + @JsonProperty("displayName") + public abstract Builder displayName(String displayName); + + /** + * Setter for photoUri. + * + *

photoUri: Profile photo URI of the author of the Photo or Review. + */ + @JsonProperty("photoUri") + public abstract Builder photoUri(String photoUri); + + /** + * Setter for uri. + * + *

uri: URI of the author of the Photo or Review. + */ + @JsonProperty("uri") + public abstract Builder uri(String uri); + + public abstract GroundingChunkMapsPlaceAnswerSourcesAuthorAttribution build(); + } + + /** + * Deserializes a JSON string to a GroundingChunkMapsPlaceAnswerSourcesAuthorAttribution object. + */ + @ExcludeFromGeneratedCoverageReport + public static GroundingChunkMapsPlaceAnswerSourcesAuthorAttribution fromJson(String jsonString) { + return JsonSerializable.fromJsonString( + jsonString, GroundingChunkMapsPlaceAnswerSourcesAuthorAttribution.class); + } +} diff --git a/src/main/java/com/google/genai/types/GroundingChunkMapsPlaceAnswerSourcesReviewSnippet.java b/src/main/java/com/google/genai/types/GroundingChunkMapsPlaceAnswerSourcesReviewSnippet.java new file mode 100644 index 00000000000..9c5530fb0f6 --- /dev/null +++ b/src/main/java/com/google/genai/types/GroundingChunkMapsPlaceAnswerSourcesReviewSnippet.java @@ -0,0 +1,166 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Auto-generated code. Do not edit. + +package com.google.genai.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.google.auto.value.AutoValue; +import com.google.genai.JsonSerializable; +import java.util.Optional; + +/** Encapsulates a review snippet. This data type is not supported in Gemini API. */ +@AutoValue +@JsonDeserialize(builder = GroundingChunkMapsPlaceAnswerSourcesReviewSnippet.Builder.class) +public abstract class GroundingChunkMapsPlaceAnswerSourcesReviewSnippet extends JsonSerializable { + /** This review's author. */ + @JsonProperty("authorAttribution") + public abstract Optional + authorAttribution(); + + /** A link where users can flag a problem with the review. */ + @JsonProperty("flagContentUri") + public abstract Optional flagContentUri(); + + /** A link to show the review on Google Maps. */ + @JsonProperty("googleMapsUri") + public abstract Optional googleMapsUri(); + + /** + * A string of formatted recent time, expressing the review time relative to the current time in a + * form appropriate for the language and country. + */ + @JsonProperty("relativePublishTimeDescription") + public abstract Optional relativePublishTimeDescription(); + + /** + * A reference representing this place review which may be used to look up this place review + * again. + */ + @JsonProperty("review") + public abstract Optional review(); + + /** Id of the review referencing the place. */ + @JsonProperty("reviewId") + public abstract Optional reviewId(); + + /** Title of the review. */ + @JsonProperty("title") + public abstract Optional title(); + + /** Instantiates a builder for GroundingChunkMapsPlaceAnswerSourcesReviewSnippet. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_GroundingChunkMapsPlaceAnswerSourcesReviewSnippet.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for GroundingChunkMapsPlaceAnswerSourcesReviewSnippet. */ + @AutoValue.Builder + public abstract static class Builder { + /** + * For internal usage. Please use `GroundingChunkMapsPlaceAnswerSourcesReviewSnippet.builder()` + * for instantiation. + */ + @JsonCreator + private static Builder create() { + return new AutoValue_GroundingChunkMapsPlaceAnswerSourcesReviewSnippet.Builder(); + } + + /** + * Setter for authorAttribution. + * + *

authorAttribution: This review's author. + */ + @JsonProperty("authorAttribution") + public abstract Builder authorAttribution( + GroundingChunkMapsPlaceAnswerSourcesAuthorAttribution authorAttribution); + + /** + * Setter for authorAttribution builder. + * + *

authorAttribution: This review's author. + */ + public Builder authorAttribution( + GroundingChunkMapsPlaceAnswerSourcesAuthorAttribution.Builder authorAttributionBuilder) { + return authorAttribution(authorAttributionBuilder.build()); + } + + /** + * Setter for flagContentUri. + * + *

flagContentUri: A link where users can flag a problem with the review. + */ + @JsonProperty("flagContentUri") + public abstract Builder flagContentUri(String flagContentUri); + + /** + * Setter for googleMapsUri. + * + *

googleMapsUri: A link to show the review on Google Maps. + */ + @JsonProperty("googleMapsUri") + public abstract Builder googleMapsUri(String googleMapsUri); + + /** + * Setter for relativePublishTimeDescription. + * + *

relativePublishTimeDescription: A string of formatted recent time, expressing the review + * time relative to the current time in a form appropriate for the language and country. + */ + @JsonProperty("relativePublishTimeDescription") + public abstract Builder relativePublishTimeDescription(String relativePublishTimeDescription); + + /** + * Setter for review. + * + *

review: A reference representing this place review which may be used to look up this place + * review again. + */ + @JsonProperty("review") + public abstract Builder review(String review); + + /** + * Setter for reviewId. + * + *

reviewId: Id of the review referencing the place. + */ + @JsonProperty("reviewId") + public abstract Builder reviewId(String reviewId); + + /** + * Setter for title. + * + *

title: Title of the review. + */ + @JsonProperty("title") + public abstract Builder title(String title); + + public abstract GroundingChunkMapsPlaceAnswerSourcesReviewSnippet build(); + } + + /** Deserializes a JSON string to a GroundingChunkMapsPlaceAnswerSourcesReviewSnippet object. */ + @ExcludeFromGeneratedCoverageReport + public static GroundingChunkMapsPlaceAnswerSourcesReviewSnippet fromJson(String jsonString) { + return JsonSerializable.fromJsonString( + jsonString, GroundingChunkMapsPlaceAnswerSourcesReviewSnippet.class); + } +} diff --git a/src/main/java/com/google/genai/types/GroundingChunkRetrievedContext.java b/src/main/java/com/google/genai/types/GroundingChunkRetrievedContext.java index 01a1bcbbdd9..d9004b976d8 100644 --- a/src/main/java/com/google/genai/types/GroundingChunkRetrievedContext.java +++ b/src/main/java/com/google/genai/types/GroundingChunkRetrievedContext.java @@ -25,10 +25,17 @@ import com.google.genai.JsonSerializable; import java.util.Optional; -/** Chunk from context retrieved by the retrieval tools. */ +/** + * Chunk from context retrieved by the retrieval tools. This data type is not supported in Gemini + * API. + */ @AutoValue @JsonDeserialize(builder = GroundingChunkRetrievedContext.Builder.class) public abstract class GroundingChunkRetrievedContext extends JsonSerializable { + /** Output only. The full document name for the referenced Vertex AI Search document. */ + @JsonProperty("documentName") + public abstract Optional documentName(); + /** * Additional context for the RAG retrieval result. This is only populated when using the RAG * retrieval tool. @@ -49,6 +56,7 @@ public abstract class GroundingChunkRetrievedContext extends JsonSerializable { public abstract Optional uri(); /** Instantiates a builder for GroundingChunkRetrievedContext. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_GroundingChunkRetrievedContext.Builder(); } @@ -67,6 +75,15 @@ private static Builder create() { return new AutoValue_GroundingChunkRetrievedContext.Builder(); } + /** + * Setter for documentName. + * + *

documentName: Output only. The full document name for the referenced Vertex AI Search + * document. + */ + @JsonProperty("documentName") + public abstract Builder documentName(String documentName); + /** * Setter for ragChunk. * @@ -114,6 +131,7 @@ public Builder ragChunk(RagChunk.Builder ragChunkBuilder) { } /** Deserializes a JSON string to a GroundingChunkRetrievedContext object. */ + @ExcludeFromGeneratedCoverageReport public static GroundingChunkRetrievedContext fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, GroundingChunkRetrievedContext.class); } diff --git a/src/main/java/com/google/genai/types/GroundingChunkWeb.java b/src/main/java/com/google/genai/types/GroundingChunkWeb.java index de1226b74ed..34b8e7bd4d5 100644 --- a/src/main/java/com/google/genai/types/GroundingChunkWeb.java +++ b/src/main/java/com/google/genai/types/GroundingChunkWeb.java @@ -29,7 +29,7 @@ @AutoValue @JsonDeserialize(builder = GroundingChunkWeb.Builder.class) public abstract class GroundingChunkWeb extends JsonSerializable { - /** Domain of the (original) URI. */ + /** Domain of the (original) URI. This field is not supported in Gemini API. */ @JsonProperty("domain") public abstract Optional domain(); @@ -42,6 +42,7 @@ public abstract class GroundingChunkWeb extends JsonSerializable { public abstract Optional uri(); /** Instantiates a builder for GroundingChunkWeb. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_GroundingChunkWeb.Builder(); } @@ -61,7 +62,7 @@ private static Builder create() { /** * Setter for domain. * - *

domain: Domain of the (original) URI. + *

domain: Domain of the (original) URI. This field is not supported in Gemini API. */ @JsonProperty("domain") public abstract Builder domain(String domain); @@ -86,6 +87,7 @@ private static Builder create() { } /** Deserializes a JSON string to a GroundingChunkWeb object. */ + @ExcludeFromGeneratedCoverageReport public static GroundingChunkWeb fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, GroundingChunkWeb.class); } diff --git a/src/main/java/com/google/genai/types/GroundingMetadata.java b/src/main/java/com/google/genai/types/GroundingMetadata.java index 129c8b63523..c7eab5a182d 100644 --- a/src/main/java/com/google/genai/types/GroundingMetadata.java +++ b/src/main/java/com/google/genai/types/GroundingMetadata.java @@ -33,6 +33,14 @@ @AutoValue @JsonDeserialize(builder = GroundingMetadata.Builder.class) public abstract class GroundingMetadata extends JsonSerializable { + /** + * Optional. Output only. Resource name of the Google Maps widget context token to be used with + * the PlacesContextElement widget to render contextual data. This is populated only for Google + * Maps grounding. This field is not supported in Gemini API. + */ + @JsonProperty("googleMapsWidgetContextToken") + public abstract Optional googleMapsWidgetContextToken(); + /** List of supporting references retrieved from specified grounding source. */ @JsonProperty("groundingChunks") public abstract Optional> groundingChunks(); @@ -45,7 +53,9 @@ public abstract class GroundingMetadata extends JsonSerializable { @JsonProperty("retrievalMetadata") public abstract Optional retrievalMetadata(); - /** Optional. Queries executed by the retrieval tools. */ + /** + * Optional. Queries executed by the retrieval tools. This field is not supported in Gemini API. + */ @JsonProperty("retrievalQueries") public abstract Optional> retrievalQueries(); @@ -53,11 +63,19 @@ public abstract class GroundingMetadata extends JsonSerializable { @JsonProperty("searchEntryPoint") public abstract Optional searchEntryPoint(); + /** + * Optional. Output only. List of source flagging uris. This is currently populated only for + * Google Maps grounding. This field is not supported in Gemini API. + */ + @JsonProperty("sourceFlaggingUris") + public abstract Optional> sourceFlaggingUris(); + /** Optional. Web search queries for the following-up web search. */ @JsonProperty("webSearchQueries") public abstract Optional> webSearchQueries(); /** Instantiates a builder for GroundingMetadata. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_GroundingMetadata.Builder(); } @@ -74,6 +92,17 @@ private static Builder create() { return new AutoValue_GroundingMetadata.Builder(); } + /** + * Setter for googleMapsWidgetContextToken. + * + *

googleMapsWidgetContextToken: Optional. Output only. Resource name of the Google Maps + * widget context token to be used with the PlacesContextElement widget to render contextual + * data. This is populated only for Google Maps grounding. This field is not supported in Gemini + * API. + */ + @JsonProperty("googleMapsWidgetContextToken") + public abstract Builder googleMapsWidgetContextToken(String googleMapsWidgetContextToken); + /** * Setter for groundingChunks. * @@ -152,7 +181,8 @@ public Builder retrievalMetadata(RetrievalMetadata.Builder retrievalMetadataBuil /** * Setter for retrievalQueries. * - *

retrievalQueries: Optional. Queries executed by the retrieval tools. + *

retrievalQueries: Optional. Queries executed by the retrieval tools. This field is not + * supported in Gemini API. */ @JsonProperty("retrievalQueries") public abstract Builder retrievalQueries(List retrievalQueries); @@ -160,7 +190,8 @@ public Builder retrievalMetadata(RetrievalMetadata.Builder retrievalMetadataBuil /** * Setter for retrievalQueries. * - *

retrievalQueries: Optional. Queries executed by the retrieval tools. + *

retrievalQueries: Optional. Queries executed by the retrieval tools. This field is not + * supported in Gemini API. */ public Builder retrievalQueries(String... retrievalQueries) { return retrievalQueries(Arrays.asList(retrievalQueries)); @@ -183,6 +214,40 @@ public Builder searchEntryPoint(SearchEntryPoint.Builder searchEntryPointBuilder return searchEntryPoint(searchEntryPointBuilder.build()); } + /** + * Setter for sourceFlaggingUris. + * + *

sourceFlaggingUris: Optional. Output only. List of source flagging uris. This is currently + * populated only for Google Maps grounding. This field is not supported in Gemini API. + */ + @JsonProperty("sourceFlaggingUris") + public abstract Builder sourceFlaggingUris( + List sourceFlaggingUris); + + /** + * Setter for sourceFlaggingUris. + * + *

sourceFlaggingUris: Optional. Output only. List of source flagging uris. This is currently + * populated only for Google Maps grounding. This field is not supported in Gemini API. + */ + public Builder sourceFlaggingUris(GroundingMetadataSourceFlaggingUri... sourceFlaggingUris) { + return sourceFlaggingUris(Arrays.asList(sourceFlaggingUris)); + } + + /** + * Setter for sourceFlaggingUris builder. + * + *

sourceFlaggingUris: Optional. Output only. List of source flagging uris. This is currently + * populated only for Google Maps grounding. This field is not supported in Gemini API. + */ + public Builder sourceFlaggingUris( + GroundingMetadataSourceFlaggingUri.Builder... sourceFlaggingUrisBuilders) { + return sourceFlaggingUris( + Arrays.asList(sourceFlaggingUrisBuilders).stream() + .map(GroundingMetadataSourceFlaggingUri.Builder::build) + .collect(toImmutableList())); + } + /** * Setter for webSearchQueries. * @@ -204,6 +269,7 @@ public Builder webSearchQueries(String... webSearchQueries) { } /** Deserializes a JSON string to a GroundingMetadata object. */ + @ExcludeFromGeneratedCoverageReport public static GroundingMetadata fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, GroundingMetadata.class); } diff --git a/src/main/java/com/google/genai/types/GroundingMetadataSourceFlaggingUri.java b/src/main/java/com/google/genai/types/GroundingMetadataSourceFlaggingUri.java new file mode 100644 index 00000000000..a416da6091d --- /dev/null +++ b/src/main/java/com/google/genai/types/GroundingMetadataSourceFlaggingUri.java @@ -0,0 +1,88 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Auto-generated code. Do not edit. + +package com.google.genai.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.google.auto.value.AutoValue; +import com.google.genai.JsonSerializable; +import java.util.Optional; + +/** + * Source content flagging uri for a place or review. This is currently populated only for Google + * Maps grounding. This data type is not supported in Gemini API. + */ +@AutoValue +@JsonDeserialize(builder = GroundingMetadataSourceFlaggingUri.Builder.class) +public abstract class GroundingMetadataSourceFlaggingUri extends JsonSerializable { + /** A link where users can flag a problem with the source (place or review). */ + @JsonProperty("flagContentUri") + public abstract Optional flagContentUri(); + + /** Id of the place or review. */ + @JsonProperty("sourceId") + public abstract Optional sourceId(); + + /** Instantiates a builder for GroundingMetadataSourceFlaggingUri. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_GroundingMetadataSourceFlaggingUri.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for GroundingMetadataSourceFlaggingUri. */ + @AutoValue.Builder + public abstract static class Builder { + /** + * For internal usage. Please use `GroundingMetadataSourceFlaggingUri.builder()` for + * instantiation. + */ + @JsonCreator + private static Builder create() { + return new AutoValue_GroundingMetadataSourceFlaggingUri.Builder(); + } + + /** + * Setter for flagContentUri. + * + *

flagContentUri: A link where users can flag a problem with the source (place or review). + */ + @JsonProperty("flagContentUri") + public abstract Builder flagContentUri(String flagContentUri); + + /** + * Setter for sourceId. + * + *

sourceId: Id of the place or review. + */ + @JsonProperty("sourceId") + public abstract Builder sourceId(String sourceId); + + public abstract GroundingMetadataSourceFlaggingUri build(); + } + + /** Deserializes a JSON string to a GroundingMetadataSourceFlaggingUri object. */ + @ExcludeFromGeneratedCoverageReport + public static GroundingMetadataSourceFlaggingUri fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, GroundingMetadataSourceFlaggingUri.class); + } +} diff --git a/src/main/java/com/google/genai/types/GroundingSupport.java b/src/main/java/com/google/genai/types/GroundingSupport.java index 4dd2d897560..1bc664b6eaa 100644 --- a/src/main/java/com/google/genai/types/GroundingSupport.java +++ b/src/main/java/com/google/genai/types/GroundingSupport.java @@ -52,6 +52,7 @@ public abstract class GroundingSupport extends JsonSerializable { public abstract Optional segment(); /** Instantiates a builder for GroundingSupport. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_GroundingSupport.Builder(); } @@ -133,6 +134,7 @@ public Builder segment(Segment.Builder segmentBuilder) { } /** Deserializes a JSON string to a GroundingSupport object. */ + @ExcludeFromGeneratedCoverageReport public static GroundingSupport fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, GroundingSupport.class); } diff --git a/src/main/java/com/google/genai/types/HarmBlockMethod.java b/src/main/java/com/google/genai/types/HarmBlockMethod.java index 2d2ddef1948..5e44259b323 100644 --- a/src/main/java/com/google/genai/types/HarmBlockMethod.java +++ b/src/main/java/com/google/genai/types/HarmBlockMethod.java @@ -24,8 +24,8 @@ import java.util.Objects; /** - * Optional. Specify if the threshold is used for probability or severity score. If not specified, - * the threshold is used for probability score. + * Specify if the threshold is used for probability or severity score. If not specified, the + * threshold is used for probability score. This enum is not supported in Gemini API. */ public class HarmBlockMethod { @@ -63,12 +63,14 @@ public HarmBlockMethod(Known knownValue) { this.value = knownValue.toString(); } + @ExcludeFromGeneratedCoverageReport @Override @JsonValue public String toString() { return this.value; } + @ExcludeFromGeneratedCoverageReport @SuppressWarnings("PatternMatchingInstanceof") @Override public boolean equals(Object o) { @@ -95,6 +97,7 @@ public boolean equals(Object o) { return false; } + @ExcludeFromGeneratedCoverageReport @Override public int hashCode() { if (this.harmBlockMethodEnum != Known.HARM_BLOCK_METHOD_UNSPECIFIED) { @@ -104,6 +107,7 @@ public int hashCode() { } } + @ExcludeFromGeneratedCoverageReport public Known knownEnum() { return this.harmBlockMethodEnum; } diff --git a/src/main/java/com/google/genai/types/HarmBlockThreshold.java b/src/main/java/com/google/genai/types/HarmBlockThreshold.java index 6059466582f..7c7b9f440be 100644 --- a/src/main/java/com/google/genai/types/HarmBlockThreshold.java +++ b/src/main/java/com/google/genai/types/HarmBlockThreshold.java @@ -23,7 +23,7 @@ import com.google.common.base.Ascii; import java.util.Objects; -/** Required. The harm block threshold. */ +/** The harm block threshold. */ public class HarmBlockThreshold { /** Enum representing the known values for HarmBlockThreshold. */ @@ -69,12 +69,14 @@ public HarmBlockThreshold(Known knownValue) { this.value = knownValue.toString(); } + @ExcludeFromGeneratedCoverageReport @Override @JsonValue public String toString() { return this.value; } + @ExcludeFromGeneratedCoverageReport @SuppressWarnings("PatternMatchingInstanceof") @Override public boolean equals(Object o) { @@ -101,6 +103,7 @@ public boolean equals(Object o) { return false; } + @ExcludeFromGeneratedCoverageReport @Override public int hashCode() { if (this.harmBlockThresholdEnum != Known.HARM_BLOCK_THRESHOLD_UNSPECIFIED) { @@ -110,6 +113,7 @@ public int hashCode() { } } + @ExcludeFromGeneratedCoverageReport public Known knownEnum() { return this.harmBlockThresholdEnum; } diff --git a/src/main/java/com/google/genai/types/HarmCategory.java b/src/main/java/com/google/genai/types/HarmCategory.java index 290644dcc59..95a7e942fca 100644 --- a/src/main/java/com/google/genai/types/HarmCategory.java +++ b/src/main/java/com/google/genai/types/HarmCategory.java @@ -23,7 +23,7 @@ import com.google.common.base.Ascii; import java.util.Objects; -/** Required. Harm category. */ +/** Harm category. */ public class HarmCategory { /** Enum representing the known values for HarmCategory. */ @@ -31,34 +31,44 @@ public enum Known { /** The harm category is unspecified. */ HARM_CATEGORY_UNSPECIFIED, - /** The harm category is hate speech. */ - HARM_CATEGORY_HATE_SPEECH, - - /** The harm category is dangerous content. */ - HARM_CATEGORY_DANGEROUS_CONTENT, - /** The harm category is harassment. */ HARM_CATEGORY_HARASSMENT, + /** The harm category is hate speech. */ + HARM_CATEGORY_HATE_SPEECH, + /** The harm category is sexually explicit content. */ HARM_CATEGORY_SEXUALLY_EXPLICIT, + /** The harm category is dangerous content. */ + HARM_CATEGORY_DANGEROUS_CONTENT, + /** * Deprecated: Election filter is not longer supported. The harm category is civic integrity. */ HARM_CATEGORY_CIVIC_INTEGRITY, - /** The harm category is image hate. */ + /** The harm category is image hate. This enum value is not supported in Gemini API. */ HARM_CATEGORY_IMAGE_HATE, - /** The harm category is image dangerous content. */ + /** + * The harm category is image dangerous content. This enum value is not supported in Gemini API. + */ HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT, - /** The harm category is image harassment. */ + /** The harm category is image harassment. This enum value is not supported in Gemini API. */ HARM_CATEGORY_IMAGE_HARASSMENT, - /** The harm category is image sexually explicit content. */ - HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT + /** + * The harm category is image sexually explicit content. This enum value is not supported in + * Gemini API. + */ + HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT, + + /** + * The harm category is for jailbreak prompts. This enum value is not supported in Gemini API. + */ + HARM_CATEGORY_JAILBREAK } private Known harmCategoryEnum; @@ -83,12 +93,14 @@ public HarmCategory(Known knownValue) { this.value = knownValue.toString(); } + @ExcludeFromGeneratedCoverageReport @Override @JsonValue public String toString() { return this.value; } + @ExcludeFromGeneratedCoverageReport @SuppressWarnings("PatternMatchingInstanceof") @Override public boolean equals(Object o) { @@ -115,6 +127,7 @@ public boolean equals(Object o) { return false; } + @ExcludeFromGeneratedCoverageReport @Override public int hashCode() { if (this.harmCategoryEnum != Known.HARM_CATEGORY_UNSPECIFIED) { @@ -124,6 +137,7 @@ public int hashCode() { } } + @ExcludeFromGeneratedCoverageReport public Known knownEnum() { return this.harmCategoryEnum; } diff --git a/src/main/java/com/google/genai/types/HarmProbability.java b/src/main/java/com/google/genai/types/HarmProbability.java index 047483b1302..b2d94f46a5b 100644 --- a/src/main/java/com/google/genai/types/HarmProbability.java +++ b/src/main/java/com/google/genai/types/HarmProbability.java @@ -66,12 +66,14 @@ public HarmProbability(Known knownValue) { this.value = knownValue.toString(); } + @ExcludeFromGeneratedCoverageReport @Override @JsonValue public String toString() { return this.value; } + @ExcludeFromGeneratedCoverageReport @SuppressWarnings("PatternMatchingInstanceof") @Override public boolean equals(Object o) { @@ -98,6 +100,7 @@ public boolean equals(Object o) { return false; } + @ExcludeFromGeneratedCoverageReport @Override public int hashCode() { if (this.harmProbabilityEnum != Known.HARM_PROBABILITY_UNSPECIFIED) { @@ -107,6 +110,7 @@ public int hashCode() { } } + @ExcludeFromGeneratedCoverageReport public Known knownEnum() { return this.harmProbabilityEnum; } diff --git a/src/main/java/com/google/genai/types/HarmSeverity.java b/src/main/java/com/google/genai/types/HarmSeverity.java index 74dbd626abe..9dba676bf1a 100644 --- a/src/main/java/com/google/genai/types/HarmSeverity.java +++ b/src/main/java/com/google/genai/types/HarmSeverity.java @@ -23,7 +23,7 @@ import com.google.common.base.Ascii; import java.util.Objects; -/** Output only. Harm severity levels in the content. */ +/** Output only. Harm severity levels in the content. This enum is not supported in Gemini API. */ public class HarmSeverity { /** Enum representing the known values for HarmSeverity. */ @@ -66,12 +66,14 @@ public HarmSeverity(Known knownValue) { this.value = knownValue.toString(); } + @ExcludeFromGeneratedCoverageReport @Override @JsonValue public String toString() { return this.value; } + @ExcludeFromGeneratedCoverageReport @SuppressWarnings("PatternMatchingInstanceof") @Override public boolean equals(Object o) { @@ -98,6 +100,7 @@ public boolean equals(Object o) { return false; } + @ExcludeFromGeneratedCoverageReport @Override public int hashCode() { if (this.harmSeverityEnum != Known.HARM_SEVERITY_UNSPECIFIED) { @@ -107,6 +110,7 @@ public int hashCode() { } } + @ExcludeFromGeneratedCoverageReport public Known knownEnum() { return this.harmSeverityEnum; } diff --git a/src/main/java/com/google/genai/types/HttpOptions.java b/src/main/java/com/google/genai/types/HttpOptions.java index 46326f2778f..f701bd6911f 100644 --- a/src/main/java/com/google/genai/types/HttpOptions.java +++ b/src/main/java/com/google/genai/types/HttpOptions.java @@ -46,7 +46,20 @@ public abstract class HttpOptions extends JsonSerializable { @JsonProperty("timeout") public abstract Optional timeout(); + /** + * Extra parameters to add to the request body. The structure must match the backend API's request + * structure. - VertexAI backend API docs: https://cloud.google.com/vertex-ai/docs/reference/rest + * - GeminiAPI backend API docs: https://ai.google.dev/api/rest + */ + @JsonProperty("extraBody") + public abstract Optional> extraBody(); + + /** HTTP retry options for the request. */ + @JsonProperty("retryOptions") + public abstract Optional retryOptions(); + /** Instantiates a builder for HttpOptions. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_HttpOptions.Builder(); } @@ -95,10 +108,39 @@ private static Builder create() { @JsonProperty("timeout") public abstract Builder timeout(Integer timeout); + /** + * Setter for extraBody. + * + *

extraBody: Extra parameters to add to the request body. The structure must match the + * backend API's request structure. - VertexAI backend API docs: + * https://cloud.google.com/vertex-ai/docs/reference/rest - GeminiAPI backend API docs: + * https://ai.google.dev/api/rest + */ + @JsonProperty("extraBody") + public abstract Builder extraBody(Map extraBody); + + /** + * Setter for retryOptions. + * + *

retryOptions: HTTP retry options for the request. + */ + @JsonProperty("retryOptions") + public abstract Builder retryOptions(HttpRetryOptions retryOptions); + + /** + * Setter for retryOptions builder. + * + *

retryOptions: HTTP retry options for the request. + */ + public Builder retryOptions(HttpRetryOptions.Builder retryOptionsBuilder) { + return retryOptions(retryOptionsBuilder.build()); + } + public abstract HttpOptions build(); } /** Deserializes a JSON string to a HttpOptions object. */ + @ExcludeFromGeneratedCoverageReport public static HttpOptions fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, HttpOptions.class); } diff --git a/src/main/java/com/google/genai/types/HttpResponse.java b/src/main/java/com/google/genai/types/HttpResponse.java index 13120d09214..01c539ee849 100644 --- a/src/main/java/com/google/genai/types/HttpResponse.java +++ b/src/main/java/com/google/genai/types/HttpResponse.java @@ -39,6 +39,7 @@ public abstract class HttpResponse extends JsonSerializable { public abstract Optional body(); /** Instantiates a builder for HttpResponse. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_HttpResponse.Builder(); } @@ -75,6 +76,7 @@ private static Builder create() { } /** Deserializes a JSON string to a HttpResponse object. */ + @ExcludeFromGeneratedCoverageReport public static HttpResponse fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, HttpResponse.class); } diff --git a/src/main/java/com/google/genai/types/HttpRetryOptions.java b/src/main/java/com/google/genai/types/HttpRetryOptions.java new file mode 100644 index 00000000000..4bb092c8d64 --- /dev/null +++ b/src/main/java/com/google/genai/types/HttpRetryOptions.java @@ -0,0 +1,161 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Auto-generated code. Do not edit. + +package com.google.genai.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.google.auto.value.AutoValue; +import com.google.genai.JsonSerializable; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +/** HTTP retry options to be used in each of the requests. */ +@AutoValue +@JsonDeserialize(builder = HttpRetryOptions.Builder.class) +public abstract class HttpRetryOptions extends JsonSerializable { + /** + * Maximum number of attempts, including the original request. If 0 or 1, it means no retries. If + * not specified, default to 5. + */ + @JsonProperty("attempts") + public abstract Optional attempts(); + + /** + * Initial delay before the first retry, in fractions of a second. If not specified, default to + * 1.0 second. + */ + @JsonProperty("initialDelay") + public abstract Optional initialDelay(); + + /** + * Maximum delay between retries, in fractions of a second. If not specified, default to 60.0 + * seconds. + */ + @JsonProperty("maxDelay") + public abstract Optional maxDelay(); + + /** + * Multiplier by which the delay increases after each attempt. If not specified, default to 2.0. + */ + @JsonProperty("expBase") + public abstract Optional expBase(); + + /** Randomness factor for the delay. If not specified, default to 1.0. */ + @JsonProperty("jitter") + public abstract Optional jitter(); + + /** + * List of HTTP status codes that should trigger a retry. If not specified, a default set of + * retryable codes (408, 429, and 5xx) may be used. + */ + @JsonProperty("httpStatusCodes") + public abstract Optional> httpStatusCodes(); + + /** Instantiates a builder for HttpRetryOptions. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_HttpRetryOptions.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for HttpRetryOptions. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `HttpRetryOptions.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_HttpRetryOptions.Builder(); + } + + /** + * Setter for attempts. + * + *

attempts: Maximum number of attempts, including the original request. If 0 or 1, it means + * no retries. If not specified, default to 5. + */ + @JsonProperty("attempts") + public abstract Builder attempts(Integer attempts); + + /** + * Setter for initialDelay. + * + *

initialDelay: Initial delay before the first retry, in fractions of a second. If not + * specified, default to 1.0 second. + */ + @JsonProperty("initialDelay") + public abstract Builder initialDelay(Double initialDelay); + + /** + * Setter for maxDelay. + * + *

maxDelay: Maximum delay between retries, in fractions of a second. If not specified, + * default to 60.0 seconds. + */ + @JsonProperty("maxDelay") + public abstract Builder maxDelay(Double maxDelay); + + /** + * Setter for expBase. + * + *

expBase: Multiplier by which the delay increases after each attempt. If not specified, + * default to 2.0. + */ + @JsonProperty("expBase") + public abstract Builder expBase(Double expBase); + + /** + * Setter for jitter. + * + *

jitter: Randomness factor for the delay. If not specified, default to 1.0. + */ + @JsonProperty("jitter") + public abstract Builder jitter(Double jitter); + + /** + * Setter for httpStatusCodes. + * + *

httpStatusCodes: List of HTTP status codes that should trigger a retry. If not specified, + * a default set of retryable codes (408, 429, and 5xx) may be used. + */ + @JsonProperty("httpStatusCodes") + public abstract Builder httpStatusCodes(List httpStatusCodes); + + /** + * Setter for httpStatusCodes. + * + *

httpStatusCodes: List of HTTP status codes that should trigger a retry. If not specified, + * a default set of retryable codes (408, 429, and 5xx) may be used. + */ + public Builder httpStatusCodes(Integer... httpStatusCodes) { + return httpStatusCodes(Arrays.asList(httpStatusCodes)); + } + + public abstract HttpRetryOptions build(); + } + + /** Deserializes a JSON string to a HttpRetryOptions object. */ + @ExcludeFromGeneratedCoverageReport + public static HttpRetryOptions fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, HttpRetryOptions.class); + } +} diff --git a/src/main/java/com/google/genai/types/Image.java b/src/main/java/com/google/genai/types/Image.java index 91be75dc7ea..b2581f4d95c 100644 --- a/src/main/java/com/google/genai/types/Image.java +++ b/src/main/java/com/google/genai/types/Image.java @@ -53,6 +53,7 @@ public abstract class Image extends JsonSerializable { public abstract Optional mimeType(); /** Instantiates a builder for Image. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_Image.Builder(); } @@ -99,6 +100,7 @@ private static Builder create() { } /** Deserializes a JSON string to a Image object. */ + @ExcludeFromGeneratedCoverageReport public static Image fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, Image.class); } diff --git a/src/main/java/com/google/genai/types/ImageConfig.java b/src/main/java/com/google/genai/types/ImageConfig.java new file mode 100644 index 00000000000..cd6ea890aff --- /dev/null +++ b/src/main/java/com/google/genai/types/ImageConfig.java @@ -0,0 +1,74 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Auto-generated code. Do not edit. + +package com.google.genai.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.google.auto.value.AutoValue; +import com.google.genai.JsonSerializable; +import java.util.Optional; + +/** The image generation configuration to be used in GenerateContentConfig. */ +@AutoValue +@JsonDeserialize(builder = ImageConfig.Builder.class) +public abstract class ImageConfig extends JsonSerializable { + /** + * Aspect ratio of the generated images. Supported values are "1:1", "2:3", "3:2", "3:4", "4:3", + * "9:16", "16:9", and "21:9". + */ + @JsonProperty("aspectRatio") + public abstract Optional aspectRatio(); + + /** Instantiates a builder for ImageConfig. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_ImageConfig.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for ImageConfig. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `ImageConfig.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_ImageConfig.Builder(); + } + + /** + * Setter for aspectRatio. + * + *

aspectRatio: Aspect ratio of the generated images. Supported values are "1:1", "2:3", + * "3:2", "3:4", "4:3", "9:16", "16:9", and "21:9". + */ + @JsonProperty("aspectRatio") + public abstract Builder aspectRatio(String aspectRatio); + + public abstract ImageConfig build(); + } + + /** Deserializes a JSON string to a ImageConfig object. */ + @ExcludeFromGeneratedCoverageReport + public static ImageConfig fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, ImageConfig.class); + } +} diff --git a/src/main/java/com/google/genai/types/ImagePromptLanguage.java b/src/main/java/com/google/genai/types/ImagePromptLanguage.java index 3bfe8c30b2b..0aab1b13aba 100644 --- a/src/main/java/com/google/genai/types/ImagePromptLanguage.java +++ b/src/main/java/com/google/genai/types/ImagePromptLanguage.java @@ -77,12 +77,14 @@ public ImagePromptLanguage(Known knownValue) { this.value = knownValue.toString(); } + @ExcludeFromGeneratedCoverageReport @Override @JsonValue public String toString() { return this.value; } + @ExcludeFromGeneratedCoverageReport @SuppressWarnings("PatternMatchingInstanceof") @Override public boolean equals(Object o) { @@ -109,6 +111,7 @@ public boolean equals(Object o) { return false; } + @ExcludeFromGeneratedCoverageReport @Override public int hashCode() { if (this.imagePromptLanguageEnum != Known.IMAGE_PROMPT_LANGUAGE_UNSPECIFIED) { @@ -118,6 +121,7 @@ public int hashCode() { } } + @ExcludeFromGeneratedCoverageReport public Known knownEnum() { return this.imagePromptLanguageEnum; } diff --git a/src/main/java/com/google/genai/types/InlinedEmbedContentResponse.java b/src/main/java/com/google/genai/types/InlinedEmbedContentResponse.java new file mode 100644 index 00000000000..2dabb117d26 --- /dev/null +++ b/src/main/java/com/google/genai/types/InlinedEmbedContentResponse.java @@ -0,0 +1,100 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Auto-generated code. Do not edit. + +package com.google.genai.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.google.auto.value.AutoValue; +import com.google.genai.JsonSerializable; +import java.util.Optional; + +/** Config for `inlined_embedding_responses` parameter. */ +@AutoValue +@JsonDeserialize(builder = InlinedEmbedContentResponse.Builder.class) +public abstract class InlinedEmbedContentResponse extends JsonSerializable { + /** The response to the request. */ + @JsonProperty("response") + public abstract Optional response(); + + /** The error encountered while processing the request. */ + @JsonProperty("error") + public abstract Optional error(); + + /** Instantiates a builder for InlinedEmbedContentResponse. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_InlinedEmbedContentResponse.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for InlinedEmbedContentResponse. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `InlinedEmbedContentResponse.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_InlinedEmbedContentResponse.Builder(); + } + + /** + * Setter for response. + * + *

response: The response to the request. + */ + @JsonProperty("response") + public abstract Builder response(SingleEmbedContentResponse response); + + /** + * Setter for response builder. + * + *

response: The response to the request. + */ + public Builder response(SingleEmbedContentResponse.Builder responseBuilder) { + return response(responseBuilder.build()); + } + + /** + * Setter for error. + * + *

error: The error encountered while processing the request. + */ + @JsonProperty("error") + public abstract Builder error(JobError error); + + /** + * Setter for error builder. + * + *

error: The error encountered while processing the request. + */ + public Builder error(JobError.Builder errorBuilder) { + return error(errorBuilder.build()); + } + + public abstract InlinedEmbedContentResponse build(); + } + + /** Deserializes a JSON string to a InlinedEmbedContentResponse object. */ + @ExcludeFromGeneratedCoverageReport + public static InlinedEmbedContentResponse fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, InlinedEmbedContentResponse.class); + } +} diff --git a/src/main/java/com/google/genai/types/InlinedRequest.java b/src/main/java/com/google/genai/types/InlinedRequest.java index 33c2aee7141..2aeda758178 100644 --- a/src/main/java/com/google/genai/types/InlinedRequest.java +++ b/src/main/java/com/google/genai/types/InlinedRequest.java @@ -27,6 +27,7 @@ import com.google.genai.JsonSerializable; import java.util.Arrays; import java.util.List; +import java.util.Map; import java.util.Optional; /** Config for inlined request. */ @@ -44,11 +45,16 @@ public abstract class InlinedRequest extends JsonSerializable { @JsonProperty("contents") public abstract Optional> contents(); + /** The metadata to be associated with the request. */ + @JsonProperty("metadata") + public abstract Optional> metadata(); + /** Configuration that contains optional model parameters. */ @JsonProperty("config") public abstract Optional config(); /** Instantiates a builder for InlinedRequest. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_InlinedRequest.Builder(); } @@ -103,6 +109,14 @@ public Builder contents(Content.Builder... contentsBuilders) { .collect(toImmutableList())); } + /** + * Setter for metadata. + * + *

metadata: The metadata to be associated with the request. + */ + @JsonProperty("metadata") + public abstract Builder metadata(Map metadata); + /** * Setter for config. * @@ -124,6 +138,7 @@ public Builder config(GenerateContentConfig.Builder configBuilder) { } /** Deserializes a JSON string to a InlinedRequest object. */ + @ExcludeFromGeneratedCoverageReport public static InlinedRequest fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, InlinedRequest.class); } diff --git a/src/main/java/com/google/genai/types/InlinedResponse.java b/src/main/java/com/google/genai/types/InlinedResponse.java index ae0e13ad674..acc198b8bed 100644 --- a/src/main/java/com/google/genai/types/InlinedResponse.java +++ b/src/main/java/com/google/genai/types/InlinedResponse.java @@ -38,6 +38,7 @@ public abstract class InlinedResponse extends JsonSerializable { public abstract Optional error(); /** Instantiates a builder for InlinedResponse. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_InlinedResponse.Builder(); } @@ -92,6 +93,7 @@ public Builder error(JobError.Builder errorBuilder) { } /** Deserializes a JSON string to a InlinedResponse object. */ + @ExcludeFromGeneratedCoverageReport public static InlinedResponse fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, InlinedResponse.class); } diff --git a/src/main/java/com/google/genai/types/Interval.java b/src/main/java/com/google/genai/types/Interval.java index 4d594132fed..839e9872391 100644 --- a/src/main/java/com/google/genai/types/Interval.java +++ b/src/main/java/com/google/genai/types/Interval.java @@ -27,24 +27,30 @@ import java.util.Optional; /** - * Represents a time interval, encoded as a start time (inclusive) and an end time (exclusive). - * - *

The start time must be less than or equal to the end time. When the start equals the end time, - * the interval is an empty interval. (matches no time) When both start and end are unspecified, the - * interval matches any time. + * Represents a time interval, encoded as a Timestamp start (inclusive) and a Timestamp end + * (exclusive). The start must be less than or equal to the end. When the start equals the end, the + * interval is empty (matches no time). When both start and end are unspecified, the interval + * matches any time. */ @AutoValue @JsonDeserialize(builder = Interval.Builder.class) public abstract class Interval extends JsonSerializable { - /** The start time of the interval. */ - @JsonProperty("startTime") - public abstract Optional startTime(); - - /** The end time of the interval. */ + /** + * Optional. Exclusive end of the interval. If specified, a Timestamp matching this interval will + * have to be before the end. + */ @JsonProperty("endTime") public abstract Optional endTime(); + /** + * Optional. Inclusive start of the interval. If specified, a Timestamp matching this interval + * will have to be the same or after the start. + */ + @JsonProperty("startTime") + public abstract Optional startTime(); + /** Instantiates a builder for Interval. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_Interval.Builder(); } @@ -62,25 +68,28 @@ private static Builder create() { } /** - * Setter for startTime. + * Setter for endTime. * - *

startTime: The start time of the interval. + *

endTime: Optional. Exclusive end of the interval. If specified, a Timestamp matching this + * interval will have to be before the end. */ - @JsonProperty("startTime") - public abstract Builder startTime(Instant startTime); + @JsonProperty("endTime") + public abstract Builder endTime(Instant endTime); /** - * Setter for endTime. + * Setter for startTime. * - *

endTime: The end time of the interval. + *

startTime: Optional. Inclusive start of the interval. If specified, a Timestamp matching + * this interval will have to be the same or after the start. */ - @JsonProperty("endTime") - public abstract Builder endTime(Instant endTime); + @JsonProperty("startTime") + public abstract Builder startTime(Instant startTime); public abstract Interval build(); } /** Deserializes a JSON string to a Interval object. */ + @ExcludeFromGeneratedCoverageReport public static Interval fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, Interval.class); } diff --git a/src/main/java/com/google/genai/types/JobError.java b/src/main/java/com/google/genai/types/JobError.java index 5f2983b912f..39967cd4f06 100644 --- a/src/main/java/com/google/genai/types/JobError.java +++ b/src/main/java/com/google/genai/types/JobError.java @@ -50,6 +50,7 @@ public abstract class JobError extends JsonSerializable { public abstract Optional message(); /** Instantiates a builder for JobError. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_JobError.Builder(); } @@ -106,6 +107,7 @@ public Builder details(String... details) { } /** Deserializes a JSON string to a JobError object. */ + @ExcludeFromGeneratedCoverageReport public static JobError fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, JobError.class); } diff --git a/src/main/java/com/google/genai/types/JobState.java b/src/main/java/com/google/genai/types/JobState.java index 8c0038e47b4..09a7f8b0e98 100644 --- a/src/main/java/com/google/genai/types/JobState.java +++ b/src/main/java/com/google/genai/types/JobState.java @@ -93,12 +93,14 @@ public JobState(Known knownValue) { this.value = knownValue.toString(); } + @ExcludeFromGeneratedCoverageReport @Override @JsonValue public String toString() { return this.value; } + @ExcludeFromGeneratedCoverageReport @SuppressWarnings("PatternMatchingInstanceof") @Override public boolean equals(Object o) { @@ -125,6 +127,7 @@ public boolean equals(Object o) { return false; } + @ExcludeFromGeneratedCoverageReport @Override public int hashCode() { if (this.jobStateEnum != Known.JOB_STATE_UNSPECIFIED) { @@ -134,6 +137,7 @@ public int hashCode() { } } + @ExcludeFromGeneratedCoverageReport public Known knownEnum() { return this.jobStateEnum; } diff --git a/src/main/java/com/google/genai/types/Language.java b/src/main/java/com/google/genai/types/Language.java index 477a3bef61d..aac076fa822 100644 --- a/src/main/java/com/google/genai/types/Language.java +++ b/src/main/java/com/google/genai/types/Language.java @@ -23,7 +23,7 @@ import com.google.common.base.Ascii; import java.util.Objects; -/** Required. Programming language of the `code`. */ +/** Programming language of the `code`. */ public class Language { /** Enum representing the known values for Language. */ @@ -57,12 +57,14 @@ public Language(Known knownValue) { this.value = knownValue.toString(); } + @ExcludeFromGeneratedCoverageReport @Override @JsonValue public String toString() { return this.value; } + @ExcludeFromGeneratedCoverageReport @SuppressWarnings("PatternMatchingInstanceof") @Override public boolean equals(Object o) { @@ -89,6 +91,7 @@ public boolean equals(Object o) { return false; } + @ExcludeFromGeneratedCoverageReport @Override public int hashCode() { if (this.languageEnum != Known.LANGUAGE_UNSPECIFIED) { @@ -98,6 +101,7 @@ public int hashCode() { } } + @ExcludeFromGeneratedCoverageReport public Known knownEnum() { return this.languageEnum; } diff --git a/src/main/java/com/google/genai/types/LatLng.java b/src/main/java/com/google/genai/types/LatLng.java index ad5bfc526fc..41f0a1d49ac 100644 --- a/src/main/java/com/google/genai/types/LatLng.java +++ b/src/main/java/com/google/genai/types/LatLng.java @@ -45,6 +45,7 @@ public abstract class LatLng extends JsonSerializable { public abstract Optional longitude(); /** Instantiates a builder for LatLng. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_LatLng.Builder(); } @@ -81,6 +82,7 @@ private static Builder create() { } /** Deserializes a JSON string to a LatLng object. */ + @ExcludeFromGeneratedCoverageReport public static LatLng fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, LatLng.class); } diff --git a/src/main/java/com/google/genai/types/ListBatchJobsConfig.java b/src/main/java/com/google/genai/types/ListBatchJobsConfig.java index 30923c639d2..65a6389766c 100644 --- a/src/main/java/com/google/genai/types/ListBatchJobsConfig.java +++ b/src/main/java/com/google/genai/types/ListBatchJobsConfig.java @@ -46,6 +46,7 @@ public abstract class ListBatchJobsConfig extends JsonSerializable { public abstract Optional filter(); /** Instantiates a builder for ListBatchJobsConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_ListBatchJobsConfig.Builder(); } @@ -107,6 +108,7 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { } /** Deserializes a JSON string to a ListBatchJobsConfig object. */ + @ExcludeFromGeneratedCoverageReport public static ListBatchJobsConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, ListBatchJobsConfig.class); } diff --git a/src/main/java/com/google/genai/types/ListBatchJobsParameters.java b/src/main/java/com/google/genai/types/ListBatchJobsParameters.java index 3be2d047235..606878f8dc6 100644 --- a/src/main/java/com/google/genai/types/ListBatchJobsParameters.java +++ b/src/main/java/com/google/genai/types/ListBatchJobsParameters.java @@ -36,6 +36,7 @@ public abstract class ListBatchJobsParameters extends JsonSerializable { public abstract Optional config(); /** Instantiates a builder for ListBatchJobsParameters. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_ListBatchJobsParameters.Builder(); } @@ -73,6 +74,7 @@ public Builder config(ListBatchJobsConfig.Builder configBuilder) { } /** Deserializes a JSON string to a ListBatchJobsParameters object. */ + @ExcludeFromGeneratedCoverageReport public static ListBatchJobsParameters fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, ListBatchJobsParameters.class); } diff --git a/src/main/java/com/google/genai/types/ListBatchJobsResponse.java b/src/main/java/com/google/genai/types/ListBatchJobsResponse.java index b57695adb9d..4655c444510 100644 --- a/src/main/java/com/google/genai/types/ListBatchJobsResponse.java +++ b/src/main/java/com/google/genai/types/ListBatchJobsResponse.java @@ -33,6 +33,10 @@ @AutoValue @JsonDeserialize(builder = ListBatchJobsResponse.Builder.class) public abstract class ListBatchJobsResponse extends JsonSerializable { + /** Used to retain the full HTTP response. */ + @JsonProperty("sdkHttpResponse") + public abstract Optional sdkHttpResponse(); + /** */ @JsonProperty("nextPageToken") public abstract Optional nextPageToken(); @@ -42,6 +46,7 @@ public abstract class ListBatchJobsResponse extends JsonSerializable { public abstract Optional> batchJobs(); /** Instantiates a builder for ListBatchJobsResponse. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_ListBatchJobsResponse.Builder(); } @@ -58,6 +63,23 @@ private static Builder create() { return new AutoValue_ListBatchJobsResponse.Builder(); } + /** + * Setter for sdkHttpResponse. + * + *

sdkHttpResponse: Used to retain the full HTTP response. + */ + @JsonProperty("sdkHttpResponse") + public abstract Builder sdkHttpResponse(HttpResponse sdkHttpResponse); + + /** + * Setter for sdkHttpResponse builder. + * + *

sdkHttpResponse: Used to retain the full HTTP response. + */ + public Builder sdkHttpResponse(HttpResponse.Builder sdkHttpResponseBuilder) { + return sdkHttpResponse(sdkHttpResponseBuilder.build()); + } + /** * Setter for nextPageToken. * @@ -99,6 +121,7 @@ public Builder batchJobs(BatchJob.Builder... batchJobsBuilders) { } /** Deserializes a JSON string to a ListBatchJobsResponse object. */ + @ExcludeFromGeneratedCoverageReport public static ListBatchJobsResponse fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, ListBatchJobsResponse.class); } diff --git a/src/main/java/com/google/genai/types/ListCachedContentsConfig.java b/src/main/java/com/google/genai/types/ListCachedContentsConfig.java index 338a9297f6d..4a29a20c3f4 100644 --- a/src/main/java/com/google/genai/types/ListCachedContentsConfig.java +++ b/src/main/java/com/google/genai/types/ListCachedContentsConfig.java @@ -42,6 +42,7 @@ public abstract class ListCachedContentsConfig extends JsonSerializable { public abstract Optional pageToken(); /** Instantiates a builder for ListCachedContentsConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_ListCachedContentsConfig.Builder(); } @@ -95,6 +96,7 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { } /** Deserializes a JSON string to a ListCachedContentsConfig object. */ + @ExcludeFromGeneratedCoverageReport public static ListCachedContentsConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, ListCachedContentsConfig.class); } diff --git a/src/main/java/com/google/genai/types/ListCachedContentsParameters.java b/src/main/java/com/google/genai/types/ListCachedContentsParameters.java index 4ce8f98ed27..a8bc82fea91 100644 --- a/src/main/java/com/google/genai/types/ListCachedContentsParameters.java +++ b/src/main/java/com/google/genai/types/ListCachedContentsParameters.java @@ -36,6 +36,7 @@ public abstract class ListCachedContentsParameters extends JsonSerializable { public abstract Optional config(); /** Instantiates a builder for ListCachedContentsParameters. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_ListCachedContentsParameters.Builder(); } @@ -75,6 +76,7 @@ public Builder config(ListCachedContentsConfig.Builder configBuilder) { } /** Deserializes a JSON string to a ListCachedContentsParameters object. */ + @ExcludeFromGeneratedCoverageReport public static ListCachedContentsParameters fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, ListCachedContentsParameters.class); } diff --git a/src/main/java/com/google/genai/types/ListCachedContentsResponse.java b/src/main/java/com/google/genai/types/ListCachedContentsResponse.java index da5d0f0b25d..a5045ada02c 100644 --- a/src/main/java/com/google/genai/types/ListCachedContentsResponse.java +++ b/src/main/java/com/google/genai/types/ListCachedContentsResponse.java @@ -33,6 +33,10 @@ @AutoValue @JsonDeserialize(builder = ListCachedContentsResponse.Builder.class) public abstract class ListCachedContentsResponse extends JsonSerializable { + /** Used to retain the full HTTP response. */ + @JsonProperty("sdkHttpResponse") + public abstract Optional sdkHttpResponse(); + /** */ @JsonProperty("nextPageToken") public abstract Optional nextPageToken(); @@ -42,6 +46,7 @@ public abstract class ListCachedContentsResponse extends JsonSerializable { public abstract Optional> cachedContents(); /** Instantiates a builder for ListCachedContentsResponse. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_ListCachedContentsResponse.Builder(); } @@ -58,6 +63,23 @@ private static Builder create() { return new AutoValue_ListCachedContentsResponse.Builder(); } + /** + * Setter for sdkHttpResponse. + * + *

sdkHttpResponse: Used to retain the full HTTP response. + */ + @JsonProperty("sdkHttpResponse") + public abstract Builder sdkHttpResponse(HttpResponse sdkHttpResponse); + + /** + * Setter for sdkHttpResponse builder. + * + *

sdkHttpResponse: Used to retain the full HTTP response. + */ + public Builder sdkHttpResponse(HttpResponse.Builder sdkHttpResponseBuilder) { + return sdkHttpResponse(sdkHttpResponseBuilder.build()); + } + /** * Setter for nextPageToken. * @@ -99,6 +121,7 @@ public Builder cachedContents(CachedContent.Builder... cachedContentsBuilders) { } /** Deserializes a JSON string to a ListCachedContentsResponse object. */ + @ExcludeFromGeneratedCoverageReport public static ListCachedContentsResponse fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, ListCachedContentsResponse.class); } diff --git a/src/main/java/com/google/genai/types/ListFilesConfig.java b/src/main/java/com/google/genai/types/ListFilesConfig.java index a46083ddac2..649fce5524a 100644 --- a/src/main/java/com/google/genai/types/ListFilesConfig.java +++ b/src/main/java/com/google/genai/types/ListFilesConfig.java @@ -42,6 +42,7 @@ public abstract class ListFilesConfig extends JsonSerializable { public abstract Optional pageToken(); /** Instantiates a builder for ListFilesConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_ListFilesConfig.Builder(); } @@ -95,6 +96,7 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { } /** Deserializes a JSON string to a ListFilesConfig object. */ + @ExcludeFromGeneratedCoverageReport public static ListFilesConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, ListFilesConfig.class); } diff --git a/src/main/java/com/google/genai/types/ListFilesParameters.java b/src/main/java/com/google/genai/types/ListFilesParameters.java index e2417de3ebd..7eeaedd873c 100644 --- a/src/main/java/com/google/genai/types/ListFilesParameters.java +++ b/src/main/java/com/google/genai/types/ListFilesParameters.java @@ -36,6 +36,7 @@ public abstract class ListFilesParameters extends JsonSerializable { public abstract Optional config(); /** Instantiates a builder for ListFilesParameters. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_ListFilesParameters.Builder(); } @@ -73,6 +74,7 @@ public Builder config(ListFilesConfig.Builder configBuilder) { } /** Deserializes a JSON string to a ListFilesParameters object. */ + @ExcludeFromGeneratedCoverageReport public static ListFilesParameters fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, ListFilesParameters.class); } diff --git a/src/main/java/com/google/genai/types/ListFilesResponse.java b/src/main/java/com/google/genai/types/ListFilesResponse.java index 4867007b571..60bf3b3a993 100644 --- a/src/main/java/com/google/genai/types/ListFilesResponse.java +++ b/src/main/java/com/google/genai/types/ListFilesResponse.java @@ -33,15 +33,20 @@ @AutoValue @JsonDeserialize(builder = ListFilesResponse.Builder.class) public abstract class ListFilesResponse extends JsonSerializable { - /** A token to retrieve next page of results. */ + /** Used to retain the full HTTP response. */ + @JsonProperty("sdkHttpResponse") + public abstract Optional sdkHttpResponse(); + + /** A token that can be sent as a `page_token` into a subsequent `ListFiles` call. */ @JsonProperty("nextPageToken") public abstract Optional nextPageToken(); - /** The list of files. */ + /** The list of `File`s. */ @JsonProperty("files") public abstract Optional> files(); /** Instantiates a builder for ListFilesResponse. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_ListFilesResponse.Builder(); } @@ -58,10 +63,28 @@ private static Builder create() { return new AutoValue_ListFilesResponse.Builder(); } + /** + * Setter for sdkHttpResponse. + * + *

sdkHttpResponse: Used to retain the full HTTP response. + */ + @JsonProperty("sdkHttpResponse") + public abstract Builder sdkHttpResponse(HttpResponse sdkHttpResponse); + + /** + * Setter for sdkHttpResponse builder. + * + *

sdkHttpResponse: Used to retain the full HTTP response. + */ + public Builder sdkHttpResponse(HttpResponse.Builder sdkHttpResponseBuilder) { + return sdkHttpResponse(sdkHttpResponseBuilder.build()); + } + /** * Setter for nextPageToken. * - *

nextPageToken: A token to retrieve next page of results. + *

nextPageToken: A token that can be sent as a `page_token` into a subsequent `ListFiles` + * call. */ @JsonProperty("nextPageToken") public abstract Builder nextPageToken(String nextPageToken); @@ -69,7 +92,7 @@ private static Builder create() { /** * Setter for files. * - *

files: The list of files. + *

files: The list of `File`s. */ @JsonProperty("files") public abstract Builder files(List files); @@ -77,7 +100,7 @@ private static Builder create() { /** * Setter for files. * - *

files: The list of files. + *

files: The list of `File`s. */ public Builder files(File... files) { return files(Arrays.asList(files)); @@ -86,7 +109,7 @@ public Builder files(File... files) { /** * Setter for files builder. * - *

files: The list of files. + *

files: The list of `File`s. */ public Builder files(File.Builder... filesBuilders) { return files( @@ -99,6 +122,7 @@ public Builder files(File.Builder... filesBuilders) { } /** Deserializes a JSON string to a ListFilesResponse object. */ + @ExcludeFromGeneratedCoverageReport public static ListFilesResponse fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, ListFilesResponse.class); } diff --git a/src/main/java/com/google/genai/types/ListModelsConfig.java b/src/main/java/com/google/genai/types/ListModelsConfig.java index 9dfe672fcd2..90ca40b96ca 100644 --- a/src/main/java/com/google/genai/types/ListModelsConfig.java +++ b/src/main/java/com/google/genai/types/ListModelsConfig.java @@ -50,6 +50,7 @@ public abstract class ListModelsConfig extends JsonSerializable { public abstract Optional queryBase(); /** Instantiates a builder for ListModelsConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_ListModelsConfig.Builder(); } @@ -119,6 +120,7 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { } /** Deserializes a JSON string to a ListModelsConfig object. */ + @ExcludeFromGeneratedCoverageReport public static ListModelsConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, ListModelsConfig.class); } diff --git a/src/main/java/com/google/genai/types/ListModelsParameters.java b/src/main/java/com/google/genai/types/ListModelsParameters.java index fa4169b3e2b..99bb4b2f738 100644 --- a/src/main/java/com/google/genai/types/ListModelsParameters.java +++ b/src/main/java/com/google/genai/types/ListModelsParameters.java @@ -36,6 +36,7 @@ public abstract class ListModelsParameters extends JsonSerializable { public abstract Optional config(); /** Instantiates a builder for ListModelsParameters. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_ListModelsParameters.Builder(); } @@ -73,6 +74,7 @@ public Builder config(ListModelsConfig.Builder configBuilder) { } /** Deserializes a JSON string to a ListModelsParameters object. */ + @ExcludeFromGeneratedCoverageReport public static ListModelsParameters fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, ListModelsParameters.class); } diff --git a/src/main/java/com/google/genai/types/ListModelsResponse.java b/src/main/java/com/google/genai/types/ListModelsResponse.java index cad1837255b..d67ad7dacdf 100644 --- a/src/main/java/com/google/genai/types/ListModelsResponse.java +++ b/src/main/java/com/google/genai/types/ListModelsResponse.java @@ -33,6 +33,10 @@ @AutoValue @JsonDeserialize(builder = ListModelsResponse.Builder.class) public abstract class ListModelsResponse extends JsonSerializable { + /** Used to retain the full HTTP response. */ + @JsonProperty("sdkHttpResponse") + public abstract Optional sdkHttpResponse(); + /** */ @JsonProperty("nextPageToken") public abstract Optional nextPageToken(); @@ -42,6 +46,7 @@ public abstract class ListModelsResponse extends JsonSerializable { public abstract Optional> models(); /** Instantiates a builder for ListModelsResponse. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_ListModelsResponse.Builder(); } @@ -58,6 +63,23 @@ private static Builder create() { return new AutoValue_ListModelsResponse.Builder(); } + /** + * Setter for sdkHttpResponse. + * + *

sdkHttpResponse: Used to retain the full HTTP response. + */ + @JsonProperty("sdkHttpResponse") + public abstract Builder sdkHttpResponse(HttpResponse sdkHttpResponse); + + /** + * Setter for sdkHttpResponse builder. + * + *

sdkHttpResponse: Used to retain the full HTTP response. + */ + public Builder sdkHttpResponse(HttpResponse.Builder sdkHttpResponseBuilder) { + return sdkHttpResponse(sdkHttpResponseBuilder.build()); + } + /** * Setter for nextPageToken. * @@ -99,6 +121,7 @@ public Builder models(Model.Builder... modelsBuilders) { } /** Deserializes a JSON string to a ListModelsResponse object. */ + @ExcludeFromGeneratedCoverageReport public static ListModelsResponse fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, ListModelsResponse.class); } diff --git a/src/main/java/com/google/genai/types/ListTuningJobsConfig.java b/src/main/java/com/google/genai/types/ListTuningJobsConfig.java index 3e5cac6644b..0fd8076116d 100644 --- a/src/main/java/com/google/genai/types/ListTuningJobsConfig.java +++ b/src/main/java/com/google/genai/types/ListTuningJobsConfig.java @@ -46,6 +46,7 @@ public abstract class ListTuningJobsConfig extends JsonSerializable { public abstract Optional filter(); /** Instantiates a builder for ListTuningJobsConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_ListTuningJobsConfig.Builder(); } @@ -107,6 +108,7 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { } /** Deserializes a JSON string to a ListTuningJobsConfig object. */ + @ExcludeFromGeneratedCoverageReport public static ListTuningJobsConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, ListTuningJobsConfig.class); } diff --git a/src/main/java/com/google/genai/types/ListTuningJobsParameters.java b/src/main/java/com/google/genai/types/ListTuningJobsParameters.java index 26765a4eb27..00d6baf7752 100644 --- a/src/main/java/com/google/genai/types/ListTuningJobsParameters.java +++ b/src/main/java/com/google/genai/types/ListTuningJobsParameters.java @@ -36,6 +36,7 @@ public abstract class ListTuningJobsParameters extends JsonSerializable { public abstract Optional config(); /** Instantiates a builder for ListTuningJobsParameters. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_ListTuningJobsParameters.Builder(); } @@ -73,6 +74,7 @@ public Builder config(ListTuningJobsConfig.Builder configBuilder) { } /** Deserializes a JSON string to a ListTuningJobsParameters object. */ + @ExcludeFromGeneratedCoverageReport public static ListTuningJobsParameters fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, ListTuningJobsParameters.class); } diff --git a/src/main/java/com/google/genai/types/ListTuningJobsResponse.java b/src/main/java/com/google/genai/types/ListTuningJobsResponse.java index 635484714e3..dc12d347bdf 100644 --- a/src/main/java/com/google/genai/types/ListTuningJobsResponse.java +++ b/src/main/java/com/google/genai/types/ListTuningJobsResponse.java @@ -33,6 +33,10 @@ @AutoValue @JsonDeserialize(builder = ListTuningJobsResponse.Builder.class) public abstract class ListTuningJobsResponse extends JsonSerializable { + /** Used to retain the full HTTP response. */ + @JsonProperty("sdkHttpResponse") + public abstract Optional sdkHttpResponse(); + /** * A token to retrieve the next page of results. Pass to ListTuningJobsRequest.page_token to * obtain that page. @@ -45,6 +49,7 @@ public abstract class ListTuningJobsResponse extends JsonSerializable { public abstract Optional> tuningJobs(); /** Instantiates a builder for ListTuningJobsResponse. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_ListTuningJobsResponse.Builder(); } @@ -61,6 +66,23 @@ private static Builder create() { return new AutoValue_ListTuningJobsResponse.Builder(); } + /** + * Setter for sdkHttpResponse. + * + *

sdkHttpResponse: Used to retain the full HTTP response. + */ + @JsonProperty("sdkHttpResponse") + public abstract Builder sdkHttpResponse(HttpResponse sdkHttpResponse); + + /** + * Setter for sdkHttpResponse builder. + * + *

sdkHttpResponse: Used to retain the full HTTP response. + */ + public Builder sdkHttpResponse(HttpResponse.Builder sdkHttpResponseBuilder) { + return sdkHttpResponse(sdkHttpResponseBuilder.build()); + } + /** * Setter for nextPageToken. * @@ -103,6 +125,7 @@ public Builder tuningJobs(TuningJob.Builder... tuningJobsBuilders) { } /** Deserializes a JSON string to a ListTuningJobsResponse object. */ + @ExcludeFromGeneratedCoverageReport public static ListTuningJobsResponse fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, ListTuningJobsResponse.class); } diff --git a/src/main/java/com/google/genai/types/LiveClientContent.java b/src/main/java/com/google/genai/types/LiveClientContent.java index f712b1c9a20..ae900e9d8c7 100644 --- a/src/main/java/com/google/genai/types/LiveClientContent.java +++ b/src/main/java/com/google/genai/types/LiveClientContent.java @@ -58,6 +58,7 @@ public abstract class LiveClientContent extends JsonSerializable { public abstract Optional turnComplete(); /** Instantiates a builder for LiveClientContent. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_LiveClientContent.Builder(); } @@ -126,6 +127,7 @@ public Builder turns(Content.Builder... turnsBuilders) { } /** Deserializes a JSON string to a LiveClientContent object. */ + @ExcludeFromGeneratedCoverageReport public static LiveClientContent fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, LiveClientContent.class); } diff --git a/src/main/java/com/google/genai/types/LiveClientMessage.java b/src/main/java/com/google/genai/types/LiveClientMessage.java index b794b050d26..9762ae2c86d 100644 --- a/src/main/java/com/google/genai/types/LiveClientMessage.java +++ b/src/main/java/com/google/genai/types/LiveClientMessage.java @@ -57,6 +57,7 @@ public abstract class LiveClientMessage extends JsonSerializable { public abstract Optional toolResponse(); /** Instantiates a builder for LiveClientMessage. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_LiveClientMessage.Builder(); } @@ -170,6 +171,7 @@ public Builder toolResponse(LiveClientToolResponse.Builder toolResponseBuilder) } /** Deserializes a JSON string to a LiveClientMessage object. */ + @ExcludeFromGeneratedCoverageReport public static LiveClientMessage fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, LiveClientMessage.class); } diff --git a/src/main/java/com/google/genai/types/LiveClientRealtimeInput.java b/src/main/java/com/google/genai/types/LiveClientRealtimeInput.java index 512d317cfc7..2b2adf713e1 100644 --- a/src/main/java/com/google/genai/types/LiveClientRealtimeInput.java +++ b/src/main/java/com/google/genai/types/LiveClientRealtimeInput.java @@ -81,6 +81,7 @@ public abstract class LiveClientRealtimeInput extends JsonSerializable { public abstract Optional activityEnd(); /** Instantiates a builder for LiveClientRealtimeInput. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_LiveClientRealtimeInput.Builder(); } @@ -220,6 +221,7 @@ public Builder activityEnd(ActivityEnd.Builder activityEndBuilder) { } /** Deserializes a JSON string to a LiveClientRealtimeInput object. */ + @ExcludeFromGeneratedCoverageReport public static LiveClientRealtimeInput fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, LiveClientRealtimeInput.class); } diff --git a/src/main/java/com/google/genai/types/LiveClientSetup.java b/src/main/java/com/google/genai/types/LiveClientSetup.java index d11f227f463..f82dd8c611e 100644 --- a/src/main/java/com/google/genai/types/LiveClientSetup.java +++ b/src/main/java/com/google/genai/types/LiveClientSetup.java @@ -95,6 +95,7 @@ public abstract class LiveClientSetup extends JsonSerializable { public abstract Optional proactivity(); /** Instantiates a builder for LiveClientSetup. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_LiveClientSetup.Builder(); } @@ -321,6 +322,7 @@ public Builder proactivity(ProactivityConfig.Builder proactivityBuilder) { } /** Deserializes a JSON string to a LiveClientSetup object. */ + @ExcludeFromGeneratedCoverageReport public static LiveClientSetup fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, LiveClientSetup.class); } diff --git a/src/main/java/com/google/genai/types/LiveClientToolResponse.java b/src/main/java/com/google/genai/types/LiveClientToolResponse.java index ea6f7d4b297..bd4a942ebd3 100644 --- a/src/main/java/com/google/genai/types/LiveClientToolResponse.java +++ b/src/main/java/com/google/genai/types/LiveClientToolResponse.java @@ -47,6 +47,7 @@ public abstract class LiveClientToolResponse extends JsonSerializable { public abstract Optional> functionResponses(); /** Instantiates a builder for LiveClientToolResponse. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_LiveClientToolResponse.Builder(); } @@ -96,6 +97,7 @@ public Builder functionResponses(FunctionResponse.Builder... functionResponsesBu } /** Deserializes a JSON string to a LiveClientToolResponse object. */ + @ExcludeFromGeneratedCoverageReport public static LiveClientToolResponse fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, LiveClientToolResponse.class); } diff --git a/src/main/java/com/google/genai/types/LiveConnectConfig.java b/src/main/java/com/google/genai/types/LiveConnectConfig.java index b345e177f68..2a9576524d2 100644 --- a/src/main/java/com/google/genai/types/LiveConnectConfig.java +++ b/src/main/java/com/google/genai/types/LiveConnectConfig.java @@ -90,6 +90,13 @@ public abstract class LiveConnectConfig extends JsonSerializable { @JsonProperty("speechConfig") public abstract Optional speechConfig(); + /** + * Config for thinking features. An error will be returned if this field is set for models that + * don't support thinking. + */ + @JsonProperty("thinkingConfig") + public abstract Optional thinkingConfig(); + /** If enabled, the model will detect emotions and adapt its responses accordingly. */ @JsonProperty("enableAffectiveDialog") public abstract Optional enableAffectiveDialog(); @@ -148,6 +155,7 @@ public abstract class LiveConnectConfig extends JsonSerializable { public abstract Optional proactivity(); /** Instantiates a builder for LiveConnectConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_LiveConnectConfig.Builder(); } @@ -341,6 +349,25 @@ public Builder speechConfig(SpeechConfig.Builder speechConfigBuilder) { return speechConfig(speechConfigBuilder.build()); } + /** + * Setter for thinkingConfig. + * + *

thinkingConfig: Config for thinking features. An error will be returned if this field is + * set for models that don't support thinking. + */ + @JsonProperty("thinkingConfig") + public abstract Builder thinkingConfig(ThinkingConfig thinkingConfig); + + /** + * Setter for thinkingConfig builder. + * + *

thinkingConfig: Config for thinking features. An error will be returned if this field is + * set for models that don't support thinking. + */ + public Builder thinkingConfig(ThinkingConfig.Builder thinkingConfigBuilder) { + return thinkingConfig(thinkingConfigBuilder.build()); + } + /** * Setter for enableAffectiveDialog. * @@ -533,6 +560,7 @@ public Builder proactivity(ProactivityConfig.Builder proactivityBuilder) { } /** Deserializes a JSON string to a LiveConnectConfig object. */ + @ExcludeFromGeneratedCoverageReport public static LiveConnectConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, LiveConnectConfig.class); } diff --git a/src/main/java/com/google/genai/types/LiveConnectConstraints.java b/src/main/java/com/google/genai/types/LiveConnectConstraints.java deleted file mode 100644 index 7917044eda4..00000000000 --- a/src/main/java/com/google/genai/types/LiveConnectConstraints.java +++ /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 - * - * 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. - */ - -// Auto-generated code. Do not edit. - -package com.google.genai.types; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.google.auto.value.AutoValue; -import com.google.genai.JsonSerializable; -import java.util.Optional; - -/** Config for LiveConnectConstraints for Auth Token creation. */ -@AutoValue -@JsonDeserialize(builder = LiveConnectConstraints.Builder.class) -public abstract class LiveConnectConstraints extends JsonSerializable { - /** - * ID of the model to configure in the ephemeral token for Live API. For a list of models, see - * `Gemini models `. - */ - @JsonProperty("model") - public abstract Optional model(); - - /** Configuration specific to Live API connections created using this token. */ - @JsonProperty("config") - public abstract Optional config(); - - /** Instantiates a builder for LiveConnectConstraints. */ - public static Builder builder() { - return new AutoValue_LiveConnectConstraints.Builder(); - } - - /** Creates a builder with the same values as this instance. */ - public abstract Builder toBuilder(); - - /** Builder for LiveConnectConstraints. */ - @AutoValue.Builder - public abstract static class Builder { - /** For internal usage. Please use `LiveConnectConstraints.builder()` for instantiation. */ - @JsonCreator - private static Builder create() { - return new AutoValue_LiveConnectConstraints.Builder(); - } - - /** - * Setter for model. - * - *

model: ID of the model to configure in the ephemeral token for Live API. For a list of - * models, see `Gemini models `. - */ - @JsonProperty("model") - public abstract Builder model(String model); - - /** - * Setter for config. - * - *

config: Configuration specific to Live API connections created using this token. - */ - @JsonProperty("config") - public abstract Builder config(LiveConnectConfig config); - - /** - * Setter for config builder. - * - *

config: Configuration specific to Live API connections created using this token. - */ - public Builder config(LiveConnectConfig.Builder configBuilder) { - return config(configBuilder.build()); - } - - public abstract LiveConnectConstraints build(); - } - - /** Deserializes a JSON string to a LiveConnectConstraints object. */ - public static LiveConnectConstraints fromJson(String jsonString) { - return JsonSerializable.fromJsonString(jsonString, LiveConnectConstraints.class); - } -} diff --git a/src/main/java/com/google/genai/types/LiveConnectParameters.java b/src/main/java/com/google/genai/types/LiveConnectParameters.java index 4378d220025..dbafc2a4d85 100644 --- a/src/main/java/com/google/genai/types/LiveConnectParameters.java +++ b/src/main/java/com/google/genai/types/LiveConnectParameters.java @@ -41,6 +41,7 @@ public abstract class LiveConnectParameters extends JsonSerializable { public abstract Optional config(); /** Instantiates a builder for LiveConnectParameters. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_LiveConnectParameters.Builder(); } @@ -87,6 +88,7 @@ public Builder config(LiveConnectConfig.Builder configBuilder) { } /** Deserializes a JSON string to a LiveConnectParameters object. */ + @ExcludeFromGeneratedCoverageReport public static LiveConnectParameters fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, LiveConnectParameters.class); } diff --git a/src/main/java/com/google/genai/types/LiveConstrainedParameters.java b/src/main/java/com/google/genai/types/LiveConstrainedParameters.java deleted file mode 100644 index abe2fb5f2fb..00000000000 --- a/src/main/java/com/google/genai/types/LiveConstrainedParameters.java +++ /dev/null @@ -1,73 +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 - * - * 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. - */ - -// Auto-generated code. Do not edit. - -package com.google.genai.types; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.google.auto.value.AutoValue; -import com.google.genai.JsonSerializable; -import java.util.Optional; - -/** Config for LiveConstrainedParameters for Auth Token creation. */ -@AutoValue -@JsonDeserialize(builder = LiveConstrainedParameters.Builder.class) -public abstract class LiveConstrainedParameters extends JsonSerializable { - /** - * ID of the model to configure in the ephemeral token for Live API. For a list of models, see - * `Gemini models `. - */ - @JsonProperty("model") - public abstract Optional model(); - - /** Configuration specific to Live API connections created using this token. */ - @JsonProperty("config") - public abstract Optional config(); - - /** Instantiates a builder for LiveConstrainedParameters. */ - public static Builder builder() { - return new AutoValue_LiveConstrainedParameters.Builder(); - } - - /** Creates a builder with the same values as this instance. */ - public abstract Builder toBuilder(); - - /** Builder for LiveConstrainedParameters. */ - @AutoValue.Builder - public abstract static class Builder { - /** For internal usage. Please use `LiveConstrainedParameters.builder()` for instantiation. */ - @JsonCreator - private static Builder create() { - return new AutoValue_LiveConstrainedParameters.Builder(); - } - - @JsonProperty("model") - public abstract Builder model(String model); - - @JsonProperty("config") - public abstract Builder config(LiveConnectConfig config); - - public abstract LiveConstrainedParameters build(); - } - - /** Deserializes a JSON string to a LiveConstrainedParameters object. */ - public static LiveConstrainedParameters fromJson(String jsonString) { - return JsonSerializable.fromJsonString(jsonString, LiveConstrainedParameters.class); - } -} diff --git a/src/main/java/com/google/genai/types/LiveSendClientContentParameters.java b/src/main/java/com/google/genai/types/LiveSendClientContentParameters.java index 65fdd34d568..383749da750 100644 --- a/src/main/java/com/google/genai/types/LiveSendClientContentParameters.java +++ b/src/main/java/com/google/genai/types/LiveSendClientContentParameters.java @@ -46,6 +46,7 @@ public abstract class LiveSendClientContentParameters extends JsonSerializable { public abstract Optional turnComplete(); /** Instantiates a builder for LiveSendClientContentParameters. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_LiveSendClientContentParameters.Builder(); } @@ -107,6 +108,7 @@ public Builder turns(Content.Builder... turnsBuilders) { } /** Deserializes a JSON string to a LiveSendClientContentParameters object. */ + @ExcludeFromGeneratedCoverageReport public static LiveSendClientContentParameters fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, LiveSendClientContentParameters.class); } diff --git a/src/main/java/com/google/genai/types/LiveSendRealtimeInputParameters.java b/src/main/java/com/google/genai/types/LiveSendRealtimeInputParameters.java index 3d5f67fa9f3..8bbb330fdbe 100644 --- a/src/main/java/com/google/genai/types/LiveSendRealtimeInputParameters.java +++ b/src/main/java/com/google/genai/types/LiveSendRealtimeInputParameters.java @@ -65,6 +65,7 @@ public abstract class LiveSendRealtimeInputParameters extends JsonSerializable { public abstract Optional activityEnd(); /** Instantiates a builder for LiveSendRealtimeInputParameters. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_LiveSendRealtimeInputParameters.Builder(); } @@ -194,6 +195,7 @@ public Builder activityEnd(ActivityEnd.Builder activityEndBuilder) { } /** Deserializes a JSON string to a LiveSendRealtimeInputParameters object. */ + @ExcludeFromGeneratedCoverageReport public static LiveSendRealtimeInputParameters fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, LiveSendRealtimeInputParameters.class); } diff --git a/src/main/java/com/google/genai/types/LiveSendToolResponseParameters.java b/src/main/java/com/google/genai/types/LiveSendToolResponseParameters.java index 1bdc2edb7b2..efa3155eefc 100644 --- a/src/main/java/com/google/genai/types/LiveSendToolResponseParameters.java +++ b/src/main/java/com/google/genai/types/LiveSendToolResponseParameters.java @@ -38,6 +38,7 @@ public abstract class LiveSendToolResponseParameters extends JsonSerializable { public abstract Optional> functionResponses(); /** Instantiates a builder for LiveSendToolResponseParameters. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_LiveSendToolResponseParameters.Builder(); } @@ -89,6 +90,7 @@ public Builder functionResponses(FunctionResponse.Builder... functionResponsesBu } /** Deserializes a JSON string to a LiveSendToolResponseParameters object. */ + @ExcludeFromGeneratedCoverageReport public static LiveSendToolResponseParameters fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, LiveSendToolResponseParameters.class); } diff --git a/src/main/java/com/google/genai/types/LiveServerContent.java b/src/main/java/com/google/genai/types/LiveServerContent.java index fc444eb5fc6..f9a43f481b2 100644 --- a/src/main/java/com/google/genai/types/LiveServerContent.java +++ b/src/main/java/com/google/genai/types/LiveServerContent.java @@ -22,6 +22,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.google.auto.value.AutoValue; +import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.genai.JsonSerializable; import java.util.Optional; @@ -87,7 +88,19 @@ public abstract class LiveServerContent extends JsonSerializable { @JsonProperty("urlContextMetadata") public abstract Optional urlContextMetadata(); + /** Reason for the turn is complete. */ + @JsonProperty("turnCompleteReason") + public abstract Optional turnCompleteReason(); + + /** + * If true, indicates that the model is not generating content because it is waiting for more + * input from the user, e.g. because it expects the user to continue talking. + */ + @JsonProperty("waitingForInput") + public abstract Optional waitingForInput(); + /** Instantiates a builder for LiveServerContent. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_LiveServerContent.Builder(); } @@ -228,10 +241,48 @@ public Builder urlContextMetadata(UrlContextMetadata.Builder urlContextMetadataB return urlContextMetadata(urlContextMetadataBuilder.build()); } + /** + * Setter for turnCompleteReason. + * + *

turnCompleteReason: Reason for the turn is complete. + */ + @JsonProperty("turnCompleteReason") + public abstract Builder turnCompleteReason(TurnCompleteReason turnCompleteReason); + + /** + * Setter for turnCompleteReason given a known enum. + * + *

turnCompleteReason: Reason for the turn is complete. + */ + @CanIgnoreReturnValue + public Builder turnCompleteReason(TurnCompleteReason.Known knownType) { + return turnCompleteReason(new TurnCompleteReason(knownType)); + } + + /** + * Setter for turnCompleteReason given a string. + * + *

turnCompleteReason: Reason for the turn is complete. + */ + @CanIgnoreReturnValue + public Builder turnCompleteReason(String turnCompleteReason) { + return turnCompleteReason(new TurnCompleteReason(turnCompleteReason)); + } + + /** + * Setter for waitingForInput. + * + *

waitingForInput: If true, indicates that the model is not generating content because it is + * waiting for more input from the user, e.g. because it expects the user to continue talking. + */ + @JsonProperty("waitingForInput") + public abstract Builder waitingForInput(boolean waitingForInput); + public abstract LiveServerContent build(); } /** Deserializes a JSON string to a LiveServerContent object. */ + @ExcludeFromGeneratedCoverageReport public static LiveServerContent fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, LiveServerContent.class); } diff --git a/src/main/java/com/google/genai/types/LiveServerGoAway.java b/src/main/java/com/google/genai/types/LiveServerGoAway.java index 7a19ead4d2f..a6d9ce157ec 100644 --- a/src/main/java/com/google/genai/types/LiveServerGoAway.java +++ b/src/main/java/com/google/genai/types/LiveServerGoAway.java @@ -38,6 +38,7 @@ public abstract class LiveServerGoAway extends JsonSerializable { public abstract Optional timeLeft(); /** Instantiates a builder for LiveServerGoAway. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_LiveServerGoAway.Builder(); } @@ -68,6 +69,7 @@ private static Builder create() { } /** Deserializes a JSON string to a LiveServerGoAway object. */ + @ExcludeFromGeneratedCoverageReport public static LiveServerGoAway fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, LiveServerGoAway.class); } diff --git a/src/main/java/com/google/genai/types/LiveServerMessage.java b/src/main/java/com/google/genai/types/LiveServerMessage.java index 531433598f3..a62b76d76d3 100644 --- a/src/main/java/com/google/genai/types/LiveServerMessage.java +++ b/src/main/java/com/google/genai/types/LiveServerMessage.java @@ -64,6 +64,7 @@ public abstract class LiveServerMessage extends JsonSerializable { public abstract Optional sessionResumptionUpdate(); /** Instantiates a builder for LiveServerMessage. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_LiveServerMessage.Builder(); } @@ -213,6 +214,7 @@ public Builder sessionResumptionUpdate( } /** Deserializes a JSON string to a LiveServerMessage object. */ + @ExcludeFromGeneratedCoverageReport public static LiveServerMessage fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, LiveServerMessage.class); } diff --git a/src/main/java/com/google/genai/types/LiveServerSessionResumptionUpdate.java b/src/main/java/com/google/genai/types/LiveServerSessionResumptionUpdate.java index c6005af149e..e28a943e71e 100644 --- a/src/main/java/com/google/genai/types/LiveServerSessionResumptionUpdate.java +++ b/src/main/java/com/google/genai/types/LiveServerSessionResumptionUpdate.java @@ -63,6 +63,7 @@ public abstract class LiveServerSessionResumptionUpdate extends JsonSerializable public abstract Optional lastConsumedClientMessageIndex(); /** Instantiates a builder for LiveServerSessionResumptionUpdate. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_LiveServerSessionResumptionUpdate.Builder(); } @@ -126,6 +127,7 @@ private static Builder create() { } /** Deserializes a JSON string to a LiveServerSessionResumptionUpdate object. */ + @ExcludeFromGeneratedCoverageReport public static LiveServerSessionResumptionUpdate fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, LiveServerSessionResumptionUpdate.class); } diff --git a/src/main/java/com/google/genai/types/LiveServerSetupComplete.java b/src/main/java/com/google/genai/types/LiveServerSetupComplete.java index ebf53b7feee..3289b5d328a 100644 --- a/src/main/java/com/google/genai/types/LiveServerSetupComplete.java +++ b/src/main/java/com/google/genai/types/LiveServerSetupComplete.java @@ -34,6 +34,7 @@ public abstract class LiveServerSetupComplete extends JsonSerializable { public abstract Optional sessionId(); /** Instantiates a builder for LiveServerSetupComplete. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_LiveServerSetupComplete.Builder(); } @@ -62,6 +63,7 @@ private static Builder create() { } /** Deserializes a JSON string to a LiveServerSetupComplete object. */ + @ExcludeFromGeneratedCoverageReport public static LiveServerSetupComplete fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, LiveServerSetupComplete.class); } diff --git a/src/main/java/com/google/genai/types/LiveServerToolCall.java b/src/main/java/com/google/genai/types/LiveServerToolCall.java index 0c342f708c3..fceef9db700 100644 --- a/src/main/java/com/google/genai/types/LiveServerToolCall.java +++ b/src/main/java/com/google/genai/types/LiveServerToolCall.java @@ -41,6 +41,7 @@ public abstract class LiveServerToolCall extends JsonSerializable { public abstract Optional> functionCalls(); /** Instantiates a builder for LiveServerToolCall. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_LiveServerToolCall.Builder(); } @@ -90,6 +91,7 @@ public Builder functionCalls(FunctionCall.Builder... functionCallsBuilders) { } /** Deserializes a JSON string to a LiveServerToolCall object. */ + @ExcludeFromGeneratedCoverageReport public static LiveServerToolCall fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, LiveServerToolCall.class); } diff --git a/src/main/java/com/google/genai/types/LiveServerToolCallCancellation.java b/src/main/java/com/google/genai/types/LiveServerToolCallCancellation.java index e4fa4defff8..bec7558e457 100644 --- a/src/main/java/com/google/genai/types/LiveServerToolCallCancellation.java +++ b/src/main/java/com/google/genai/types/LiveServerToolCallCancellation.java @@ -42,6 +42,7 @@ public abstract class LiveServerToolCallCancellation extends JsonSerializable { public abstract Optional> ids(); /** Instantiates a builder for LiveServerToolCallCancellation. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_LiveServerToolCallCancellation.Builder(); } @@ -81,6 +82,7 @@ public Builder ids(String... ids) { } /** Deserializes a JSON string to a LiveServerToolCallCancellation object. */ + @ExcludeFromGeneratedCoverageReport public static LiveServerToolCallCancellation fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, LiveServerToolCallCancellation.class); } diff --git a/src/main/java/com/google/genai/types/LogprobsResult.java b/src/main/java/com/google/genai/types/LogprobsResult.java index 9aa0b0ba1b5..cdaee4368cc 100644 --- a/src/main/java/com/google/genai/types/LogprobsResult.java +++ b/src/main/java/com/google/genai/types/LogprobsResult.java @@ -45,6 +45,7 @@ public abstract class LogprobsResult extends JsonSerializable { public abstract Optional> topCandidates(); /** Instantiates a builder for LogprobsResult. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_LogprobsResult.Builder(); } @@ -126,6 +127,7 @@ public Builder topCandidates(LogprobsResultTopCandidates.Builder... topCandidate } /** Deserializes a JSON string to a LogprobsResult object. */ + @ExcludeFromGeneratedCoverageReport public static LogprobsResult fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, LogprobsResult.class); } diff --git a/src/main/java/com/google/genai/types/LogprobsResultCandidate.java b/src/main/java/com/google/genai/types/LogprobsResultCandidate.java index 9db693c6197..05a003cdff0 100644 --- a/src/main/java/com/google/genai/types/LogprobsResultCandidate.java +++ b/src/main/java/com/google/genai/types/LogprobsResultCandidate.java @@ -42,6 +42,7 @@ public abstract class LogprobsResultCandidate extends JsonSerializable { public abstract Optional tokenId(); /** Instantiates a builder for LogprobsResultCandidate. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_LogprobsResultCandidate.Builder(); } @@ -86,6 +87,7 @@ private static Builder create() { } /** Deserializes a JSON string to a LogprobsResultCandidate object. */ + @ExcludeFromGeneratedCoverageReport public static LogprobsResultCandidate fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, LogprobsResultCandidate.class); } diff --git a/src/main/java/com/google/genai/types/LogprobsResultTopCandidates.java b/src/main/java/com/google/genai/types/LogprobsResultTopCandidates.java index ca1cfe6694a..1f819568e64 100644 --- a/src/main/java/com/google/genai/types/LogprobsResultTopCandidates.java +++ b/src/main/java/com/google/genai/types/LogprobsResultTopCandidates.java @@ -38,6 +38,7 @@ public abstract class LogprobsResultTopCandidates extends JsonSerializable { public abstract Optional> candidates(); /** Instantiates a builder for LogprobsResultTopCandidates. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_LogprobsResultTopCandidates.Builder(); } @@ -87,6 +88,7 @@ public Builder candidates(LogprobsResultCandidate.Builder... candidatesBuilders) } /** Deserializes a JSON string to a LogprobsResultTopCandidates object. */ + @ExcludeFromGeneratedCoverageReport public static LogprobsResultTopCandidates fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, LogprobsResultTopCandidates.class); } diff --git a/src/main/java/com/google/genai/types/MaskReferenceConfig.java b/src/main/java/com/google/genai/types/MaskReferenceConfig.java index ac484ca90d2..64327e37685 100644 --- a/src/main/java/com/google/genai/types/MaskReferenceConfig.java +++ b/src/main/java/com/google/genai/types/MaskReferenceConfig.java @@ -51,6 +51,7 @@ public abstract class MaskReferenceConfig extends JsonSerializable { public abstract Optional maskDilation(); /** Instantiates a builder for MaskReferenceConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_MaskReferenceConfig.Builder(); } @@ -129,6 +130,7 @@ public Builder segmentationClasses(Integer... segmentationClasses) { } /** Deserializes a JSON string to a MaskReferenceConfig object. */ + @ExcludeFromGeneratedCoverageReport public static MaskReferenceConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, MaskReferenceConfig.class); } diff --git a/src/main/java/com/google/genai/types/MaskReferenceImage.java b/src/main/java/com/google/genai/types/MaskReferenceImage.java index 8ce0489598e..d630b2ede6f 100644 --- a/src/main/java/com/google/genai/types/MaskReferenceImage.java +++ b/src/main/java/com/google/genai/types/MaskReferenceImage.java @@ -54,6 +54,7 @@ public abstract class MaskReferenceImage extends JsonSerializable implements Ref public abstract Optional config(); /** Instantiates a builder for MaskReferenceImage. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_MaskReferenceImage.Builder(); } @@ -124,6 +125,7 @@ public Builder config(MaskReferenceConfig.Builder configBuilder) { } /** Deserializes a JSON string to a MaskReferenceImage object. */ + @ExcludeFromGeneratedCoverageReport public static MaskReferenceImage fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, MaskReferenceImage.class); } diff --git a/src/main/java/com/google/genai/types/MaskReferenceMode.java b/src/main/java/com/google/genai/types/MaskReferenceMode.java index b60bc575390..ae80d78b3c8 100644 --- a/src/main/java/com/google/genai/types/MaskReferenceMode.java +++ b/src/main/java/com/google/genai/types/MaskReferenceMode.java @@ -63,12 +63,14 @@ public MaskReferenceMode(Known knownValue) { this.value = knownValue.toString(); } + @ExcludeFromGeneratedCoverageReport @Override @JsonValue public String toString() { return this.value; } + @ExcludeFromGeneratedCoverageReport @SuppressWarnings("PatternMatchingInstanceof") @Override public boolean equals(Object o) { @@ -95,6 +97,7 @@ public boolean equals(Object o) { return false; } + @ExcludeFromGeneratedCoverageReport @Override public int hashCode() { if (this.maskReferenceModeEnum != Known.MASK_REFERENCE_MODE_UNSPECIFIED) { @@ -104,6 +107,7 @@ public int hashCode() { } } + @ExcludeFromGeneratedCoverageReport public Known knownEnum() { return this.maskReferenceModeEnum; } diff --git a/src/main/java/com/google/genai/types/MediaModality.java b/src/main/java/com/google/genai/types/MediaModality.java index e7914b8ebbd..2275086a2be 100644 --- a/src/main/java/com/google/genai/types/MediaModality.java +++ b/src/main/java/com/google/genai/types/MediaModality.java @@ -71,12 +71,14 @@ public MediaModality(Known knownValue) { this.value = knownValue.toString(); } + @ExcludeFromGeneratedCoverageReport @Override @JsonValue public String toString() { return this.value; } + @ExcludeFromGeneratedCoverageReport @SuppressWarnings("PatternMatchingInstanceof") @Override public boolean equals(Object o) { @@ -103,6 +105,7 @@ public boolean equals(Object o) { return false; } + @ExcludeFromGeneratedCoverageReport @Override public int hashCode() { if (this.mediaModalityEnum != Known.MEDIA_MODALITY_UNSPECIFIED) { @@ -112,6 +115,7 @@ public int hashCode() { } } + @ExcludeFromGeneratedCoverageReport public Known knownEnum() { return this.mediaModalityEnum; } diff --git a/src/main/java/com/google/genai/types/MediaResolution.java b/src/main/java/com/google/genai/types/MediaResolution.java index 89520a6f410..3a404907c98 100644 --- a/src/main/java/com/google/genai/types/MediaResolution.java +++ b/src/main/java/com/google/genai/types/MediaResolution.java @@ -63,12 +63,14 @@ public MediaResolution(Known knownValue) { this.value = knownValue.toString(); } + @ExcludeFromGeneratedCoverageReport @Override @JsonValue public String toString() { return this.value; } + @ExcludeFromGeneratedCoverageReport @SuppressWarnings("PatternMatchingInstanceof") @Override public boolean equals(Object o) { @@ -95,6 +97,7 @@ public boolean equals(Object o) { return false; } + @ExcludeFromGeneratedCoverageReport @Override public int hashCode() { if (this.mediaResolutionEnum != Known.MEDIA_RESOLUTION_UNSPECIFIED) { @@ -104,6 +107,7 @@ public int hashCode() { } } + @ExcludeFromGeneratedCoverageReport public Known knownEnum() { return this.mediaResolutionEnum; } diff --git a/src/main/java/com/google/genai/types/Modality.java b/src/main/java/com/google/genai/types/Modality.java index f1686383199..194d16ee4ac 100644 --- a/src/main/java/com/google/genai/types/Modality.java +++ b/src/main/java/com/google/genai/types/Modality.java @@ -63,12 +63,14 @@ public Modality(Known knownValue) { this.value = knownValue.toString(); } + @ExcludeFromGeneratedCoverageReport @Override @JsonValue public String toString() { return this.value; } + @ExcludeFromGeneratedCoverageReport @SuppressWarnings("PatternMatchingInstanceof") @Override public boolean equals(Object o) { @@ -95,6 +97,7 @@ public boolean equals(Object o) { return false; } + @ExcludeFromGeneratedCoverageReport @Override public int hashCode() { if (this.modalityEnum != Known.MODALITY_UNSPECIFIED) { @@ -104,6 +107,7 @@ public int hashCode() { } } + @ExcludeFromGeneratedCoverageReport public Known knownEnum() { return this.modalityEnum; } diff --git a/src/main/java/com/google/genai/types/ModalityTokenCount.java b/src/main/java/com/google/genai/types/ModalityTokenCount.java index 985366b09f7..69e97574ff9 100644 --- a/src/main/java/com/google/genai/types/ModalityTokenCount.java +++ b/src/main/java/com/google/genai/types/ModalityTokenCount.java @@ -39,6 +39,7 @@ public abstract class ModalityTokenCount extends JsonSerializable { public abstract Optional tokenCount(); /** Instantiates a builder for ModalityTokenCount. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_ModalityTokenCount.Builder(); } @@ -95,6 +96,7 @@ public Builder modality(String modality) { } /** Deserializes a JSON string to a ModalityTokenCount object. */ + @ExcludeFromGeneratedCoverageReport public static ModalityTokenCount fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, ModalityTokenCount.class); } diff --git a/src/main/java/com/google/genai/types/Mode.java b/src/main/java/com/google/genai/types/Mode.java index 73fa6bcf904..8ef57cf582a 100644 --- a/src/main/java/com/google/genai/types/Mode.java +++ b/src/main/java/com/google/genai/types/Mode.java @@ -57,12 +57,14 @@ public Mode(Known knownValue) { this.value = knownValue.toString(); } + @ExcludeFromGeneratedCoverageReport @Override @JsonValue public String toString() { return this.value; } + @ExcludeFromGeneratedCoverageReport @SuppressWarnings("PatternMatchingInstanceof") @Override public boolean equals(Object o) { @@ -88,6 +90,7 @@ public boolean equals(Object o) { return false; } + @ExcludeFromGeneratedCoverageReport @Override public int hashCode() { if (this.modeEnum != Known.MODE_UNSPECIFIED) { @@ -97,6 +100,7 @@ public int hashCode() { } } + @ExcludeFromGeneratedCoverageReport public Known knownEnum() { return this.modeEnum; } diff --git a/src/main/java/com/google/genai/types/Model.java b/src/main/java/com/google/genai/types/Model.java index 82eda2633f9..dc211287942 100644 --- a/src/main/java/com/google/genai/types/Model.java +++ b/src/main/java/com/google/genai/types/Model.java @@ -90,6 +90,7 @@ public abstract class Model extends JsonSerializable { public abstract Optional> checkpoints(); /** Instantiates a builder for Model. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_Model.Builder(); } @@ -271,6 +272,7 @@ public Builder checkpoints(Checkpoint.Builder... checkpointsBuilders) { } /** Deserializes a JSON string to a Model object. */ + @ExcludeFromGeneratedCoverageReport public static Model fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, Model.class); } diff --git a/src/main/java/com/google/genai/types/ModelRoutingPreference.java b/src/main/java/com/google/genai/types/ModelRoutingPreference.java index f5da5818198..d1178bff498 100644 --- a/src/main/java/com/google/genai/types/ModelRoutingPreference.java +++ b/src/main/java/com/google/genai/types/ModelRoutingPreference.java @@ -61,12 +61,14 @@ public ModelRoutingPreference(Known knownValue) { this.value = knownValue.toString(); } + @ExcludeFromGeneratedCoverageReport @Override @JsonValue public String toString() { return this.value; } + @ExcludeFromGeneratedCoverageReport @SuppressWarnings("PatternMatchingInstanceof") @Override public boolean equals(Object o) { @@ -93,6 +95,7 @@ public boolean equals(Object o) { return false; } + @ExcludeFromGeneratedCoverageReport @Override public int hashCode() { if (this.modelRoutingPreferenceEnum != Known.MODEL_ROUTING_PREFERENCE_UNSPECIFIED) { @@ -102,6 +105,7 @@ public int hashCode() { } } + @ExcludeFromGeneratedCoverageReport public Known knownEnum() { return this.modelRoutingPreferenceEnum; } diff --git a/src/main/java/com/google/genai/types/ModelSelectionConfig.java b/src/main/java/com/google/genai/types/ModelSelectionConfig.java index 0d2a30b591d..ad8d9de29c0 100644 --- a/src/main/java/com/google/genai/types/ModelSelectionConfig.java +++ b/src/main/java/com/google/genai/types/ModelSelectionConfig.java @@ -35,6 +35,7 @@ public abstract class ModelSelectionConfig extends JsonSerializable { public abstract Optional featureSelectionPreference(); /** Instantiates a builder for ModelSelectionConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_ModelSelectionConfig.Builder(); } @@ -84,6 +85,7 @@ public Builder featureSelectionPreference(String featureSelectionPreference) { } /** Deserializes a JSON string to a ModelSelectionConfig object. */ + @ExcludeFromGeneratedCoverageReport public static ModelSelectionConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, ModelSelectionConfig.class); } diff --git a/src/main/java/com/google/genai/types/MultiSpeakerVoiceConfig.java b/src/main/java/com/google/genai/types/MultiSpeakerVoiceConfig.java index 0dac3c4f6eb..d628d3a35f1 100644 --- a/src/main/java/com/google/genai/types/MultiSpeakerVoiceConfig.java +++ b/src/main/java/com/google/genai/types/MultiSpeakerVoiceConfig.java @@ -29,15 +29,16 @@ import java.util.List; import java.util.Optional; -/** The configuration for the multi-speaker setup. */ +/** The configuration for the multi-speaker setup. This data type is not supported in Vertex AI. */ @AutoValue @JsonDeserialize(builder = MultiSpeakerVoiceConfig.Builder.class) public abstract class MultiSpeakerVoiceConfig extends JsonSerializable { - /** The configuration for the speaker to use. */ + /** Required. All the enabled speaker voices. */ @JsonProperty("speakerVoiceConfigs") public abstract Optional> speakerVoiceConfigs(); /** Instantiates a builder for MultiSpeakerVoiceConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_MultiSpeakerVoiceConfig.Builder(); } @@ -57,7 +58,7 @@ private static Builder create() { /** * Setter for speakerVoiceConfigs. * - *

speakerVoiceConfigs: The configuration for the speaker to use. + *

speakerVoiceConfigs: Required. All the enabled speaker voices. */ @JsonProperty("speakerVoiceConfigs") public abstract Builder speakerVoiceConfigs(List speakerVoiceConfigs); @@ -65,7 +66,7 @@ private static Builder create() { /** * Setter for speakerVoiceConfigs. * - *

speakerVoiceConfigs: The configuration for the speaker to use. + *

speakerVoiceConfigs: Required. All the enabled speaker voices. */ public Builder speakerVoiceConfigs(SpeakerVoiceConfig... speakerVoiceConfigs) { return speakerVoiceConfigs(Arrays.asList(speakerVoiceConfigs)); @@ -74,7 +75,7 @@ public Builder speakerVoiceConfigs(SpeakerVoiceConfig... speakerVoiceConfigs) { /** * Setter for speakerVoiceConfigs builder. * - *

speakerVoiceConfigs: The configuration for the speaker to use. + *

speakerVoiceConfigs: Required. All the enabled speaker voices. */ public Builder speakerVoiceConfigs(SpeakerVoiceConfig.Builder... speakerVoiceConfigsBuilders) { return speakerVoiceConfigs( @@ -87,6 +88,7 @@ public Builder speakerVoiceConfigs(SpeakerVoiceConfig.Builder... speakerVoiceCon } /** Deserializes a JSON string to a MultiSpeakerVoiceConfig object. */ + @ExcludeFromGeneratedCoverageReport public static MultiSpeakerVoiceConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, MultiSpeakerVoiceConfig.class); } diff --git a/src/main/java/com/google/genai/types/Operation.java b/src/main/java/com/google/genai/types/Operation.java index 297d338f24f..c9b54702b6c 100644 --- a/src/main/java/com/google/genai/types/Operation.java +++ b/src/main/java/com/google/genai/types/Operation.java @@ -18,18 +18,14 @@ package com.google.genai.types; -import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.google.auto.value.AutoValue; +import com.fasterxml.jackson.databind.JsonNode; import com.google.genai.JsonSerializable; import java.util.Map; import java.util.Optional; /** A long-running operation. */ -@AutoValue -@JsonDeserialize(builder = Operation.Builder.class) -public abstract class Operation extends JsonSerializable { +public abstract class Operation> extends JsonSerializable { /** * The server-assigned name, which is only unique within the same service that originally returns * it. If you use the default HTTP mapping, the `name` should be a resource name ending with @@ -58,66 +54,16 @@ public abstract class Operation extends JsonSerializable { @JsonProperty("error") public abstract Optional> error(); - /** Instantiates a builder for Operation. */ - public static Builder builder() { - return new AutoValue_Operation.Builder(); - } + /** The result of the operation. */ + @JsonProperty("response") + public abstract Optional response(); - /** Creates a builder with the same values as this instance. */ - public abstract Builder toBuilder(); - - /** Builder for Operation. */ - @AutoValue.Builder - public abstract static class Builder { - /** For internal usage. Please use `Operation.builder()` for instantiation. */ - @JsonCreator - private static Builder create() { - return new AutoValue_Operation.Builder(); - } - - /** - * Setter for name. - * - *

name: The server-assigned name, which is only unique within the same service that - * originally returns it. If you use the default HTTP mapping, the `name` should be a resource - * name ending with `operations/{unique_id}`. - */ - @JsonProperty("name") - public abstract Builder name(String name); - - /** - * Setter for metadata. - * - *

metadata: Service-specific metadata associated with the operation. It typically contains - * progress information and common metadata such as create time. Some services might not provide - * such metadata. Any method that returns a long-running operation should document the metadata - * type, if any. - */ - @JsonProperty("metadata") - public abstract Builder metadata(Map metadata); - - /** - * Setter for done. - * - *

done: If the value is `false`, it means the operation is still in progress. If `true`, the - * operation is completed, and either `error` or `response` is available. - */ - @JsonProperty("done") - public abstract Builder done(boolean done); - - /** - * Setter for error. - * - *

error: The error result of the operation in case of failure or cancellation. - */ - @JsonProperty("error") - public abstract Builder error(Map error); - - public abstract Operation build(); - } - - /** Deserializes a JSON string to a Operation object. */ - public static Operation fromJson(String jsonString) { - return JsonSerializable.fromJsonString(jsonString, Operation.class); - } + /** + * Creates a new Operation object from an API response. + * + * @param apiResponse The API response. + * @param isVertexAi Whether the API response is from Vertex AI. + * @return The new Operation object. + */ + public abstract O fromApiResponse(JsonNode apiResponse, boolean isVertexAi); } diff --git a/src/main/java/com/google/genai/types/Outcome.java b/src/main/java/com/google/genai/types/Outcome.java index 14b034b2f45..1b07350fa1e 100644 --- a/src/main/java/com/google/genai/types/Outcome.java +++ b/src/main/java/com/google/genai/types/Outcome.java @@ -23,7 +23,7 @@ import com.google.common.base.Ascii; import java.util.Objects; -/** Required. Outcome of the code execution. */ +/** Outcome of the code execution. */ public class Outcome { /** Enum representing the known values for Outcome. */ @@ -66,12 +66,14 @@ public Outcome(Known knownValue) { this.value = knownValue.toString(); } + @ExcludeFromGeneratedCoverageReport @Override @JsonValue public String toString() { return this.value; } + @ExcludeFromGeneratedCoverageReport @SuppressWarnings("PatternMatchingInstanceof") @Override public boolean equals(Object o) { @@ -98,6 +100,7 @@ public boolean equals(Object o) { return false; } + @ExcludeFromGeneratedCoverageReport @Override public int hashCode() { if (this.outcomeEnum != Known.OUTCOME_UNSPECIFIED) { @@ -107,6 +110,7 @@ public int hashCode() { } } + @ExcludeFromGeneratedCoverageReport public Known knownEnum() { return this.outcomeEnum; } diff --git a/src/main/java/com/google/genai/types/Part.java b/src/main/java/com/google/genai/types/Part.java index 6fbb2363575..549e2568b1f 100644 --- a/src/main/java/com/google/genai/types/Part.java +++ b/src/main/java/com/google/genai/types/Part.java @@ -35,25 +35,13 @@ @AutoValue @JsonDeserialize(builder = Part.Builder.class) public abstract class Part extends JsonSerializable { - /** Metadata for a given video. */ - @JsonProperty("videoMetadata") - public abstract Optional videoMetadata(); - - /** Indicates if the part is thought from the model. */ - @JsonProperty("thought") - public abstract Optional thought(); - - /** Optional. Inlined bytes data. */ - @JsonProperty("inlineData") - public abstract Optional inlineData(); - - /** Optional. URI based data. */ - @JsonProperty("fileData") - public abstract Optional fileData(); - - /** An opaque signature for the thought so it can be reused in subsequent requests. */ - @JsonProperty("thoughtSignature") - public abstract Optional thoughtSignature(); + /** + * A predicted [FunctionCall] returned from the model that contains a string representing the + * [FunctionDeclaration.name] and a structured JSON object containing the parameters and their + * values. + */ + @JsonProperty("functionCall") + public abstract Optional functionCall(); /** Optional. Result of executing the [ExecutableCode]. */ @JsonProperty("codeExecutionResult") @@ -63,12 +51,9 @@ public abstract class Part extends JsonSerializable { @JsonProperty("executableCode") public abstract Optional executableCode(); - /** - * Optional. A predicted [FunctionCall] returned from the model that contains a string - * representing the [FunctionDeclaration.name] with the parameters and their values. - */ - @JsonProperty("functionCall") - public abstract Optional functionCall(); + /** Optional. URI based data. */ + @JsonProperty("fileData") + public abstract Optional fileData(); /** * Optional. The result output of a [FunctionCall] that contains a string representing the @@ -78,11 +63,31 @@ public abstract class Part extends JsonSerializable { @JsonProperty("functionResponse") public abstract Optional functionResponse(); + /** Optional. Inlined bytes data. */ + @JsonProperty("inlineData") + public abstract Optional inlineData(); + /** Optional. Text part (can be code). */ @JsonProperty("text") public abstract Optional text(); + /** Optional. Indicates if the part is thought from the model. */ + @JsonProperty("thought") + public abstract Optional thought(); + + /** Optional. An opaque signature for the thought so it can be reused in subsequent requests. */ + @JsonProperty("thoughtSignature") + public abstract Optional thoughtSignature(); + + /** + * Optional. Video metadata. The metadata should only be specified while the video data is + * presented in inline_data or file_data. + */ + @JsonProperty("videoMetadata") + public abstract Optional videoMetadata(); + /** Instantiates a builder for Part. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_Part.Builder(); } @@ -100,73 +105,26 @@ private static Builder create() { } /** - * Setter for videoMetadata. - * - *

videoMetadata: Metadata for a given video. - */ - @JsonProperty("videoMetadata") - public abstract Builder videoMetadata(VideoMetadata videoMetadata); - - /** - * Setter for videoMetadata builder. - * - *

videoMetadata: Metadata for a given video. - */ - public Builder videoMetadata(VideoMetadata.Builder videoMetadataBuilder) { - return videoMetadata(videoMetadataBuilder.build()); - } - - /** - * Setter for thought. - * - *

thought: Indicates if the part is thought from the model. - */ - @JsonProperty("thought") - public abstract Builder thought(boolean thought); - - /** - * Setter for inlineData. - * - *

inlineData: Optional. Inlined bytes data. - */ - @JsonProperty("inlineData") - public abstract Builder inlineData(Blob inlineData); - - /** - * Setter for inlineData builder. - * - *

inlineData: Optional. Inlined bytes data. - */ - public Builder inlineData(Blob.Builder inlineDataBuilder) { - return inlineData(inlineDataBuilder.build()); - } - - /** - * Setter for fileData. + * Setter for functionCall. * - *

fileData: Optional. URI based data. + *

functionCall: A predicted [FunctionCall] returned from the model that contains a string + * representing the [FunctionDeclaration.name] and a structured JSON object containing the + * parameters and their values. */ - @JsonProperty("fileData") - public abstract Builder fileData(FileData fileData); + @JsonProperty("functionCall") + public abstract Builder functionCall(FunctionCall functionCall); /** - * Setter for fileData builder. + * Setter for functionCall builder. * - *

fileData: Optional. URI based data. + *

functionCall: A predicted [FunctionCall] returned from the model that contains a string + * representing the [FunctionDeclaration.name] and a structured JSON object containing the + * parameters and their values. */ - public Builder fileData(FileData.Builder fileDataBuilder) { - return fileData(fileDataBuilder.build()); + public Builder functionCall(FunctionCall.Builder functionCallBuilder) { + return functionCall(functionCallBuilder.build()); } - /** - * Setter for thoughtSignature. - * - *

thoughtSignature: An opaque signature for the thought so it can be reused in subsequent - * requests. - */ - @JsonProperty("thoughtSignature") - public abstract Builder thoughtSignature(byte[] thoughtSignature); - /** * Setter for codeExecutionResult. * @@ -202,22 +160,20 @@ public Builder executableCode(ExecutableCode.Builder executableCodeBuilder) { } /** - * Setter for functionCall. + * Setter for fileData. * - *

functionCall: Optional. A predicted [FunctionCall] returned from the model that contains a - * string representing the [FunctionDeclaration.name] with the parameters and their values. + *

fileData: Optional. URI based data. */ - @JsonProperty("functionCall") - public abstract Builder functionCall(FunctionCall functionCall); + @JsonProperty("fileData") + public abstract Builder fileData(FileData fileData); /** - * Setter for functionCall builder. + * Setter for fileData builder. * - *

functionCall: Optional. A predicted [FunctionCall] returned from the model that contains a - * string representing the [FunctionDeclaration.name] with the parameters and their values. + *

fileData: Optional. URI based data. */ - public Builder functionCall(FunctionCall.Builder functionCallBuilder) { - return functionCall(functionCallBuilder.build()); + public Builder fileData(FileData.Builder fileDataBuilder) { + return fileData(fileDataBuilder.build()); } /** @@ -241,6 +197,23 @@ public Builder functionResponse(FunctionResponse.Builder functionResponseBuilder return functionResponse(functionResponseBuilder.build()); } + /** + * Setter for inlineData. + * + *

inlineData: Optional. Inlined bytes data. + */ + @JsonProperty("inlineData") + public abstract Builder inlineData(Blob inlineData); + + /** + * Setter for inlineData builder. + * + *

inlineData: Optional. Inlined bytes data. + */ + public Builder inlineData(Blob.Builder inlineDataBuilder) { + return inlineData(inlineDataBuilder.build()); + } + /** * Setter for text. * @@ -249,10 +222,47 @@ public Builder functionResponse(FunctionResponse.Builder functionResponseBuilder @JsonProperty("text") public abstract Builder text(String text); + /** + * Setter for thought. + * + *

thought: Optional. Indicates if the part is thought from the model. + */ + @JsonProperty("thought") + public abstract Builder thought(boolean thought); + + /** + * Setter for thoughtSignature. + * + *

thoughtSignature: Optional. An opaque signature for the thought so it can be reused in + * subsequent requests. + */ + @JsonProperty("thoughtSignature") + public abstract Builder thoughtSignature(byte[] thoughtSignature); + + /** + * Setter for videoMetadata. + * + *

videoMetadata: Optional. Video metadata. The metadata should only be specified while the + * video data is presented in inline_data or file_data. + */ + @JsonProperty("videoMetadata") + public abstract Builder videoMetadata(VideoMetadata videoMetadata); + + /** + * Setter for videoMetadata builder. + * + *

videoMetadata: Optional. Video metadata. The metadata should only be specified while the + * video data is presented in inline_data or file_data. + */ + public Builder videoMetadata(VideoMetadata.Builder videoMetadataBuilder) { + return videoMetadata(videoMetadataBuilder.build()); + } + public abstract Part build(); } /** Deserializes a JSON string to a Part object. */ + @ExcludeFromGeneratedCoverageReport public static Part fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, Part.class); } @@ -279,10 +289,14 @@ public static Part fromFunctionCall(String name, Map args) { return builder().functionCall(FunctionCall.builder().name(name).args(args).build()).build(); } - /** Constructs a FunctionResponse Part from a function name and response. */ - public static Part fromFunctionResponse(String name, Map response) { + /** + * Constructs a FunctionResponse Part from a function name, response and function response parts. + */ + public static Part fromFunctionResponse( + String name, Map response, FunctionResponsePart... functionResponseParts) { return builder() - .functionResponse(FunctionResponse.builder().name(name).response(response).build()) + .functionResponse( + FunctionResponse.builder().name(name).response(response).parts(functionResponseParts)) .build(); } } diff --git a/src/main/java/com/google/genai/types/PartnerModelTuningSpec.java b/src/main/java/com/google/genai/types/PartnerModelTuningSpec.java index 8d8a70e12b3..37ae5ca0d63 100644 --- a/src/main/java/com/google/genai/types/PartnerModelTuningSpec.java +++ b/src/main/java/com/google/genai/types/PartnerModelTuningSpec.java @@ -26,7 +26,7 @@ import java.util.Map; import java.util.Optional; -/** Tuning spec for Partner models. */ +/** Tuning spec for Partner models. This data type is not supported in Gemini API. */ @AutoValue @JsonDeserialize(builder = PartnerModelTuningSpec.Builder.class) public abstract class PartnerModelTuningSpec extends JsonSerializable { @@ -52,6 +52,7 @@ public abstract class PartnerModelTuningSpec extends JsonSerializable { public abstract Optional validationDatasetUri(); /** Instantiates a builder for PartnerModelTuningSpec. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_PartnerModelTuningSpec.Builder(); } @@ -99,6 +100,7 @@ private static Builder create() { } /** Deserializes a JSON string to a PartnerModelTuningSpec object. */ + @ExcludeFromGeneratedCoverageReport public static PartnerModelTuningSpec fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, PartnerModelTuningSpec.class); } diff --git a/src/main/java/com/google/genai/types/PersonGeneration.java b/src/main/java/com/google/genai/types/PersonGeneration.java index 8023702e92f..e7ef0f9c5c6 100644 --- a/src/main/java/com/google/genai/types/PersonGeneration.java +++ b/src/main/java/com/google/genai/types/PersonGeneration.java @@ -62,12 +62,14 @@ public PersonGeneration(Known knownValue) { this.value = knownValue.toString(); } + @ExcludeFromGeneratedCoverageReport @Override @JsonValue public String toString() { return this.value; } + @ExcludeFromGeneratedCoverageReport @SuppressWarnings("PatternMatchingInstanceof") @Override public boolean equals(Object o) { @@ -94,6 +96,7 @@ public boolean equals(Object o) { return false; } + @ExcludeFromGeneratedCoverageReport @Override public int hashCode() { if (this.personGenerationEnum != Known.PERSON_GENERATION_UNSPECIFIED) { @@ -103,6 +106,7 @@ public int hashCode() { } } + @ExcludeFromGeneratedCoverageReport public Known knownEnum() { return this.personGenerationEnum; } diff --git a/src/main/java/com/google/genai/types/PreTunedModel.java b/src/main/java/com/google/genai/types/PreTunedModel.java new file mode 100644 index 00000000000..6d53bc25cbe --- /dev/null +++ b/src/main/java/com/google/genai/types/PreTunedModel.java @@ -0,0 +1,104 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Auto-generated code. Do not edit. + +package com.google.genai.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.google.auto.value.AutoValue; +import com.google.genai.JsonSerializable; +import java.util.Optional; + +/** A pre-tuned model for continuous tuning. This data type is not supported in Gemini API. */ +@AutoValue +@JsonDeserialize(builder = PreTunedModel.Builder.class) +public abstract class PreTunedModel extends JsonSerializable { + /** Output only. The name of the base model this PreTunedModel was tuned from. */ + @JsonProperty("baseModel") + public abstract Optional baseModel(); + + /** Optional. The source checkpoint id. If not specified, the default checkpoint will be used. */ + @JsonProperty("checkpointId") + public abstract Optional checkpointId(); + + /** + * The resource name of the Model. E.g., a model resource name with a specified version id or + * alias: `projects/{project}/locations/{location}/models/{model}@{version_id}` + * `projects/{project}/locations/{location}/models/{model}@{alias}` Or, omit the version id to use + * the default version: `projects/{project}/locations/{location}/models/{model}` + */ + @JsonProperty("tunedModelName") + public abstract Optional tunedModelName(); + + /** Instantiates a builder for PreTunedModel. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_PreTunedModel.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for PreTunedModel. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `PreTunedModel.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_PreTunedModel.Builder(); + } + + /** + * Setter for baseModel. + * + *

baseModel: Output only. The name of the base model this PreTunedModel was tuned from. + */ + @JsonProperty("baseModel") + public abstract Builder baseModel(String baseModel); + + /** + * Setter for checkpointId. + * + *

checkpointId: Optional. The source checkpoint id. If not specified, the default checkpoint + * will be used. + */ + @JsonProperty("checkpointId") + public abstract Builder checkpointId(String checkpointId); + + /** + * Setter for tunedModelName. + * + *

tunedModelName: The resource name of the Model. E.g., a model resource name with a + * specified version id or alias: + * `projects/{project}/locations/{location}/models/{model}@{version_id}` + * `projects/{project}/locations/{location}/models/{model}@{alias}` Or, omit the version id to + * use the default version: `projects/{project}/locations/{location}/models/{model}` + */ + @JsonProperty("tunedModelName") + public abstract Builder tunedModelName(String tunedModelName); + + public abstract PreTunedModel build(); + } + + /** Deserializes a JSON string to a PreTunedModel object. */ + @ExcludeFromGeneratedCoverageReport + public static PreTunedModel fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, PreTunedModel.class); + } +} diff --git a/src/main/java/com/google/genai/types/PrebuiltVoiceConfig.java b/src/main/java/com/google/genai/types/PrebuiltVoiceConfig.java index 03222a6334f..3276c254ff9 100644 --- a/src/main/java/com/google/genai/types/PrebuiltVoiceConfig.java +++ b/src/main/java/com/google/genai/types/PrebuiltVoiceConfig.java @@ -29,11 +29,12 @@ @AutoValue @JsonDeserialize(builder = PrebuiltVoiceConfig.Builder.class) public abstract class PrebuiltVoiceConfig extends JsonSerializable { - /** The name of the prebuilt voice to use. */ + /** The name of the preset voice to use. */ @JsonProperty("voiceName") public abstract Optional voiceName(); /** Instantiates a builder for PrebuiltVoiceConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_PrebuiltVoiceConfig.Builder(); } @@ -53,7 +54,7 @@ private static Builder create() { /** * Setter for voiceName. * - *

voiceName: The name of the prebuilt voice to use. + *

voiceName: The name of the preset voice to use. */ @JsonProperty("voiceName") public abstract Builder voiceName(String voiceName); @@ -62,6 +63,7 @@ private static Builder create() { } /** Deserializes a JSON string to a PrebuiltVoiceConfig object. */ + @ExcludeFromGeneratedCoverageReport public static PrebuiltVoiceConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, PrebuiltVoiceConfig.class); } diff --git a/src/main/java/com/google/genai/types/PreferenceOptimizationDataStats.java b/src/main/java/com/google/genai/types/PreferenceOptimizationDataStats.java new file mode 100644 index 00000000000..ccf3d260791 --- /dev/null +++ b/src/main/java/com/google/genai/types/PreferenceOptimizationDataStats.java @@ -0,0 +1,232 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Auto-generated code. Do not edit. + +package com.google.genai.types; + +import static com.google.common.collect.ImmutableList.toImmutableList; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.google.auto.value.AutoValue; +import com.google.genai.JsonSerializable; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +/** + * Statistics computed for datasets used for preference optimization. This data type is not + * supported in Gemini API. + */ +@AutoValue +@JsonDeserialize(builder = PreferenceOptimizationDataStats.Builder.class) +public abstract class PreferenceOptimizationDataStats extends JsonSerializable { + /** Output only. Dataset distributions for scores variance per example. */ + @JsonProperty("scoreVariancePerExampleDistribution") + public abstract Optional scoreVariancePerExampleDistribution(); + + /** Output only. Dataset distributions for scores. */ + @JsonProperty("scoresDistribution") + public abstract Optional scoresDistribution(); + + /** Output only. Number of billable tokens in the tuning dataset. */ + @JsonProperty("totalBillableTokenCount") + public abstract Optional totalBillableTokenCount(); + + /** Output only. Number of examples in the tuning dataset. */ + @JsonProperty("tuningDatasetExampleCount") + public abstract Optional tuningDatasetExampleCount(); + + /** Output only. Number of tuning steps for this Tuning Job. */ + @JsonProperty("tuningStepCount") + public abstract Optional tuningStepCount(); + + /** Output only. Sample user examples in the training dataset. */ + @JsonProperty("userDatasetExamples") + public abstract Optional> userDatasetExamples(); + + /** Output only. Dataset distributions for the user input tokens. */ + @JsonProperty("userInputTokenDistribution") + public abstract Optional userInputTokenDistribution(); + + /** Output only. Dataset distributions for the user output tokens. */ + @JsonProperty("userOutputTokenDistribution") + public abstract Optional userOutputTokenDistribution(); + + /** Instantiates a builder for PreferenceOptimizationDataStats. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_PreferenceOptimizationDataStats.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for PreferenceOptimizationDataStats. */ + @AutoValue.Builder + public abstract static class Builder { + /** + * For internal usage. Please use `PreferenceOptimizationDataStats.builder()` for instantiation. + */ + @JsonCreator + private static Builder create() { + return new AutoValue_PreferenceOptimizationDataStats.Builder(); + } + + /** + * Setter for scoreVariancePerExampleDistribution. + * + *

scoreVariancePerExampleDistribution: Output only. Dataset distributions for scores + * variance per example. + */ + @JsonProperty("scoreVariancePerExampleDistribution") + public abstract Builder scoreVariancePerExampleDistribution( + DatasetDistribution scoreVariancePerExampleDistribution); + + /** + * Setter for scoreVariancePerExampleDistribution builder. + * + *

scoreVariancePerExampleDistribution: Output only. Dataset distributions for scores + * variance per example. + */ + public Builder scoreVariancePerExampleDistribution( + DatasetDistribution.Builder scoreVariancePerExampleDistributionBuilder) { + return scoreVariancePerExampleDistribution( + scoreVariancePerExampleDistributionBuilder.build()); + } + + /** + * Setter for scoresDistribution. + * + *

scoresDistribution: Output only. Dataset distributions for scores. + */ + @JsonProperty("scoresDistribution") + public abstract Builder scoresDistribution(DatasetDistribution scoresDistribution); + + /** + * Setter for scoresDistribution builder. + * + *

scoresDistribution: Output only. Dataset distributions for scores. + */ + public Builder scoresDistribution(DatasetDistribution.Builder scoresDistributionBuilder) { + return scoresDistribution(scoresDistributionBuilder.build()); + } + + /** + * Setter for totalBillableTokenCount. + * + *

totalBillableTokenCount: Output only. Number of billable tokens in the tuning dataset. + */ + @JsonProperty("totalBillableTokenCount") + public abstract Builder totalBillableTokenCount(Long totalBillableTokenCount); + + /** + * Setter for tuningDatasetExampleCount. + * + *

tuningDatasetExampleCount: Output only. Number of examples in the tuning dataset. + */ + @JsonProperty("tuningDatasetExampleCount") + public abstract Builder tuningDatasetExampleCount(Long tuningDatasetExampleCount); + + /** + * Setter for tuningStepCount. + * + *

tuningStepCount: Output only. Number of tuning steps for this Tuning Job. + */ + @JsonProperty("tuningStepCount") + public abstract Builder tuningStepCount(Long tuningStepCount); + + /** + * Setter for userDatasetExamples. + * + *

userDatasetExamples: Output only. Sample user examples in the training dataset. + */ + @JsonProperty("userDatasetExamples") + public abstract Builder userDatasetExamples(List userDatasetExamples); + + /** + * Setter for userDatasetExamples. + * + *

userDatasetExamples: Output only. Sample user examples in the training dataset. + */ + public Builder userDatasetExamples(GeminiPreferenceExample... userDatasetExamples) { + return userDatasetExamples(Arrays.asList(userDatasetExamples)); + } + + /** + * Setter for userDatasetExamples builder. + * + *

userDatasetExamples: Output only. Sample user examples in the training dataset. + */ + public Builder userDatasetExamples( + GeminiPreferenceExample.Builder... userDatasetExamplesBuilders) { + return userDatasetExamples( + Arrays.asList(userDatasetExamplesBuilders).stream() + .map(GeminiPreferenceExample.Builder::build) + .collect(toImmutableList())); + } + + /** + * Setter for userInputTokenDistribution. + * + *

userInputTokenDistribution: Output only. Dataset distributions for the user input tokens. + */ + @JsonProperty("userInputTokenDistribution") + public abstract Builder userInputTokenDistribution( + DatasetDistribution userInputTokenDistribution); + + /** + * Setter for userInputTokenDistribution builder. + * + *

userInputTokenDistribution: Output only. Dataset distributions for the user input tokens. + */ + public Builder userInputTokenDistribution( + DatasetDistribution.Builder userInputTokenDistributionBuilder) { + return userInputTokenDistribution(userInputTokenDistributionBuilder.build()); + } + + /** + * Setter for userOutputTokenDistribution. + * + *

userOutputTokenDistribution: Output only. Dataset distributions for the user output + * tokens. + */ + @JsonProperty("userOutputTokenDistribution") + public abstract Builder userOutputTokenDistribution( + DatasetDistribution userOutputTokenDistribution); + + /** + * Setter for userOutputTokenDistribution builder. + * + *

userOutputTokenDistribution: Output only. Dataset distributions for the user output + * tokens. + */ + public Builder userOutputTokenDistribution( + DatasetDistribution.Builder userOutputTokenDistributionBuilder) { + return userOutputTokenDistribution(userOutputTokenDistributionBuilder.build()); + } + + public abstract PreferenceOptimizationDataStats build(); + } + + /** Deserializes a JSON string to a PreferenceOptimizationDataStats object. */ + @ExcludeFromGeneratedCoverageReport + public static PreferenceOptimizationDataStats fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, PreferenceOptimizationDataStats.class); + } +} diff --git a/src/main/java/com/google/genai/types/DistillationHyperParameters.java b/src/main/java/com/google/genai/types/PreferenceOptimizationHyperParameters.java similarity index 63% rename from src/main/java/com/google/genai/types/DistillationHyperParameters.java rename to src/main/java/com/google/genai/types/PreferenceOptimizationHyperParameters.java index be717feef84..11c520c3151 100644 --- a/src/main/java/com/google/genai/types/DistillationHyperParameters.java +++ b/src/main/java/com/google/genai/types/PreferenceOptimizationHyperParameters.java @@ -27,15 +27,19 @@ import com.google.genai.JsonSerializable; import java.util.Optional; -/** Hyperparameters for Distillation. */ +/** Hyperparameters for Preference Optimization. This data type is not supported in Gemini API. */ @AutoValue @InternalApi -@JsonDeserialize(builder = DistillationHyperParameters.Builder.class) -public abstract class DistillationHyperParameters extends JsonSerializable { - /** Optional. Adapter size for distillation. */ +@JsonDeserialize(builder = PreferenceOptimizationHyperParameters.Builder.class) +public abstract class PreferenceOptimizationHyperParameters extends JsonSerializable { + /** Optional. Adapter size for preference optimization. */ @JsonProperty("adapterSize") public abstract Optional adapterSize(); + /** Optional. Weight for KL Divergence regularization. */ + @JsonProperty("beta") + public abstract Optional beta(); + /** * Optional. Number of complete passes the model makes over the entire training dataset during * training. @@ -47,27 +51,31 @@ public abstract class DistillationHyperParameters extends JsonSerializable { @JsonProperty("learningRateMultiplier") public abstract Optional learningRateMultiplier(); - /** Instantiates a builder for DistillationHyperParameters. */ + /** Instantiates a builder for PreferenceOptimizationHyperParameters. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { - return new AutoValue_DistillationHyperParameters.Builder(); + return new AutoValue_PreferenceOptimizationHyperParameters.Builder(); } /** Creates a builder with the same values as this instance. */ public abstract Builder toBuilder(); - /** Builder for DistillationHyperParameters. */ + /** Builder for PreferenceOptimizationHyperParameters. */ @AutoValue.Builder public abstract static class Builder { - /** For internal usage. Please use `DistillationHyperParameters.builder()` for instantiation. */ + /** + * For internal usage. Please use `PreferenceOptimizationHyperParameters.builder()` for + * instantiation. + */ @JsonCreator private static Builder create() { - return new AutoValue_DistillationHyperParameters.Builder(); + return new AutoValue_PreferenceOptimizationHyperParameters.Builder(); } /** * Setter for adapterSize. * - *

adapterSize: Optional. Adapter size for distillation. + *

adapterSize: Optional. Adapter size for preference optimization. */ @JsonProperty("adapterSize") public abstract Builder adapterSize(AdapterSize adapterSize); @@ -75,7 +83,7 @@ private static Builder create() { /** * Setter for adapterSize given a known enum. * - *

adapterSize: Optional. Adapter size for distillation. + *

adapterSize: Optional. Adapter size for preference optimization. */ @CanIgnoreReturnValue public Builder adapterSize(AdapterSize.Known knownType) { @@ -85,13 +93,21 @@ public Builder adapterSize(AdapterSize.Known knownType) { /** * Setter for adapterSize given a string. * - *

adapterSize: Optional. Adapter size for distillation. + *

adapterSize: Optional. Adapter size for preference optimization. */ @CanIgnoreReturnValue public Builder adapterSize(String adapterSize) { return adapterSize(new AdapterSize(adapterSize)); } + /** + * Setter for beta. + * + *

beta: Optional. Weight for KL Divergence regularization. + */ + @JsonProperty("beta") + public abstract Builder beta(Double beta); + /** * Setter for epochCount. * @@ -109,11 +125,12 @@ public Builder adapterSize(String adapterSize) { @JsonProperty("learningRateMultiplier") public abstract Builder learningRateMultiplier(Double learningRateMultiplier); - public abstract DistillationHyperParameters build(); + public abstract PreferenceOptimizationHyperParameters build(); } - /** Deserializes a JSON string to a DistillationHyperParameters object. */ - public static DistillationHyperParameters fromJson(String jsonString) { - return JsonSerializable.fromJsonString(jsonString, DistillationHyperParameters.class); + /** Deserializes a JSON string to a PreferenceOptimizationHyperParameters object. */ + @ExcludeFromGeneratedCoverageReport + public static PreferenceOptimizationHyperParameters fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, PreferenceOptimizationHyperParameters.class); } } diff --git a/src/main/java/com/google/genai/types/PreferenceOptimizationSpec.java b/src/main/java/com/google/genai/types/PreferenceOptimizationSpec.java new file mode 100644 index 00000000000..c2226120f58 --- /dev/null +++ b/src/main/java/com/google/genai/types/PreferenceOptimizationSpec.java @@ -0,0 +1,112 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Auto-generated code. Do not edit. + +package com.google.genai.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.google.auto.value.AutoValue; +import com.google.genai.JsonSerializable; +import java.util.Optional; + +/** Preference optimization tuning spec for tuning. */ +@AutoValue +@JsonDeserialize(builder = PreferenceOptimizationSpec.Builder.class) +public abstract class PreferenceOptimizationSpec extends JsonSerializable { + /** Optional. Hyperparameters for Preference Optimization. */ + @JsonProperty("hyperParameters") + public abstract Optional hyperParameters(); + + /** + * Required. Cloud Storage path to file containing training dataset for preference optimization + * tuning. The dataset must be formatted as a JSONL file. + */ + @JsonProperty("trainingDatasetUri") + public abstract Optional trainingDatasetUri(); + + /** + * Optional. Cloud Storage path to file containing validation dataset for preference optimization + * tuning. The dataset must be formatted as a JSONL file. + */ + @JsonProperty("validationDatasetUri") + public abstract Optional validationDatasetUri(); + + /** Instantiates a builder for PreferenceOptimizationSpec. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_PreferenceOptimizationSpec.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for PreferenceOptimizationSpec. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `PreferenceOptimizationSpec.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_PreferenceOptimizationSpec.Builder(); + } + + /** + * Setter for hyperParameters. + * + *

hyperParameters: Optional. Hyperparameters for Preference Optimization. + */ + @JsonProperty("hyperParameters") + public abstract Builder hyperParameters(PreferenceOptimizationHyperParameters hyperParameters); + + /** + * Setter for hyperParameters builder. + * + *

hyperParameters: Optional. Hyperparameters for Preference Optimization. + */ + public Builder hyperParameters( + PreferenceOptimizationHyperParameters.Builder hyperParametersBuilder) { + return hyperParameters(hyperParametersBuilder.build()); + } + + /** + * Setter for trainingDatasetUri. + * + *

trainingDatasetUri: Required. Cloud Storage path to file containing training dataset for + * preference optimization tuning. The dataset must be formatted as a JSONL file. + */ + @JsonProperty("trainingDatasetUri") + public abstract Builder trainingDatasetUri(String trainingDatasetUri); + + /** + * Setter for validationDatasetUri. + * + *

validationDatasetUri: Optional. Cloud Storage path to file containing validation dataset + * for preference optimization tuning. The dataset must be formatted as a JSONL file. + */ + @JsonProperty("validationDatasetUri") + public abstract Builder validationDatasetUri(String validationDatasetUri); + + public abstract PreferenceOptimizationSpec build(); + } + + /** Deserializes a JSON string to a PreferenceOptimizationSpec object. */ + @ExcludeFromGeneratedCoverageReport + public static PreferenceOptimizationSpec fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, PreferenceOptimizationSpec.class); + } +} diff --git a/src/main/java/com/google/genai/types/ProactivityConfig.java b/src/main/java/com/google/genai/types/ProactivityConfig.java index 8eced7b7112..8b3b79ea350 100644 --- a/src/main/java/com/google/genai/types/ProactivityConfig.java +++ b/src/main/java/com/google/genai/types/ProactivityConfig.java @@ -38,6 +38,7 @@ public abstract class ProactivityConfig extends JsonSerializable { public abstract Optional proactiveAudio(); /** Instantiates a builder for ProactivityConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_ProactivityConfig.Builder(); } @@ -68,6 +69,7 @@ private static Builder create() { } /** Deserializes a JSON string to a ProactivityConfig object. */ + @ExcludeFromGeneratedCoverageReport public static ProactivityConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, ProactivityConfig.class); } diff --git a/src/main/java/com/google/genai/types/ProductImage.java b/src/main/java/com/google/genai/types/ProductImage.java new file mode 100644 index 00000000000..abdc4df0037 --- /dev/null +++ b/src/main/java/com/google/genai/types/ProductImage.java @@ -0,0 +1,79 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Auto-generated code. Do not edit. + +package com.google.genai.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.google.auto.value.AutoValue; +import com.google.genai.JsonSerializable; +import java.util.Optional; + +/** An image of the product. */ +@AutoValue +@JsonDeserialize(builder = ProductImage.Builder.class) +public abstract class ProductImage extends JsonSerializable { + /** An image of the product to be recontextualized. */ + @JsonProperty("productImage") + public abstract Optional productImage(); + + /** Instantiates a builder for ProductImage. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_ProductImage.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for ProductImage. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `ProductImage.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_ProductImage.Builder(); + } + + /** + * Setter for productImage. + * + *

productImage: An image of the product to be recontextualized. + */ + @JsonProperty("productImage") + public abstract Builder productImage(Image productImage); + + /** + * Setter for productImage builder. + * + *

productImage: An image of the product to be recontextualized. + */ + public Builder productImage(Image.Builder productImageBuilder) { + return productImage(productImageBuilder.build()); + } + + public abstract ProductImage build(); + } + + /** Deserializes a JSON string to a ProductImage object. */ + @ExcludeFromGeneratedCoverageReport + public static ProductImage fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, ProductImage.class); + } +} diff --git a/src/main/java/com/google/genai/types/RagChunk.java b/src/main/java/com/google/genai/types/RagChunk.java index f0543c60808..fcf163e2a6e 100644 --- a/src/main/java/com/google/genai/types/RagChunk.java +++ b/src/main/java/com/google/genai/types/RagChunk.java @@ -25,7 +25,10 @@ import com.google.genai.JsonSerializable; import java.util.Optional; -/** A RagChunk includes the content of a chunk of a RagFile, and associated metadata. */ +/** + * A RagChunk includes the content of a chunk of a RagFile, and associated metadata. This data type + * is not supported in Gemini API. + */ @AutoValue @JsonDeserialize(builder = RagChunk.Builder.class) public abstract class RagChunk extends JsonSerializable { @@ -38,6 +41,7 @@ public abstract class RagChunk extends JsonSerializable { public abstract Optional text(); /** Instantiates a builder for RagChunk. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_RagChunk.Builder(); } @@ -83,6 +87,7 @@ public Builder pageSpan(RagChunkPageSpan.Builder pageSpanBuilder) { } /** Deserializes a JSON string to a RagChunk object. */ + @ExcludeFromGeneratedCoverageReport public static RagChunk fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, RagChunk.class); } diff --git a/src/main/java/com/google/genai/types/RagChunkPageSpan.java b/src/main/java/com/google/genai/types/RagChunkPageSpan.java index 6570ddc7023..b2a736a8fa8 100644 --- a/src/main/java/com/google/genai/types/RagChunkPageSpan.java +++ b/src/main/java/com/google/genai/types/RagChunkPageSpan.java @@ -25,7 +25,10 @@ import com.google.genai.JsonSerializable; import java.util.Optional; -/** Represents where the chunk starts and ends in the document. */ +/** + * Represents where the chunk starts and ends in the document. This data type is not supported in + * Gemini API. + */ @AutoValue @JsonDeserialize(builder = RagChunkPageSpan.Builder.class) public abstract class RagChunkPageSpan extends JsonSerializable { @@ -38,6 +41,7 @@ public abstract class RagChunkPageSpan extends JsonSerializable { public abstract Optional lastPage(); /** Instantiates a builder for RagChunkPageSpan. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_RagChunkPageSpan.Builder(); } @@ -74,6 +78,7 @@ private static Builder create() { } /** Deserializes a JSON string to a RagChunkPageSpan object. */ + @ExcludeFromGeneratedCoverageReport public static RagChunkPageSpan fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, RagChunkPageSpan.class); } diff --git a/src/main/java/com/google/genai/types/RagRetrievalConfig.java b/src/main/java/com/google/genai/types/RagRetrievalConfig.java index 3d5db4aae3a..76ad4230ecc 100644 --- a/src/main/java/com/google/genai/types/RagRetrievalConfig.java +++ b/src/main/java/com/google/genai/types/RagRetrievalConfig.java @@ -25,7 +25,7 @@ import com.google.genai.JsonSerializable; import java.util.Optional; -/** Specifies the context retrieval config. */ +/** Specifies the context retrieval config. This data type is not supported in Gemini API. */ @AutoValue @JsonDeserialize(builder = RagRetrievalConfig.Builder.class) public abstract class RagRetrievalConfig extends JsonSerializable { @@ -46,6 +46,7 @@ public abstract class RagRetrievalConfig extends JsonSerializable { public abstract Optional topK(); /** Instantiates a builder for RagRetrievalConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_RagRetrievalConfig.Builder(); } @@ -125,6 +126,7 @@ public Builder ranking(RagRetrievalConfigRanking.Builder rankingBuilder) { } /** Deserializes a JSON string to a RagRetrievalConfig object. */ + @ExcludeFromGeneratedCoverageReport public static RagRetrievalConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, RagRetrievalConfig.class); } diff --git a/src/main/java/com/google/genai/types/RagRetrievalConfigFilter.java b/src/main/java/com/google/genai/types/RagRetrievalConfigFilter.java index 8f6a13dfa6d..beebb033eda 100644 --- a/src/main/java/com/google/genai/types/RagRetrievalConfigFilter.java +++ b/src/main/java/com/google/genai/types/RagRetrievalConfigFilter.java @@ -25,7 +25,7 @@ import com.google.genai.JsonSerializable; import java.util.Optional; -/** Config for filters. */ +/** Config for filters. This data type is not supported in Gemini API. */ @AutoValue @JsonDeserialize(builder = RagRetrievalConfigFilter.Builder.class) public abstract class RagRetrievalConfigFilter extends JsonSerializable { @@ -42,6 +42,7 @@ public abstract class RagRetrievalConfigFilter extends JsonSerializable { public abstract Optional vectorSimilarityThreshold(); /** Instantiates a builder for RagRetrievalConfigFilter. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_RagRetrievalConfigFilter.Builder(); } @@ -88,6 +89,7 @@ private static Builder create() { } /** Deserializes a JSON string to a RagRetrievalConfigFilter object. */ + @ExcludeFromGeneratedCoverageReport public static RagRetrievalConfigFilter fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, RagRetrievalConfigFilter.class); } diff --git a/src/main/java/com/google/genai/types/RagRetrievalConfigHybridSearch.java b/src/main/java/com/google/genai/types/RagRetrievalConfigHybridSearch.java index be8849cf584..6b81e68a221 100644 --- a/src/main/java/com/google/genai/types/RagRetrievalConfigHybridSearch.java +++ b/src/main/java/com/google/genai/types/RagRetrievalConfigHybridSearch.java @@ -25,7 +25,7 @@ import com.google.genai.JsonSerializable; import java.util.Optional; -/** Config for Hybrid Search. */ +/** Config for Hybrid Search. This data type is not supported in Gemini API. */ @AutoValue @JsonDeserialize(builder = RagRetrievalConfigHybridSearch.Builder.class) public abstract class RagRetrievalConfigHybridSearch extends JsonSerializable { @@ -38,6 +38,7 @@ public abstract class RagRetrievalConfigHybridSearch extends JsonSerializable { public abstract Optional alpha(); /** Instantiates a builder for RagRetrievalConfigHybridSearch. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_RagRetrievalConfigHybridSearch.Builder(); } @@ -71,6 +72,7 @@ private static Builder create() { } /** Deserializes a JSON string to a RagRetrievalConfigHybridSearch object. */ + @ExcludeFromGeneratedCoverageReport public static RagRetrievalConfigHybridSearch fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, RagRetrievalConfigHybridSearch.class); } diff --git a/src/main/java/com/google/genai/types/RagRetrievalConfigRanking.java b/src/main/java/com/google/genai/types/RagRetrievalConfigRanking.java index d9185c1f82f..7c8e9c6c70c 100644 --- a/src/main/java/com/google/genai/types/RagRetrievalConfigRanking.java +++ b/src/main/java/com/google/genai/types/RagRetrievalConfigRanking.java @@ -25,7 +25,7 @@ import com.google.genai.JsonSerializable; import java.util.Optional; -/** Config for ranking and reranking. */ +/** Config for ranking and reranking. This data type is not supported in Gemini API. */ @AutoValue @JsonDeserialize(builder = RagRetrievalConfigRanking.Builder.class) public abstract class RagRetrievalConfigRanking extends JsonSerializable { @@ -38,6 +38,7 @@ public abstract class RagRetrievalConfigRanking extends JsonSerializable { public abstract Optional rankService(); /** Instantiates a builder for RagRetrievalConfigRanking. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_RagRetrievalConfigRanking.Builder(); } @@ -92,6 +93,7 @@ public Builder rankService(RagRetrievalConfigRankingRankService.Builder rankServ } /** Deserializes a JSON string to a RagRetrievalConfigRanking object. */ + @ExcludeFromGeneratedCoverageReport public static RagRetrievalConfigRanking fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, RagRetrievalConfigRanking.class); } diff --git a/src/main/java/com/google/genai/types/RagRetrievalConfigRankingLlmRanker.java b/src/main/java/com/google/genai/types/RagRetrievalConfigRankingLlmRanker.java index db4dc0b56c0..aaf7f81a05a 100644 --- a/src/main/java/com/google/genai/types/RagRetrievalConfigRankingLlmRanker.java +++ b/src/main/java/com/google/genai/types/RagRetrievalConfigRankingLlmRanker.java @@ -25,7 +25,7 @@ import com.google.genai.JsonSerializable; import java.util.Optional; -/** Config for LlmRanker. */ +/** Config for LlmRanker. This data type is not supported in Gemini API. */ @AutoValue @JsonDeserialize(builder = RagRetrievalConfigRankingLlmRanker.Builder.class) public abstract class RagRetrievalConfigRankingLlmRanker extends JsonSerializable { @@ -37,6 +37,7 @@ public abstract class RagRetrievalConfigRankingLlmRanker extends JsonSerializabl public abstract Optional modelName(); /** Instantiates a builder for RagRetrievalConfigRankingLlmRanker. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_RagRetrievalConfigRankingLlmRanker.Builder(); } @@ -69,6 +70,7 @@ private static Builder create() { } /** Deserializes a JSON string to a RagRetrievalConfigRankingLlmRanker object. */ + @ExcludeFromGeneratedCoverageReport public static RagRetrievalConfigRankingLlmRanker fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, RagRetrievalConfigRankingLlmRanker.class); } diff --git a/src/main/java/com/google/genai/types/RagRetrievalConfigRankingRankService.java b/src/main/java/com/google/genai/types/RagRetrievalConfigRankingRankService.java index e400e9d4860..3f8c221e232 100644 --- a/src/main/java/com/google/genai/types/RagRetrievalConfigRankingRankService.java +++ b/src/main/java/com/google/genai/types/RagRetrievalConfigRankingRankService.java @@ -25,7 +25,7 @@ import com.google.genai.JsonSerializable; import java.util.Optional; -/** Config for Rank Service. */ +/** Config for Rank Service. This data type is not supported in Gemini API. */ @AutoValue @JsonDeserialize(builder = RagRetrievalConfigRankingRankService.Builder.class) public abstract class RagRetrievalConfigRankingRankService extends JsonSerializable { @@ -34,6 +34,7 @@ public abstract class RagRetrievalConfigRankingRankService extends JsonSerializa public abstract Optional modelName(); /** Instantiates a builder for RagRetrievalConfigRankingRankService. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_RagRetrievalConfigRankingRankService.Builder(); } @@ -66,6 +67,7 @@ private static Builder create() { } /** Deserializes a JSON string to a RagRetrievalConfigRankingRankService object. */ + @ExcludeFromGeneratedCoverageReport public static RagRetrievalConfigRankingRankService fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, RagRetrievalConfigRankingRankService.class); } diff --git a/src/main/java/com/google/genai/types/RawReferenceImage.java b/src/main/java/com/google/genai/types/RawReferenceImage.java index ea1e54edeb9..016a3462c4c 100644 --- a/src/main/java/com/google/genai/types/RawReferenceImage.java +++ b/src/main/java/com/google/genai/types/RawReferenceImage.java @@ -47,6 +47,7 @@ public abstract class RawReferenceImage extends JsonSerializable implements Refe public abstract Optional referenceType(); /** Instantiates a builder for RawReferenceImage. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_RawReferenceImage.Builder(); } @@ -100,6 +101,7 @@ public Builder referenceImage(Image.Builder referenceImageBuilder) { } /** Deserializes a JSON string to a RawReferenceImage object. */ + @ExcludeFromGeneratedCoverageReport public static RawReferenceImage fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, RawReferenceImage.class); } diff --git a/src/main/java/com/google/genai/types/RealtimeInputConfig.java b/src/main/java/com/google/genai/types/RealtimeInputConfig.java index 745ea404704..d2099975765 100644 --- a/src/main/java/com/google/genai/types/RealtimeInputConfig.java +++ b/src/main/java/com/google/genai/types/RealtimeInputConfig.java @@ -50,6 +50,7 @@ public abstract class RealtimeInputConfig extends JsonSerializable { public abstract Optional turnCoverage(); /** Instantiates a builder for RealtimeInputConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_RealtimeInputConfig.Builder(); } @@ -147,6 +148,7 @@ public Builder turnCoverage(String turnCoverage) { } /** Deserializes a JSON string to a RealtimeInputConfig object. */ + @ExcludeFromGeneratedCoverageReport public static RealtimeInputConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, RealtimeInputConfig.class); } diff --git a/src/main/java/com/google/genai/types/RecontextImageConfig.java b/src/main/java/com/google/genai/types/RecontextImageConfig.java new file mode 100644 index 00000000000..6419e22e2ea --- /dev/null +++ b/src/main/java/com/google/genai/types/RecontextImageConfig.java @@ -0,0 +1,258 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Auto-generated code. Do not edit. + +package com.google.genai.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.google.auto.value.AutoValue; +import com.google.errorprone.annotations.CanIgnoreReturnValue; +import com.google.genai.JsonSerializable; +import java.util.Map; +import java.util.Optional; + +/** Configuration for recontextualizing an image. */ +@AutoValue +@JsonDeserialize(builder = RecontextImageConfig.Builder.class) +public abstract class RecontextImageConfig extends JsonSerializable { + /** Used to override HTTP request options. */ + @JsonProperty("httpOptions") + public abstract Optional httpOptions(); + + /** Number of images to generate. */ + @JsonProperty("numberOfImages") + public abstract Optional numberOfImages(); + + /** + * The number of sampling steps. A higher value has better image quality, while a lower value has + * better latency. + */ + @JsonProperty("baseSteps") + public abstract Optional baseSteps(); + + /** Cloud Storage URI used to store the generated images. */ + @JsonProperty("outputGcsUri") + public abstract Optional outputGcsUri(); + + /** Random seed for image generation. */ + @JsonProperty("seed") + public abstract Optional seed(); + + /** Filter level for safety filtering. */ + @JsonProperty("safetyFilterLevel") + public abstract Optional safetyFilterLevel(); + + /** Whether allow to generate person images, and restrict to specific ages. */ + @JsonProperty("personGeneration") + public abstract Optional personGeneration(); + + /** Whether to add a SynthID watermark to the generated images. */ + @JsonProperty("addWatermark") + public abstract Optional addWatermark(); + + /** MIME type of the generated image. */ + @JsonProperty("outputMimeType") + public abstract Optional outputMimeType(); + + /** Compression quality of the generated image (for ``image/jpeg`` only). */ + @JsonProperty("outputCompressionQuality") + public abstract Optional outputCompressionQuality(); + + /** Whether to use the prompt rewriting logic. */ + @JsonProperty("enhancePrompt") + public abstract Optional enhancePrompt(); + + /** User specified labels to track billing usage. */ + @JsonProperty("labels") + public abstract Optional> labels(); + + /** Instantiates a builder for RecontextImageConfig. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_RecontextImageConfig.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for RecontextImageConfig. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `RecontextImageConfig.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_RecontextImageConfig.Builder(); + } + + /** + * Setter for httpOptions. + * + *

httpOptions: Used to override HTTP request options. + */ + @JsonProperty("httpOptions") + public abstract Builder httpOptions(HttpOptions httpOptions); + + /** + * Setter for httpOptions builder. + * + *

httpOptions: Used to override HTTP request options. + */ + public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { + return httpOptions(httpOptionsBuilder.build()); + } + + /** + * Setter for numberOfImages. + * + *

numberOfImages: Number of images to generate. + */ + @JsonProperty("numberOfImages") + public abstract Builder numberOfImages(Integer numberOfImages); + + /** + * Setter for baseSteps. + * + *

baseSteps: The number of sampling steps. A higher value has better image quality, while a + * lower value has better latency. + */ + @JsonProperty("baseSteps") + public abstract Builder baseSteps(Integer baseSteps); + + /** + * Setter for outputGcsUri. + * + *

outputGcsUri: Cloud Storage URI used to store the generated images. + */ + @JsonProperty("outputGcsUri") + public abstract Builder outputGcsUri(String outputGcsUri); + + /** + * Setter for seed. + * + *

seed: Random seed for image generation. + */ + @JsonProperty("seed") + public abstract Builder seed(Integer seed); + + /** + * Setter for safetyFilterLevel. + * + *

safetyFilterLevel: Filter level for safety filtering. + */ + @JsonProperty("safetyFilterLevel") + public abstract Builder safetyFilterLevel(SafetyFilterLevel safetyFilterLevel); + + /** + * Setter for safetyFilterLevel given a known enum. + * + *

safetyFilterLevel: Filter level for safety filtering. + */ + @CanIgnoreReturnValue + public Builder safetyFilterLevel(SafetyFilterLevel.Known knownType) { + return safetyFilterLevel(new SafetyFilterLevel(knownType)); + } + + /** + * Setter for safetyFilterLevel given a string. + * + *

safetyFilterLevel: Filter level for safety filtering. + */ + @CanIgnoreReturnValue + public Builder safetyFilterLevel(String safetyFilterLevel) { + return safetyFilterLevel(new SafetyFilterLevel(safetyFilterLevel)); + } + + /** + * Setter for personGeneration. + * + *

personGeneration: Whether allow to generate person images, and restrict to specific ages. + */ + @JsonProperty("personGeneration") + public abstract Builder personGeneration(PersonGeneration personGeneration); + + /** + * Setter for personGeneration given a known enum. + * + *

personGeneration: Whether allow to generate person images, and restrict to specific ages. + */ + @CanIgnoreReturnValue + public Builder personGeneration(PersonGeneration.Known knownType) { + return personGeneration(new PersonGeneration(knownType)); + } + + /** + * Setter for personGeneration given a string. + * + *

personGeneration: Whether allow to generate person images, and restrict to specific ages. + */ + @CanIgnoreReturnValue + public Builder personGeneration(String personGeneration) { + return personGeneration(new PersonGeneration(personGeneration)); + } + + /** + * Setter for addWatermark. + * + *

addWatermark: Whether to add a SynthID watermark to the generated images. + */ + @JsonProperty("addWatermark") + public abstract Builder addWatermark(boolean addWatermark); + + /** + * Setter for outputMimeType. + * + *

outputMimeType: MIME type of the generated image. + */ + @JsonProperty("outputMimeType") + public abstract Builder outputMimeType(String outputMimeType); + + /** + * Setter for outputCompressionQuality. + * + *

outputCompressionQuality: Compression quality of the generated image (for ``image/jpeg`` + * only). + */ + @JsonProperty("outputCompressionQuality") + public abstract Builder outputCompressionQuality(Integer outputCompressionQuality); + + /** + * Setter for enhancePrompt. + * + *

enhancePrompt: Whether to use the prompt rewriting logic. + */ + @JsonProperty("enhancePrompt") + public abstract Builder enhancePrompt(boolean enhancePrompt); + + /** + * Setter for labels. + * + *

labels: User specified labels to track billing usage. + */ + @JsonProperty("labels") + public abstract Builder labels(Map labels); + + public abstract RecontextImageConfig build(); + } + + /** Deserializes a JSON string to a RecontextImageConfig object. */ + @ExcludeFromGeneratedCoverageReport + public static RecontextImageConfig fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, RecontextImageConfig.class); + } +} diff --git a/src/main/java/com/google/genai/types/RecontextImageParameters.java b/src/main/java/com/google/genai/types/RecontextImageParameters.java new file mode 100644 index 00000000000..196aacd68a3 --- /dev/null +++ b/src/main/java/com/google/genai/types/RecontextImageParameters.java @@ -0,0 +1,118 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Auto-generated code. Do not edit. + +package com.google.genai.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.google.api.core.InternalApi; +import com.google.auto.value.AutoValue; +import com.google.genai.JsonSerializable; +import java.util.Optional; + +/** The parameters for recontextualizing an image. */ +@AutoValue +@InternalApi +@JsonDeserialize(builder = RecontextImageParameters.Builder.class) +public abstract class RecontextImageParameters extends JsonSerializable { + /** + * ID of the model to use. For a list of models, see `Google models + * `_. + */ + @JsonProperty("model") + public abstract Optional model(); + + /** A set of source input(s) for image recontextualization. */ + @JsonProperty("source") + public abstract Optional source(); + + /** Configuration for image recontextualization. */ + @JsonProperty("config") + public abstract Optional config(); + + /** Instantiates a builder for RecontextImageParameters. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_RecontextImageParameters.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for RecontextImageParameters. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `RecontextImageParameters.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_RecontextImageParameters.Builder(); + } + + /** + * Setter for model. + * + *

model: ID of the model to use. For a list of models, see `Google models + * `_. + */ + @JsonProperty("model") + public abstract Builder model(String model); + + /** + * Setter for source. + * + *

source: A set of source input(s) for image recontextualization. + */ + @JsonProperty("source") + public abstract Builder source(RecontextImageSource source); + + /** + * Setter for source builder. + * + *

source: A set of source input(s) for image recontextualization. + */ + public Builder source(RecontextImageSource.Builder sourceBuilder) { + return source(sourceBuilder.build()); + } + + /** + * Setter for config. + * + *

config: Configuration for image recontextualization. + */ + @JsonProperty("config") + public abstract Builder config(RecontextImageConfig config); + + /** + * Setter for config builder. + * + *

config: Configuration for image recontextualization. + */ + public Builder config(RecontextImageConfig.Builder configBuilder) { + return config(configBuilder.build()); + } + + public abstract RecontextImageParameters build(); + } + + /** Deserializes a JSON string to a RecontextImageParameters object. */ + @ExcludeFromGeneratedCoverageReport + public static RecontextImageParameters fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, RecontextImageParameters.class); + } +} diff --git a/src/main/java/com/google/genai/types/RecontextImageResponse.java b/src/main/java/com/google/genai/types/RecontextImageResponse.java new file mode 100644 index 00000000000..1efd22f5de4 --- /dev/null +++ b/src/main/java/com/google/genai/types/RecontextImageResponse.java @@ -0,0 +1,95 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Auto-generated code. Do not edit. + +package com.google.genai.types; + +import static com.google.common.collect.ImmutableList.toImmutableList; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.google.auto.value.AutoValue; +import com.google.genai.JsonSerializable; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +/** The output images response. */ +@AutoValue +@JsonDeserialize(builder = RecontextImageResponse.Builder.class) +public abstract class RecontextImageResponse extends JsonSerializable { + /** List of generated images. */ + @JsonProperty("generatedImages") + public abstract Optional> generatedImages(); + + /** Instantiates a builder for RecontextImageResponse. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_RecontextImageResponse.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for RecontextImageResponse. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `RecontextImageResponse.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_RecontextImageResponse.Builder(); + } + + /** + * Setter for generatedImages. + * + *

generatedImages: List of generated images. + */ + @JsonProperty("generatedImages") + public abstract Builder generatedImages(List generatedImages); + + /** + * Setter for generatedImages. + * + *

generatedImages: List of generated images. + */ + public Builder generatedImages(GeneratedImage... generatedImages) { + return generatedImages(Arrays.asList(generatedImages)); + } + + /** + * Setter for generatedImages builder. + * + *

generatedImages: List of generated images. + */ + public Builder generatedImages(GeneratedImage.Builder... generatedImagesBuilders) { + return generatedImages( + Arrays.asList(generatedImagesBuilders).stream() + .map(GeneratedImage.Builder::build) + .collect(toImmutableList())); + } + + public abstract RecontextImageResponse build(); + } + + /** Deserializes a JSON string to a RecontextImageResponse object. */ + @ExcludeFromGeneratedCoverageReport + public static RecontextImageResponse fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, RecontextImageResponse.class); + } +} diff --git a/src/main/java/com/google/genai/types/RecontextImageSource.java b/src/main/java/com/google/genai/types/RecontextImageSource.java new file mode 100644 index 00000000000..9327e16fc5f --- /dev/null +++ b/src/main/java/com/google/genai/types/RecontextImageSource.java @@ -0,0 +1,132 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Auto-generated code. Do not edit. + +package com.google.genai.types; + +import static com.google.common.collect.ImmutableList.toImmutableList; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.google.auto.value.AutoValue; +import com.google.genai.JsonSerializable; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +/** A set of source input(s) for image recontextualization. */ +@AutoValue +@JsonDeserialize(builder = RecontextImageSource.Builder.class) +public abstract class RecontextImageSource extends JsonSerializable { + /** + * A text prompt for guiding the model during image recontextualization. Not supported for Virtual + * Try-On. + */ + @JsonProperty("prompt") + public abstract Optional prompt(); + + /** Image of the person or subject who will be wearing the product(s). */ + @JsonProperty("personImage") + public abstract Optional personImage(); + + /** A list of product images. */ + @JsonProperty("productImages") + public abstract Optional> productImages(); + + /** Instantiates a builder for RecontextImageSource. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_RecontextImageSource.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for RecontextImageSource. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `RecontextImageSource.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_RecontextImageSource.Builder(); + } + + /** + * Setter for prompt. + * + *

prompt: A text prompt for guiding the model during image recontextualization. Not + * supported for Virtual Try-On. + */ + @JsonProperty("prompt") + public abstract Builder prompt(String prompt); + + /** + * Setter for personImage. + * + *

personImage: Image of the person or subject who will be wearing the product(s). + */ + @JsonProperty("personImage") + public abstract Builder personImage(Image personImage); + + /** + * Setter for personImage builder. + * + *

personImage: Image of the person or subject who will be wearing the product(s). + */ + public Builder personImage(Image.Builder personImageBuilder) { + return personImage(personImageBuilder.build()); + } + + /** + * Setter for productImages. + * + *

productImages: A list of product images. + */ + @JsonProperty("productImages") + public abstract Builder productImages(List productImages); + + /** + * Setter for productImages. + * + *

productImages: A list of product images. + */ + public Builder productImages(ProductImage... productImages) { + return productImages(Arrays.asList(productImages)); + } + + /** + * Setter for productImages builder. + * + *

productImages: A list of product images. + */ + public Builder productImages(ProductImage.Builder... productImagesBuilders) { + return productImages( + Arrays.asList(productImagesBuilders).stream() + .map(ProductImage.Builder::build) + .collect(toImmutableList())); + } + + public abstract RecontextImageSource build(); + } + + /** Deserializes a JSON string to a RecontextImageSource object. */ + @ExcludeFromGeneratedCoverageReport + public static RecontextImageSource fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, RecontextImageSource.class); + } +} diff --git a/src/main/java/com/google/genai/types/ReferenceImageAPI.java b/src/main/java/com/google/genai/types/ReferenceImageAPI.java index 9b5389f71d8..867ac552c7d 100644 --- a/src/main/java/com/google/genai/types/ReferenceImageAPI.java +++ b/src/main/java/com/google/genai/types/ReferenceImageAPI.java @@ -60,6 +60,7 @@ public abstract class ReferenceImageAPI extends JsonSerializable { public abstract Optional subjectImageConfig(); /** Instantiates a builder for ReferenceImageAPI. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_ReferenceImageAPI.Builder(); } @@ -181,6 +182,7 @@ public Builder subjectImageConfig(SubjectReferenceConfig.Builder subjectImageCon } /** Deserializes a JSON string to a ReferenceImageAPI object. */ + @ExcludeFromGeneratedCoverageReport public static ReferenceImageAPI fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, ReferenceImageAPI.class); } diff --git a/src/main/java/com/google/genai/types/ReplayFile.java b/src/main/java/com/google/genai/types/ReplayFile.java index 0c12d4d142c..4ce9bf574f3 100644 --- a/src/main/java/com/google/genai/types/ReplayFile.java +++ b/src/main/java/com/google/genai/types/ReplayFile.java @@ -42,6 +42,7 @@ public abstract class ReplayFile extends JsonSerializable { public abstract Optional> interactions(); /** Instantiates a builder for ReplayFile. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_ReplayFile.Builder(); } @@ -99,6 +100,7 @@ public Builder interactions(ReplayInteraction.Builder... interactionsBuilders) { } /** Deserializes a JSON string to a ReplayFile object. */ + @ExcludeFromGeneratedCoverageReport public static ReplayFile fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, ReplayFile.class); } diff --git a/src/main/java/com/google/genai/types/ReplayInteraction.java b/src/main/java/com/google/genai/types/ReplayInteraction.java index 800e2b359ef..77eb5496a55 100644 --- a/src/main/java/com/google/genai/types/ReplayInteraction.java +++ b/src/main/java/com/google/genai/types/ReplayInteraction.java @@ -38,6 +38,7 @@ public abstract class ReplayInteraction extends JsonSerializable { public abstract Optional response(); /** Instantiates a builder for ReplayInteraction. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_ReplayInteraction.Builder(); } @@ -92,6 +93,7 @@ public Builder response(ReplayResponse.Builder responseBuilder) { } /** Deserializes a JSON string to a ReplayInteraction object. */ + @ExcludeFromGeneratedCoverageReport public static ReplayInteraction fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, ReplayInteraction.class); } diff --git a/src/main/java/com/google/genai/types/ReplayRequest.java b/src/main/java/com/google/genai/types/ReplayRequest.java index 5da5d149cb6..35cdab9bf3b 100644 --- a/src/main/java/com/google/genai/types/ReplayRequest.java +++ b/src/main/java/com/google/genai/types/ReplayRequest.java @@ -49,6 +49,7 @@ public abstract class ReplayRequest extends JsonSerializable { public abstract Optional>> bodySegments(); /** Instantiates a builder for ReplayRequest. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_ReplayRequest.Builder(); } @@ -110,6 +111,7 @@ public Builder bodySegments(Map... bodySegments) { } /** Deserializes a JSON string to a ReplayRequest object. */ + @ExcludeFromGeneratedCoverageReport public static ReplayRequest fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, ReplayRequest.class); } diff --git a/src/main/java/com/google/genai/types/ReplayResponse.java b/src/main/java/com/google/genai/types/ReplayResponse.java index 85de3549581..f89c9811ea6 100644 --- a/src/main/java/com/google/genai/types/ReplayResponse.java +++ b/src/main/java/com/google/genai/types/ReplayResponse.java @@ -49,6 +49,7 @@ public abstract class ReplayResponse extends JsonSerializable { public abstract Optional>> sdkResponseSegments(); /** Instantiates a builder for ReplayResponse. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_ReplayResponse.Builder(); } @@ -119,6 +120,7 @@ public Builder sdkResponseSegments(Map... sdkResponseSegments) { } /** Deserializes a JSON string to a ReplayResponse object. */ + @ExcludeFromGeneratedCoverageReport public static ReplayResponse fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, ReplayResponse.class); } diff --git a/src/main/java/com/google/genai/types/Retrieval.java b/src/main/java/com/google/genai/types/Retrieval.java index d98e2e6ecb1..798b92b1571 100644 --- a/src/main/java/com/google/genai/types/Retrieval.java +++ b/src/main/java/com/google/genai/types/Retrieval.java @@ -25,7 +25,10 @@ import com.google.genai.JsonSerializable; import java.util.Optional; -/** Defines a retrieval tool that model can call to access external knowledge. */ +/** + * Defines a retrieval tool that model can call to access external knowledge. This data type is not + * supported in Gemini API. + */ @AutoValue @JsonDeserialize(builder = Retrieval.Builder.class) public abstract class Retrieval extends JsonSerializable { @@ -49,6 +52,7 @@ public abstract class Retrieval extends JsonSerializable { public abstract Optional vertexRagStore(); /** Instantiates a builder for Retrieval. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_Retrieval.Builder(); } @@ -130,6 +134,7 @@ public Builder vertexRagStore(VertexRagStore.Builder vertexRagStoreBuilder) { } /** Deserializes a JSON string to a Retrieval object. */ + @ExcludeFromGeneratedCoverageReport public static Retrieval fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, Retrieval.class); } diff --git a/src/main/java/com/google/genai/types/RetrievalConfig.java b/src/main/java/com/google/genai/types/RetrievalConfig.java index f2654a24af9..2d77b4ee3b9 100644 --- a/src/main/java/com/google/genai/types/RetrievalConfig.java +++ b/src/main/java/com/google/genai/types/RetrievalConfig.java @@ -38,6 +38,7 @@ public abstract class RetrievalConfig extends JsonSerializable { public abstract Optional languageCode(); /** Instantiates a builder for RetrievalConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_RetrievalConfig.Builder(); } @@ -83,6 +84,7 @@ public Builder latLng(LatLng.Builder latLngBuilder) { } /** Deserializes a JSON string to a RetrievalConfig object. */ + @ExcludeFromGeneratedCoverageReport public static RetrievalConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, RetrievalConfig.class); } diff --git a/src/main/java/com/google/genai/types/RetrievalMetadata.java b/src/main/java/com/google/genai/types/RetrievalMetadata.java index 805d9c1a1f7..c8652e88680 100644 --- a/src/main/java/com/google/genai/types/RetrievalMetadata.java +++ b/src/main/java/com/google/genai/types/RetrievalMetadata.java @@ -39,6 +39,7 @@ public abstract class RetrievalMetadata extends JsonSerializable { public abstract Optional googleSearchDynamicRetrievalScore(); /** Instantiates a builder for RetrievalMetadata. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_RetrievalMetadata.Builder(); } @@ -72,6 +73,7 @@ public abstract Builder googleSearchDynamicRetrievalScore( } /** Deserializes a JSON string to a RetrievalMetadata object. */ + @ExcludeFromGeneratedCoverageReport public static RetrievalMetadata fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, RetrievalMetadata.class); } diff --git a/src/main/java/com/google/genai/types/SafetyAttributes.java b/src/main/java/com/google/genai/types/SafetyAttributes.java index 7a51f5b5320..6ffcee8f410 100644 --- a/src/main/java/com/google/genai/types/SafetyAttributes.java +++ b/src/main/java/com/google/genai/types/SafetyAttributes.java @@ -44,6 +44,7 @@ public abstract class SafetyAttributes extends JsonSerializable { public abstract Optional contentType(); /** Instantiates a builder for SafetyAttributes. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_SafetyAttributes.Builder(); } @@ -106,6 +107,7 @@ public Builder scores(Float... scores) { } /** Deserializes a JSON string to a SafetyAttributes object. */ + @ExcludeFromGeneratedCoverageReport public static SafetyAttributes fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, SafetyAttributes.class); } diff --git a/src/main/java/com/google/genai/types/SafetyFilterLevel.java b/src/main/java/com/google/genai/types/SafetyFilterLevel.java index 549023804ab..9dc80565f51 100644 --- a/src/main/java/com/google/genai/types/SafetyFilterLevel.java +++ b/src/main/java/com/google/genai/types/SafetyFilterLevel.java @@ -61,12 +61,14 @@ public SafetyFilterLevel(Known knownValue) { this.value = knownValue.toString(); } + @ExcludeFromGeneratedCoverageReport @Override @JsonValue public String toString() { return this.value; } + @ExcludeFromGeneratedCoverageReport @SuppressWarnings("PatternMatchingInstanceof") @Override public boolean equals(Object o) { @@ -93,6 +95,7 @@ public boolean equals(Object o) { return false; } + @ExcludeFromGeneratedCoverageReport @Override public int hashCode() { if (this.safetyFilterLevelEnum != Known.SAFETY_FILTER_LEVEL_UNSPECIFIED) { @@ -102,6 +105,7 @@ public int hashCode() { } } + @ExcludeFromGeneratedCoverageReport public Known knownEnum() { return this.safetyFilterLevelEnum; } diff --git a/src/main/java/com/google/genai/types/SafetyRating.java b/src/main/java/com/google/genai/types/SafetyRating.java index e215792912a..ad7dac7dfcb 100644 --- a/src/main/java/com/google/genai/types/SafetyRating.java +++ b/src/main/java/com/google/genai/types/SafetyRating.java @@ -41,7 +41,7 @@ public abstract class SafetyRating extends JsonSerializable { /** * Output only. The overwritten threshold for the safety category of Gemini 2.0 image out. If * minors are detected in the output image, the threshold of each safety category will be - * overwritten if user sets a lower threshold. + * overwritten if user sets a lower threshold. This field is not supported in Gemini API. */ @JsonProperty("overwrittenThreshold") public abstract Optional overwrittenThreshold(); @@ -50,19 +50,22 @@ public abstract class SafetyRating extends JsonSerializable { @JsonProperty("probability") public abstract Optional probability(); - /** Output only. Harm probability score. */ + /** Output only. Harm probability score. This field is not supported in Gemini API. */ @JsonProperty("probabilityScore") public abstract Optional probabilityScore(); - /** Output only. Harm severity levels in the content. */ + /** + * Output only. Harm severity levels in the content. This field is not supported in Gemini API. + */ @JsonProperty("severity") public abstract Optional severity(); - /** Output only. Harm severity score. */ + /** Output only. Harm severity score. This field is not supported in Gemini API. */ @JsonProperty("severityScore") public abstract Optional severityScore(); /** Instantiates a builder for SafetyRating. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_SafetyRating.Builder(); } @@ -121,7 +124,8 @@ public Builder category(String category) { * *

overwrittenThreshold: Output only. The overwritten threshold for the safety category of * Gemini 2.0 image out. If minors are detected in the output image, the threshold of each - * safety category will be overwritten if user sets a lower threshold. + * safety category will be overwritten if user sets a lower threshold. This field is not + * supported in Gemini API. */ @JsonProperty("overwrittenThreshold") public abstract Builder overwrittenThreshold(HarmBlockThreshold overwrittenThreshold); @@ -131,7 +135,8 @@ public Builder category(String category) { * *

overwrittenThreshold: Output only. The overwritten threshold for the safety category of * Gemini 2.0 image out. If minors are detected in the output image, the threshold of each - * safety category will be overwritten if user sets a lower threshold. + * safety category will be overwritten if user sets a lower threshold. This field is not + * supported in Gemini API. */ @CanIgnoreReturnValue public Builder overwrittenThreshold(HarmBlockThreshold.Known knownType) { @@ -143,7 +148,8 @@ public Builder overwrittenThreshold(HarmBlockThreshold.Known knownType) { * *

overwrittenThreshold: Output only. The overwritten threshold for the safety category of * Gemini 2.0 image out. If minors are detected in the output image, the threshold of each - * safety category will be overwritten if user sets a lower threshold. + * safety category will be overwritten if user sets a lower threshold. This field is not + * supported in Gemini API. */ @CanIgnoreReturnValue public Builder overwrittenThreshold(String overwrittenThreshold) { @@ -181,7 +187,8 @@ public Builder probability(String probability) { /** * Setter for probabilityScore. * - *

probabilityScore: Output only. Harm probability score. + *

probabilityScore: Output only. Harm probability score. This field is not supported in + * Gemini API. */ @JsonProperty("probabilityScore") public abstract Builder probabilityScore(Float probabilityScore); @@ -189,7 +196,8 @@ public Builder probability(String probability) { /** * Setter for severity. * - *

severity: Output only. Harm severity levels in the content. + *

severity: Output only. Harm severity levels in the content. This field is not supported in + * Gemini API. */ @JsonProperty("severity") public abstract Builder severity(HarmSeverity severity); @@ -197,7 +205,8 @@ public Builder probability(String probability) { /** * Setter for severity given a known enum. * - *

severity: Output only. Harm severity levels in the content. + *

severity: Output only. Harm severity levels in the content. This field is not supported in + * Gemini API. */ @CanIgnoreReturnValue public Builder severity(HarmSeverity.Known knownType) { @@ -207,7 +216,8 @@ public Builder severity(HarmSeverity.Known knownType) { /** * Setter for severity given a string. * - *

severity: Output only. Harm severity levels in the content. + *

severity: Output only. Harm severity levels in the content. This field is not supported in + * Gemini API. */ @CanIgnoreReturnValue public Builder severity(String severity) { @@ -217,7 +227,8 @@ public Builder severity(String severity) { /** * Setter for severityScore. * - *

severityScore: Output only. Harm severity score. + *

severityScore: Output only. Harm severity score. This field is not supported in Gemini + * API. */ @JsonProperty("severityScore") public abstract Builder severityScore(Float severityScore); @@ -226,6 +237,7 @@ public Builder severity(String severity) { } /** Deserializes a JSON string to a SafetyRating object. */ + @ExcludeFromGeneratedCoverageReport public static SafetyRating fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, SafetyRating.class); } diff --git a/src/main/java/com/google/genai/types/SafetySetting.java b/src/main/java/com/google/genai/types/SafetySetting.java index d9612db5a2c..16b6e56cb79 100644 --- a/src/main/java/com/google/genai/types/SafetySetting.java +++ b/src/main/java/com/google/genai/types/SafetySetting.java @@ -30,19 +30,23 @@ @AutoValue @JsonDeserialize(builder = SafetySetting.Builder.class) public abstract class SafetySetting extends JsonSerializable { - /** Determines if the harm block method uses probability or probability and severity scores. */ - @JsonProperty("method") - public abstract Optional method(); - /** Required. Harm category. */ @JsonProperty("category") public abstract Optional category(); + /** + * Optional. Specify if the threshold is used for probability or severity score. If not specified, + * the threshold is used for probability score. This field is not supported in Gemini API. + */ + @JsonProperty("method") + public abstract Optional method(); + /** Required. The harm block threshold. */ @JsonProperty("threshold") public abstract Optional threshold(); /** Instantiates a builder for SafetySetting. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_SafetySetting.Builder(); } @@ -60,62 +64,65 @@ private static Builder create() { } /** - * Setter for method. + * Setter for category. * - *

method: Determines if the harm block method uses probability or probability and severity - * scores. + *

category: Required. Harm category. */ - @JsonProperty("method") - public abstract Builder method(HarmBlockMethod method); + @JsonProperty("category") + public abstract Builder category(HarmCategory category); /** - * Setter for method given a known enum. + * Setter for category given a known enum. * - *

method: Determines if the harm block method uses probability or probability and severity - * scores. + *

category: Required. Harm category. */ @CanIgnoreReturnValue - public Builder method(HarmBlockMethod.Known knownType) { - return method(new HarmBlockMethod(knownType)); + public Builder category(HarmCategory.Known knownType) { + return category(new HarmCategory(knownType)); } /** - * Setter for method given a string. + * Setter for category given a string. * - *

method: Determines if the harm block method uses probability or probability and severity - * scores. + *

category: Required. Harm category. */ @CanIgnoreReturnValue - public Builder method(String method) { - return method(new HarmBlockMethod(method)); + public Builder category(String category) { + return category(new HarmCategory(category)); } /** - * Setter for category. + * Setter for method. * - *

category: Required. Harm category. + *

method: Optional. Specify if the threshold is used for probability or severity score. If + * not specified, the threshold is used for probability score. This field is not supported in + * Gemini API. */ - @JsonProperty("category") - public abstract Builder category(HarmCategory category); + @JsonProperty("method") + public abstract Builder method(HarmBlockMethod method); /** - * Setter for category given a known enum. + * Setter for method given a known enum. * - *

category: Required. Harm category. + *

method: Optional. Specify if the threshold is used for probability or severity score. If + * not specified, the threshold is used for probability score. This field is not supported in + * Gemini API. */ @CanIgnoreReturnValue - public Builder category(HarmCategory.Known knownType) { - return category(new HarmCategory(knownType)); + public Builder method(HarmBlockMethod.Known knownType) { + return method(new HarmBlockMethod(knownType)); } /** - * Setter for category given a string. + * Setter for method given a string. * - *

category: Required. Harm category. + *

method: Optional. Specify if the threshold is used for probability or severity score. If + * not specified, the threshold is used for probability score. This field is not supported in + * Gemini API. */ @CanIgnoreReturnValue - public Builder category(String category) { - return category(new HarmCategory(category)); + public Builder method(String method) { + return method(new HarmBlockMethod(method)); } /** @@ -150,6 +157,7 @@ public Builder threshold(String threshold) { } /** Deserializes a JSON string to a SafetySetting object. */ + @ExcludeFromGeneratedCoverageReport public static SafetySetting fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, SafetySetting.class); } diff --git a/src/main/java/com/google/genai/types/Schema.java b/src/main/java/com/google/genai/types/Schema.java index e87186890f0..e8a58d2aba2 100644 --- a/src/main/java/com/google/genai/types/Schema.java +++ b/src/main/java/com/google/genai/types/Schema.java @@ -146,6 +146,7 @@ public abstract class Schema extends JsonSerializable { public abstract Optional type(); /** Instantiates a builder for Schema. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_Schema.Builder(); } @@ -433,6 +434,7 @@ public Builder type(String type) { } /** Deserializes a JSON string to a Schema object. */ + @ExcludeFromGeneratedCoverageReport public static Schema fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, Schema.class); } diff --git a/src/main/java/com/google/genai/types/ScribbleImage.java b/src/main/java/com/google/genai/types/ScribbleImage.java new file mode 100644 index 00000000000..68b9be5203b --- /dev/null +++ b/src/main/java/com/google/genai/types/ScribbleImage.java @@ -0,0 +1,79 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Auto-generated code. Do not edit. + +package com.google.genai.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.google.auto.value.AutoValue; +import com.google.genai.JsonSerializable; +import java.util.Optional; + +/** An image mask representing a brush scribble. */ +@AutoValue +@JsonDeserialize(builder = ScribbleImage.Builder.class) +public abstract class ScribbleImage extends JsonSerializable { + /** The brush scribble to guide segmentation. Valid for the interactive mode. */ + @JsonProperty("image") + public abstract Optional image(); + + /** Instantiates a builder for ScribbleImage. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_ScribbleImage.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for ScribbleImage. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `ScribbleImage.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_ScribbleImage.Builder(); + } + + /** + * Setter for image. + * + *

image: The brush scribble to guide segmentation. Valid for the interactive mode. + */ + @JsonProperty("image") + public abstract Builder image(Image image); + + /** + * Setter for image builder. + * + *

image: The brush scribble to guide segmentation. Valid for the interactive mode. + */ + public Builder image(Image.Builder imageBuilder) { + return image(imageBuilder.build()); + } + + public abstract ScribbleImage build(); + } + + /** Deserializes a JSON string to a ScribbleImage object. */ + @ExcludeFromGeneratedCoverageReport + public static ScribbleImage fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, ScribbleImage.class); + } +} diff --git a/src/main/java/com/google/genai/types/SearchEntryPoint.java b/src/main/java/com/google/genai/types/SearchEntryPoint.java index 398a223af3b..acf7b10e202 100644 --- a/src/main/java/com/google/genai/types/SearchEntryPoint.java +++ b/src/main/java/com/google/genai/types/SearchEntryPoint.java @@ -38,6 +38,7 @@ public abstract class SearchEntryPoint extends JsonSerializable { public abstract Optional sdkBlob(); /** Instantiates a builder for SearchEntryPoint. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_SearchEntryPoint.Builder(); } @@ -75,6 +76,7 @@ private static Builder create() { } /** Deserializes a JSON string to a SearchEntryPoint object. */ + @ExcludeFromGeneratedCoverageReport public static SearchEntryPoint fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, SearchEntryPoint.class); } diff --git a/src/main/java/com/google/genai/types/Segment.java b/src/main/java/com/google/genai/types/Segment.java index d39ca735487..7f6852c86e6 100644 --- a/src/main/java/com/google/genai/types/Segment.java +++ b/src/main/java/com/google/genai/types/Segment.java @@ -52,6 +52,7 @@ public abstract class Segment extends JsonSerializable { public abstract Optional text(); /** Instantiates a builder for Segment. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_Segment.Builder(); } @@ -106,6 +107,7 @@ private static Builder create() { } /** Deserializes a JSON string to a Segment object. */ + @ExcludeFromGeneratedCoverageReport public static Segment fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, Segment.class); } diff --git a/src/main/java/com/google/genai/types/SegmentImageConfig.java b/src/main/java/com/google/genai/types/SegmentImageConfig.java new file mode 100644 index 00000000000..6f42b8afa03 --- /dev/null +++ b/src/main/java/com/google/genai/types/SegmentImageConfig.java @@ -0,0 +1,187 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Auto-generated code. Do not edit. + +package com.google.genai.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.google.auto.value.AutoValue; +import com.google.errorprone.annotations.CanIgnoreReturnValue; +import com.google.genai.JsonSerializable; +import java.util.Map; +import java.util.Optional; + +/** Configuration for segmenting an image. */ +@AutoValue +@JsonDeserialize(builder = SegmentImageConfig.Builder.class) +public abstract class SegmentImageConfig extends JsonSerializable { + /** Used to override HTTP request options. */ + @JsonProperty("httpOptions") + public abstract Optional httpOptions(); + + /** The segmentation mode to use. */ + @JsonProperty("mode") + public abstract Optional mode(); + + /** The maximum number of predictions to return up to, by top confidence score. */ + @JsonProperty("maxPredictions") + public abstract Optional maxPredictions(); + + /** + * The confidence score threshold for the detections as a decimal value. Only predictions with a + * confidence score higher than this threshold will be returned. + */ + @JsonProperty("confidenceThreshold") + public abstract Optional confidenceThreshold(); + + /** + * A decimal value representing how much dilation to apply to the masks. 0 for no dilation. 1.0 + * means the masked area covers the whole image. + */ + @JsonProperty("maskDilation") + public abstract Optional maskDilation(); + + /** + * The binary color threshold to apply to the masks. The threshold can be set to a decimal value + * between 0 and 255 non-inclusive. Set to -1 for no binary color thresholding. + */ + @JsonProperty("binaryColorThreshold") + public abstract Optional binaryColorThreshold(); + + /** User specified labels to track billing usage. */ + @JsonProperty("labels") + public abstract Optional> labels(); + + /** Instantiates a builder for SegmentImageConfig. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_SegmentImageConfig.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for SegmentImageConfig. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `SegmentImageConfig.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_SegmentImageConfig.Builder(); + } + + /** + * Setter for httpOptions. + * + *

httpOptions: Used to override HTTP request options. + */ + @JsonProperty("httpOptions") + public abstract Builder httpOptions(HttpOptions httpOptions); + + /** + * Setter for httpOptions builder. + * + *

httpOptions: Used to override HTTP request options. + */ + public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { + return httpOptions(httpOptionsBuilder.build()); + } + + /** + * Setter for mode. + * + *

mode: The segmentation mode to use. + */ + @JsonProperty("mode") + public abstract Builder mode(SegmentMode mode); + + /** + * Setter for mode given a known enum. + * + *

mode: The segmentation mode to use. + */ + @CanIgnoreReturnValue + public Builder mode(SegmentMode.Known knownType) { + return mode(new SegmentMode(knownType)); + } + + /** + * Setter for mode given a string. + * + *

mode: The segmentation mode to use. + */ + @CanIgnoreReturnValue + public Builder mode(String mode) { + return mode(new SegmentMode(mode)); + } + + /** + * Setter for maxPredictions. + * + *

maxPredictions: The maximum number of predictions to return up to, by top confidence + * score. + */ + @JsonProperty("maxPredictions") + public abstract Builder maxPredictions(Integer maxPredictions); + + /** + * Setter for confidenceThreshold. + * + *

confidenceThreshold: The confidence score threshold for the detections as a decimal value. + * Only predictions with a confidence score higher than this threshold will be returned. + */ + @JsonProperty("confidenceThreshold") + public abstract Builder confidenceThreshold(Float confidenceThreshold); + + /** + * Setter for maskDilation. + * + *

maskDilation: A decimal value representing how much dilation to apply to the masks. 0 for + * no dilation. 1.0 means the masked area covers the whole image. + */ + @JsonProperty("maskDilation") + public abstract Builder maskDilation(Float maskDilation); + + /** + * Setter for binaryColorThreshold. + * + *

binaryColorThreshold: The binary color threshold to apply to the masks. The threshold can + * be set to a decimal value between 0 and 255 non-inclusive. Set to -1 for no binary color + * thresholding. + */ + @JsonProperty("binaryColorThreshold") + public abstract Builder binaryColorThreshold(Float binaryColorThreshold); + + /** + * Setter for labels. + * + *

labels: User specified labels to track billing usage. + */ + @JsonProperty("labels") + public abstract Builder labels(Map labels); + + public abstract SegmentImageConfig build(); + } + + /** Deserializes a JSON string to a SegmentImageConfig object. */ + @ExcludeFromGeneratedCoverageReport + public static SegmentImageConfig fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, SegmentImageConfig.class); + } +} diff --git a/src/main/java/com/google/genai/types/SegmentImageParameters.java b/src/main/java/com/google/genai/types/SegmentImageParameters.java new file mode 100644 index 00000000000..9c8989b5b5f --- /dev/null +++ b/src/main/java/com/google/genai/types/SegmentImageParameters.java @@ -0,0 +1,118 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Auto-generated code. Do not edit. + +package com.google.genai.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.google.api.core.InternalApi; +import com.google.auto.value.AutoValue; +import com.google.genai.JsonSerializable; +import java.util.Optional; + +/** The parameters for segmenting an image. */ +@AutoValue +@InternalApi +@JsonDeserialize(builder = SegmentImageParameters.Builder.class) +public abstract class SegmentImageParameters extends JsonSerializable { + /** + * ID of the model to use. For a list of models, see `Google models + * `_. + */ + @JsonProperty("model") + public abstract Optional model(); + + /** A set of source input(s) for image segmentation. */ + @JsonProperty("source") + public abstract Optional source(); + + /** Configuration for image segmentation. */ + @JsonProperty("config") + public abstract Optional config(); + + /** Instantiates a builder for SegmentImageParameters. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_SegmentImageParameters.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for SegmentImageParameters. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `SegmentImageParameters.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_SegmentImageParameters.Builder(); + } + + /** + * Setter for model. + * + *

model: ID of the model to use. For a list of models, see `Google models + * `_. + */ + @JsonProperty("model") + public abstract Builder model(String model); + + /** + * Setter for source. + * + *

source: A set of source input(s) for image segmentation. + */ + @JsonProperty("source") + public abstract Builder source(SegmentImageSource source); + + /** + * Setter for source builder. + * + *

source: A set of source input(s) for image segmentation. + */ + public Builder source(SegmentImageSource.Builder sourceBuilder) { + return source(sourceBuilder.build()); + } + + /** + * Setter for config. + * + *

config: Configuration for image segmentation. + */ + @JsonProperty("config") + public abstract Builder config(SegmentImageConfig config); + + /** + * Setter for config builder. + * + *

config: Configuration for image segmentation. + */ + public Builder config(SegmentImageConfig.Builder configBuilder) { + return config(configBuilder.build()); + } + + public abstract SegmentImageParameters build(); + } + + /** Deserializes a JSON string to a SegmentImageParameters object. */ + @ExcludeFromGeneratedCoverageReport + public static SegmentImageParameters fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, SegmentImageParameters.class); + } +} diff --git a/src/main/java/com/google/genai/types/SegmentImageResponse.java b/src/main/java/com/google/genai/types/SegmentImageResponse.java new file mode 100644 index 00000000000..738ad271f46 --- /dev/null +++ b/src/main/java/com/google/genai/types/SegmentImageResponse.java @@ -0,0 +1,95 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Auto-generated code. Do not edit. + +package com.google.genai.types; + +import static com.google.common.collect.ImmutableList.toImmutableList; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.google.auto.value.AutoValue; +import com.google.genai.JsonSerializable; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +/** The output images response. */ +@AutoValue +@JsonDeserialize(builder = SegmentImageResponse.Builder.class) +public abstract class SegmentImageResponse extends JsonSerializable { + /** List of generated image masks. */ + @JsonProperty("generatedMasks") + public abstract Optional> generatedMasks(); + + /** Instantiates a builder for SegmentImageResponse. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_SegmentImageResponse.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for SegmentImageResponse. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `SegmentImageResponse.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_SegmentImageResponse.Builder(); + } + + /** + * Setter for generatedMasks. + * + *

generatedMasks: List of generated image masks. + */ + @JsonProperty("generatedMasks") + public abstract Builder generatedMasks(List generatedMasks); + + /** + * Setter for generatedMasks. + * + *

generatedMasks: List of generated image masks. + */ + public Builder generatedMasks(GeneratedImageMask... generatedMasks) { + return generatedMasks(Arrays.asList(generatedMasks)); + } + + /** + * Setter for generatedMasks builder. + * + *

generatedMasks: List of generated image masks. + */ + public Builder generatedMasks(GeneratedImageMask.Builder... generatedMasksBuilders) { + return generatedMasks( + Arrays.asList(generatedMasksBuilders).stream() + .map(GeneratedImageMask.Builder::build) + .collect(toImmutableList())); + } + + public abstract SegmentImageResponse build(); + } + + /** Deserializes a JSON string to a SegmentImageResponse object. */ + @ExcludeFromGeneratedCoverageReport + public static SegmentImageResponse fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, SegmentImageResponse.class); + } +} diff --git a/src/main/java/com/google/genai/types/SegmentImageSource.java b/src/main/java/com/google/genai/types/SegmentImageSource.java new file mode 100644 index 00000000000..7d4ce569a93 --- /dev/null +++ b/src/main/java/com/google/genai/types/SegmentImageSource.java @@ -0,0 +1,121 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Auto-generated code. Do not edit. + +package com.google.genai.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.google.auto.value.AutoValue; +import com.google.genai.JsonSerializable; +import java.util.Optional; + +/** A set of source input(s) for image segmentation. */ +@AutoValue +@JsonDeserialize(builder = SegmentImageSource.Builder.class) +public abstract class SegmentImageSource extends JsonSerializable { + /** + * A text prompt for guiding the model during image segmentation. Required for prompt mode and + * semantic mode, disallowed for other modes. + */ + @JsonProperty("prompt") + public abstract Optional prompt(); + + /** The image to be segmented. */ + @JsonProperty("image") + public abstract Optional image(); + + /** + * The brush scribble to guide segmentation. Required for the interactive mode, disallowed for + * other modes. + */ + @JsonProperty("scribbleImage") + public abstract Optional scribbleImage(); + + /** Instantiates a builder for SegmentImageSource. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_SegmentImageSource.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for SegmentImageSource. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `SegmentImageSource.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_SegmentImageSource.Builder(); + } + + /** + * Setter for prompt. + * + *

prompt: A text prompt for guiding the model during image segmentation. Required for prompt + * mode and semantic mode, disallowed for other modes. + */ + @JsonProperty("prompt") + public abstract Builder prompt(String prompt); + + /** + * Setter for image. + * + *

image: The image to be segmented. + */ + @JsonProperty("image") + public abstract Builder image(Image image); + + /** + * Setter for image builder. + * + *

image: The image to be segmented. + */ + public Builder image(Image.Builder imageBuilder) { + return image(imageBuilder.build()); + } + + /** + * Setter for scribbleImage. + * + *

scribbleImage: The brush scribble to guide segmentation. Required for the interactive + * mode, disallowed for other modes. + */ + @JsonProperty("scribbleImage") + public abstract Builder scribbleImage(ScribbleImage scribbleImage); + + /** + * Setter for scribbleImage builder. + * + *

scribbleImage: The brush scribble to guide segmentation. Required for the interactive + * mode, disallowed for other modes. + */ + public Builder scribbleImage(ScribbleImage.Builder scribbleImageBuilder) { + return scribbleImage(scribbleImageBuilder.build()); + } + + public abstract SegmentImageSource build(); + } + + /** Deserializes a JSON string to a SegmentImageSource object. */ + @ExcludeFromGeneratedCoverageReport + public static SegmentImageSource fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, SegmentImageSource.class); + } +} diff --git a/src/main/java/com/google/genai/types/SegmentMode.java b/src/main/java/com/google/genai/types/SegmentMode.java new file mode 100644 index 00000000000..6f05e6dab18 --- /dev/null +++ b/src/main/java/com/google/genai/types/SegmentMode.java @@ -0,0 +1,114 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Auto-generated code. Do not edit. + +package com.google.genai.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.google.common.base.Ascii; +import java.util.Objects; + +/** Enum that represents the segmentation mode. */ +public class SegmentMode { + + /** Enum representing the known values for SegmentMode. */ + public enum Known { + FOREGROUND, + + BACKGROUND, + + PROMPT, + + SEMANTIC, + + INTERACTIVE, + + SEGMENT_MODE_UNSPECIFIED + } + + private Known segmentModeEnum; + private final String value; + + @JsonCreator + public SegmentMode(String value) { + this.value = value; + for (Known segmentModeEnum : Known.values()) { + if (Ascii.equalsIgnoreCase(segmentModeEnum.toString(), value)) { + this.segmentModeEnum = segmentModeEnum; + break; + } + } + if (this.segmentModeEnum == null) { + this.segmentModeEnum = Known.SEGMENT_MODE_UNSPECIFIED; + } + } + + public SegmentMode(Known knownValue) { + this.segmentModeEnum = knownValue; + this.value = knownValue.toString(); + } + + @ExcludeFromGeneratedCoverageReport + @Override + @JsonValue + public String toString() { + return this.value; + } + + @ExcludeFromGeneratedCoverageReport + @SuppressWarnings("PatternMatchingInstanceof") + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null) { + return false; + } + + if (!(o instanceof SegmentMode)) { + return false; + } + + SegmentMode other = (SegmentMode) o; + + if (this.segmentModeEnum != Known.SEGMENT_MODE_UNSPECIFIED + && other.segmentModeEnum != Known.SEGMENT_MODE_UNSPECIFIED) { + return this.segmentModeEnum == other.segmentModeEnum; + } else if (this.segmentModeEnum == Known.SEGMENT_MODE_UNSPECIFIED + && other.segmentModeEnum == Known.SEGMENT_MODE_UNSPECIFIED) { + return this.value.equals(other.value); + } + return false; + } + + @ExcludeFromGeneratedCoverageReport + @Override + public int hashCode() { + if (this.segmentModeEnum != Known.SEGMENT_MODE_UNSPECIFIED) { + return this.segmentModeEnum.hashCode(); + } else { + return Objects.hashCode(this.value); + } + } + + @ExcludeFromGeneratedCoverageReport + public Known knownEnum() { + return this.segmentModeEnum; + } +} diff --git a/src/main/java/com/google/genai/types/SessionResumptionConfig.java b/src/main/java/com/google/genai/types/SessionResumptionConfig.java index 1b14201f4ec..ec40523d09b 100644 --- a/src/main/java/com/google/genai/types/SessionResumptionConfig.java +++ b/src/main/java/com/google/genai/types/SessionResumptionConfig.java @@ -50,6 +50,7 @@ public abstract class SessionResumptionConfig extends JsonSerializable { public abstract Optional transparent(); /** Instantiates a builder for SessionResumptionConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_SessionResumptionConfig.Builder(); } @@ -89,6 +90,7 @@ private static Builder create() { } /** Deserializes a JSON string to a SessionResumptionConfig object. */ + @ExcludeFromGeneratedCoverageReport public static SessionResumptionConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, SessionResumptionConfig.class); } diff --git a/src/main/java/com/google/genai/types/SingleEmbedContentResponse.java b/src/main/java/com/google/genai/types/SingleEmbedContentResponse.java new file mode 100644 index 00000000000..7a0153803de --- /dev/null +++ b/src/main/java/com/google/genai/types/SingleEmbedContentResponse.java @@ -0,0 +1,91 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Auto-generated code. Do not edit. + +package com.google.genai.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.google.auto.value.AutoValue; +import com.google.genai.JsonSerializable; +import java.util.Optional; + +/** Config for `response` parameter. */ +@AutoValue +@JsonDeserialize(builder = SingleEmbedContentResponse.Builder.class) +public abstract class SingleEmbedContentResponse extends JsonSerializable { + /** The response to the request. */ + @JsonProperty("embedding") + public abstract Optional embedding(); + + /** The error encountered while processing the request. */ + @JsonProperty("tokenCount") + public abstract Optional tokenCount(); + + /** Instantiates a builder for SingleEmbedContentResponse. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_SingleEmbedContentResponse.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for SingleEmbedContentResponse. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `SingleEmbedContentResponse.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_SingleEmbedContentResponse.Builder(); + } + + /** + * Setter for embedding. + * + *

embedding: The response to the request. + */ + @JsonProperty("embedding") + public abstract Builder embedding(ContentEmbedding embedding); + + /** + * Setter for embedding builder. + * + *

embedding: The response to the request. + */ + public Builder embedding(ContentEmbedding.Builder embeddingBuilder) { + return embedding(embeddingBuilder.build()); + } + + /** + * Setter for tokenCount. + * + *

tokenCount: The error encountered while processing the request. + */ + @JsonProperty("tokenCount") + public abstract Builder tokenCount(Long tokenCount); + + public abstract SingleEmbedContentResponse build(); + } + + /** Deserializes a JSON string to a SingleEmbedContentResponse object. */ + @ExcludeFromGeneratedCoverageReport + public static SingleEmbedContentResponse fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, SingleEmbedContentResponse.class); + } +} diff --git a/src/main/java/com/google/genai/types/SlidingWindow.java b/src/main/java/com/google/genai/types/SlidingWindow.java index d15d28e4a49..172f53f630a 100644 --- a/src/main/java/com/google/genai/types/SlidingWindow.java +++ b/src/main/java/com/google/genai/types/SlidingWindow.java @@ -44,6 +44,7 @@ public abstract class SlidingWindow extends JsonSerializable { public abstract Optional targetTokens(); /** Instantiates a builder for SlidingWindow. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_SlidingWindow.Builder(); } @@ -74,6 +75,7 @@ private static Builder create() { } /** Deserializes a JSON string to a SlidingWindow object. */ + @ExcludeFromGeneratedCoverageReport public static SlidingWindow fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, SlidingWindow.class); } diff --git a/src/main/java/com/google/genai/types/SpeakerVoiceConfig.java b/src/main/java/com/google/genai/types/SpeakerVoiceConfig.java index 0c4d9b4c793..19879437965 100644 --- a/src/main/java/com/google/genai/types/SpeakerVoiceConfig.java +++ b/src/main/java/com/google/genai/types/SpeakerVoiceConfig.java @@ -25,19 +25,23 @@ import com.google.genai.JsonSerializable; import java.util.Optional; -/** The configuration for the speaker to use. */ +/** + * The configuration for a single speaker in a multi speaker setup. This data type is not supported + * in Vertex AI. + */ @AutoValue @JsonDeserialize(builder = SpeakerVoiceConfig.Builder.class) public abstract class SpeakerVoiceConfig extends JsonSerializable { - /** The name of the speaker to use. Should be the same as in the prompt. */ + /** Required. The name of the speaker to use. Should be the same as in the prompt. */ @JsonProperty("speaker") public abstract Optional speaker(); - /** The configuration for the voice to use. */ + /** Required. The configuration for the voice to use. */ @JsonProperty("voiceConfig") public abstract Optional voiceConfig(); /** Instantiates a builder for SpeakerVoiceConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_SpeakerVoiceConfig.Builder(); } @@ -57,7 +61,7 @@ private static Builder create() { /** * Setter for speaker. * - *

speaker: The name of the speaker to use. Should be the same as in the prompt. + *

speaker: Required. The name of the speaker to use. Should be the same as in the prompt. */ @JsonProperty("speaker") public abstract Builder speaker(String speaker); @@ -65,7 +69,7 @@ private static Builder create() { /** * Setter for voiceConfig. * - *

voiceConfig: The configuration for the voice to use. + *

voiceConfig: Required. The configuration for the voice to use. */ @JsonProperty("voiceConfig") public abstract Builder voiceConfig(VoiceConfig voiceConfig); @@ -73,7 +77,7 @@ private static Builder create() { /** * Setter for voiceConfig builder. * - *

voiceConfig: The configuration for the voice to use. + *

voiceConfig: Required. The configuration for the voice to use. */ public Builder voiceConfig(VoiceConfig.Builder voiceConfigBuilder) { return voiceConfig(voiceConfigBuilder.build()); @@ -83,6 +87,7 @@ public Builder voiceConfig(VoiceConfig.Builder voiceConfigBuilder) { } /** Deserializes a JSON string to a SpeakerVoiceConfig object. */ + @ExcludeFromGeneratedCoverageReport public static SpeakerVoiceConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, SpeakerVoiceConfig.class); } diff --git a/src/main/java/com/google/genai/types/SpeechConfig.java b/src/main/java/com/google/genai/types/SpeechConfig.java index 5fd29639b98..7f9e7ef9dea 100644 --- a/src/main/java/com/google/genai/types/SpeechConfig.java +++ b/src/main/java/com/google/genai/types/SpeechConfig.java @@ -25,28 +25,27 @@ import com.google.genai.JsonSerializable; import java.util.Optional; -/** The speech generation configuration. */ +/** The speech generation config. */ @AutoValue @JsonDeserialize(builder = SpeechConfig.Builder.class) public abstract class SpeechConfig extends JsonSerializable { + /** Optional. Language code (ISO 639. e.g. en-US) for the speech synthesization. */ + @JsonProperty("languageCode") + public abstract Optional languageCode(); + /** The configuration for the speaker to use. */ @JsonProperty("voiceConfig") public abstract Optional voiceConfig(); /** - * The configuration for the multi-speaker setup. It is mutually exclusive with the voice_config - * field. + * Optional. The configuration for the multi-speaker setup. It is mutually exclusive with the + * voice_config field. This field is not supported in Vertex AI. */ @JsonProperty("multiSpeakerVoiceConfig") public abstract Optional multiSpeakerVoiceConfig(); - /** - * Language code (ISO 639. e.g. en-US) for the speech synthesization. Only available for Live API. - */ - @JsonProperty("languageCode") - public abstract Optional languageCode(); - /** Instantiates a builder for SpeechConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_SpeechConfig.Builder(); } @@ -63,6 +62,14 @@ private static Builder create() { return new AutoValue_SpeechConfig.Builder(); } + /** + * Setter for languageCode. + * + *

languageCode: Optional. Language code (ISO 639. e.g. en-US) for the speech synthesization. + */ + @JsonProperty("languageCode") + public abstract Builder languageCode(String languageCode); + /** * Setter for voiceConfig. * @@ -83,8 +90,8 @@ public Builder voiceConfig(VoiceConfig.Builder voiceConfigBuilder) { /** * Setter for multiSpeakerVoiceConfig. * - *

multiSpeakerVoiceConfig: The configuration for the multi-speaker setup. It is mutually - * exclusive with the voice_config field. + *

multiSpeakerVoiceConfig: Optional. The configuration for the multi-speaker setup. It is + * mutually exclusive with the voice_config field. This field is not supported in Vertex AI. */ @JsonProperty("multiSpeakerVoiceConfig") public abstract Builder multiSpeakerVoiceConfig( @@ -93,27 +100,19 @@ public abstract Builder multiSpeakerVoiceConfig( /** * Setter for multiSpeakerVoiceConfig builder. * - *

multiSpeakerVoiceConfig: The configuration for the multi-speaker setup. It is mutually - * exclusive with the voice_config field. + *

multiSpeakerVoiceConfig: Optional. The configuration for the multi-speaker setup. It is + * mutually exclusive with the voice_config field. This field is not supported in Vertex AI. */ public Builder multiSpeakerVoiceConfig( MultiSpeakerVoiceConfig.Builder multiSpeakerVoiceConfigBuilder) { return multiSpeakerVoiceConfig(multiSpeakerVoiceConfigBuilder.build()); } - /** - * Setter for languageCode. - * - *

languageCode: Language code (ISO 639. e.g. en-US) for the speech synthesization. Only - * available for Live API. - */ - @JsonProperty("languageCode") - public abstract Builder languageCode(String languageCode); - public abstract SpeechConfig build(); } /** Deserializes a JSON string to a SpeechConfig object. */ + @ExcludeFromGeneratedCoverageReport public static SpeechConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, SpeechConfig.class); } diff --git a/src/main/java/com/google/genai/types/StartSensitivity.java b/src/main/java/com/google/genai/types/StartSensitivity.java index d1b13a93d35..6b4b75438e2 100644 --- a/src/main/java/com/google/genai/types/StartSensitivity.java +++ b/src/main/java/com/google/genai/types/StartSensitivity.java @@ -60,12 +60,14 @@ public StartSensitivity(Known knownValue) { this.value = knownValue.toString(); } + @ExcludeFromGeneratedCoverageReport @Override @JsonValue public String toString() { return this.value; } + @ExcludeFromGeneratedCoverageReport @SuppressWarnings("PatternMatchingInstanceof") @Override public boolean equals(Object o) { @@ -92,6 +94,7 @@ public boolean equals(Object o) { return false; } + @ExcludeFromGeneratedCoverageReport @Override public int hashCode() { if (this.startSensitivityEnum != Known.START_SENSITIVITY_UNSPECIFIED) { @@ -101,6 +104,7 @@ public int hashCode() { } } + @ExcludeFromGeneratedCoverageReport public Known knownEnum() { return this.startSensitivityEnum; } diff --git a/src/main/java/com/google/genai/types/StyleReferenceConfig.java b/src/main/java/com/google/genai/types/StyleReferenceConfig.java index d37ae97ed21..cd4cba36768 100644 --- a/src/main/java/com/google/genai/types/StyleReferenceConfig.java +++ b/src/main/java/com/google/genai/types/StyleReferenceConfig.java @@ -34,6 +34,7 @@ public abstract class StyleReferenceConfig extends JsonSerializable { public abstract Optional styleDescription(); /** Instantiates a builder for StyleReferenceConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_StyleReferenceConfig.Builder(); } @@ -62,6 +63,7 @@ private static Builder create() { } /** Deserializes a JSON string to a StyleReferenceConfig object. */ + @ExcludeFromGeneratedCoverageReport public static StyleReferenceConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, StyleReferenceConfig.class); } diff --git a/src/main/java/com/google/genai/types/StyleReferenceImage.java b/src/main/java/com/google/genai/types/StyleReferenceImage.java index 1608364c36b..328b74d1e62 100644 --- a/src/main/java/com/google/genai/types/StyleReferenceImage.java +++ b/src/main/java/com/google/genai/types/StyleReferenceImage.java @@ -53,6 +53,7 @@ public abstract class StyleReferenceImage extends JsonSerializable implements Re public abstract Optional config(); /** Instantiates a builder for StyleReferenceImage. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_StyleReferenceImage.Builder(); } @@ -123,6 +124,7 @@ public Builder config(StyleReferenceConfig.Builder configBuilder) { } /** Deserializes a JSON string to a StyleReferenceImage object. */ + @ExcludeFromGeneratedCoverageReport public static StyleReferenceImage fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, StyleReferenceImage.class); } diff --git a/src/main/java/com/google/genai/types/SubjectReferenceConfig.java b/src/main/java/com/google/genai/types/SubjectReferenceConfig.java index 0b6dac72ada..112f4569026 100644 --- a/src/main/java/com/google/genai/types/SubjectReferenceConfig.java +++ b/src/main/java/com/google/genai/types/SubjectReferenceConfig.java @@ -39,6 +39,7 @@ public abstract class SubjectReferenceConfig extends JsonSerializable { public abstract Optional subjectDescription(); /** Instantiates a builder for SubjectReferenceConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_SubjectReferenceConfig.Builder(); } @@ -95,6 +96,7 @@ public Builder subjectType(String subjectType) { } /** Deserializes a JSON string to a SubjectReferenceConfig object. */ + @ExcludeFromGeneratedCoverageReport public static SubjectReferenceConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, SubjectReferenceConfig.class); } diff --git a/src/main/java/com/google/genai/types/SubjectReferenceImage.java b/src/main/java/com/google/genai/types/SubjectReferenceImage.java index 7b7ec8d8940..80a9ca1c9b7 100644 --- a/src/main/java/com/google/genai/types/SubjectReferenceImage.java +++ b/src/main/java/com/google/genai/types/SubjectReferenceImage.java @@ -53,6 +53,7 @@ public abstract class SubjectReferenceImage extends JsonSerializable implements public abstract Optional config(); /** Instantiates a builder for SubjectReferenceImage. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_SubjectReferenceImage.Builder(); } @@ -123,6 +124,7 @@ public Builder config(SubjectReferenceConfig.Builder configBuilder) { } /** Deserializes a JSON string to a SubjectReferenceImage object. */ + @ExcludeFromGeneratedCoverageReport public static SubjectReferenceImage fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, SubjectReferenceImage.class); } diff --git a/src/main/java/com/google/genai/types/SubjectReferenceType.java b/src/main/java/com/google/genai/types/SubjectReferenceType.java index 8ab9165f9ad..b6462978f80 100644 --- a/src/main/java/com/google/genai/types/SubjectReferenceType.java +++ b/src/main/java/com/google/genai/types/SubjectReferenceType.java @@ -61,12 +61,14 @@ public SubjectReferenceType(Known knownValue) { this.value = knownValue.toString(); } + @ExcludeFromGeneratedCoverageReport @Override @JsonValue public String toString() { return this.value; } + @ExcludeFromGeneratedCoverageReport @SuppressWarnings("PatternMatchingInstanceof") @Override public boolean equals(Object o) { @@ -93,6 +95,7 @@ public boolean equals(Object o) { return false; } + @ExcludeFromGeneratedCoverageReport @Override public int hashCode() { if (this.subjectReferenceTypeEnum != Known.SUBJECT_REFERENCE_TYPE_UNSPECIFIED) { @@ -102,6 +105,7 @@ public int hashCode() { } } + @ExcludeFromGeneratedCoverageReport public Known knownEnum() { return this.subjectReferenceTypeEnum; } diff --git a/src/main/java/com/google/genai/types/SupervisedHyperParameters.java b/src/main/java/com/google/genai/types/SupervisedHyperParameters.java index 18ee356bc4a..ba865e404ef 100644 --- a/src/main/java/com/google/genai/types/SupervisedHyperParameters.java +++ b/src/main/java/com/google/genai/types/SupervisedHyperParameters.java @@ -27,7 +27,7 @@ import com.google.genai.JsonSerializable; import java.util.Optional; -/** Hyperparameters for SFT. */ +/** Hyperparameters for SFT. This data type is not supported in Gemini API. */ @AutoValue @InternalApi @JsonDeserialize(builder = SupervisedHyperParameters.Builder.class) @@ -36,6 +36,10 @@ public abstract class SupervisedHyperParameters extends JsonSerializable { @JsonProperty("adapterSize") public abstract Optional adapterSize(); + /** Optional. Batch size for tuning. This feature is only available for open source models. */ + @JsonProperty("batchSize") + public abstract Optional batchSize(); + /** * Optional. Number of complete passes the model makes over the entire training dataset during * training. @@ -43,14 +47,22 @@ public abstract class SupervisedHyperParameters extends JsonSerializable { @JsonProperty("epochCount") public abstract Optional epochCount(); + /** + * Optional. Learning rate for tuning. Mutually exclusive with `learning_rate_multiplier`. This + * feature is only available for open source models. + */ + @JsonProperty("learningRate") + public abstract Optional learningRate(); + /** * Optional. Multiplier for adjusting the default learning rate. Mutually exclusive with - * `learning_rate`. + * `learning_rate`. This feature is only available for 1P models. */ @JsonProperty("learningRateMultiplier") public abstract Optional learningRateMultiplier(); /** Instantiates a builder for SupervisedHyperParameters. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_SupervisedHyperParameters.Builder(); } @@ -95,6 +107,15 @@ public Builder adapterSize(String adapterSize) { return adapterSize(new AdapterSize(adapterSize)); } + /** + * Setter for batchSize. + * + *

batchSize: Optional. Batch size for tuning. This feature is only available for open source + * models. + */ + @JsonProperty("batchSize") + public abstract Builder batchSize(Long batchSize); + /** * Setter for epochCount. * @@ -104,11 +125,20 @@ public Builder adapterSize(String adapterSize) { @JsonProperty("epochCount") public abstract Builder epochCount(Long epochCount); + /** + * Setter for learningRate. + * + *

learningRate: Optional. Learning rate for tuning. Mutually exclusive with + * `learning_rate_multiplier`. This feature is only available for open source models. + */ + @JsonProperty("learningRate") + public abstract Builder learningRate(Double learningRate); + /** * Setter for learningRateMultiplier. * *

learningRateMultiplier: Optional. Multiplier for adjusting the default learning rate. - * Mutually exclusive with `learning_rate`. + * Mutually exclusive with `learning_rate`. This feature is only available for 1P models. */ @JsonProperty("learningRateMultiplier") public abstract Builder learningRateMultiplier(Double learningRateMultiplier); @@ -117,6 +147,7 @@ public Builder adapterSize(String adapterSize) { } /** Deserializes a JSON string to a SupervisedHyperParameters object. */ + @ExcludeFromGeneratedCoverageReport public static SupervisedHyperParameters fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, SupervisedHyperParameters.class); } diff --git a/src/main/java/com/google/genai/types/SupervisedTuningDataStats.java b/src/main/java/com/google/genai/types/SupervisedTuningDataStats.java index 888301e5534..5896a86b375 100644 --- a/src/main/java/com/google/genai/types/SupervisedTuningDataStats.java +++ b/src/main/java/com/google/genai/types/SupervisedTuningDataStats.java @@ -29,7 +29,7 @@ import java.util.List; import java.util.Optional; -/** Tuning data statistics for Supervised Tuning. */ +/** Tuning data statistics for Supervised Tuning. This data type is not supported in Gemini API. */ @AutoValue @JsonDeserialize(builder = SupervisedTuningDataStats.Builder.class) public abstract class SupervisedTuningDataStats extends JsonSerializable { @@ -89,6 +89,7 @@ public abstract class SupervisedTuningDataStats extends JsonSerializable { public abstract Optional userOutputTokenDistribution(); /** Instantiates a builder for SupervisedTuningDataStats. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_SupervisedTuningDataStats.Builder(); } @@ -288,6 +289,7 @@ public Builder userOutputTokenDistribution( } /** Deserializes a JSON string to a SupervisedTuningDataStats object. */ + @ExcludeFromGeneratedCoverageReport public static SupervisedTuningDataStats fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, SupervisedTuningDataStats.class); } diff --git a/src/main/java/com/google/genai/types/SupervisedTuningDatasetDistribution.java b/src/main/java/com/google/genai/types/SupervisedTuningDatasetDistribution.java index 89702f52955..7e1f16528c2 100644 --- a/src/main/java/com/google/genai/types/SupervisedTuningDatasetDistribution.java +++ b/src/main/java/com/google/genai/types/SupervisedTuningDatasetDistribution.java @@ -29,7 +29,7 @@ import java.util.List; import java.util.Optional; -/** Dataset distribution for Supervised Tuning. */ +/** Dataset distribution for Supervised Tuning. This data type is not supported in Gemini API. */ @AutoValue @JsonDeserialize(builder = SupervisedTuningDatasetDistribution.Builder.class) public abstract class SupervisedTuningDatasetDistribution extends JsonSerializable { @@ -70,6 +70,7 @@ public abstract class SupervisedTuningDatasetDistribution extends JsonSerializab public abstract Optional sum(); /** Instantiates a builder for SupervisedTuningDatasetDistribution. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_SupervisedTuningDatasetDistribution.Builder(); } @@ -187,6 +188,7 @@ public Builder buckets( } /** Deserializes a JSON string to a SupervisedTuningDatasetDistribution object. */ + @ExcludeFromGeneratedCoverageReport public static SupervisedTuningDatasetDistribution fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, SupervisedTuningDatasetDistribution.class); } diff --git a/src/main/java/com/google/genai/types/SupervisedTuningDatasetDistributionDatasetBucket.java b/src/main/java/com/google/genai/types/SupervisedTuningDatasetDistributionDatasetBucket.java index a12f8e23a01..945d24fa5cb 100644 --- a/src/main/java/com/google/genai/types/SupervisedTuningDatasetDistributionDatasetBucket.java +++ b/src/main/java/com/google/genai/types/SupervisedTuningDatasetDistributionDatasetBucket.java @@ -25,7 +25,10 @@ import com.google.genai.JsonSerializable; import java.util.Optional; -/** Dataset bucket used to create a histogram for the distribution given a population of values. */ +/** + * Dataset bucket used to create a histogram for the distribution given a population of values. This + * data type is not supported in Gemini API. + */ @AutoValue @JsonDeserialize(builder = SupervisedTuningDatasetDistributionDatasetBucket.Builder.class) public abstract class SupervisedTuningDatasetDistributionDatasetBucket extends JsonSerializable { @@ -42,6 +45,7 @@ public abstract class SupervisedTuningDatasetDistributionDatasetBucket extends J public abstract Optional right(); /** Instantiates a builder for SupervisedTuningDatasetDistributionDatasetBucket. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_SupervisedTuningDatasetDistributionDatasetBucket.Builder(); } @@ -89,6 +93,7 @@ private static Builder create() { } /** Deserializes a JSON string to a SupervisedTuningDatasetDistributionDatasetBucket object. */ + @ExcludeFromGeneratedCoverageReport public static SupervisedTuningDatasetDistributionDatasetBucket fromJson(String jsonString) { return JsonSerializable.fromJsonString( jsonString, SupervisedTuningDatasetDistributionDatasetBucket.class); diff --git a/src/main/java/com/google/genai/types/SupervisedTuningSpec.java b/src/main/java/com/google/genai/types/SupervisedTuningSpec.java index 5ddf6550fc8..ba54810e220 100644 --- a/src/main/java/com/google/genai/types/SupervisedTuningSpec.java +++ b/src/main/java/com/google/genai/types/SupervisedTuningSpec.java @@ -22,10 +22,11 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.google.auto.value.AutoValue; +import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.genai.JsonSerializable; import java.util.Optional; -/** Tuning Spec for Supervised Tuning for first party models. */ +/** Supervised tuning spec for tuning. */ @AutoValue @JsonDeserialize(builder = SupervisedTuningSpec.Builder.class) public abstract class SupervisedTuningSpec extends JsonSerializable { @@ -47,6 +48,10 @@ public abstract class SupervisedTuningSpec extends JsonSerializable { @JsonProperty("trainingDatasetUri") public abstract Optional trainingDatasetUri(); + /** Tuning mode. */ + @JsonProperty("tuningMode") + public abstract Optional tuningMode(); + /** * Optional. Validation dataset used for tuning. The dataset can be specified as either a Cloud * Storage path to a JSONL file or as the resource name of a Vertex Multimodal Dataset. @@ -55,6 +60,7 @@ public abstract class SupervisedTuningSpec extends JsonSerializable { public abstract Optional validationDatasetUri(); /** Instantiates a builder for SupervisedTuningSpec. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_SupervisedTuningSpec.Builder(); } @@ -108,6 +114,34 @@ public Builder hyperParameters(SupervisedHyperParameters.Builder hyperParameters @JsonProperty("trainingDatasetUri") public abstract Builder trainingDatasetUri(String trainingDatasetUri); + /** + * Setter for tuningMode. + * + *

tuningMode: Tuning mode. + */ + @JsonProperty("tuningMode") + public abstract Builder tuningMode(TuningMode tuningMode); + + /** + * Setter for tuningMode given a known enum. + * + *

tuningMode: Tuning mode. + */ + @CanIgnoreReturnValue + public Builder tuningMode(TuningMode.Known knownType) { + return tuningMode(new TuningMode(knownType)); + } + + /** + * Setter for tuningMode given a string. + * + *

tuningMode: Tuning mode. + */ + @CanIgnoreReturnValue + public Builder tuningMode(String tuningMode) { + return tuningMode(new TuningMode(tuningMode)); + } + /** * Setter for validationDatasetUri. * @@ -122,6 +156,7 @@ public Builder hyperParameters(SupervisedHyperParameters.Builder hyperParameters } /** Deserializes a JSON string to a SupervisedTuningSpec object. */ + @ExcludeFromGeneratedCoverageReport public static SupervisedTuningSpec fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, SupervisedTuningSpec.class); } diff --git a/src/main/java/com/google/genai/types/TestTableFile.java b/src/main/java/com/google/genai/types/TestTableFile.java index ef6965de0dd..604fcd0f28e 100644 --- a/src/main/java/com/google/genai/types/TestTableFile.java +++ b/src/main/java/com/google/genai/types/TestTableFile.java @@ -50,6 +50,7 @@ public abstract class TestTableFile extends JsonSerializable { public abstract Optional> testTable(); /** Instantiates a builder for TestTableFile. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_TestTableFile.Builder(); } @@ -132,6 +133,7 @@ public Builder testTable(TestTableItem.Builder... testTableBuilders) { } /** Deserializes a JSON string to a TestTableFile object. */ + @ExcludeFromGeneratedCoverageReport public static TestTableFile fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, TestTableFile.class); } diff --git a/src/main/java/com/google/genai/types/TestTableItem.java b/src/main/java/com/google/genai/types/TestTableItem.java index 48579e0b7bc..86f74582da6 100644 --- a/src/main/java/com/google/genai/types/TestTableItem.java +++ b/src/main/java/com/google/genai/types/TestTableItem.java @@ -74,6 +74,7 @@ public abstract class TestTableItem extends JsonSerializable { public abstract Optional> ignoreKeys(); /** Instantiates a builder for TestTableItem. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_TestTableItem.Builder(); } @@ -173,6 +174,7 @@ public Builder ignoreKeys(String... ignoreKeys) { } /** Deserializes a JSON string to a TestTableItem object. */ + @ExcludeFromGeneratedCoverageReport public static TestTableItem fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, TestTableItem.class); } diff --git a/src/main/java/com/google/genai/types/ThinkingConfig.java b/src/main/java/com/google/genai/types/ThinkingConfig.java index 144de51f19c..758c4807c5b 100644 --- a/src/main/java/com/google/genai/types/ThinkingConfig.java +++ b/src/main/java/com/google/genai/types/ThinkingConfig.java @@ -44,6 +44,7 @@ public abstract class ThinkingConfig extends JsonSerializable { public abstract Optional thinkingBudget(); /** Instantiates a builder for ThinkingConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_ThinkingConfig.Builder(); } @@ -82,6 +83,7 @@ private static Builder create() { } /** Deserializes a JSON string to a ThinkingConfig object. */ + @ExcludeFromGeneratedCoverageReport public static ThinkingConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, ThinkingConfig.class); } diff --git a/src/main/java/com/google/genai/types/TokensInfo.java b/src/main/java/com/google/genai/types/TokensInfo.java index 7d9caafe4dd..c510e489bc6 100644 --- a/src/main/java/com/google/genai/types/TokensInfo.java +++ b/src/main/java/com/google/genai/types/TokensInfo.java @@ -31,7 +31,7 @@ @AutoValue @JsonDeserialize(builder = TokensInfo.Builder.class) public abstract class TokensInfo extends JsonSerializable { - /** Optional. Optional fields for the role from the corresponding Content. */ + /** Optional fields for the role from the corresponding Content. */ @JsonProperty("role") public abstract Optional role(); @@ -44,6 +44,7 @@ public abstract class TokensInfo extends JsonSerializable { public abstract Optional> tokens(); /** Instantiates a builder for TokensInfo. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_TokensInfo.Builder(); } @@ -63,7 +64,7 @@ private static Builder create() { /** * Setter for role. * - *

role: Optional. Optional fields for the role from the corresponding Content. + *

role: Optional fields for the role from the corresponding Content. */ @JsonProperty("role") public abstract Builder role(String role); @@ -106,6 +107,7 @@ public Builder tokens(byte[]... tokens) { } /** Deserializes a JSON string to a TokensInfo object. */ + @ExcludeFromGeneratedCoverageReport public static TokensInfo fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, TokensInfo.class); } diff --git a/src/main/java/com/google/genai/types/Tool.java b/src/main/java/com/google/genai/types/Tool.java index 7c81f57e17d..36607867f03 100644 --- a/src/main/java/com/google/genai/types/Tool.java +++ b/src/main/java/com/google/genai/types/Tool.java @@ -42,17 +42,11 @@ public abstract class Tool extends JsonSerializable { /** * Optional. Retrieval tool type. System will always execute the provided retrieval tool(s) to get * external knowledge to answer the prompt. Retrieval results are presented to the model for - * generation. + * generation. This field is not supported in Gemini API. */ @JsonProperty("retrieval") public abstract Optional retrieval(); - /** - * Optional. Google Search tool type. Specialized retrieval tool that is powered by Google Search. - */ - @JsonProperty("googleSearch") - public abstract Optional googleSearch(); - /** * Optional. GoogleSearchRetrieval tool type. Specialized retrieval tool that is powered by Google * search. @@ -60,21 +54,10 @@ public abstract class Tool extends JsonSerializable { @JsonProperty("googleSearchRetrieval") public abstract Optional googleSearchRetrieval(); - /** - * Optional. Enterprise web search tool type. Specialized retrieval tool that is powered by Vertex - * AI Search and Sec4 compliance. - */ - @JsonProperty("enterpriseWebSearch") - public abstract Optional enterpriseWebSearch(); - /** Optional. Google Maps tool type. Specialized retrieval tool that is powered by Google Maps. */ @JsonProperty("googleMaps") public abstract Optional googleMaps(); - /** Optional. Tool to support URL context retrieval. */ - @JsonProperty("urlContext") - public abstract Optional urlContext(); - /** * The java.lang.reflect.Method instance. If provided, it will to be parsed into a list of * FunctionDeclaration instances, and be assigned to the functionDeclarations field. @@ -82,18 +65,36 @@ public abstract class Tool extends JsonSerializable { @JsonIgnore public abstract Optional> functions(); + /** + * Optional. Tool to support the model interacting directly with the computer. If enabled, it + * automatically populates computer-use specific Function Declarations. + */ + @JsonProperty("computerUse") + public abstract Optional computerUse(); + /** Optional. CodeExecution tool type. Enables the model to execute code as part of generation. */ @JsonProperty("codeExecution") public abstract Optional codeExecution(); /** - * Optional. Tool to support the model interacting directly with the computer. If enabled, it - * automatically populates computer-use specific Function Declarations. + * Optional. Tool to support searching public web data, powered by Vertex AI Search and Sec4 + * compliance. This field is not supported in Gemini API. */ - @JsonProperty("computerUse") - public abstract Optional computerUse(); + @JsonProperty("enterpriseWebSearch") + public abstract Optional enterpriseWebSearch(); + + /** + * Optional. GoogleSearch tool type. Tool to support Google Search in Model. Powered by Google. + */ + @JsonProperty("googleSearch") + public abstract Optional googleSearch(); + + /** Optional. Tool to support URL context retrieval. */ + @JsonProperty("urlContext") + public abstract Optional urlContext(); /** Instantiates a builder for Tool. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_Tool.Builder(); } @@ -145,7 +146,7 @@ public Builder functionDeclarations( * *

retrieval: Optional. Retrieval tool type. System will always execute the provided * retrieval tool(s) to get external knowledge to answer the prompt. Retrieval results are - * presented to the model for generation. + * presented to the model for generation. This field is not supported in Gemini API. */ @JsonProperty("retrieval") public abstract Builder retrieval(Retrieval retrieval); @@ -155,31 +156,12 @@ public Builder functionDeclarations( * *

retrieval: Optional. Retrieval tool type. System will always execute the provided * retrieval tool(s) to get external knowledge to answer the prompt. Retrieval results are - * presented to the model for generation. + * presented to the model for generation. This field is not supported in Gemini API. */ public Builder retrieval(Retrieval.Builder retrievalBuilder) { return retrieval(retrievalBuilder.build()); } - /** - * Setter for googleSearch. - * - *

googleSearch: Optional. Google Search tool type. Specialized retrieval tool that is - * powered by Google Search. - */ - @JsonProperty("googleSearch") - public abstract Builder googleSearch(GoogleSearch googleSearch); - - /** - * Setter for googleSearch builder. - * - *

googleSearch: Optional. Google Search tool type. Specialized retrieval tool that is - * powered by Google Search. - */ - public Builder googleSearch(GoogleSearch.Builder googleSearchBuilder) { - return googleSearch(googleSearchBuilder.build()); - } - /** * Setter for googleSearchRetrieval. * @@ -200,25 +182,6 @@ public Builder googleSearchRetrieval( return googleSearchRetrieval(googleSearchRetrievalBuilder.build()); } - /** - * Setter for enterpriseWebSearch. - * - *

enterpriseWebSearch: Optional. Enterprise web search tool type. Specialized retrieval tool - * that is powered by Vertex AI Search and Sec4 compliance. - */ - @JsonProperty("enterpriseWebSearch") - public abstract Builder enterpriseWebSearch(EnterpriseWebSearch enterpriseWebSearch); - - /** - * Setter for enterpriseWebSearch builder. - * - *

enterpriseWebSearch: Optional. Enterprise web search tool type. Specialized retrieval tool - * that is powered by Vertex AI Search and Sec4 compliance. - */ - public Builder enterpriseWebSearch(EnterpriseWebSearch.Builder enterpriseWebSearchBuilder) { - return enterpriseWebSearch(enterpriseWebSearchBuilder.build()); - } - /** * Setter for googleMaps. * @@ -238,23 +201,6 @@ public Builder googleMaps(GoogleMaps.Builder googleMapsBuilder) { return googleMaps(googleMapsBuilder.build()); } - /** - * Setter for urlContext. - * - *

urlContext: Optional. Tool to support URL context retrieval. - */ - @JsonProperty("urlContext") - public abstract Builder urlContext(UrlContext urlContext); - - /** - * Setter for urlContext builder. - * - *

urlContext: Optional. Tool to support URL context retrieval. - */ - public Builder urlContext(UrlContext.Builder urlContextBuilder) { - return urlContext(urlContextBuilder.build()); - } - /** * Setter for functions. * @@ -274,6 +220,25 @@ public Builder functions(Method... functions) { return functions(Arrays.asList(functions)); } + /** + * Setter for computerUse. + * + *

computerUse: Optional. Tool to support the model interacting directly with the computer. + * If enabled, it automatically populates computer-use specific Function Declarations. + */ + @JsonProperty("computerUse") + public abstract Builder computerUse(ComputerUse computerUse); + + /** + * Setter for computerUse builder. + * + *

computerUse: Optional. Tool to support the model interacting directly with the computer. + * If enabled, it automatically populates computer-use specific Function Declarations. + */ + public Builder computerUse(ComputerUse.Builder computerUseBuilder) { + return computerUse(computerUseBuilder.build()); + } + /** * Setter for codeExecution. * @@ -294,28 +259,65 @@ public Builder codeExecution(ToolCodeExecution.Builder codeExecutionBuilder) { } /** - * Setter for computerUse. + * Setter for enterpriseWebSearch. * - *

computerUse: Optional. Tool to support the model interacting directly with the computer. - * If enabled, it automatically populates computer-use specific Function Declarations. + *

enterpriseWebSearch: Optional. Tool to support searching public web data, powered by + * Vertex AI Search and Sec4 compliance. This field is not supported in Gemini API. */ - @JsonProperty("computerUse") - public abstract Builder computerUse(ToolComputerUse computerUse); + @JsonProperty("enterpriseWebSearch") + public abstract Builder enterpriseWebSearch(EnterpriseWebSearch enterpriseWebSearch); /** - * Setter for computerUse builder. + * Setter for enterpriseWebSearch builder. * - *

computerUse: Optional. Tool to support the model interacting directly with the computer. - * If enabled, it automatically populates computer-use specific Function Declarations. + *

enterpriseWebSearch: Optional. Tool to support searching public web data, powered by + * Vertex AI Search and Sec4 compliance. This field is not supported in Gemini API. */ - public Builder computerUse(ToolComputerUse.Builder computerUseBuilder) { - return computerUse(computerUseBuilder.build()); + public Builder enterpriseWebSearch(EnterpriseWebSearch.Builder enterpriseWebSearchBuilder) { + return enterpriseWebSearch(enterpriseWebSearchBuilder.build()); + } + + /** + * Setter for googleSearch. + * + *

googleSearch: Optional. GoogleSearch tool type. Tool to support Google Search in Model. + * Powered by Google. + */ + @JsonProperty("googleSearch") + public abstract Builder googleSearch(GoogleSearch googleSearch); + + /** + * Setter for googleSearch builder. + * + *

googleSearch: Optional. GoogleSearch tool type. Tool to support Google Search in Model. + * Powered by Google. + */ + public Builder googleSearch(GoogleSearch.Builder googleSearchBuilder) { + return googleSearch(googleSearchBuilder.build()); + } + + /** + * Setter for urlContext. + * + *

urlContext: Optional. Tool to support URL context retrieval. + */ + @JsonProperty("urlContext") + public abstract Builder urlContext(UrlContext urlContext); + + /** + * Setter for urlContext builder. + * + *

urlContext: Optional. Tool to support URL context retrieval. + */ + public Builder urlContext(UrlContext.Builder urlContextBuilder) { + return urlContext(urlContextBuilder.build()); } public abstract Tool build(); } /** Deserializes a JSON string to a Tool object. */ + @ExcludeFromGeneratedCoverageReport public static Tool fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, Tool.class); } diff --git a/src/main/java/com/google/genai/types/ToolCodeExecution.java b/src/main/java/com/google/genai/types/ToolCodeExecution.java index 8f9060ffaae..ef62807939e 100644 --- a/src/main/java/com/google/genai/types/ToolCodeExecution.java +++ b/src/main/java/com/google/genai/types/ToolCodeExecution.java @@ -26,12 +26,13 @@ /** * Tool that executes code generated by the model, and automatically returns the result to the * model. See also [ExecutableCode]and [CodeExecutionResult] which are input and output to this - * tool. + * tool. This data type is not supported in Gemini API. */ @AutoValue @JsonDeserialize(builder = ToolCodeExecution.Builder.class) public abstract class ToolCodeExecution extends JsonSerializable { /** Instantiates a builder for ToolCodeExecution. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_ToolCodeExecution.Builder(); } @@ -52,6 +53,7 @@ private static Builder create() { } /** Deserializes a JSON string to a ToolCodeExecution object. */ + @ExcludeFromGeneratedCoverageReport public static ToolCodeExecution fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, ToolCodeExecution.class); } diff --git a/src/main/java/com/google/genai/types/ToolComputerUse.java b/src/main/java/com/google/genai/types/ToolComputerUse.java deleted file mode 100644 index 45b18fa995e..00000000000 --- a/src/main/java/com/google/genai/types/ToolComputerUse.java +++ /dev/null @@ -1,89 +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 - * - * 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. - */ - -// Auto-generated code. Do not edit. - -package com.google.genai.types; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.google.auto.value.AutoValue; -import com.google.errorprone.annotations.CanIgnoreReturnValue; -import com.google.genai.JsonSerializable; -import java.util.Optional; - -/** Tool to support computer use. */ -@AutoValue -@JsonDeserialize(builder = ToolComputerUse.Builder.class) -public abstract class ToolComputerUse extends JsonSerializable { - /** Required. The environment being operated. */ - @JsonProperty("environment") - public abstract Optional environment(); - - /** Instantiates a builder for ToolComputerUse. */ - public static Builder builder() { - return new AutoValue_ToolComputerUse.Builder(); - } - - /** Creates a builder with the same values as this instance. */ - public abstract Builder toBuilder(); - - /** Builder for ToolComputerUse. */ - @AutoValue.Builder - public abstract static class Builder { - /** For internal usage. Please use `ToolComputerUse.builder()` for instantiation. */ - @JsonCreator - private static Builder create() { - return new AutoValue_ToolComputerUse.Builder(); - } - - /** - * Setter for environment. - * - *

environment: Required. The environment being operated. - */ - @JsonProperty("environment") - public abstract Builder environment(Environment environment); - - /** - * Setter for environment given a known enum. - * - *

environment: Required. The environment being operated. - */ - @CanIgnoreReturnValue - public Builder environment(Environment.Known knownType) { - return environment(new Environment(knownType)); - } - - /** - * Setter for environment given a string. - * - *

environment: Required. The environment being operated. - */ - @CanIgnoreReturnValue - public Builder environment(String environment) { - return environment(new Environment(environment)); - } - - public abstract ToolComputerUse build(); - } - - /** Deserializes a JSON string to a ToolComputerUse object. */ - public static ToolComputerUse fromJson(String jsonString) { - return JsonSerializable.fromJsonString(jsonString, ToolComputerUse.class); - } -} diff --git a/src/main/java/com/google/genai/types/ToolConfig.java b/src/main/java/com/google/genai/types/ToolConfig.java index 3f4341f98d1..65835c03f16 100644 --- a/src/main/java/com/google/genai/types/ToolConfig.java +++ b/src/main/java/com/google/genai/types/ToolConfig.java @@ -42,6 +42,7 @@ public abstract class ToolConfig extends JsonSerializable { public abstract Optional retrievalConfig(); /** Instantiates a builder for ToolConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_ToolConfig.Builder(); } @@ -97,6 +98,7 @@ public Builder retrievalConfig(RetrievalConfig.Builder retrievalConfigBuilder) { } /** Deserializes a JSON string to a ToolConfig object. */ + @ExcludeFromGeneratedCoverageReport public static ToolConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, ToolConfig.class); } diff --git a/src/main/java/com/google/genai/types/TrafficType.java b/src/main/java/com/google/genai/types/TrafficType.java index a4b8a7d457b..2a7291e50b3 100644 --- a/src/main/java/com/google/genai/types/TrafficType.java +++ b/src/main/java/com/google/genai/types/TrafficType.java @@ -25,7 +25,7 @@ /** * Output only. Traffic type. This shows whether a request consumes Pay-As-You-Go or Provisioned - * Throughput quota. + * Throughput quota. This enum is not supported in Gemini API. */ public class TrafficType { @@ -63,12 +63,14 @@ public TrafficType(Known knownValue) { this.value = knownValue.toString(); } + @ExcludeFromGeneratedCoverageReport @Override @JsonValue public String toString() { return this.value; } + @ExcludeFromGeneratedCoverageReport @SuppressWarnings("PatternMatchingInstanceof") @Override public boolean equals(Object o) { @@ -95,6 +97,7 @@ public boolean equals(Object o) { return false; } + @ExcludeFromGeneratedCoverageReport @Override public int hashCode() { if (this.trafficTypeEnum != Known.TRAFFIC_TYPE_UNSPECIFIED) { @@ -104,6 +107,7 @@ public int hashCode() { } } + @ExcludeFromGeneratedCoverageReport public Known knownEnum() { return this.trafficTypeEnum; } diff --git a/src/main/java/com/google/genai/types/Transcription.java b/src/main/java/com/google/genai/types/Transcription.java index fc66ccf93c2..aebc3db7e92 100644 --- a/src/main/java/com/google/genai/types/Transcription.java +++ b/src/main/java/com/google/genai/types/Transcription.java @@ -38,6 +38,7 @@ public abstract class Transcription extends JsonSerializable { public abstract Optional finished(); /** Instantiates a builder for Transcription. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_Transcription.Builder(); } @@ -74,6 +75,7 @@ private static Builder create() { } /** Deserializes a JSON string to a Transcription object. */ + @ExcludeFromGeneratedCoverageReport public static Transcription fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, Transcription.class); } diff --git a/src/main/java/com/google/genai/types/TunedModel.java b/src/main/java/com/google/genai/types/TunedModel.java index 605fe5e6760..d97618aefd0 100644 --- a/src/main/java/com/google/genai/types/TunedModel.java +++ b/src/main/java/com/google/genai/types/TunedModel.java @@ -29,13 +29,16 @@ import java.util.List; import java.util.Optional; -/** None */ +/** TunedModel for the Tuned Model of a Tuning Job. */ @AutoValue @JsonDeserialize(builder = TunedModel.Builder.class) public abstract class TunedModel extends JsonSerializable { /** * Output only. The resource name of the TunedModel. Format: - * `projects/{project}/locations/{location}/models/{model}`. + * `projects/{project}/locations/{location}/models/{model}@{version_id}` When tuning from a base + * model, the version_id will be 1. For continuous tuning, the version id will be incremented by 1 + * from the last version id in the parent model. E.g., + * `projects/{project}/locations/{location}/models/{model}@{last_version_id + 1}` */ @JsonProperty("model") public abstract Optional model(); @@ -55,6 +58,7 @@ public abstract class TunedModel extends JsonSerializable { public abstract Optional> checkpoints(); /** Instantiates a builder for TunedModel. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_TunedModel.Builder(); } @@ -75,7 +79,10 @@ private static Builder create() { * Setter for model. * *

model: Output only. The resource name of the TunedModel. Format: - * `projects/{project}/locations/{location}/models/{model}`. + * `projects/{project}/locations/{location}/models/{model}@{version_id}` When tuning from a base + * model, the version_id will be 1. For continuous tuning, the version id will be incremented by + * 1 from the last version id in the parent model. E.g., + * `projects/{project}/locations/{location}/models/{model}@{last_version_id + 1}` */ @JsonProperty("model") public abstract Builder model(String model); @@ -125,6 +132,7 @@ public Builder checkpoints(TunedModelCheckpoint.Builder... checkpointsBuilders) } /** Deserializes a JSON string to a TunedModel object. */ + @ExcludeFromGeneratedCoverageReport public static TunedModel fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, TunedModel.class); } diff --git a/src/main/java/com/google/genai/types/TunedModelCheckpoint.java b/src/main/java/com/google/genai/types/TunedModelCheckpoint.java index bdacc9a9090..ce015018214 100644 --- a/src/main/java/com/google/genai/types/TunedModelCheckpoint.java +++ b/src/main/java/com/google/genai/types/TunedModelCheckpoint.java @@ -49,6 +49,7 @@ public abstract class TunedModelCheckpoint extends JsonSerializable { public abstract Optional endpoint(); /** Instantiates a builder for TunedModelCheckpoint. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_TunedModelCheckpoint.Builder(); } @@ -102,6 +103,7 @@ private static Builder create() { } /** Deserializes a JSON string to a TunedModelCheckpoint object. */ + @ExcludeFromGeneratedCoverageReport public static TunedModelCheckpoint fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, TunedModelCheckpoint.class); } diff --git a/src/main/java/com/google/genai/types/TunedModelInfo.java b/src/main/java/com/google/genai/types/TunedModelInfo.java index 5eda5da04b9..434de79e6eb 100644 --- a/src/main/java/com/google/genai/types/TunedModelInfo.java +++ b/src/main/java/com/google/genai/types/TunedModelInfo.java @@ -43,6 +43,7 @@ public abstract class TunedModelInfo extends JsonSerializable { public abstract Optional updateTime(); /** Instantiates a builder for TunedModelInfo. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_TunedModelInfo.Builder(); } @@ -87,6 +88,7 @@ private static Builder create() { } /** Deserializes a JSON string to a TunedModelInfo object. */ + @ExcludeFromGeneratedCoverageReport public static TunedModelInfo fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, TunedModelInfo.class); } diff --git a/src/main/java/com/google/genai/types/TuningDataStats.java b/src/main/java/com/google/genai/types/TuningDataStats.java index 32e3111bd88..8c62f08fbbc 100644 --- a/src/main/java/com/google/genai/types/TuningDataStats.java +++ b/src/main/java/com/google/genai/types/TuningDataStats.java @@ -25,7 +25,9 @@ import com.google.genai.JsonSerializable; import java.util.Optional; -/** The tuning data statistic values for TuningJob. */ +/** + * The tuning data statistic values for TuningJob. This data type is not supported in Gemini API. + */ @AutoValue @JsonDeserialize(builder = TuningDataStats.Builder.class) public abstract class TuningDataStats extends JsonSerializable { @@ -33,11 +35,16 @@ public abstract class TuningDataStats extends JsonSerializable { @JsonProperty("distillationDataStats") public abstract Optional distillationDataStats(); + /** Output only. Statistics for preference optimization. */ + @JsonProperty("preferenceOptimizationDataStats") + public abstract Optional preferenceOptimizationDataStats(); + /** The SFT Tuning data stats. */ @JsonProperty("supervisedTuningDataStats") public abstract Optional supervisedTuningDataStats(); /** Instantiates a builder for TuningDataStats. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_TuningDataStats.Builder(); } @@ -72,6 +79,25 @@ public Builder distillationDataStats( return distillationDataStats(distillationDataStatsBuilder.build()); } + /** + * Setter for preferenceOptimizationDataStats. + * + *

preferenceOptimizationDataStats: Output only. Statistics for preference optimization. + */ + @JsonProperty("preferenceOptimizationDataStats") + public abstract Builder preferenceOptimizationDataStats( + PreferenceOptimizationDataStats preferenceOptimizationDataStats); + + /** + * Setter for preferenceOptimizationDataStats builder. + * + *

preferenceOptimizationDataStats: Output only. Statistics for preference optimization. + */ + public Builder preferenceOptimizationDataStats( + PreferenceOptimizationDataStats.Builder preferenceOptimizationDataStatsBuilder) { + return preferenceOptimizationDataStats(preferenceOptimizationDataStatsBuilder.build()); + } + /** * Setter for supervisedTuningDataStats. * @@ -95,6 +121,7 @@ public Builder supervisedTuningDataStats( } /** Deserializes a JSON string to a TuningDataStats object. */ + @ExcludeFromGeneratedCoverageReport public static TuningDataStats fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, TuningDataStats.class); } diff --git a/src/main/java/com/google/genai/types/TuningDataset.java b/src/main/java/com/google/genai/types/TuningDataset.java index 2af07425ddd..0623a3e4ca8 100644 --- a/src/main/java/com/google/genai/types/TuningDataset.java +++ b/src/main/java/com/google/genai/types/TuningDataset.java @@ -49,6 +49,7 @@ public abstract class TuningDataset extends JsonSerializable { public abstract Optional> examples(); /** Instantiates a builder for TuningDataset. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_TuningDataset.Builder(); } @@ -116,6 +117,7 @@ public Builder examples(TuningExample.Builder... examplesBuilders) { } /** Deserializes a JSON string to a TuningDataset object. */ + @ExcludeFromGeneratedCoverageReport public static TuningDataset fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, TuningDataset.class); } diff --git a/src/main/java/com/google/genai/types/TuningExample.java b/src/main/java/com/google/genai/types/TuningExample.java index c4b5265f0e2..19addf8ba84 100644 --- a/src/main/java/com/google/genai/types/TuningExample.java +++ b/src/main/java/com/google/genai/types/TuningExample.java @@ -25,19 +25,20 @@ import com.google.genai.JsonSerializable; import java.util.Optional; -/** None */ +/** A single example for tuning. This data type is not supported in Vertex AI. */ @AutoValue @JsonDeserialize(builder = TuningExample.Builder.class) public abstract class TuningExample extends JsonSerializable { - /** Text model input. */ - @JsonProperty("textInput") - public abstract Optional textInput(); - - /** The expected model output. */ + /** Required. The expected model output. */ @JsonProperty("output") public abstract Optional output(); + /** Optional. Text model input. */ + @JsonProperty("textInput") + public abstract Optional textInput(); + /** Instantiates a builder for TuningExample. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_TuningExample.Builder(); } @@ -55,25 +56,26 @@ private static Builder create() { } /** - * Setter for textInput. + * Setter for output. * - *

textInput: Text model input. + *

output: Required. The expected model output. */ - @JsonProperty("textInput") - public abstract Builder textInput(String textInput); + @JsonProperty("output") + public abstract Builder output(String output); /** - * Setter for output. + * Setter for textInput. * - *

output: The expected model output. + *

textInput: Optional. Text model input. */ - @JsonProperty("output") - public abstract Builder output(String output); + @JsonProperty("textInput") + public abstract Builder textInput(String textInput); public abstract TuningExample build(); } /** Deserializes a JSON string to a TuningExample object. */ + @ExcludeFromGeneratedCoverageReport public static TuningExample fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, TuningExample.class); } diff --git a/src/main/java/com/google/genai/types/TuningJob.java b/src/main/java/com/google/genai/types/TuningJob.java index 5a3668fb8bd..34e722b3e15 100644 --- a/src/main/java/com/google/genai/types/TuningJob.java +++ b/src/main/java/com/google/genai/types/TuningJob.java @@ -32,6 +32,10 @@ @AutoValue @JsonDeserialize(builder = TuningJob.Builder.class) public abstract class TuningJob extends JsonSerializable { + /** Used to retain the full HTTP response. */ + @JsonProperty("sdkHttpResponse") + public abstract Optional sdkHttpResponse(); + /** * Output only. Identifier. Resource name of a TuningJob. Format: * `projects/{project}/locations/{location}/tuningJobs/{tuning_job}` @@ -85,10 +89,18 @@ public abstract class TuningJob extends JsonSerializable { @JsonProperty("tunedModel") public abstract Optional tunedModel(); + /** The pre-tuned model for continuous tuning. */ + @JsonProperty("preTunedModel") + public abstract Optional preTunedModel(); + /** Tuning Spec for Supervised Fine Tuning. */ @JsonProperty("supervisedTuningSpec") public abstract Optional supervisedTuningSpec(); + /** Tuning Spec for Preference Optimization. */ + @JsonProperty("preferenceOptimizationSpec") + public abstract Optional preferenceOptimizationSpec(); + /** Output only. The tuning data statistics associated with this TuningJob. */ @JsonProperty("tuningDataStats") public abstract Optional tuningDataStats(); @@ -104,9 +116,15 @@ public abstract class TuningJob extends JsonSerializable { @JsonProperty("partnerModelTuningSpec") public abstract Optional partnerModelTuningSpec(); - /** Tuning Spec for Distillation. */ - @JsonProperty("distillationSpec") - public abstract Optional distillationSpec(); + /** + * Optional. The user-provided path to custom model weights. Set this field to tune a custom + * model. The path must be a Cloud Storage directory that contains the model weights in + * .safetensors format along with associated model metadata files. If this field is set, the + * base_model field must still be set to indicate which base model the custom model is derived + * from. This feature is only available for open source models. + */ + @JsonProperty("customBaseModel") + public abstract Optional customBaseModel(); /** Output only. The Experiment associated with this TuningJob. */ @JsonProperty("experiment") @@ -122,6 +140,13 @@ public abstract class TuningJob extends JsonSerializable { @JsonProperty("labels") public abstract Optional> labels(); + /** + * Optional. Cloud Storage path to the directory where tuning job outputs are written to. This + * field is only available and required for open source models. + */ + @JsonProperty("outputUri") + public abstract Optional outputUri(); + /** * Output only. The resource name of the PipelineJob associated with the TuningJob. Format: * `projects/{project}/locations/{location}/pipelineJobs/{pipeline_job}`. @@ -129,14 +154,6 @@ public abstract class TuningJob extends JsonSerializable { @JsonProperty("pipelineJob") public abstract Optional pipelineJob(); - /** Output only. Reserved for future use. */ - @JsonProperty("satisfiesPzi") - public abstract Optional satisfiesPzi(); - - /** Output only. Reserved for future use. */ - @JsonProperty("satisfiesPzs") - public abstract Optional satisfiesPzs(); - /** * The service account that the tuningJob workload runs as. If not specified, the Vertex AI Secure * Fine-Tuned Service Agent in the project will be used. See @@ -154,7 +171,12 @@ public abstract class TuningJob extends JsonSerializable { @JsonProperty("tunedModelDisplayName") public abstract Optional tunedModelDisplayName(); + /** Tuning Spec for Veo Tuning. */ + @JsonProperty("veoTuningSpec") + public abstract Optional veoTuningSpec(); + /** Instantiates a builder for TuningJob. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_TuningJob.Builder(); } @@ -171,6 +193,23 @@ private static Builder create() { return new AutoValue_TuningJob.Builder(); } + /** + * Setter for sdkHttpResponse. + * + *

sdkHttpResponse: Used to retain the full HTTP response. + */ + @JsonProperty("sdkHttpResponse") + public abstract Builder sdkHttpResponse(HttpResponse sdkHttpResponse); + + /** + * Setter for sdkHttpResponse builder. + * + *

sdkHttpResponse: Used to retain the full HTTP response. + */ + public Builder sdkHttpResponse(HttpResponse.Builder sdkHttpResponseBuilder) { + return sdkHttpResponse(sdkHttpResponseBuilder.build()); + } + /** * Setter for name. * @@ -295,6 +334,23 @@ public Builder tunedModel(TunedModel.Builder tunedModelBuilder) { return tunedModel(tunedModelBuilder.build()); } + /** + * Setter for preTunedModel. + * + *

preTunedModel: The pre-tuned model for continuous tuning. + */ + @JsonProperty("preTunedModel") + public abstract Builder preTunedModel(PreTunedModel preTunedModel); + + /** + * Setter for preTunedModel builder. + * + *

preTunedModel: The pre-tuned model for continuous tuning. + */ + public Builder preTunedModel(PreTunedModel.Builder preTunedModelBuilder) { + return preTunedModel(preTunedModelBuilder.build()); + } + /** * Setter for supervisedTuningSpec. * @@ -312,6 +368,25 @@ public Builder supervisedTuningSpec(SupervisedTuningSpec.Builder supervisedTunin return supervisedTuningSpec(supervisedTuningSpecBuilder.build()); } + /** + * Setter for preferenceOptimizationSpec. + * + *

preferenceOptimizationSpec: Tuning Spec for Preference Optimization. + */ + @JsonProperty("preferenceOptimizationSpec") + public abstract Builder preferenceOptimizationSpec( + PreferenceOptimizationSpec preferenceOptimizationSpec); + + /** + * Setter for preferenceOptimizationSpec builder. + * + *

preferenceOptimizationSpec: Tuning Spec for Preference Optimization. + */ + public Builder preferenceOptimizationSpec( + PreferenceOptimizationSpec.Builder preferenceOptimizationSpecBuilder) { + return preferenceOptimizationSpec(preferenceOptimizationSpecBuilder.build()); + } + /** * Setter for tuningDataStats. * @@ -369,21 +444,16 @@ public Builder partnerModelTuningSpec( } /** - * Setter for distillationSpec. - * - *

distillationSpec: Tuning Spec for Distillation. - */ - @JsonProperty("distillationSpec") - public abstract Builder distillationSpec(DistillationSpec distillationSpec); - - /** - * Setter for distillationSpec builder. + * Setter for customBaseModel. * - *

distillationSpec: Tuning Spec for Distillation. + *

customBaseModel: Optional. The user-provided path to custom model weights. Set this field + * to tune a custom model. The path must be a Cloud Storage directory that contains the model + * weights in .safetensors format along with associated model metadata files. If this field is + * set, the base_model field must still be set to indicate which base model the custom model is + * derived from. This feature is only available for open source models. */ - public Builder distillationSpec(DistillationSpec.Builder distillationSpecBuilder) { - return distillationSpec(distillationSpecBuilder.build()); - } + @JsonProperty("customBaseModel") + public abstract Builder customBaseModel(String customBaseModel); /** * Setter for experiment. @@ -405,6 +475,15 @@ public Builder distillationSpec(DistillationSpec.Builder distillationSpecBuilder @JsonProperty("labels") public abstract Builder labels(Map labels); + /** + * Setter for outputUri. + * + *

outputUri: Optional. Cloud Storage path to the directory where tuning job outputs are + * written to. This field is only available and required for open source models. + */ + @JsonProperty("outputUri") + public abstract Builder outputUri(String outputUri); + /** * Setter for pipelineJob. * @@ -414,22 +493,6 @@ public Builder distillationSpec(DistillationSpec.Builder distillationSpecBuilder @JsonProperty("pipelineJob") public abstract Builder pipelineJob(String pipelineJob); - /** - * Setter for satisfiesPzi. - * - *

satisfiesPzi: Output only. Reserved for future use. - */ - @JsonProperty("satisfiesPzi") - public abstract Builder satisfiesPzi(boolean satisfiesPzi); - - /** - * Setter for satisfiesPzs. - * - *

satisfiesPzs: Output only. Reserved for future use. - */ - @JsonProperty("satisfiesPzs") - public abstract Builder satisfiesPzs(boolean satisfiesPzs); - /** * Setter for serviceAccount. * @@ -451,10 +514,28 @@ public Builder distillationSpec(DistillationSpec.Builder distillationSpecBuilder @JsonProperty("tunedModelDisplayName") public abstract Builder tunedModelDisplayName(String tunedModelDisplayName); + /** + * Setter for veoTuningSpec. + * + *

veoTuningSpec: Tuning Spec for Veo Tuning. + */ + @JsonProperty("veoTuningSpec") + public abstract Builder veoTuningSpec(VeoTuningSpec veoTuningSpec); + + /** + * Setter for veoTuningSpec builder. + * + *

veoTuningSpec: Tuning Spec for Veo Tuning. + */ + public Builder veoTuningSpec(VeoTuningSpec.Builder veoTuningSpecBuilder) { + return veoTuningSpec(veoTuningSpecBuilder.build()); + } + public abstract TuningJob build(); } /** Deserializes a JSON string to a TuningJob object. */ + @ExcludeFromGeneratedCoverageReport public static TuningJob fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, TuningJob.class); } diff --git a/src/main/java/com/google/genai/types/TuningMethod.java b/src/main/java/com/google/genai/types/TuningMethod.java new file mode 100644 index 00000000000..55d36d5311f --- /dev/null +++ b/src/main/java/com/google/genai/types/TuningMethod.java @@ -0,0 +1,110 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Auto-generated code. Do not edit. + +package com.google.genai.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.google.common.base.Ascii; +import java.util.Objects; + +/** Enum representing the tuning method. */ +public class TuningMethod { + + /** Enum representing the known values for TuningMethod. */ + public enum Known { + /** Supervised fine tuning. */ + SUPERVISED_FINE_TUNING, + + /** Preference optimization tuning. */ + PREFERENCE_TUNING, + + TUNING_METHOD_UNSPECIFIED + } + + private Known tuningMethodEnum; + private final String value; + + @JsonCreator + public TuningMethod(String value) { + this.value = value; + for (Known tuningMethodEnum : Known.values()) { + if (Ascii.equalsIgnoreCase(tuningMethodEnum.toString(), value)) { + this.tuningMethodEnum = tuningMethodEnum; + break; + } + } + if (this.tuningMethodEnum == null) { + this.tuningMethodEnum = Known.TUNING_METHOD_UNSPECIFIED; + } + } + + public TuningMethod(Known knownValue) { + this.tuningMethodEnum = knownValue; + this.value = knownValue.toString(); + } + + @ExcludeFromGeneratedCoverageReport + @Override + @JsonValue + public String toString() { + return this.value; + } + + @ExcludeFromGeneratedCoverageReport + @SuppressWarnings("PatternMatchingInstanceof") + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null) { + return false; + } + + if (!(o instanceof TuningMethod)) { + return false; + } + + TuningMethod other = (TuningMethod) o; + + if (this.tuningMethodEnum != Known.TUNING_METHOD_UNSPECIFIED + && other.tuningMethodEnum != Known.TUNING_METHOD_UNSPECIFIED) { + return this.tuningMethodEnum == other.tuningMethodEnum; + } else if (this.tuningMethodEnum == Known.TUNING_METHOD_UNSPECIFIED + && other.tuningMethodEnum == Known.TUNING_METHOD_UNSPECIFIED) { + return this.value.equals(other.value); + } + return false; + } + + @ExcludeFromGeneratedCoverageReport + @Override + public int hashCode() { + if (this.tuningMethodEnum != Known.TUNING_METHOD_UNSPECIFIED) { + return this.tuningMethodEnum.hashCode(); + } else { + return Objects.hashCode(this.value); + } + } + + @ExcludeFromGeneratedCoverageReport + public Known knownEnum() { + return this.tuningMethodEnum; + } +} diff --git a/src/main/java/com/google/genai/types/TuningMode.java b/src/main/java/com/google/genai/types/TuningMode.java new file mode 100644 index 00000000000..4f6e946d05e --- /dev/null +++ b/src/main/java/com/google/genai/types/TuningMode.java @@ -0,0 +1,111 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Auto-generated code. Do not edit. + +package com.google.genai.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.google.common.base.Ascii; +import java.util.Objects; + +/** Tuning mode. This enum is not supported in Gemini API. */ +public class TuningMode { + + /** Enum representing the known values for TuningMode. */ + public enum Known { + /** Tuning mode is unspecified. */ + TUNING_MODE_UNSPECIFIED, + + /** Full fine-tuning mode. */ + TUNING_MODE_FULL, + + /** PEFT adapter tuning mode. */ + TUNING_MODE_PEFT_ADAPTER + } + + private Known tuningModeEnum; + private final String value; + + @JsonCreator + public TuningMode(String value) { + this.value = value; + for (Known tuningModeEnum : Known.values()) { + if (Ascii.equalsIgnoreCase(tuningModeEnum.toString(), value)) { + this.tuningModeEnum = tuningModeEnum; + break; + } + } + if (this.tuningModeEnum == null) { + this.tuningModeEnum = Known.TUNING_MODE_UNSPECIFIED; + } + } + + public TuningMode(Known knownValue) { + this.tuningModeEnum = knownValue; + this.value = knownValue.toString(); + } + + @ExcludeFromGeneratedCoverageReport + @Override + @JsonValue + public String toString() { + return this.value; + } + + @ExcludeFromGeneratedCoverageReport + @SuppressWarnings("PatternMatchingInstanceof") + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null) { + return false; + } + + if (!(o instanceof TuningMode)) { + return false; + } + + TuningMode other = (TuningMode) o; + + if (this.tuningModeEnum != Known.TUNING_MODE_UNSPECIFIED + && other.tuningModeEnum != Known.TUNING_MODE_UNSPECIFIED) { + return this.tuningModeEnum == other.tuningModeEnum; + } else if (this.tuningModeEnum == Known.TUNING_MODE_UNSPECIFIED + && other.tuningModeEnum == Known.TUNING_MODE_UNSPECIFIED) { + return this.value.equals(other.value); + } + return false; + } + + @ExcludeFromGeneratedCoverageReport + @Override + public int hashCode() { + if (this.tuningModeEnum != Known.TUNING_MODE_UNSPECIFIED) { + return this.tuningModeEnum.hashCode(); + } else { + return Objects.hashCode(this.value); + } + } + + @ExcludeFromGeneratedCoverageReport + public Known knownEnum() { + return this.tuningModeEnum; + } +} diff --git a/src/main/java/com/google/genai/types/TuningOperation.java b/src/main/java/com/google/genai/types/TuningOperation.java index 71dbdcca844..3fe7be89fc5 100644 --- a/src/main/java/com/google/genai/types/TuningOperation.java +++ b/src/main/java/com/google/genai/types/TuningOperation.java @@ -30,6 +30,10 @@ @AutoValue @JsonDeserialize(builder = TuningOperation.Builder.class) public abstract class TuningOperation extends JsonSerializable { + /** Used to retain the full HTTP response. */ + @JsonProperty("sdkHttpResponse") + public abstract Optional sdkHttpResponse(); + /** * The server-assigned name, which is only unique within the same service that originally returns * it. If you use the default HTTP mapping, the `name` should be a resource name ending with @@ -59,6 +63,7 @@ public abstract class TuningOperation extends JsonSerializable { public abstract Optional> error(); /** Instantiates a builder for TuningOperation. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_TuningOperation.Builder(); } @@ -75,6 +80,23 @@ private static Builder create() { return new AutoValue_TuningOperation.Builder(); } + /** + * Setter for sdkHttpResponse. + * + *

sdkHttpResponse: Used to retain the full HTTP response. + */ + @JsonProperty("sdkHttpResponse") + public abstract Builder sdkHttpResponse(HttpResponse sdkHttpResponse); + + /** + * Setter for sdkHttpResponse builder. + * + *

sdkHttpResponse: Used to retain the full HTTP response. + */ + public Builder sdkHttpResponse(HttpResponse.Builder sdkHttpResponseBuilder) { + return sdkHttpResponse(sdkHttpResponseBuilder.build()); + } + /** * Setter for name. * @@ -117,6 +139,7 @@ private static Builder create() { } /** Deserializes a JSON string to a TuningOperation object. */ + @ExcludeFromGeneratedCoverageReport public static TuningOperation fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, TuningOperation.class); } diff --git a/src/main/java/com/google/genai/types/TuningTask.java b/src/main/java/com/google/genai/types/TuningTask.java new file mode 100644 index 00000000000..957cc68af8e --- /dev/null +++ b/src/main/java/com/google/genai/types/TuningTask.java @@ -0,0 +1,111 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Auto-generated code. Do not edit. + +package com.google.genai.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.google.common.base.Ascii; +import java.util.Objects; + +/** The tuning task. Either I2V or T2V. This enum is not supported in Gemini API. */ +public class TuningTask { + + /** Enum representing the known values for TuningTask. */ + public enum Known { + /** Default value. This value is unused. */ + TUNING_TASK_UNSPECIFIED, + + /** Tuning task for image to video. */ + TUNING_TASK_I2V, + + /** Tuning task for text to video. */ + TUNING_TASK_T2V + } + + private Known tuningTaskEnum; + private final String value; + + @JsonCreator + public TuningTask(String value) { + this.value = value; + for (Known tuningTaskEnum : Known.values()) { + if (Ascii.equalsIgnoreCase(tuningTaskEnum.toString(), value)) { + this.tuningTaskEnum = tuningTaskEnum; + break; + } + } + if (this.tuningTaskEnum == null) { + this.tuningTaskEnum = Known.TUNING_TASK_UNSPECIFIED; + } + } + + public TuningTask(Known knownValue) { + this.tuningTaskEnum = knownValue; + this.value = knownValue.toString(); + } + + @ExcludeFromGeneratedCoverageReport + @Override + @JsonValue + public String toString() { + return this.value; + } + + @ExcludeFromGeneratedCoverageReport + @SuppressWarnings("PatternMatchingInstanceof") + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null) { + return false; + } + + if (!(o instanceof TuningTask)) { + return false; + } + + TuningTask other = (TuningTask) o; + + if (this.tuningTaskEnum != Known.TUNING_TASK_UNSPECIFIED + && other.tuningTaskEnum != Known.TUNING_TASK_UNSPECIFIED) { + return this.tuningTaskEnum == other.tuningTaskEnum; + } else if (this.tuningTaskEnum == Known.TUNING_TASK_UNSPECIFIED + && other.tuningTaskEnum == Known.TUNING_TASK_UNSPECIFIED) { + return this.value.equals(other.value); + } + return false; + } + + @ExcludeFromGeneratedCoverageReport + @Override + public int hashCode() { + if (this.tuningTaskEnum != Known.TUNING_TASK_UNSPECIFIED) { + return this.tuningTaskEnum.hashCode(); + } else { + return Objects.hashCode(this.value); + } + } + + @ExcludeFromGeneratedCoverageReport + public Known knownEnum() { + return this.tuningTaskEnum; + } +} diff --git a/src/main/java/com/google/genai/types/TuningValidationDataset.java b/src/main/java/com/google/genai/types/TuningValidationDataset.java index 8211756d9e1..bdf9b958692 100644 --- a/src/main/java/com/google/genai/types/TuningValidationDataset.java +++ b/src/main/java/com/google/genai/types/TuningValidationDataset.java @@ -34,13 +34,14 @@ public abstract class TuningValidationDataset extends JsonSerializable { public abstract Optional gcsUri(); /** - * The resource name of the Vertex Multimodal Dataset that is used as training dataset. Example: + * The resource name of the Vertex Multimodal Dataset that is used as validation dataset. Example: * 'projects/my-project-id-or-number/locations/my-location/datasets/my-dataset-id'. */ @JsonProperty("vertexDatasetResource") public abstract Optional vertexDatasetResource(); /** Instantiates a builder for TuningValidationDataset. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_TuningValidationDataset.Builder(); } @@ -69,7 +70,7 @@ private static Builder create() { * Setter for vertexDatasetResource. * *

vertexDatasetResource: The resource name of the Vertex Multimodal Dataset that is used as - * training dataset. Example: + * validation dataset. Example: * 'projects/my-project-id-or-number/locations/my-location/datasets/my-dataset-id'. */ @JsonProperty("vertexDatasetResource") @@ -79,6 +80,7 @@ private static Builder create() { } /** Deserializes a JSON string to a TuningValidationDataset object. */ + @ExcludeFromGeneratedCoverageReport public static TuningValidationDataset fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, TuningValidationDataset.class); } diff --git a/src/main/java/com/google/genai/types/TurnCompleteReason.java b/src/main/java/com/google/genai/types/TurnCompleteReason.java new file mode 100644 index 00000000000..1af71d48443 --- /dev/null +++ b/src/main/java/com/google/genai/types/TurnCompleteReason.java @@ -0,0 +1,114 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Auto-generated code. Do not edit. + +package com.google.genai.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.google.common.base.Ascii; +import java.util.Objects; + +/** The reason why the turn is complete. */ +public class TurnCompleteReason { + + /** Enum representing the known values for TurnCompleteReason. */ + public enum Known { + /** Default value. Reason is unspecified. */ + TURN_COMPLETE_REASON_UNSPECIFIED, + + /** The function call generated by the model is invalid. */ + MALFORMED_FUNCTION_CALL, + + /** The response is rejected by the model. */ + RESPONSE_REJECTED, + + /** Needs more input from the user. */ + NEED_MORE_INPUT + } + + private Known turnCompleteReasonEnum; + private final String value; + + @JsonCreator + public TurnCompleteReason(String value) { + this.value = value; + for (Known turnCompleteReasonEnum : Known.values()) { + if (Ascii.equalsIgnoreCase(turnCompleteReasonEnum.toString(), value)) { + this.turnCompleteReasonEnum = turnCompleteReasonEnum; + break; + } + } + if (this.turnCompleteReasonEnum == null) { + this.turnCompleteReasonEnum = Known.TURN_COMPLETE_REASON_UNSPECIFIED; + } + } + + public TurnCompleteReason(Known knownValue) { + this.turnCompleteReasonEnum = knownValue; + this.value = knownValue.toString(); + } + + @ExcludeFromGeneratedCoverageReport + @Override + @JsonValue + public String toString() { + return this.value; + } + + @ExcludeFromGeneratedCoverageReport + @SuppressWarnings("PatternMatchingInstanceof") + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null) { + return false; + } + + if (!(o instanceof TurnCompleteReason)) { + return false; + } + + TurnCompleteReason other = (TurnCompleteReason) o; + + if (this.turnCompleteReasonEnum != Known.TURN_COMPLETE_REASON_UNSPECIFIED + && other.turnCompleteReasonEnum != Known.TURN_COMPLETE_REASON_UNSPECIFIED) { + return this.turnCompleteReasonEnum == other.turnCompleteReasonEnum; + } else if (this.turnCompleteReasonEnum == Known.TURN_COMPLETE_REASON_UNSPECIFIED + && other.turnCompleteReasonEnum == Known.TURN_COMPLETE_REASON_UNSPECIFIED) { + return this.value.equals(other.value); + } + return false; + } + + @ExcludeFromGeneratedCoverageReport + @Override + public int hashCode() { + if (this.turnCompleteReasonEnum != Known.TURN_COMPLETE_REASON_UNSPECIFIED) { + return this.turnCompleteReasonEnum.hashCode(); + } else { + return Objects.hashCode(this.value); + } + } + + @ExcludeFromGeneratedCoverageReport + public Known knownEnum() { + return this.turnCompleteReasonEnum; + } +} diff --git a/src/main/java/com/google/genai/types/TurnCoverage.java b/src/main/java/com/google/genai/types/TurnCoverage.java index 906b6bf9ef4..6b8afed246f 100644 --- a/src/main/java/com/google/genai/types/TurnCoverage.java +++ b/src/main/java/com/google/genai/types/TurnCoverage.java @@ -66,12 +66,14 @@ public TurnCoverage(Known knownValue) { this.value = knownValue.toString(); } + @ExcludeFromGeneratedCoverageReport @Override @JsonValue public String toString() { return this.value; } + @ExcludeFromGeneratedCoverageReport @SuppressWarnings("PatternMatchingInstanceof") @Override public boolean equals(Object o) { @@ -98,6 +100,7 @@ public boolean equals(Object o) { return false; } + @ExcludeFromGeneratedCoverageReport @Override public int hashCode() { if (this.turnCoverageEnum != Known.TURN_COVERAGE_UNSPECIFIED) { @@ -107,6 +110,7 @@ public int hashCode() { } } + @ExcludeFromGeneratedCoverageReport public Known knownEnum() { return this.turnCoverageEnum; } diff --git a/src/main/java/com/google/genai/types/Type.java b/src/main/java/com/google/genai/types/Type.java index 86e76f2af9a..3500e4695c9 100644 --- a/src/main/java/com/google/genai/types/Type.java +++ b/src/main/java/com/google/genai/types/Type.java @@ -23,7 +23,7 @@ import com.google.common.base.Ascii; import java.util.Objects; -/** Optional. The type of the data. */ +/** The type of the data. */ public class Type { /** Enum representing the known values for Type. */ @@ -75,12 +75,14 @@ public Type(Known knownValue) { this.value = knownValue.toString(); } + @ExcludeFromGeneratedCoverageReport @Override @JsonValue public String toString() { return this.value; } + @ExcludeFromGeneratedCoverageReport @SuppressWarnings("PatternMatchingInstanceof") @Override public boolean equals(Object o) { @@ -106,6 +108,7 @@ public boolean equals(Object o) { return false; } + @ExcludeFromGeneratedCoverageReport @Override public int hashCode() { if (this.typeEnum != Known.TYPE_UNSPECIFIED) { @@ -115,6 +118,7 @@ public int hashCode() { } } + @ExcludeFromGeneratedCoverageReport public Known knownEnum() { return this.typeEnum; } diff --git a/src/main/java/com/google/genai/types/UpdateCachedContentConfig.java b/src/main/java/com/google/genai/types/UpdateCachedContentConfig.java index cc9df5955d5..6c767ba350a 100644 --- a/src/main/java/com/google/genai/types/UpdateCachedContentConfig.java +++ b/src/main/java/com/google/genai/types/UpdateCachedContentConfig.java @@ -50,6 +50,7 @@ public abstract class UpdateCachedContentConfig extends JsonSerializable { public abstract Optional expireTime(); /** Instantiates a builder for UpdateCachedContentConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_UpdateCachedContentConfig.Builder(); } @@ -105,6 +106,7 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { } /** Deserializes a JSON string to a UpdateCachedContentConfig object. */ + @ExcludeFromGeneratedCoverageReport public static UpdateCachedContentConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, UpdateCachedContentConfig.class); } diff --git a/src/main/java/com/google/genai/types/UpdateCachedContentParameters.java b/src/main/java/com/google/genai/types/UpdateCachedContentParameters.java index c5f9d8b85ae..986a0f13081 100644 --- a/src/main/java/com/google/genai/types/UpdateCachedContentParameters.java +++ b/src/main/java/com/google/genai/types/UpdateCachedContentParameters.java @@ -40,6 +40,7 @@ public abstract class UpdateCachedContentParameters extends JsonSerializable { public abstract Optional config(); /** Instantiates a builder for UpdateCachedContentParameters. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_UpdateCachedContentParameters.Builder(); } @@ -87,6 +88,7 @@ public Builder config(UpdateCachedContentConfig.Builder configBuilder) { } /** Deserializes a JSON string to a UpdateCachedContentParameters object. */ + @ExcludeFromGeneratedCoverageReport public static UpdateCachedContentParameters fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, UpdateCachedContentParameters.class); } diff --git a/src/main/java/com/google/genai/types/UpdateModelConfig.java b/src/main/java/com/google/genai/types/UpdateModelConfig.java index 77b50143e9f..35d36efa057 100644 --- a/src/main/java/com/google/genai/types/UpdateModelConfig.java +++ b/src/main/java/com/google/genai/types/UpdateModelConfig.java @@ -46,6 +46,7 @@ public abstract class UpdateModelConfig extends JsonSerializable { public abstract Optional defaultCheckpointId(); /** Instantiates a builder for UpdateModelConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_UpdateModelConfig.Builder(); } @@ -107,6 +108,7 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { } /** Deserializes a JSON string to a UpdateModelConfig object. */ + @ExcludeFromGeneratedCoverageReport public static UpdateModelConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, UpdateModelConfig.class); } diff --git a/src/main/java/com/google/genai/types/UpdateModelParameters.java b/src/main/java/com/google/genai/types/UpdateModelParameters.java index 7b26f3acbb6..fed31e46a43 100644 --- a/src/main/java/com/google/genai/types/UpdateModelParameters.java +++ b/src/main/java/com/google/genai/types/UpdateModelParameters.java @@ -40,6 +40,7 @@ public abstract class UpdateModelParameters extends JsonSerializable { public abstract Optional config(); /** Instantiates a builder for UpdateModelParameters. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_UpdateModelParameters.Builder(); } @@ -85,6 +86,7 @@ public Builder config(UpdateModelConfig.Builder configBuilder) { } /** Deserializes a JSON string to a UpdateModelParameters object. */ + @ExcludeFromGeneratedCoverageReport public static UpdateModelParameters fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, UpdateModelParameters.class); } diff --git a/src/main/java/com/google/genai/types/UploadFileConfig.java b/src/main/java/com/google/genai/types/UploadFileConfig.java index 3a54500d497..d8f3210bc78 100644 --- a/src/main/java/com/google/genai/types/UploadFileConfig.java +++ b/src/main/java/com/google/genai/types/UploadFileConfig.java @@ -52,6 +52,7 @@ public abstract class UploadFileConfig extends JsonSerializable { public abstract Optional displayName(); /** Instantiates a builder for UploadFileConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_UploadFileConfig.Builder(); } @@ -115,6 +116,7 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { } /** Deserializes a JSON string to a UploadFileConfig object. */ + @ExcludeFromGeneratedCoverageReport public static UploadFileConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, UploadFileConfig.class); } diff --git a/src/main/java/com/google/genai/types/UpscaleImageAPIConfig.java b/src/main/java/com/google/genai/types/UpscaleImageAPIConfig.java index 78d294bd7e4..cf9d3f19f51 100644 --- a/src/main/java/com/google/genai/types/UpscaleImageAPIConfig.java +++ b/src/main/java/com/google/genai/types/UpscaleImageAPIConfig.java @@ -23,7 +23,9 @@ import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.google.api.core.InternalApi; import com.google.auto.value.AutoValue; +import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.genai.JsonSerializable; +import java.util.Map; import java.util.Optional; /** @@ -40,6 +42,18 @@ public abstract class UpscaleImageAPIConfig extends JsonSerializable { @JsonProperty("httpOptions") public abstract Optional httpOptions(); + /** Cloud Storage URI used to store the generated images. */ + @JsonProperty("outputGcsUri") + public abstract Optional outputGcsUri(); + + /** Filter level for safety filtering. */ + @JsonProperty("safetyFilterLevel") + public abstract Optional safetyFilterLevel(); + + /** Allows generation of people by the model. */ + @JsonProperty("personGeneration") + public abstract Optional personGeneration(); + /** Whether to include a reason for filtered-out images in the response. */ @JsonProperty("includeRaiReason") public abstract Optional includeRaiReason(); @@ -48,7 +62,7 @@ public abstract class UpscaleImageAPIConfig extends JsonSerializable { @JsonProperty("outputMimeType") public abstract Optional outputMimeType(); - /** The level of compression if the ``output_mime_type`` is ``image/jpeg``. */ + /** The level of compression. Only applicable if the ``output_mime_type`` is ``image/jpeg``. */ @JsonProperty("outputCompressionQuality") public abstract Optional outputCompressionQuality(); @@ -67,6 +81,10 @@ public abstract class UpscaleImageAPIConfig extends JsonSerializable { @JsonProperty("imagePreservationFactor") public abstract Optional imagePreservationFactor(); + /** User specified labels to track billing usage. */ + @JsonProperty("labels") + public abstract Optional> labels(); + /** */ @JsonProperty("numberOfImages") public abstract Optional numberOfImages(); @@ -76,6 +94,7 @@ public abstract class UpscaleImageAPIConfig extends JsonSerializable { public abstract Optional mode(); /** Instantiates a builder for UpscaleImageAPIConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_UpscaleImageAPIConfig.Builder(); } @@ -109,6 +128,70 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { return httpOptions(httpOptionsBuilder.build()); } + /** + * Setter for outputGcsUri. + * + *

outputGcsUri: Cloud Storage URI used to store the generated images. + */ + @JsonProperty("outputGcsUri") + public abstract Builder outputGcsUri(String outputGcsUri); + + /** + * Setter for safetyFilterLevel. + * + *

safetyFilterLevel: Filter level for safety filtering. + */ + @JsonProperty("safetyFilterLevel") + public abstract Builder safetyFilterLevel(SafetyFilterLevel safetyFilterLevel); + + /** + * Setter for safetyFilterLevel given a known enum. + * + *

safetyFilterLevel: Filter level for safety filtering. + */ + @CanIgnoreReturnValue + public Builder safetyFilterLevel(SafetyFilterLevel.Known knownType) { + return safetyFilterLevel(new SafetyFilterLevel(knownType)); + } + + /** + * Setter for safetyFilterLevel given a string. + * + *

safetyFilterLevel: Filter level for safety filtering. + */ + @CanIgnoreReturnValue + public Builder safetyFilterLevel(String safetyFilterLevel) { + return safetyFilterLevel(new SafetyFilterLevel(safetyFilterLevel)); + } + + /** + * Setter for personGeneration. + * + *

personGeneration: Allows generation of people by the model. + */ + @JsonProperty("personGeneration") + public abstract Builder personGeneration(PersonGeneration personGeneration); + + /** + * Setter for personGeneration given a known enum. + * + *

personGeneration: Allows generation of people by the model. + */ + @CanIgnoreReturnValue + public Builder personGeneration(PersonGeneration.Known knownType) { + return personGeneration(new PersonGeneration(knownType)); + } + + /** + * Setter for personGeneration given a string. + * + *

personGeneration: Allows generation of people by the model. + */ + @CanIgnoreReturnValue + public Builder personGeneration(String personGeneration) { + return personGeneration(new PersonGeneration(personGeneration)); + } + /** * Setter for includeRaiReason. * @@ -128,8 +211,8 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { /** * Setter for outputCompressionQuality. * - *

outputCompressionQuality: The level of compression if the ``output_mime_type`` is - * ``image/jpeg``. + *

outputCompressionQuality: The level of compression. Only applicable if the + * ``output_mime_type`` is ``image/jpeg``. */ @JsonProperty("outputCompressionQuality") public abstract Builder outputCompressionQuality(Integer outputCompressionQuality); @@ -153,6 +236,14 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { @JsonProperty("imagePreservationFactor") public abstract Builder imagePreservationFactor(Float imagePreservationFactor); + /** + * Setter for labels. + * + *

labels: User specified labels to track billing usage. + */ + @JsonProperty("labels") + public abstract Builder labels(Map labels); + /** * Setter for numberOfImages. * @@ -173,6 +264,7 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { } /** Deserializes a JSON string to a UpscaleImageAPIConfig object. */ + @ExcludeFromGeneratedCoverageReport public static UpscaleImageAPIConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, UpscaleImageAPIConfig.class); } diff --git a/src/main/java/com/google/genai/types/UpscaleImageAPIParameters.java b/src/main/java/com/google/genai/types/UpscaleImageAPIParameters.java index fce2039e48a..6a73452aace 100644 --- a/src/main/java/com/google/genai/types/UpscaleImageAPIParameters.java +++ b/src/main/java/com/google/genai/types/UpscaleImageAPIParameters.java @@ -48,6 +48,7 @@ public abstract class UpscaleImageAPIParameters extends JsonSerializable { public abstract Optional config(); /** Instantiates a builder for UpscaleImageAPIParameters. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_UpscaleImageAPIParameters.Builder(); } @@ -109,6 +110,7 @@ public Builder image(Image.Builder imageBuilder) { } /** Deserializes a JSON string to a UpscaleImageAPIParameters object. */ + @ExcludeFromGeneratedCoverageReport public static UpscaleImageAPIParameters fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, UpscaleImageAPIParameters.class); } diff --git a/src/main/java/com/google/genai/types/UpscaleImageConfig.java b/src/main/java/com/google/genai/types/UpscaleImageConfig.java index f9cc1e0c894..c17a7fc9483 100644 --- a/src/main/java/com/google/genai/types/UpscaleImageConfig.java +++ b/src/main/java/com/google/genai/types/UpscaleImageConfig.java @@ -22,7 +22,9 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.google.auto.value.AutoValue; +import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.genai.JsonSerializable; +import java.util.Map; import java.util.Optional; /** @@ -38,6 +40,18 @@ public abstract class UpscaleImageConfig extends JsonSerializable { @JsonProperty("httpOptions") public abstract Optional httpOptions(); + /** Cloud Storage URI used to store the generated images. */ + @JsonProperty("outputGcsUri") + public abstract Optional outputGcsUri(); + + /** Filter level for safety filtering. */ + @JsonProperty("safetyFilterLevel") + public abstract Optional safetyFilterLevel(); + + /** Allows generation of people by the model. */ + @JsonProperty("personGeneration") + public abstract Optional personGeneration(); + /** Whether to include a reason for filtered-out images in the response. */ @JsonProperty("includeRaiReason") public abstract Optional includeRaiReason(); @@ -46,7 +60,7 @@ public abstract class UpscaleImageConfig extends JsonSerializable { @JsonProperty("outputMimeType") public abstract Optional outputMimeType(); - /** The level of compression if the ``output_mime_type`` is ``image/jpeg``. */ + /** The level of compression. Only applicable if the ``output_mime_type`` is ``image/jpeg``. */ @JsonProperty("outputCompressionQuality") public abstract Optional outputCompressionQuality(); @@ -65,7 +79,12 @@ public abstract class UpscaleImageConfig extends JsonSerializable { @JsonProperty("imagePreservationFactor") public abstract Optional imagePreservationFactor(); + /** User specified labels to track billing usage. */ + @JsonProperty("labels") + public abstract Optional> labels(); + /** Instantiates a builder for UpscaleImageConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_UpscaleImageConfig.Builder(); } @@ -99,6 +118,70 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { return httpOptions(httpOptionsBuilder.build()); } + /** + * Setter for outputGcsUri. + * + *

outputGcsUri: Cloud Storage URI used to store the generated images. + */ + @JsonProperty("outputGcsUri") + public abstract Builder outputGcsUri(String outputGcsUri); + + /** + * Setter for safetyFilterLevel. + * + *

safetyFilterLevel: Filter level for safety filtering. + */ + @JsonProperty("safetyFilterLevel") + public abstract Builder safetyFilterLevel(SafetyFilterLevel safetyFilterLevel); + + /** + * Setter for safetyFilterLevel given a known enum. + * + *

safetyFilterLevel: Filter level for safety filtering. + */ + @CanIgnoreReturnValue + public Builder safetyFilterLevel(SafetyFilterLevel.Known knownType) { + return safetyFilterLevel(new SafetyFilterLevel(knownType)); + } + + /** + * Setter for safetyFilterLevel given a string. + * + *

safetyFilterLevel: Filter level for safety filtering. + */ + @CanIgnoreReturnValue + public Builder safetyFilterLevel(String safetyFilterLevel) { + return safetyFilterLevel(new SafetyFilterLevel(safetyFilterLevel)); + } + + /** + * Setter for personGeneration. + * + *

personGeneration: Allows generation of people by the model. + */ + @JsonProperty("personGeneration") + public abstract Builder personGeneration(PersonGeneration personGeneration); + + /** + * Setter for personGeneration given a known enum. + * + *

personGeneration: Allows generation of people by the model. + */ + @CanIgnoreReturnValue + public Builder personGeneration(PersonGeneration.Known knownType) { + return personGeneration(new PersonGeneration(knownType)); + } + + /** + * Setter for personGeneration given a string. + * + *

personGeneration: Allows generation of people by the model. + */ + @CanIgnoreReturnValue + public Builder personGeneration(String personGeneration) { + return personGeneration(new PersonGeneration(personGeneration)); + } + /** * Setter for includeRaiReason. * @@ -118,8 +201,8 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { /** * Setter for outputCompressionQuality. * - *

outputCompressionQuality: The level of compression if the ``output_mime_type`` is - * ``image/jpeg``. + *

outputCompressionQuality: The level of compression. Only applicable if the + * ``output_mime_type`` is ``image/jpeg``. */ @JsonProperty("outputCompressionQuality") public abstract Builder outputCompressionQuality(Integer outputCompressionQuality); @@ -143,10 +226,19 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { @JsonProperty("imagePreservationFactor") public abstract Builder imagePreservationFactor(Float imagePreservationFactor); + /** + * Setter for labels. + * + *

labels: User specified labels to track billing usage. + */ + @JsonProperty("labels") + public abstract Builder labels(Map labels); + public abstract UpscaleImageConfig build(); } /** Deserializes a JSON string to a UpscaleImageConfig object. */ + @ExcludeFromGeneratedCoverageReport public static UpscaleImageConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, UpscaleImageConfig.class); } diff --git a/src/main/java/com/google/genai/types/UpscaleImageParameters.java b/src/main/java/com/google/genai/types/UpscaleImageParameters.java index e41bb04623c..c3f424829c2 100644 --- a/src/main/java/com/google/genai/types/UpscaleImageParameters.java +++ b/src/main/java/com/google/genai/types/UpscaleImageParameters.java @@ -48,6 +48,7 @@ public abstract class UpscaleImageParameters extends JsonSerializable { public abstract Optional config(); /** Instantiates a builder for UpscaleImageParameters. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_UpscaleImageParameters.Builder(); } @@ -118,6 +119,7 @@ public Builder config(UpscaleImageConfig.Builder configBuilder) { } /** Deserializes a JSON string to a UpscaleImageParameters object. */ + @ExcludeFromGeneratedCoverageReport public static UpscaleImageParameters fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, UpscaleImageParameters.class); } diff --git a/src/main/java/com/google/genai/types/UpscaleImageResponse.java b/src/main/java/com/google/genai/types/UpscaleImageResponse.java index 4178f2669c1..e2ab64e68a1 100644 --- a/src/main/java/com/google/genai/types/UpscaleImageResponse.java +++ b/src/main/java/com/google/genai/types/UpscaleImageResponse.java @@ -33,11 +33,16 @@ @AutoValue @JsonDeserialize(builder = UpscaleImageResponse.Builder.class) public abstract class UpscaleImageResponse extends JsonSerializable { + /** Used to retain the full HTTP response. */ + @JsonProperty("sdkHttpResponse") + public abstract Optional sdkHttpResponse(); + /** Generated images. */ @JsonProperty("generatedImages") public abstract Optional> generatedImages(); /** Instantiates a builder for UpscaleImageResponse. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_UpscaleImageResponse.Builder(); } @@ -54,6 +59,23 @@ private static Builder create() { return new AutoValue_UpscaleImageResponse.Builder(); } + /** + * Setter for sdkHttpResponse. + * + *

sdkHttpResponse: Used to retain the full HTTP response. + */ + @JsonProperty("sdkHttpResponse") + public abstract Builder sdkHttpResponse(HttpResponse sdkHttpResponse); + + /** + * Setter for sdkHttpResponse builder. + * + *

sdkHttpResponse: Used to retain the full HTTP response. + */ + public Builder sdkHttpResponse(HttpResponse.Builder sdkHttpResponseBuilder) { + return sdkHttpResponse(sdkHttpResponseBuilder.build()); + } + /** * Setter for generatedImages. * @@ -87,6 +109,7 @@ public Builder generatedImages(GeneratedImage.Builder... generatedImagesBuilders } /** Deserializes a JSON string to a UpscaleImageResponse object. */ + @ExcludeFromGeneratedCoverageReport public static UpscaleImageResponse fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, UpscaleImageResponse.class); } diff --git a/src/main/java/com/google/genai/types/UrlContext.java b/src/main/java/com/google/genai/types/UrlContext.java index 28e11d9eca7..b7ffd122b32 100644 --- a/src/main/java/com/google/genai/types/UrlContext.java +++ b/src/main/java/com/google/genai/types/UrlContext.java @@ -23,11 +23,12 @@ import com.google.auto.value.AutoValue; import com.google.genai.JsonSerializable; -/** Tool to support URL context retrieval. */ +/** Tool to support URL context. */ @AutoValue @JsonDeserialize(builder = UrlContext.Builder.class) public abstract class UrlContext extends JsonSerializable { /** Instantiates a builder for UrlContext. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_UrlContext.Builder(); } @@ -48,6 +49,7 @@ private static Builder create() { } /** Deserializes a JSON string to a UrlContext object. */ + @ExcludeFromGeneratedCoverageReport public static UrlContext fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, UrlContext.class); } diff --git a/src/main/java/com/google/genai/types/UrlContextMetadata.java b/src/main/java/com/google/genai/types/UrlContextMetadata.java index 386ad9528d4..72b0a85141e 100644 --- a/src/main/java/com/google/genai/types/UrlContextMetadata.java +++ b/src/main/java/com/google/genai/types/UrlContextMetadata.java @@ -33,11 +33,12 @@ @AutoValue @JsonDeserialize(builder = UrlContextMetadata.Builder.class) public abstract class UrlContextMetadata extends JsonSerializable { - /** List of url context. */ + /** Output only. List of url context. */ @JsonProperty("urlMetadata") public abstract Optional> urlMetadata(); /** Instantiates a builder for UrlContextMetadata. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_UrlContextMetadata.Builder(); } @@ -57,7 +58,7 @@ private static Builder create() { /** * Setter for urlMetadata. * - *

urlMetadata: List of url context. + *

urlMetadata: Output only. List of url context. */ @JsonProperty("urlMetadata") public abstract Builder urlMetadata(List urlMetadata); @@ -65,7 +66,7 @@ private static Builder create() { /** * Setter for urlMetadata. * - *

urlMetadata: List of url context. + *

urlMetadata: Output only. List of url context. */ public Builder urlMetadata(UrlMetadata... urlMetadata) { return urlMetadata(Arrays.asList(urlMetadata)); @@ -74,7 +75,7 @@ public Builder urlMetadata(UrlMetadata... urlMetadata) { /** * Setter for urlMetadata builder. * - *

urlMetadata: List of url context. + *

urlMetadata: Output only. List of url context. */ public Builder urlMetadata(UrlMetadata.Builder... urlMetadataBuilders) { return urlMetadata( @@ -87,6 +88,7 @@ public Builder urlMetadata(UrlMetadata.Builder... urlMetadataBuilders) { } /** Deserializes a JSON string to a UrlContextMetadata object. */ + @ExcludeFromGeneratedCoverageReport public static UrlContextMetadata fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, UrlContextMetadata.class); } diff --git a/src/main/java/com/google/genai/types/UrlMetadata.java b/src/main/java/com/google/genai/types/UrlMetadata.java index f4316fbcf23..9c050c2b2aa 100644 --- a/src/main/java/com/google/genai/types/UrlMetadata.java +++ b/src/main/java/com/google/genai/types/UrlMetadata.java @@ -26,11 +26,11 @@ import com.google.genai.JsonSerializable; import java.util.Optional; -/** Context for a single url retrieval. */ +/** Context of the a single url retrieval. */ @AutoValue @JsonDeserialize(builder = UrlMetadata.Builder.class) public abstract class UrlMetadata extends JsonSerializable { - /** The URL retrieved by the tool. */ + /** Retrieved url by the tool. */ @JsonProperty("retrievedUrl") public abstract Optional retrievedUrl(); @@ -39,6 +39,7 @@ public abstract class UrlMetadata extends JsonSerializable { public abstract Optional urlRetrievalStatus(); /** Instantiates a builder for UrlMetadata. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_UrlMetadata.Builder(); } @@ -58,7 +59,7 @@ private static Builder create() { /** * Setter for retrievedUrl. * - *

retrievedUrl: The URL retrieved by the tool. + *

retrievedUrl: Retrieved url by the tool. */ @JsonProperty("retrievedUrl") public abstract Builder retrievedUrl(String retrievedUrl); @@ -95,6 +96,7 @@ public Builder urlRetrievalStatus(String urlRetrievalStatus) { } /** Deserializes a JSON string to a UrlMetadata object. */ + @ExcludeFromGeneratedCoverageReport public static UrlMetadata fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, UrlMetadata.class); } diff --git a/src/main/java/com/google/genai/types/UrlRetrievalStatus.java b/src/main/java/com/google/genai/types/UrlRetrievalStatus.java index 4e59731ae48..8449ac9ec5e 100644 --- a/src/main/java/com/google/genai/types/UrlRetrievalStatus.java +++ b/src/main/java/com/google/genai/types/UrlRetrievalStatus.java @@ -28,14 +28,26 @@ public class UrlRetrievalStatus { /** Enum representing the known values for UrlRetrievalStatus. */ public enum Known { - /** Default value. This value is unused */ + /** Default value. This value is unused. */ URL_RETRIEVAL_STATUS_UNSPECIFIED, /** Url retrieval is successful. */ URL_RETRIEVAL_STATUS_SUCCESS, /** Url retrieval is failed due to error. */ - URL_RETRIEVAL_STATUS_ERROR + URL_RETRIEVAL_STATUS_ERROR, + + /** + * Url retrieval is failed because the content is behind paywall. This enum value is not + * supported in Vertex AI. + */ + URL_RETRIEVAL_STATUS_PAYWALL, + + /** + * Url retrieval is failed because the content is unsafe. This enum value is not supported in + * Vertex AI. + */ + URL_RETRIEVAL_STATUS_UNSAFE } private Known urlRetrievalStatusEnum; @@ -60,12 +72,14 @@ public UrlRetrievalStatus(Known knownValue) { this.value = knownValue.toString(); } + @ExcludeFromGeneratedCoverageReport @Override @JsonValue public String toString() { return this.value; } + @ExcludeFromGeneratedCoverageReport @SuppressWarnings("PatternMatchingInstanceof") @Override public boolean equals(Object o) { @@ -92,6 +106,7 @@ public boolean equals(Object o) { return false; } + @ExcludeFromGeneratedCoverageReport @Override public int hashCode() { if (this.urlRetrievalStatusEnum != Known.URL_RETRIEVAL_STATUS_UNSPECIFIED) { @@ -101,6 +116,7 @@ public int hashCode() { } } + @ExcludeFromGeneratedCoverageReport public Known knownEnum() { return this.urlRetrievalStatusEnum; } diff --git a/src/main/java/com/google/genai/types/UsageMetadata.java b/src/main/java/com/google/genai/types/UsageMetadata.java index c1931eada88..cd5e9fcefad 100644 --- a/src/main/java/com/google/genai/types/UsageMetadata.java +++ b/src/main/java/com/google/genai/types/UsageMetadata.java @@ -85,6 +85,7 @@ public abstract class UsageMetadata extends JsonSerializable { public abstract Optional trafficType(); /** Instantiates a builder for UsageMetadata. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_UsageMetadata.Builder(); } @@ -307,6 +308,7 @@ public Builder trafficType(String trafficType) { } /** Deserializes a JSON string to a UsageMetadata object. */ + @ExcludeFromGeneratedCoverageReport public static UsageMetadata fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, UsageMetadata.class); } diff --git a/src/main/java/com/google/genai/types/VeoHyperParameters.java b/src/main/java/com/google/genai/types/VeoHyperParameters.java new file mode 100644 index 00000000000..a8724f83afe --- /dev/null +++ b/src/main/java/com/google/genai/types/VeoHyperParameters.java @@ -0,0 +1,121 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Auto-generated code. Do not edit. + +package com.google.genai.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.google.api.core.InternalApi; +import com.google.auto.value.AutoValue; +import com.google.errorprone.annotations.CanIgnoreReturnValue; +import com.google.genai.JsonSerializable; +import java.util.Optional; + +/** Hyperparameters for Veo. This data type is not supported in Gemini API. */ +@AutoValue +@InternalApi +@JsonDeserialize(builder = VeoHyperParameters.Builder.class) +public abstract class VeoHyperParameters extends JsonSerializable { + /** + * Optional. Number of complete passes the model makes over the entire training dataset during + * training. + */ + @JsonProperty("epochCount") + public abstract Optional epochCount(); + + /** Optional. Multiplier for adjusting the default learning rate. */ + @JsonProperty("learningRateMultiplier") + public abstract Optional learningRateMultiplier(); + + /** Optional. The tuning task. Either I2V or T2V. */ + @JsonProperty("tuningTask") + public abstract Optional tuningTask(); + + /** Instantiates a builder for VeoHyperParameters. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_VeoHyperParameters.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for VeoHyperParameters. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `VeoHyperParameters.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_VeoHyperParameters.Builder(); + } + + /** + * Setter for epochCount. + * + *

epochCount: Optional. Number of complete passes the model makes over the entire training + * dataset during training. + */ + @JsonProperty("epochCount") + public abstract Builder epochCount(Long epochCount); + + /** + * Setter for learningRateMultiplier. + * + *

learningRateMultiplier: Optional. Multiplier for adjusting the default learning rate. + */ + @JsonProperty("learningRateMultiplier") + public abstract Builder learningRateMultiplier(Double learningRateMultiplier); + + /** + * Setter for tuningTask. + * + *

tuningTask: Optional. The tuning task. Either I2V or T2V. + */ + @JsonProperty("tuningTask") + public abstract Builder tuningTask(TuningTask tuningTask); + + /** + * Setter for tuningTask given a known enum. + * + *

tuningTask: Optional. The tuning task. Either I2V or T2V. + */ + @CanIgnoreReturnValue + public Builder tuningTask(TuningTask.Known knownType) { + return tuningTask(new TuningTask(knownType)); + } + + /** + * Setter for tuningTask given a string. + * + *

tuningTask: Optional. The tuning task. Either I2V or T2V. + */ + @CanIgnoreReturnValue + public Builder tuningTask(String tuningTask) { + return tuningTask(new TuningTask(tuningTask)); + } + + public abstract VeoHyperParameters build(); + } + + /** Deserializes a JSON string to a VeoHyperParameters object. */ + @ExcludeFromGeneratedCoverageReport + public static VeoHyperParameters fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, VeoHyperParameters.class); + } +} diff --git a/src/main/java/com/google/genai/types/VeoTuningSpec.java b/src/main/java/com/google/genai/types/VeoTuningSpec.java new file mode 100644 index 00000000000..fa11280320b --- /dev/null +++ b/src/main/java/com/google/genai/types/VeoTuningSpec.java @@ -0,0 +1,113 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Auto-generated code. Do not edit. + +package com.google.genai.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.google.auto.value.AutoValue; +import com.google.genai.JsonSerializable; +import java.util.Optional; + +/** Tuning Spec for Veo Model Tuning. This data type is not supported in Gemini API. */ +@AutoValue +@JsonDeserialize(builder = VeoTuningSpec.Builder.class) +public abstract class VeoTuningSpec extends JsonSerializable { + /** Optional. Hyperparameters for Veo. */ + @JsonProperty("hyperParameters") + public abstract Optional hyperParameters(); + + /** + * Required. Training dataset used for tuning. The dataset can be specified as either a Cloud + * Storage path to a JSONL file or as the resource name of a Vertex Multimodal Dataset. + */ + @JsonProperty("trainingDatasetUri") + public abstract Optional trainingDatasetUri(); + + /** + * Optional. Validation dataset used for tuning. The dataset can be specified as either a Cloud + * Storage path to a JSONL file or as the resource name of a Vertex Multimodal Dataset. + */ + @JsonProperty("validationDatasetUri") + public abstract Optional validationDatasetUri(); + + /** Instantiates a builder for VeoTuningSpec. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_VeoTuningSpec.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for VeoTuningSpec. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `VeoTuningSpec.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_VeoTuningSpec.Builder(); + } + + /** + * Setter for hyperParameters. + * + *

hyperParameters: Optional. Hyperparameters for Veo. + */ + @JsonProperty("hyperParameters") + public abstract Builder hyperParameters(VeoHyperParameters hyperParameters); + + /** + * Setter for hyperParameters builder. + * + *

hyperParameters: Optional. Hyperparameters for Veo. + */ + public Builder hyperParameters(VeoHyperParameters.Builder hyperParametersBuilder) { + return hyperParameters(hyperParametersBuilder.build()); + } + + /** + * Setter for trainingDatasetUri. + * + *

trainingDatasetUri: Required. Training dataset used for tuning. The dataset can be + * specified as either a Cloud Storage path to a JSONL file or as the resource name of a Vertex + * Multimodal Dataset. + */ + @JsonProperty("trainingDatasetUri") + public abstract Builder trainingDatasetUri(String trainingDatasetUri); + + /** + * Setter for validationDatasetUri. + * + *

validationDatasetUri: Optional. Validation dataset used for tuning. The dataset can be + * specified as either a Cloud Storage path to a JSONL file or as the resource name of a Vertex + * Multimodal Dataset. + */ + @JsonProperty("validationDatasetUri") + public abstract Builder validationDatasetUri(String validationDatasetUri); + + public abstract VeoTuningSpec build(); + } + + /** Deserializes a JSON string to a VeoTuningSpec object. */ + @ExcludeFromGeneratedCoverageReport + public static VeoTuningSpec fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, VeoTuningSpec.class); + } +} diff --git a/src/main/java/com/google/genai/types/VertexAISearch.java b/src/main/java/com/google/genai/types/VertexAISearch.java index f1c8bf213dc..523b0de8bc0 100644 --- a/src/main/java/com/google/genai/types/VertexAISearch.java +++ b/src/main/java/com/google/genai/types/VertexAISearch.java @@ -31,7 +31,8 @@ /** * Retrieve from Vertex AI Search datastore or engine for grounding. datastore and engine are - * mutually exclusive. See https://cloud.google.com/products/agent-builder + * mutually exclusive. See https://cloud.google.com/products/agent-builder. This data type is not + * supported in Gemini API. */ @AutoValue @JsonDeserialize(builder = VertexAISearch.Builder.class) @@ -70,6 +71,7 @@ public abstract class VertexAISearch extends JsonSerializable { public abstract Optional maxResults(); /** Instantiates a builder for VertexAISearch. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_VertexAISearch.Builder(); } @@ -160,6 +162,7 @@ public Builder dataStoreSpecs(VertexAISearchDataStoreSpec.Builder... dataStoreSp } /** Deserializes a JSON string to a VertexAISearch object. */ + @ExcludeFromGeneratedCoverageReport public static VertexAISearch fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, VertexAISearch.class); } diff --git a/src/main/java/com/google/genai/types/VertexAISearchDataStoreSpec.java b/src/main/java/com/google/genai/types/VertexAISearchDataStoreSpec.java index 900a3027d14..fee4afd41c5 100644 --- a/src/main/java/com/google/genai/types/VertexAISearchDataStoreSpec.java +++ b/src/main/java/com/google/genai/types/VertexAISearchDataStoreSpec.java @@ -28,7 +28,8 @@ /** * Define data stores within engine to filter on in a search call and configurations for those data * stores. For more information, see - * https://cloud.google.com/generative-ai-app-builder/docs/reference/rpc/google.cloud.discoveryengine.v1#datastorespec + * https://cloud.google.com/generative-ai-app-builder/docs/reference/rpc/google.cloud.discoveryengine.v1#datastorespec. + * This data type is not supported in Gemini API. */ @AutoValue @JsonDeserialize(builder = VertexAISearchDataStoreSpec.Builder.class) @@ -49,6 +50,7 @@ public abstract class VertexAISearchDataStoreSpec extends JsonSerializable { public abstract Optional filter(); /** Instantiates a builder for VertexAISearchDataStoreSpec. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_VertexAISearchDataStoreSpec.Builder(); } @@ -88,6 +90,7 @@ private static Builder create() { } /** Deserializes a JSON string to a VertexAISearchDataStoreSpec object. */ + @ExcludeFromGeneratedCoverageReport public static VertexAISearchDataStoreSpec fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, VertexAISearchDataStoreSpec.class); } diff --git a/src/main/java/com/google/genai/types/VertexRagStore.java b/src/main/java/com/google/genai/types/VertexRagStore.java index 5ff8e3a532f..c897fcc72a2 100644 --- a/src/main/java/com/google/genai/types/VertexRagStore.java +++ b/src/main/java/com/google/genai/types/VertexRagStore.java @@ -29,7 +29,7 @@ import java.util.List; import java.util.Optional; -/** Retrieve from Vertex RAG Store for grounding. */ +/** Retrieve from Vertex RAG Store for grounding. This data type is not supported in Gemini API. */ @AutoValue @JsonDeserialize(builder = VertexRagStore.Builder.class) public abstract class VertexRagStore extends JsonSerializable { @@ -67,6 +67,7 @@ public abstract class VertexRagStore extends JsonSerializable { public abstract Optional vectorDistanceThreshold(); /** Instantiates a builder for VertexRagStore. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_VertexRagStore.Builder(); } @@ -184,6 +185,7 @@ public Builder ragRetrievalConfig(RagRetrievalConfig.Builder ragRetrievalConfigB } /** Deserializes a JSON string to a VertexRagStore object. */ + @ExcludeFromGeneratedCoverageReport public static VertexRagStore fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, VertexRagStore.class); } diff --git a/src/main/java/com/google/genai/types/VertexRagStoreRagResource.java b/src/main/java/com/google/genai/types/VertexRagStoreRagResource.java index 49c2f81e412..09bb057e5bc 100644 --- a/src/main/java/com/google/genai/types/VertexRagStoreRagResource.java +++ b/src/main/java/com/google/genai/types/VertexRagStoreRagResource.java @@ -27,7 +27,7 @@ import java.util.List; import java.util.Optional; -/** The definition of the Rag resource. */ +/** The definition of the Rag resource. This data type is not supported in Gemini API. */ @AutoValue @JsonDeserialize(builder = VertexRagStoreRagResource.Builder.class) public abstract class VertexRagStoreRagResource extends JsonSerializable { @@ -43,6 +43,7 @@ public abstract class VertexRagStoreRagResource extends JsonSerializable { public abstract Optional> ragFileIds(); /** Instantiates a builder for VertexRagStoreRagResource. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_VertexRagStoreRagResource.Builder(); } @@ -91,6 +92,7 @@ public Builder ragFileIds(String... ragFileIds) { } /** Deserializes a JSON string to a VertexRagStoreRagResource object. */ + @ExcludeFromGeneratedCoverageReport public static VertexRagStoreRagResource fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, VertexRagStoreRagResource.class); } diff --git a/src/main/java/com/google/genai/types/Video.java b/src/main/java/com/google/genai/types/Video.java index 7533629a934..4ffadf5f12d 100644 --- a/src/main/java/com/google/genai/types/Video.java +++ b/src/main/java/com/google/genai/types/Video.java @@ -37,11 +37,12 @@ public abstract class Video extends JsonSerializable { @JsonProperty("videoBytes") public abstract Optional videoBytes(); - /** Video encoding, for example "video/mp4". */ + /** Video encoding, for example ``video/mp4``. */ @JsonProperty("mimeType") public abstract Optional mimeType(); /** Instantiates a builder for Video. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_Video.Builder(); } @@ -77,7 +78,7 @@ private static Builder create() { /** * Setter for mimeType. * - *

mimeType: Video encoding, for example "video/mp4". + *

mimeType: Video encoding, for example ``video/mp4``. */ @JsonProperty("mimeType") public abstract Builder mimeType(String mimeType); @@ -86,6 +87,7 @@ private static Builder create() { } /** Deserializes a JSON string to a Video object. */ + @ExcludeFromGeneratedCoverageReport public static Video fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, Video.class); } diff --git a/src/main/java/com/google/genai/types/VideoCompressionQuality.java b/src/main/java/com/google/genai/types/VideoCompressionQuality.java index b3d9926eccd..dbba4f85789 100644 --- a/src/main/java/com/google/genai/types/VideoCompressionQuality.java +++ b/src/main/java/com/google/genai/types/VideoCompressionQuality.java @@ -62,12 +62,14 @@ public VideoCompressionQuality(Known knownValue) { this.value = knownValue.toString(); } + @ExcludeFromGeneratedCoverageReport @Override @JsonValue public String toString() { return this.value; } + @ExcludeFromGeneratedCoverageReport @SuppressWarnings("PatternMatchingInstanceof") @Override public boolean equals(Object o) { @@ -94,6 +96,7 @@ public boolean equals(Object o) { return false; } + @ExcludeFromGeneratedCoverageReport @Override public int hashCode() { if (this.videoCompressionQualityEnum != Known.VIDEO_COMPRESSION_QUALITY_UNSPECIFIED) { @@ -103,6 +106,7 @@ public int hashCode() { } } + @ExcludeFromGeneratedCoverageReport public Known knownEnum() { return this.videoCompressionQualityEnum; } diff --git a/src/main/java/com/google/genai/types/VideoGenerationMask.java b/src/main/java/com/google/genai/types/VideoGenerationMask.java new file mode 100644 index 00000000000..4a4d21e7f1e --- /dev/null +++ b/src/main/java/com/google/genai/types/VideoGenerationMask.java @@ -0,0 +1,118 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Auto-generated code. Do not edit. + +package com.google.genai.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.google.auto.value.AutoValue; +import com.google.errorprone.annotations.CanIgnoreReturnValue; +import com.google.genai.JsonSerializable; +import java.util.Optional; + +/** A mask for video generation. */ +@AutoValue +@JsonDeserialize(builder = VideoGenerationMask.Builder.class) +public abstract class VideoGenerationMask extends JsonSerializable { + /** The image mask to use for generating videos. */ + @JsonProperty("image") + public abstract Optional image(); + + /** + * Describes how the mask will be used. Inpainting masks must match the aspect ratio of the input + * video. Outpainting masks can be either 9:16 or 16:9. + */ + @JsonProperty("maskMode") + public abstract Optional maskMode(); + + /** Instantiates a builder for VideoGenerationMask. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_VideoGenerationMask.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for VideoGenerationMask. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `VideoGenerationMask.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_VideoGenerationMask.Builder(); + } + + /** + * Setter for image. + * + *

image: The image mask to use for generating videos. + */ + @JsonProperty("image") + public abstract Builder image(Image image); + + /** + * Setter for image builder. + * + *

image: The image mask to use for generating videos. + */ + public Builder image(Image.Builder imageBuilder) { + return image(imageBuilder.build()); + } + + /** + * Setter for maskMode. + * + *

maskMode: Describes how the mask will be used. Inpainting masks must match the aspect + * ratio of the input video. Outpainting masks can be either 9:16 or 16:9. + */ + @JsonProperty("maskMode") + public abstract Builder maskMode(VideoGenerationMaskMode maskMode); + + /** + * Setter for maskMode given a known enum. + * + *

maskMode: Describes how the mask will be used. Inpainting masks must match the aspect + * ratio of the input video. Outpainting masks can be either 9:16 or 16:9. + */ + @CanIgnoreReturnValue + public Builder maskMode(VideoGenerationMaskMode.Known knownType) { + return maskMode(new VideoGenerationMaskMode(knownType)); + } + + /** + * Setter for maskMode given a string. + * + *

maskMode: Describes how the mask will be used. Inpainting masks must match the aspect + * ratio of the input video. Outpainting masks can be either 9:16 or 16:9. + */ + @CanIgnoreReturnValue + public Builder maskMode(String maskMode) { + return maskMode(new VideoGenerationMaskMode(maskMode)); + } + + public abstract VideoGenerationMask build(); + } + + /** Deserializes a JSON string to a VideoGenerationMask object. */ + @ExcludeFromGeneratedCoverageReport + public static VideoGenerationMask fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, VideoGenerationMask.class); + } +} diff --git a/src/main/java/com/google/genai/types/VideoGenerationMaskMode.java b/src/main/java/com/google/genai/types/VideoGenerationMaskMode.java new file mode 100644 index 00000000000..c2c463034e7 --- /dev/null +++ b/src/main/java/com/google/genai/types/VideoGenerationMaskMode.java @@ -0,0 +1,129 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Auto-generated code. Do not edit. + +package com.google.genai.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.google.common.base.Ascii; +import java.util.Objects; + +/** Enum for the mask mode of a video generation mask. */ +public class VideoGenerationMaskMode { + + /** Enum representing the known values for VideoGenerationMaskMode. */ + public enum Known { + /** + * The image mask contains a masked rectangular region which is applied on the first frame of + * the input video. The object described in the prompt is inserted into this region and will + * appear in subsequent frames. + */ + INSERT, + + /** + * The image mask is used to determine an object in the first video frame to track. This object + * is removed from the video. + */ + REMOVE, + + /** + * The image mask is used to determine a region in the video. Objects in this region will be + * removed. + */ + REMOVE_STATIC, + + /** + * The image mask contains a masked rectangular region where the input video will go. The + * remaining area will be generated. Video masks are not supported. + */ + OUTPAINT, + + VIDEO_GENERATION_MASK_MODE_UNSPECIFIED + } + + private Known videoGenerationMaskModeEnum; + private final String value; + + @JsonCreator + public VideoGenerationMaskMode(String value) { + this.value = value; + for (Known videoGenerationMaskModeEnum : Known.values()) { + if (Ascii.equalsIgnoreCase(videoGenerationMaskModeEnum.toString(), value)) { + this.videoGenerationMaskModeEnum = videoGenerationMaskModeEnum; + break; + } + } + if (this.videoGenerationMaskModeEnum == null) { + this.videoGenerationMaskModeEnum = Known.VIDEO_GENERATION_MASK_MODE_UNSPECIFIED; + } + } + + public VideoGenerationMaskMode(Known knownValue) { + this.videoGenerationMaskModeEnum = knownValue; + this.value = knownValue.toString(); + } + + @ExcludeFromGeneratedCoverageReport + @Override + @JsonValue + public String toString() { + return this.value; + } + + @ExcludeFromGeneratedCoverageReport + @SuppressWarnings("PatternMatchingInstanceof") + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null) { + return false; + } + + if (!(o instanceof VideoGenerationMaskMode)) { + return false; + } + + VideoGenerationMaskMode other = (VideoGenerationMaskMode) o; + + if (this.videoGenerationMaskModeEnum != Known.VIDEO_GENERATION_MASK_MODE_UNSPECIFIED + && other.videoGenerationMaskModeEnum != Known.VIDEO_GENERATION_MASK_MODE_UNSPECIFIED) { + return this.videoGenerationMaskModeEnum == other.videoGenerationMaskModeEnum; + } else if (this.videoGenerationMaskModeEnum == Known.VIDEO_GENERATION_MASK_MODE_UNSPECIFIED + && other.videoGenerationMaskModeEnum == Known.VIDEO_GENERATION_MASK_MODE_UNSPECIFIED) { + return this.value.equals(other.value); + } + return false; + } + + @ExcludeFromGeneratedCoverageReport + @Override + public int hashCode() { + if (this.videoGenerationMaskModeEnum != Known.VIDEO_GENERATION_MASK_MODE_UNSPECIFIED) { + return this.videoGenerationMaskModeEnum.hashCode(); + } else { + return Objects.hashCode(this.value); + } + } + + @ExcludeFromGeneratedCoverageReport + public Known knownEnum() { + return this.videoGenerationMaskModeEnum; + } +} diff --git a/src/main/java/com/google/genai/types/VideoGenerationReferenceImage.java b/src/main/java/com/google/genai/types/VideoGenerationReferenceImage.java new file mode 100644 index 00000000000..3f3455281ed --- /dev/null +++ b/src/main/java/com/google/genai/types/VideoGenerationReferenceImage.java @@ -0,0 +1,120 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Auto-generated code. Do not edit. + +package com.google.genai.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.google.auto.value.AutoValue; +import com.google.errorprone.annotations.CanIgnoreReturnValue; +import com.google.genai.JsonSerializable; +import java.util.Optional; + +/** A reference image for video generation. */ +@AutoValue +@JsonDeserialize(builder = VideoGenerationReferenceImage.Builder.class) +public abstract class VideoGenerationReferenceImage extends JsonSerializable { + /** The reference image. */ + @JsonProperty("image") + public abstract Optional image(); + + /** + * The type of the reference image, which defines how the reference image will be used to generate + * the video. + */ + @JsonProperty("referenceType") + public abstract Optional referenceType(); + + /** Instantiates a builder for VideoGenerationReferenceImage. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_VideoGenerationReferenceImage.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for VideoGenerationReferenceImage. */ + @AutoValue.Builder + public abstract static class Builder { + /** + * For internal usage. Please use `VideoGenerationReferenceImage.builder()` for instantiation. + */ + @JsonCreator + private static Builder create() { + return new AutoValue_VideoGenerationReferenceImage.Builder(); + } + + /** + * Setter for image. + * + *

image: The reference image. + */ + @JsonProperty("image") + public abstract Builder image(Image image); + + /** + * Setter for image builder. + * + *

image: The reference image. + */ + public Builder image(Image.Builder imageBuilder) { + return image(imageBuilder.build()); + } + + /** + * Setter for referenceType. + * + *

referenceType: The type of the reference image, which defines how the reference image will + * be used to generate the video. + */ + @JsonProperty("referenceType") + public abstract Builder referenceType(VideoGenerationReferenceType referenceType); + + /** + * Setter for referenceType given a known enum. + * + *

referenceType: The type of the reference image, which defines how the reference image will + * be used to generate the video. + */ + @CanIgnoreReturnValue + public Builder referenceType(VideoGenerationReferenceType.Known knownType) { + return referenceType(new VideoGenerationReferenceType(knownType)); + } + + /** + * Setter for referenceType given a string. + * + *

referenceType: The type of the reference image, which defines how the reference image will + * be used to generate the video. + */ + @CanIgnoreReturnValue + public Builder referenceType(String referenceType) { + return referenceType(new VideoGenerationReferenceType(referenceType)); + } + + public abstract VideoGenerationReferenceImage build(); + } + + /** Deserializes a JSON string to a VideoGenerationReferenceImage object. */ + @ExcludeFromGeneratedCoverageReport + public static VideoGenerationReferenceImage fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, VideoGenerationReferenceImage.class); + } +} diff --git a/src/main/java/com/google/genai/types/VideoGenerationReferenceType.java b/src/main/java/com/google/genai/types/VideoGenerationReferenceType.java new file mode 100644 index 00000000000..edeaa1c5d00 --- /dev/null +++ b/src/main/java/com/google/genai/types/VideoGenerationReferenceType.java @@ -0,0 +1,120 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Auto-generated code. Do not edit. + +package com.google.genai.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.google.common.base.Ascii; +import java.util.Objects; + +/** Enum for the reference type of a video generation reference image. */ +public class VideoGenerationReferenceType { + + /** Enum representing the known values for VideoGenerationReferenceType. */ + public enum Known { + /** + * A reference image that provides assets to the generated video, such as the scene, an object, + * a character, etc. + */ + ASSET, + + /** + * A reference image that provides aesthetics including colors, lighting, texture, etc., to be + * used as the style of the generated video, such as 'anime', 'photography', 'origami', etc. + */ + STYLE, + + VIDEO_GENERATION_REFERENCE_TYPE_UNSPECIFIED + } + + private Known videoGenerationReferenceTypeEnum; + private final String value; + + @JsonCreator + public VideoGenerationReferenceType(String value) { + this.value = value; + for (Known videoGenerationReferenceTypeEnum : Known.values()) { + if (Ascii.equalsIgnoreCase(videoGenerationReferenceTypeEnum.toString(), value)) { + this.videoGenerationReferenceTypeEnum = videoGenerationReferenceTypeEnum; + break; + } + } + if (this.videoGenerationReferenceTypeEnum == null) { + this.videoGenerationReferenceTypeEnum = Known.VIDEO_GENERATION_REFERENCE_TYPE_UNSPECIFIED; + } + } + + public VideoGenerationReferenceType(Known knownValue) { + this.videoGenerationReferenceTypeEnum = knownValue; + this.value = knownValue.toString(); + } + + @ExcludeFromGeneratedCoverageReport + @Override + @JsonValue + public String toString() { + return this.value; + } + + @ExcludeFromGeneratedCoverageReport + @SuppressWarnings("PatternMatchingInstanceof") + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null) { + return false; + } + + if (!(o instanceof VideoGenerationReferenceType)) { + return false; + } + + VideoGenerationReferenceType other = (VideoGenerationReferenceType) o; + + if (this.videoGenerationReferenceTypeEnum != Known.VIDEO_GENERATION_REFERENCE_TYPE_UNSPECIFIED + && other.videoGenerationReferenceTypeEnum + != Known.VIDEO_GENERATION_REFERENCE_TYPE_UNSPECIFIED) { + return this.videoGenerationReferenceTypeEnum == other.videoGenerationReferenceTypeEnum; + } else if (this.videoGenerationReferenceTypeEnum + == Known.VIDEO_GENERATION_REFERENCE_TYPE_UNSPECIFIED + && other.videoGenerationReferenceTypeEnum + == Known.VIDEO_GENERATION_REFERENCE_TYPE_UNSPECIFIED) { + return this.value.equals(other.value); + } + return false; + } + + @ExcludeFromGeneratedCoverageReport + @Override + public int hashCode() { + if (this.videoGenerationReferenceTypeEnum + != Known.VIDEO_GENERATION_REFERENCE_TYPE_UNSPECIFIED) { + return this.videoGenerationReferenceTypeEnum.hashCode(); + } else { + return Objects.hashCode(this.value); + } + } + + @ExcludeFromGeneratedCoverageReport + public Known knownEnum() { + return this.videoGenerationReferenceTypeEnum; + } +} diff --git a/src/main/java/com/google/genai/types/VideoMetadata.java b/src/main/java/com/google/genai/types/VideoMetadata.java index 0dd4b5de014..ecd8be02008 100644 --- a/src/main/java/com/google/genai/types/VideoMetadata.java +++ b/src/main/java/com/google/genai/types/VideoMetadata.java @@ -26,26 +26,27 @@ import java.time.Duration; import java.util.Optional; -/** Describes how the video in the Part should be used by the model. */ +/** Metadata describes the input video content. */ @AutoValue @JsonDeserialize(builder = VideoMetadata.Builder.class) public abstract class VideoMetadata extends JsonSerializable { + /** Optional. The end offset of the video. */ + @JsonProperty("endOffset") + public abstract Optional endOffset(); + /** - * The frame rate of the video sent to the model. If not specified, the default value will be 1.0. - * The fps range is (0.0, 24.0]. + * Optional. The frame rate of the video sent to the model. If not specified, the default value + * will be 1.0. The fps range is (0.0, 24.0]. */ @JsonProperty("fps") public abstract Optional fps(); - /** Optional. The end offset of the video. */ - @JsonProperty("endOffset") - public abstract Optional endOffset(); - /** Optional. The start offset of the video. */ @JsonProperty("startOffset") public abstract Optional startOffset(); /** Instantiates a builder for VideoMetadata. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_VideoMetadata.Builder(); } @@ -62,15 +63,6 @@ private static Builder create() { return new AutoValue_VideoMetadata.Builder(); } - /** - * Setter for fps. - * - *

fps: The frame rate of the video sent to the model. If not specified, the default value - * will be 1.0. The fps range is (0.0, 24.0]. - */ - @JsonProperty("fps") - public abstract Builder fps(Double fps); - /** * Setter for endOffset. * @@ -79,6 +71,15 @@ private static Builder create() { @JsonProperty("endOffset") public abstract Builder endOffset(Duration endOffset); + /** + * Setter for fps. + * + *

fps: Optional. The frame rate of the video sent to the model. If not specified, the + * default value will be 1.0. The fps range is (0.0, 24.0]. + */ + @JsonProperty("fps") + public abstract Builder fps(Double fps); + /** * Setter for startOffset. * @@ -91,6 +92,7 @@ private static Builder create() { } /** Deserializes a JSON string to a VideoMetadata object. */ + @ExcludeFromGeneratedCoverageReport public static VideoMetadata fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, VideoMetadata.class); } diff --git a/src/main/java/com/google/genai/types/VoiceConfig.java b/src/main/java/com/google/genai/types/VoiceConfig.java index 34806ea57e1..883c9658030 100644 --- a/src/main/java/com/google/genai/types/VoiceConfig.java +++ b/src/main/java/com/google/genai/types/VoiceConfig.java @@ -29,11 +29,12 @@ @AutoValue @JsonDeserialize(builder = VoiceConfig.Builder.class) public abstract class VoiceConfig extends JsonSerializable { - /** The configuration for the speaker to use. */ + /** The configuration for the prebuilt voice to use. */ @JsonProperty("prebuiltVoiceConfig") public abstract Optional prebuiltVoiceConfig(); /** Instantiates a builder for VoiceConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_VoiceConfig.Builder(); } @@ -53,7 +54,7 @@ private static Builder create() { /** * Setter for prebuiltVoiceConfig. * - *

prebuiltVoiceConfig: The configuration for the speaker to use. + *

prebuiltVoiceConfig: The configuration for the prebuilt voice to use. */ @JsonProperty("prebuiltVoiceConfig") public abstract Builder prebuiltVoiceConfig(PrebuiltVoiceConfig prebuiltVoiceConfig); @@ -61,7 +62,7 @@ private static Builder create() { /** * Setter for prebuiltVoiceConfig builder. * - *

prebuiltVoiceConfig: The configuration for the speaker to use. + *

prebuiltVoiceConfig: The configuration for the prebuilt voice to use. */ public Builder prebuiltVoiceConfig(PrebuiltVoiceConfig.Builder prebuiltVoiceConfigBuilder) { return prebuiltVoiceConfig(prebuiltVoiceConfigBuilder.build()); @@ -71,6 +72,7 @@ public Builder prebuiltVoiceConfig(PrebuiltVoiceConfig.Builder prebuiltVoiceConf } /** Deserializes a JSON string to a VoiceConfig object. */ + @ExcludeFromGeneratedCoverageReport public static VoiceConfig fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, VoiceConfig.class); } diff --git a/src/main/proto/sentencepiece_model.proto b/src/main/proto/sentencepiece_model.proto new file mode 100644 index 00000000000..6632ac23105 --- /dev/null +++ b/src/main/proto/sentencepiece_model.proto @@ -0,0 +1,334 @@ +// 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. + +syntax = "proto2"; + +// TODO(taku): Needs to use LITE RUNTIME in OSS release. +option optimize_for = LITE_RUNTIME; + +package com.google.genai.proto; + +option java_package = "com.google.genai.proto"; + +// TrainerSpec encodes a various parameters for SentencePiece training. +// Next id: 55 +message TrainerSpec { + /////////////////////////////////////////////////////////////////// + // General parameters + // + // Input corpus files. + // Trainer accepts the following two formats: + // A) Monolingual: plain text, one sentence per line. + // B) Bilingual: TSV, source sentence target sentence + // When bilingual data is passed, shared vocabulary model is built. + // Note that the input file must be raw corpus, not a preprocessed corpus. + // Trainer only loads the first `input_sentence_size` sentences specified + // with this parameter. + repeated string input = 1; + + // Input corpus format: + // "text": one-sentence-per-line text format (default) + // "tsv": sentence freq + optional string input_format = 7; + + // Output model file prefix. + // .model and .vocab are generated. + optional string model_prefix = 2; + + // Model type. only have UNIGRAM now. + enum ModelType { + UNIGRAM = 1; // Unigram language model with dynamic algorithm + BPE = 2; // Byte Pair Encoding + WORD = 3; // Delimitered by whitespace. + CHAR = 4; // tokenizes into character sequence + } + optional ModelType model_type = 3 [default = UNIGRAM]; + + // Vocabulary size. 8k is the default size. + optional int32 vocab_size = 4 [default = 8000]; + + // List of the languages this model can accept. + // Since the model is language-agnostic, this field is used as a reference. + repeated string accept_language = 5; + + // Size of self-test samples, which are encoded in the model file. + optional int32 self_test_sample_size = 6 [default = 0]; + + // Whether to use DP version of sentencepiece. Use it with TSV input format + // (requires precomputed word tab counts to work). + optional bool enable_differential_privacy = 50 [default = false]; + // Set these parameters if you need DP version of sentencepiece. + // std of noise to add. + optional float differential_privacy_noise_level = 51 [default = 0.0]; + // Clipping threshold to apply after adding noise. All the words with + // frequency less than this value are dropped. + optional uint64 differential_privacy_clipping_threshold = 52 [default = 0]; + + /////////////////////////////////////////////////////////////////// + // Training parameters. + // + // Uses characters which cover the corpus with the ratio of `chars_coverage`. + // This parameter determines the set of basic Alphabet of sentence piece. + // 1.0 - `chars_coverage` characters are treated as UNK. + // See also required_chars field. + optional float character_coverage = 10 [default = 0.9995]; + + // Maximum size of sentences the trainer loads from `input` parameter. + // Trainer simply loads the `input` files in sequence. + // It is better to shuffle the input corpus randomly. + optional uint64 input_sentence_size = 11 [default = 0]; + optional bool shuffle_input_sentence = 19 [default = true]; + + // Maximum size of sentences to make seed sentence pieces. + // Extended suffix array is constructed to extract frequent + // sub-strings from the corpus. This uses 20N working space, + // where N is the size of corpus. + optional int32 mining_sentence_size = 12 [deprecated = true]; + + // Maximum size of sentences to train sentence pieces. + optional int32 training_sentence_size = 13 [deprecated = true]; + + // The size of seed sentencepieces. + // `seed_sentencepiece_size` must be larger than `vocab_size`. + optional int32 seed_sentencepiece_size = 14 [default = 1000000]; + + // In every EM sub-iterations, keeps top + // `shrinking_factor` * `current sentencepieces size` with respect to + // the loss of the sentence piece. This value should be smaller than 1.0. + optional float shrinking_factor = 15 [default = 0.75]; + + // The maximum sentence length in byte. The sentences with the length + // larger than `max_sentence_length` is simply ignored. + // Longer input tends to bring the following risks: + // * Overflow during EM training (unigram language model only) + // * Performance drop because of O(n log n) cost in BPE. + optional int32 max_sentence_length = 18 [default = 4192]; + + // Number of threads in the training. + optional int32 num_threads = 16 [default = 16]; + + // Number of EM sub iterations. + optional int32 num_sub_iterations = 17 [default = 2]; + + /////////////////////////////////////////////////////////////////// + // SentencePiece parameters which control the shapes of sentence piece. + // + // Maximum length of sentencepiece. + optional int32 max_sentencepiece_length = 20 [default = 16]; + + // Uses Unicode script to split sentence pieces. + // When `split_by_unicode_script` is true, we do not allow sentence piece to + // include multiple Unicode scripts, e.g. "F1" is not a valid piece. + // Exception: CJ characters (Hiragana/Katakana/Han) are all handled + // as one script type, since Japanese word can consist of multiple scripts. + // This exception is always applied regardless of the accept-language + // parameter. + optional bool split_by_unicode_script = 21 [default = true]; + + // When `split_by_number` is true, put a boundary between number and + // non-number transition. If we want to treat "F1" is one token, set this flag + // to be false. + optional bool split_by_number = 23 [default = true]; + + // Use a white space to split sentence pieces. + // When `split_by_whitespace` is false, we may have the piece containing + // a white space in the middle. e.g., "in_the". + optional bool split_by_whitespace = 22 [default = true]; + + // Adds whitespace symbol (_) as a suffix instead of prefix. e.g., _hello => + // hello_. When `treat_whitespace_as_suffix` is true, + // NormalizerSpec::add_dummy_prefix will add the dummy whitespace to the end + // of sentence. + optional bool treat_whitespace_as_suffix = 24 [default = false]; + + // Allows pieces that only contain whitespaces instead of appearing only as + // prefix or suffix of other pieces. + optional bool allow_whitespace_only_pieces = 26 [default = false]; + + // Split all digits (0-9) into separate pieces. + optional bool split_digits = 25 [default = false]; + + // Defines the pre-tokenization delimiter. + // When specified, no pieces crossing this delimiter is not included + // in the vocab. Then the delimiter string is virtually ignored + // during the training. This field can allows constraints on the vocabulary + // selection. Note that this field is available on unigram mode. + optional string pretokenization_delimiter = 53 [ default = ""]; + + /////////////////////////////////////////////////////////////////// + // Vocabulary management + // + // Defines control symbols used as an indicator to + // change the behavior of the decoder. and are pre-defined. + // We can use this field to encode various meta information, + // including language indicator in multilingual model. + // These symbols are not visible to users, but visible to + // the decoder. Note that when the input sentence contains control symbols, + // they are not treated as one token, but segmented into normal pieces. + // Control symbols must be inserted independently from the segmentation. + repeated string control_symbols = 30; + + // Defines user defined symbols. + // These symbols are added with extremely high score + // so they are always treated as one unique symbol in any context. + // Typical usage of user_defined_symbols is placeholder for named entities. + repeated string user_defined_symbols = 31; + + // Defines required characters. Each UTF8 character in this string is included + // in the character set regardless of character_coverage value. Unlike + // user_defined_symbols, these characters have scores based on the frequency + // on input sentences, and the model can form subwords using characters + // in this field. + optional string required_chars = 36; + + // Decomposes unknown pieces into UTF-8 bytes. + optional bool byte_fallback = 35 [default = false]; + + // When creating the vocabulary file, defines whether or not to additionally + // output the score for each piece. + optional bool vocabulary_output_piece_score = 32 [default = true]; + + // `vocab_size` is treated as hard limit. Crash if + // the model can not produce the vocab of size `vocab_size`, + // When `hard_vocab_limit` is false, vocab_size is treated + // as soft limit. Note that when model_type=char, + // always assumes hard_vocab_limit = false. + optional bool hard_vocab_limit = 33 [default = true]; + + // use all symbols for vocab extraction. This flag is valid + // if model type is either CHAR or WORD + optional bool use_all_vocab = 34 [default = false]; + + /////////////////////////////////////////////////////////////////// + // Reserved special meta tokens. + // * -1 is not used. + // * unk_id must not be -1. + // Id must starts with 0 and be contiguous. + optional int32 unk_id = 40 [default = 0]; // + optional int32 bos_id = 41 [default = 1]; // + optional int32 eos_id = 42 [default = 2]; // + optional int32 pad_id = 43 [default = -1]; // (padding) + optional string unk_piece = 45 [default = ""]; + optional string bos_piece = 46 [default = ""]; + optional string eos_piece = 47 [default = ""]; + optional string pad_piece = 48 [default = ""]; + + // Encodes into U+2047 (DOUBLE QUESTION MARK), + // since this character can be useful both for user and + // developer. We can easily figure out that is emitted. + optional string unk_surface = 44 [default = " \xE2\x81\x87 "]; + + // Increase bit depth to allow unigram model training on large + // (>10M sentences) corpora. A Side-effect of enabling this flag + // is increased memory usage. + optional bool train_extremely_large_corpus = 49 [default = false]; + + // Path to a seed sentencepieces file, with one tab-separated + // seed sentencepiece frequency per line. + optional string seed_sentencepieces_file = 54 [default = ""]; + + // Customized extensions: the range of field numbers + // are open to third-party extensions. + extensions 200 to max; +} + +// NormalizerSpec encodes a various parameters for string normalization +message NormalizerSpec { + // name of normalization rule. + optional string name = 1; + + // Pre-compiled normalization rule created by + // Builder::GetPrecompiledCharsMap() or Builder::CompileCharsMap() method. + // Usually this field is set by Builder::GetNormalizerSpec() method. + optional bytes precompiled_charsmap = 2; + + // Adds dummy whitespace at the beginning of text in order to + // treat "world" in "world" and "hello world" in the same way. + optional bool add_dummy_prefix = 3 [default = true]; + + // Removes leading, trailing, and duplicate internal whitespace. + optional bool remove_extra_whitespaces = 4 [default = true]; + + // Replaces whitespace with meta symbol. + // This field must be true to train sentence piece model. + optional bool escape_whitespaces = 5 [default = true]; + + // Custom normalization rule file in TSV format. + // https://github.com/google/sentencepiece/blob/master/doc/normalization.md + // This field is only used in SentencePieceTrainer::Train() method, which + // compiles the rule into the binary rule stored in `precompiled_charsmap`. + optional string normalization_rule_tsv = 6; + + // Customized extensions: the range of field numbers + // are open to third-party extensions. + extensions 200 to max; +} + +// Proto to store samples for self-testing. +message SelfTestData { + message Sample { + optional string input = 1; + optional string expected = 2; + } + repeated Sample samples = 1; + + // Customized extensions: the range of field numbers + // are open to third-party extensions. + extensions 200 to max; +} + +// ModelProto stores model parameters. +// SentencePieceProcessor is supposed to be self-contained. +// All settings/parameters which may change the behavior must be encoded +// in ModelProto. +message ModelProto { + message SentencePiece { + enum Type { + NORMAL = 1; // normal symbol + UNKNOWN = 2; // unknown symbol. only for now. + CONTROL = 3; // control symbols. , , <2ja> etc. + USER_DEFINED = 4; // user defined symbols. + // Typical usage of USER_DEFINED symbol + // is placeholder. + BYTE = 6; // byte symbols. Used when `byte_fallback` is true. + UNUSED = 5; // this piece is not used. + } + optional string piece = 1; // piece must not be empty. + optional float score = 2; + optional Type type = 3 [default = NORMAL]; + + // Customized extensions: the range of field numbers + // are open to third-party extensions. + extensions 200 to max; + } + + // Sentence pieces with scores. + repeated SentencePiece pieces = 1; + + // Spec used to generate this model file. + optional TrainerSpec trainer_spec = 2; + + // Spec for text normalization. + optional NormalizerSpec normalizer_spec = 3; + + // Stores sample input and its expected segmentation to verify the model. + optional SelfTestData self_test_data = 4; + + // Spec for text de-normalization. + optional NormalizerSpec denormalizer_spec = 5; + + // Customized extensions: the range of field numbers + // are open to third-party extensions. + extensions 200 to max; +} diff --git a/src/test/java/com/google/genai/AsyncBatchesTest.java b/src/test/java/com/google/genai/AsyncBatchesTest.java index 4b92c61cb07..dbe25369280 100644 --- a/src/test/java/com/google/genai/AsyncBatchesTest.java +++ b/src/test/java/com/google/genai/AsyncBatchesTest.java @@ -21,6 +21,8 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; import com.google.genai.errors.GenAiIOException; import com.google.genai.types.BatchJob; import com.google.genai.types.BatchJobDestination; @@ -28,9 +30,14 @@ import com.google.genai.types.Content; import com.google.genai.types.CreateBatchJobConfig; import com.google.genai.types.DeleteResourceJob; +import com.google.genai.types.GenerateContentConfig; +import com.google.genai.types.HarmBlockThreshold; +import com.google.genai.types.HarmCategory; import com.google.genai.types.InlinedRequest; import com.google.genai.types.ListBatchJobsConfig; import com.google.genai.types.Part; +import com.google.genai.types.SafetySetting; +import java.util.List; import java.util.concurrent.ExecutionException; import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; import org.junit.jupiter.api.extension.ExtendWith; @@ -96,15 +103,13 @@ public void testAsyncCreateWithBigquery(boolean vertexAI) assertNotNull(batchJob); assertTrue(batchJob.name().get().startsWith("projects/")); } else { - ExecutionException exception = + GenAiIOException exception = assertThrows( - ExecutionException.class, + GenAiIOException.class, () -> client.async.batches.create("gemini-1.5-flash-002", bqInput, config).get()); // Assert - assertTrue(exception.getCause() instanceof GenAiIOException); - assertEquals( - exception.getCause().getMessage(), "One of fileName and InlinedRequests must be set."); + assertEquals(exception.getMessage(), "one of fileName and InlinedRequests must be set."); } } @@ -122,14 +127,13 @@ public void testAsyncCreateWithFile(boolean vertexAI) // Act if (vertexAI) { - ExecutionException exception = + GenAiIOException exception = assertThrows( - ExecutionException.class, + GenAiIOException.class, () -> client.async.batches.create("gemini-2.0-flash", src, config).get()); // Assert - assertTrue(exception.getCause() instanceof GenAiIOException); - assertEquals(exception.getCause().getMessage(), "fileName is not supported for Vertex AI."); + assertEquals(exception.getMessage(), "fileName is not supported for Vertex AI."); } else { BatchJob batchJob = client.async.batches.create("gemini-2.0-flash", src, config).get(); @@ -172,15 +176,13 @@ public void testAsyncCreateWithGcs(boolean vertexAI) assertNotNull(batchJob); assertTrue(batchJob.name().get().startsWith("projects/")); } else { - ExecutionException exception = + GenAiIOException exception = assertThrows( - ExecutionException.class, + GenAiIOException.class, () -> client.async.batches.create("gemini-1.5-flash-002", src, config).get()); // Assert - assertTrue(exception.getCause() instanceof GenAiIOException); - assertEquals( - exception.getCause().getMessage(), "One of fileName and InlinedRequests must be set."); + assertEquals(exception.getMessage(), "one of fileName and InlinedRequests must be set."); } } @@ -195,29 +197,36 @@ public void testAsyncCreateWithInlinedRequests(boolean vertexAI) vertexAI, "tests/batches/create_with_inlined_requests/test_async_create." + suffix + ".json"); + List safetySettings = + ImmutableList.of( + (SafetySetting.builder() + .category(new HarmCategory("HARM_CATEGORY_HATE_SPEECH")) + .threshold(new HarmBlockThreshold("BLOCK_ONLY_HIGH")) + .build()), + (SafetySetting.builder() + .category(new HarmCategory("HARM_CATEGORY_DANGEROUS_CONTENT")) + .threshold(new HarmBlockThreshold("BLOCK_LOW_AND_ABOVE")) + .build())); BatchJobSource src = BatchJobSource.builder() .inlinedRequests( InlinedRequest.builder() - .contents(Content.builder().parts(Part.fromText("Hello!")).role("user"))) + .contents(Content.builder().parts(Part.fromText("Hello!")).role("user")) + .metadata(ImmutableMap.of("key", "request-1")) + .config(GenerateContentConfig.builder().safetySettings(safetySettings))) .build(); // Act if (vertexAI) { - ExecutionException exception = + GenAiIOException exception = assertThrows( - ExecutionException.class, - () -> client.async.batches.create("gemini-1.5-flash-002", src, null).get()); + GenAiIOException.class, + () -> client.async.batches.create("gemini-2.5-flash-lite", src, null).get()); // Assert - assertTrue(exception.getCause() instanceof GenAiIOException); - assertTrue( - exception - .getCause() - .getMessage() - .equals("inlinedRequests is not supported for Vertex AI.")); + assertTrue(exception.getMessage().equals("inlinedRequests is not supported for Vertex AI.")); } else { - BatchJob batchJob = client.async.batches.create("gemini-1.5-flash-002", src, null).get(); + BatchJob batchJob = client.async.batches.create("gemini-2.5-flash-lite", src, null).get(); // Assert assertNotNull(batchJob); @@ -278,5 +287,6 @@ public void testAsyncList(boolean vertexAI) throws ExecutionException, Interrupt assertNotNull(pager); assertEquals(pager.pageSize().get(), 10); pager.page().get().forEach(item -> assertNotNull(item)); + assertNotNull(pager.sdkHttpResponse().get().get().headers().get()); } } diff --git a/src/test/java/com/google/genai/AsyncCachesTest.java b/src/test/java/com/google/genai/AsyncCachesTest.java index 7fce66c3cb4..d5793eeb7ce 100644 --- a/src/test/java/com/google/genai/AsyncCachesTest.java +++ b/src/test/java/com/google/genai/AsyncCachesTest.java @@ -138,6 +138,7 @@ public void testAsyncListCachedContents(boolean vertexAI) assertEquals(pager.pageSize().get(), 2); assertTrue(pager.size().get() <= 2); pager.forEach(item -> assertNotNull(item)).get(); + assertNotNull(pager.sdkHttpResponse().get().get().headers().get()); } @ParameterizedTest diff --git a/src/test/java/com/google/genai/AsyncChatTest.java b/src/test/java/com/google/genai/AsyncChatTest.java index 40163a1b46d..91c6ba9304d 100644 --- a/src/test/java/com/google/genai/AsyncChatTest.java +++ b/src/test/java/com/google/genai/AsyncChatTest.java @@ -113,8 +113,8 @@ public class AsyncChatTest { void setUp() { mockedClient = Mockito.mock(ApiClient.class); mockedResponse = Mockito.mock(ApiResponse.class); - when(mockedClient.request(anyString(), anyString(), anyString(), any())) - .thenReturn(mockedResponse); + when(mockedClient.asyncRequest(anyString(), anyString(), anyString(), any())) + .thenReturn(CompletableFuture.completedFuture(mockedResponse)); String apiKey = Optional.ofNullable(ApiClient.getApiKeyFromEnv()).orElse("api-key"); client = Client.builder().apiKey(apiKey).vertexAI(false).build(); @@ -154,8 +154,10 @@ public void testGetAsyncChatMessage() throws Exception { when(mockedResponse1.getBody()).thenReturn(content1); when(mockedResponse2.getBody()).thenReturn(content2); - when(mockedClient.request(anyString(), anyString(), anyString(), any())) - .thenReturn(mockedResponse1, mockedResponse2); + when(mockedClient.asyncRequest(anyString(), anyString(), anyString(), any())) + .thenReturn( + CompletableFuture.completedFuture(mockedResponse1), + CompletableFuture.completedFuture(mockedResponse2)); AsyncChat chat = client.async.chats.create("gemini-2.0-flash-exp", null); @@ -187,8 +189,10 @@ public void testGetHistoryAsync() throws Exception { when(mockedResponse1.getBody()).thenReturn(content1); when(mockedResponse2.getBody()).thenReturn(content2); - when(mockedClient.request(anyString(), anyString(), anyString(), any())) - .thenReturn(mockedResponse1, mockedResponse2); + when(mockedClient.asyncRequest(anyString(), anyString(), anyString(), any())) + .thenReturn( + CompletableFuture.completedFuture(mockedResponse1), + CompletableFuture.completedFuture(mockedResponse2)); AsyncChat chat = client.async.chats.create("gemini-2.0-flash-exp", null); @@ -220,8 +224,11 @@ public void testIterateOverAsyncResponseStream() throws Exception { when(mockedResponse1.getBody()).thenReturn(body1); when(mockedResponse2.getBody()).thenReturn(body2); when(mockedResponse3.getBody()).thenReturn(body3); - when(mockedClient.request(anyString(), anyString(), anyString(), any())) - .thenReturn(mockedResponse1, mockedResponse2, mockedResponse3); + when(mockedClient.asyncRequest(anyString(), anyString(), anyString(), any())) + .thenReturn( + CompletableFuture.completedFuture(mockedResponse1), + CompletableFuture.completedFuture(mockedResponse2), + CompletableFuture.completedFuture(mockedResponse3)); assert chatSession.getHistory(false).isEmpty(); @@ -297,12 +304,14 @@ public void testThrowsIfAsyncStreamResponseIsNotConsumed() throws Exception { ResponseBody body2 = ResponseBody.create(streamData2, MediaType.get("application/json")); when(mockedResponse1.getBody()).thenReturn(body1); when(mockedResponse2.getBody()).thenReturn(body2); - when(mockedClient.request(anyString(), anyString(), anyString(), any())) - .thenReturn(mockedResponse1, mockedResponse2); + when(mockedClient.asyncRequest(anyString(), anyString(), anyString(), any())) + .thenReturn( + CompletableFuture.completedFuture(mockedResponse1), + CompletableFuture.completedFuture(mockedResponse2)); assert chatSession.getHistory(false).isEmpty(); - ResponseStream responseStreamFuture = + ResponseStream responseStream = chatSession.sendMessageStream("Tell me a story.", null).join(); IllegalStateException exception = diff --git a/src/test/java/com/google/genai/AsyncFilesTest.java b/src/test/java/com/google/genai/AsyncFilesTest.java index f21d1e64e1d..19b989ed827 100644 --- a/src/test/java/com/google/genai/AsyncFilesTest.java +++ b/src/test/java/com/google/genai/AsyncFilesTest.java @@ -46,15 +46,14 @@ public void testAsyncGetFile(boolean vertexAI) throws ExecutionException, Interr // Act if (vertexAI) { - ExecutionException exception = + UnsupportedOperationException exception = assertThrows( - ExecutionException.class, () -> client.async.files.get(fileName, null).get()); + UnsupportedOperationException.class, + () -> client.async.files.get(fileName, null).get()); // Assert assertEquals( - "This method is only supported in the Gemini Developer client.", - exception.getCause().getMessage()); - assertTrue(exception.getCause() instanceof UnsupportedOperationException); + "This method is only supported in the Gemini Developer client.", exception.getMessage()); } else { File file = client.async.files.get(fileName, null).get(); @@ -75,13 +74,10 @@ public void testAsyncListFiles(boolean vertexAI) throws ExecutionException, Inte // Act if (vertexAI) { - AsyncPager pager = client.async.files.list(config).get(); - // Assert ExecutionException exception = - assertThrows( - ExecutionException.class, () -> pager.forEach(file -> assertNotNull(file)).get()); - assertTrue(exception.getCause() instanceof GenAiIOException); + assertThrows(ExecutionException.class, () -> client.async.files.list(config).get()); + assertTrue(exception.getCause() instanceof UnsupportedOperationException); assertTrue( exception .getCause() @@ -95,6 +91,7 @@ public void testAsyncListFiles(boolean vertexAI) throws ExecutionException, Inte assertEquals(pager.pageSize().get(), 2); assertTrue(pager.size().get() <= 2); pager.forEach(item -> assertNotNull(item)).get(); + assertNotNull(pager.sdkHttpResponse().get().get().headers().get()); } } diff --git a/src/test/java/com/google/genai/AsyncModelsTest.java b/src/test/java/com/google/genai/AsyncModelsTest.java index 75747d2139c..0f8cfdcd76f 100644 --- a/src/test/java/com/google/genai/AsyncModelsTest.java +++ b/src/test/java/com/google/genai/AsyncModelsTest.java @@ -47,10 +47,12 @@ import com.google.genai.types.MaskReferenceImage; import com.google.genai.types.Model; import com.google.genai.types.Part; +import com.google.genai.types.PersonGeneration; import com.google.genai.types.RagRetrievalConfig; import com.google.genai.types.RagRetrievalConfigFilter; import com.google.genai.types.RawReferenceImage; import com.google.genai.types.Retrieval; +import com.google.genai.types.SafetyFilterLevel; import com.google.genai.types.Tool; import com.google.genai.types.ToolCodeExecution; import com.google.genai.types.UpdateModelConfig; @@ -138,6 +140,7 @@ public void testListModelsAsync(boolean vertexAI) throws Exception { assertEquals(pager.pageSize().get(), 10); assertTrue(pager.size().get() <= 10); pager.forEach(item -> assertNotNull(item)).get(); + assertNotNull(pager.sdkHttpResponse().get().get().headers().get()); } @ParameterizedTest @@ -160,6 +163,7 @@ public void testListTunedModelsAsync(boolean vertexAI) throws Exception { // Assert assertEquals(10, pager.size().get()); pager.forEach(item -> assertNotNull(item)).get(); + assertNotNull(pager.sdkHttpResponse().get().get().headers().get()); } @ParameterizedTest @@ -433,6 +437,7 @@ public void testEditImage_withMaskReferenceAsync(boolean vertexAI) throws Except .outputCompressionQuality(80) .baseSteps(32) .addWatermark(false) + .labels(ImmutableMap.of("imagen_label_key", "edit_image")) .build(); // Act @@ -448,9 +453,9 @@ public void testEditImage_withMaskReferenceAsync(boolean vertexAI) throws Except // Assert assertTrue(response.generatedImages().get().get(0).image().isPresent()); } else { - CompletionException exception = + UnsupportedOperationException exception = assertThrows( - CompletionException.class, + UnsupportedOperationException.class, () -> client .async @@ -463,8 +468,7 @@ public void testEditImage_withMaskReferenceAsync(boolean vertexAI) throws Except .join()); // Assert assertEquals( - "This method is only supported in the Vertex AI client.", - exception.getCause().getMessage()); + "This method is only supported in the Vertex AI client.", exception.getMessage()); } } @@ -624,24 +628,27 @@ public void testUpscaleImageAsync(boolean vertexAI) throws Exception { UpscaleImageConfig config = UpscaleImageConfig.builder() .includeRaiReason(true) + .safetyFilterLevel(SafetyFilterLevel.Known.BLOCK_LOW_AND_ABOVE) + .personGeneration(PersonGeneration.Known.ALLOW_ADULT) .outputMimeType("image/jpeg") .outputCompressionQuality(80) .enhanceInputImage(true) .imagePreservationFactor(0.6f) + .labels(ImmutableMap.of("imagen_label_key", "upscale_image")) .build(); // Act if (vertexAI) { CompletableFuture responseFuture = - client.async.models.upscaleImage("imagen-3.0-generate-001", image, "x2", config); + client.async.models.upscaleImage("imagen-3.0-generate-002", image, "x2", config); UpscaleImageResponse response = responseFuture.join(); // Assert assertTrue(response.generatedImages().get().get(0).image().isPresent()); } else { - CompletionException exception = + UnsupportedOperationException exception = assertThrows( - CompletionException.class, + UnsupportedOperationException.class, () -> client .async @@ -650,8 +657,7 @@ public void testUpscaleImageAsync(boolean vertexAI) throws Exception { .join()); // Assert assertEquals( - "This method is only supported in the Vertex AI client.", - exception.getCause().getMessage()); + "This method is only supported in the Vertex AI client.", exception.getMessage()); } } @@ -666,14 +672,17 @@ public void testGenerateVideosAsync(boolean vertexAI) throws Exception { GenerateVideosConfig.Builder configBuilder = GenerateVideosConfig.builder(); if (vertexAI) { - configBuilder.outputGcsUri("gs://unified-genai-tests/tmp/genai/video/outputs"); + configBuilder.outputGcsUri("gs://genai-sdk-tests/temp/videos/"); } GenerateVideosConfig config = configBuilder.build(); // Act CompletableFuture responseFuture = client.async.models.generateVideos( - "veo-2.0-generate-001", "A neon hologram of a cat driving at top speed", null, config); + "veo-3.1-generate-preview", + "A neon hologram of a cat driving at top speed", + null, + config); GenerateVideosOperation operation = responseFuture.join(); // Assert diff --git a/src/test/java/com/google/genai/AsyncOperationsTest.java b/src/test/java/com/google/genai/AsyncOperationsTest.java index 65ef52139b1..6ebb21f1dcd 100644 --- a/src/test/java/com/google/genai/AsyncOperationsTest.java +++ b/src/test/java/com/google/genai/AsyncOperationsTest.java @@ -46,8 +46,8 @@ public void testAsyncGetVideosOperation(boolean vertexAI) String operationName = vertexAI - ? "projects//locations//publishers/google/models/veo-2.0-generate-001/operations/ddb46542-07ed-4000-958d-655fbffb05a4" - : "models/veo-2.0-generate-001/operations/ren0ubieaocs"; + ? "projects//locations//publishers/google/models/veo-3.1-generate-preview/operations/6a55ba83-558a-4b29-9999-325b1eb218cf" + : "models/veo-3.1-generate-preview/operations/9jwcbmi5tkvw"; // Act GenerateVideosOperation generateVideosOperation = @@ -89,11 +89,11 @@ public void testTextToVideoPollAsync(boolean vertexAI) vertexAI, "tests/models/generate_videos/test_text_to_video_poll_async." + suffix + ".json"); - String model = "veo-2.0-generate-001"; + String model = "veo-3.1-generate-preview"; String prompt = "A neon hologram of a cat driving at top speed"; GenerateVideosConfig.Builder configBuilder = GenerateVideosConfig.builder(); if (vertexAI) { - configBuilder.outputGcsUri("gs://unified-genai-tests/tmp/genai/video/outputs"); + configBuilder.outputGcsUri("gs://genai-sdk-tests/temp/videos/"); } GenerateVideosConfig config = configBuilder.build(); diff --git a/src/test/java/com/google/genai/AsyncTuningsTest.java b/src/test/java/com/google/genai/AsyncTuningsTest.java index 1ea204c169e..51b691e87d2 100644 --- a/src/test/java/com/google/genai/AsyncTuningsTest.java +++ b/src/test/java/com/google/genai/AsyncTuningsTest.java @@ -20,6 +20,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; +import com.google.genai.types.CreateTuningJobConfig; import com.google.genai.types.JobState; import com.google.genai.types.ListTuningJobsConfig; import com.google.genai.types.TuningDataset; @@ -51,6 +52,7 @@ public void testAsyncPager(boolean vertexAI) throws ExecutionException, Interrup assertNotNull(pager); assertEquals(pager.pageSize().get(), 2); pager.forEach(item -> assertNotNull(item)).get(); + assertNotNull(pager.sdkHttpResponse().get().get().headers().get()); } @ParameterizedTest @@ -94,7 +96,9 @@ public void testTuneUntilSuccess(boolean vertexAI) .gcsUri( "gs://cloud-samples-data/ai-platform/generative_ai/gemini-2_0/text/sft_train_data.jsonl") .build(); - TuningJob job = client.async.tunings.tune("gemini-2.0-flash-001", tuningDataset, null).get(); + CreateTuningJobConfig tuningConfig = CreateTuningJobConfig.builder().epochCount(1).build(); + TuningJob job = + client.async.tunings.tune("gemini-2.0-flash-001", tuningDataset, tuningConfig).get(); // Act TuningJob currentJob = job; @@ -112,4 +116,76 @@ public void testTuneUntilSuccess(boolean vertexAI) assertNotNull(currentJob); assertTrue(currentJob.state().get().knownEnum() == JobState.Known.JOB_STATE_SUCCEEDED); } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + public void testContinuousTuning(boolean vertexAI) + throws ExecutionException, InterruptedException { + if (!vertexAI) { // MLDev test removed, tune not supported anymore + return; + } + + // Arrange + String suffix = vertexAI ? "vertex" : "mldev"; + Client client = + TestUtils.createClient( + vertexAI, "tests/tunings/end_to_end/test_continuous_tuning." + suffix + ".json"); + + TuningDataset tuningDataset = + TuningDataset.builder() + .gcsUri( + "gs://cloud-samples-data/ai-platform/generative_ai/gemini-2_0/text/sft_train_data.jsonl") + .build(); + CreateTuningJobConfig tuningConfig = CreateTuningJobConfig.builder().epochCount(1).build(); + TuningJob job = + client.async.tunings.tune("gemini-2.5-flash", tuningDataset, tuningConfig).get(); + + // Act + TuningJob currentJob = job; + JobState.Known state = job.state().get().knownEnum(); + + // Needed to go through the running + pending tuning job states. + while (state != JobState.Known.JOB_STATE_SUCCEEDED + && state != JobState.Known.JOB_STATE_FAILED + && state != JobState.Known.JOB_STATE_CANCELLED) { + currentJob = client.async.tunings.get(currentJob.name().get(), null).get(); + state = currentJob.state().get().knownEnum(); + } + + // Assert + assertNotNull(currentJob); + assertTrue(currentJob.state().get().knownEnum() == JobState.Known.JOB_STATE_SUCCEEDED); + + // Arrange + CreateTuningJobConfig continuousTuningConfig = + CreateTuningJobConfig.builder() + .tunedModelDisplayName("continuous tuning job") + .epochCount(1) + .build(); + TuningJob continuousJob = + client + .async + .tunings + .tune( + currentJob.tunedModel().get().model().get(), tuningDataset, continuousTuningConfig) + .get(); + + // Act + TuningJob currentContinuousJob = continuousJob; + JobState.Known continuousState = continuousJob.state().get().knownEnum(); + + // Needed to go through the running + pending tuning job states. + while (continuousState != JobState.Known.JOB_STATE_SUCCEEDED + && continuousState != JobState.Known.JOB_STATE_FAILED + && continuousState != JobState.Known.JOB_STATE_CANCELLED) { + currentContinuousJob = + client.async.tunings.get(currentContinuousJob.name().get(), null).get(); + continuousState = currentContinuousJob.state().get().knownEnum(); + } + + // Assert + assertNotNull(currentContinuousJob); + assertTrue( + currentContinuousJob.state().get().knownEnum() == JobState.Known.JOB_STATE_SUCCEEDED); + } } diff --git a/src/test/java/com/google/genai/CommonTest.java b/src/test/java/com/google/genai/CommonTest.java index 1f01e67915a..f0156761da0 100644 --- a/src/test/java/com/google/genai/CommonTest.java +++ b/src/test/java/com/google/genai/CommonTest.java @@ -25,7 +25,9 @@ import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import java.util.Arrays; +import java.util.HashMap; import java.util.List; +import java.util.Map; import org.junit.jupiter.api.Test; public class CommonTest { @@ -72,6 +74,19 @@ public void testSetValueByPath_firstArrayElement() { assertEquals("v4", data.get("a").get("b").get(0).get("c").asText()); } + @Test + public void testSetValueByPath_selfKey() { + ObjectNode data = JsonSerializable.objectMapper.createObjectNode(); + data.putObject("a").putObject("b"); + ObjectNode value = JsonSerializable.objectMapper.createObjectNode(); + value.put("c", "v"); + Common.setValueByPath(data, new String[] {"_self"}, value); + + // expected output: {a: {b: {}}, c: "v"} + assertEquals("", data.get("a").get("b").asText()); + assertEquals("v", data.get("c").asText()); + } + @Test public void testGetValueByPath_simpleObject() { ObjectNode data = JsonSerializable.objectMapper.createObjectNode(); @@ -194,4 +209,128 @@ public void testIsZero_otherObject() { assertFalse(Common.isZero("test")); assertFalse(Common.isZero(new Object())); } + + @Test + public void testMoveValueByPath_docstringExample() { + // Test the exact example from the moveValueByPath docstring + // Input: {'requests': [{'content': v1}, {'content': v2}]} + // Path: {'requests[].*': 'requests[].request.*'} + // Output: {'requests': [{'request': {'content': v1}}, {'request': {'content': v2}}]} + + ObjectNode data = JsonSerializable.objectMapper.createObjectNode(); + ArrayNode requests = data.putArray("requests"); + + // Add first request with content + ObjectNode request1 = requests.addObject(); + request1.put("content", "v1"); + + // Add second request with content + ObjectNode request2 = requests.addObject(); + request2.put("content", "v2"); + + // Define the paths to move + Map paths = new HashMap<>(); + paths.put("requests[].*", "requests[].request.*"); + + // Execute the move operation + Common.moveValueByPath(data, paths); + + // Verify the result + ArrayNode resultRequests = (ArrayNode) data.get("requests"); + + // Check first request + ObjectNode resultRequest1 = (ObjectNode) resultRequests.get(0); + ObjectNode resultRequest1Inner = (ObjectNode) resultRequest1.get("request"); + assertEquals("v1", resultRequest1Inner.get("content").asText()); + assertNull(resultRequest1.get("content")); // Should be moved to request.content + + // Check second request + ObjectNode resultRequest2 = (ObjectNode) resultRequests.get(1); + ObjectNode resultRequest2Inner = (ObjectNode) resultRequest2.get("request"); + assertEquals("v2", resultRequest2Inner.get("content").asText()); + assertNull(resultRequest2.get("content")); // Should be moved to request.content + } + + @Test + public void testMoveValueByPath() { + // Create test data structure + ObjectNode data = JsonSerializable.objectMapper.createObjectNode(); + ArrayNode requests = data.putArray("requests"); + + // First request + ObjectNode request1 = requests.addObject(); + ObjectNode request1Inner = request1.putObject("request"); + ObjectNode content1 = request1Inner.putObject("content"); + ArrayNode parts1 = content1.putArray("parts"); + parts1.addObject().put("text", "1"); + request1.put("outputDimensionality", 64); + + // Second request + ObjectNode request2 = requests.addObject(); + ObjectNode request2Inner = request2.putObject("request"); + ObjectNode content2 = request2Inner.putObject("content"); + ArrayNode parts2 = content2.putArray("parts"); + parts2.addObject().put("text", "2"); + request2.put("outputDimensionality", 64); + + // Third request + ObjectNode request3 = requests.addObject(); + ObjectNode request3Inner = request3.putObject("request"); + ObjectNode content3 = request3Inner.putObject("content"); + ArrayNode parts3 = content3.putArray("parts"); + parts3.addObject().put("text", "3"); + request3.put("outputDimensionality", 64); + + // Define the paths to move + Map paths = new HashMap<>(); + paths.put("requests[].*", "requests[].request.*"); + + // Execute the move operation + Common.moveValueByPath(data, paths); + + // Verify the result + ArrayNode resultRequests = (ArrayNode) data.get("requests"); + + // Check first request + ObjectNode resultRequest1 = (ObjectNode) resultRequests.get(0); + ObjectNode resultRequest1Inner = (ObjectNode) resultRequest1.get("request"); + assertEquals( + "1", + resultRequest1Inner + .get("content") + .get("parts") + .get(0) + .get("text") + .asText()); + assertEquals(64, resultRequest1Inner.get("outputDimensionality").asInt()); + assertNull(resultRequest1.get("outputDimensionality")); // Should be moved + + // Check second request + ObjectNode resultRequest2 = (ObjectNode) resultRequests.get(1); + ObjectNode resultRequest2Inner = (ObjectNode) resultRequest2.get("request"); + assertEquals( + "2", + resultRequest2Inner + .get("content") + .get("parts") + .get(0) + .get("text") + .asText()); + assertEquals(64, resultRequest2Inner.get("outputDimensionality").asInt()); + assertNull(resultRequest2.get("outputDimensionality")); // Should be moved + + // Check third request + ObjectNode resultRequest3 = (ObjectNode) resultRequests.get(2); + ObjectNode resultRequest3Inner = (ObjectNode) resultRequest3.get("request"); + assertEquals( + "3", + resultRequest3Inner + .get("content") + .get("parts") + .get(0) + .get("text") + .asText()); + assertEquals(64, resultRequest3Inner.get("outputDimensionality").asInt()); + assertNull(resultRequest3.get("outputDimensionality")); // Should be moved + } } diff --git a/src/test/java/com/google/genai/FakeUploadApiClient.java b/src/test/java/com/google/genai/FakeUploadApiClient.java index 7956eb2fbe0..662a80bf3b6 100644 --- a/src/test/java/com/google/genai/FakeUploadApiClient.java +++ b/src/test/java/com/google/genai/FakeUploadApiClient.java @@ -22,14 +22,12 @@ import java.util.HashMap; import java.util.Map; import java.util.Optional; +import java.util.concurrent.CompletableFuture; import okhttp3.Headers; import okhttp3.MediaType; -import okhttp3.Protocol; -import okhttp3.Request; -import okhttp3.Response; import okhttp3.ResponseBody; -/** */ +/** A fake client for testing File upload requests. */ public final class FakeUploadApiClient extends ApiClient { public final Map files; @@ -116,6 +114,26 @@ public ApiResponse request( ResponseBody.create("", MediaType.get("text/plain"))); } + /** + * Sends an asynchronous Http request given the http method, path, request json string, and http + * options. + */ + @Override + public CompletableFuture asyncRequest( + String httpMethod, String path, String requestJson, Optional httpOptions) { + throw new UnsupportedOperationException("Not implemented yet."); + } + + /** + * Sends an asynchronous Http request given the http method, path, request bytes, and http + * options. + */ + @Override + public CompletableFuture asyncRequest( + String httpMethod, String path, byte[] requestBytes, Optional httpOptions) { + return CompletableFuture.completedFuture(request(httpMethod, path, requestBytes, httpOptions)); + } + public class UploadedFile { public int uploadedByteCount; public ArrayList uploadedBytes; diff --git a/src/test/java/com/google/genai/HttpApiClientTest.java b/src/test/java/com/google/genai/HttpApiClientTest.java index 9a065cb909a..d76a3d7958e 100644 --- a/src/test/java/com/google/genai/HttpApiClientTest.java +++ b/src/test/java/com/google/genai/HttpApiClientTest.java @@ -16,11 +16,6 @@ package com.google.genai; -import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; -import static com.github.tomakehurst.wiremock.client.WireMock.post; -import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; -import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; -import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -28,23 +23,27 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import com.github.tomakehurst.wiremock.WireMockServer; -import com.github.tomakehurst.wiremock.client.WireMock; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; import com.google.auth.oauth2.AccessToken; import com.google.auth.oauth2.GoogleCredentials; import com.google.common.collect.ImmutableMap; -import com.google.genai.types.Candidate; +import com.google.genai.errors.GenAiIOException; import com.google.genai.types.ClientOptions; -import com.google.genai.types.Content; -import com.google.genai.types.GenerateContentResponse; import com.google.genai.types.HttpOptions; -import com.google.genai.types.Part; +import com.google.genai.types.HttpRetryOptions; +import java.io.IOException; import java.lang.reflect.Field; +import java.util.Map; import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; import okhttp3.Call; +import okhttp3.Callback; import okhttp3.Dispatcher; import okhttp3.OkHttpClient; import okhttp3.Protocol; @@ -214,6 +213,233 @@ public void testRequestWithHttpOptions() throws Exception { assertEquals("header", capturedRequest.header("test")); } + @Test + public void testRequestWithHttpOptions_extraBody_addNewKey() throws Exception { + // Arrange + HttpApiClient client = + new HttpApiClient(Optional.of(API_KEY), Optional.empty(), Optional.empty()); + setMockClient(client); + HttpOptions httpOptions = + HttpOptions.builder().extraBody(ImmutableMap.of("newKey", "newValue")).build(); + + // Act + client.request("POST", TEST_PATH, TEST_REQUEST_JSON, Optional.of(httpOptions)); + + // Assert + ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(Request.class); + verify(mockHttpClient).newCall(requestCaptor.capture()); + Request capturedRequest = requestCaptor.getValue(); + + RequestBody body = capturedRequest.body(); + assertNotNull(body); + final Buffer buffer = new Buffer(); + body.writeTo(buffer); + String requestBody = buffer.readUtf8(); + + Map expectedMap = + ImmutableMap.of("test", "request-json", "newKey", "newValue"); + ObjectMapper mapper = new ObjectMapper(); + Map actualMap = mapper.readValue(requestBody, new TypeReference>() {}); + + assertEquals(expectedMap, actualMap); + } + + @Test + public void testRequestWithHttpOptions_extraBody_overwriteKey() throws Exception { + // Arrange + HttpApiClient client = + new HttpApiClient(Optional.of(API_KEY), Optional.empty(), Optional.empty()); + setMockClient(client); + HttpOptions httpOptions = + HttpOptions.builder().extraBody(ImmutableMap.of("test", "overwritten")).build(); + + // Act + client.request("POST", TEST_PATH, TEST_REQUEST_JSON, Optional.of(httpOptions)); + + // Assert + ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(Request.class); + verify(mockHttpClient).newCall(requestCaptor.capture()); + Request capturedRequest = requestCaptor.getValue(); + + RequestBody body = capturedRequest.body(); + assertNotNull(body); + final Buffer buffer = new Buffer(); + body.writeTo(buffer); + String requestBody = buffer.readUtf8(); + + Map expectedMap = ImmutableMap.of("test", "overwritten"); + ObjectMapper mapper = new ObjectMapper(); + Map actualMap = mapper.readValue(requestBody, new TypeReference>() {}); + + assertEquals(expectedMap, actualMap); + } + + @Test + public void testRequestWithHttpOptions_extraBody_recursiveMerge() throws Exception { + // Arrange + HttpApiClient client = + new HttpApiClient(Optional.of(API_KEY), Optional.empty(), Optional.empty()); + setMockClient(client); + String initialJson = "{\"nested\": {\"key1\": \"value1\"}, \"key_to_keep\": \"v_keep\"}"; + HttpOptions httpOptions = + HttpOptions.builder() + .extraBody(ImmutableMap.of("nested", ImmutableMap.of("key2", "value2"))) + .build(); + + // Act + client.request("POST", TEST_PATH, initialJson, Optional.of(httpOptions)); + + // Assert + ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(Request.class); + verify(mockHttpClient).newCall(requestCaptor.capture()); + Request capturedRequest = requestCaptor.getValue(); + + RequestBody body = capturedRequest.body(); + assertNotNull(body); + final Buffer buffer = new Buffer(); + body.writeTo(buffer); + String requestBody = buffer.readUtf8(); + + Map expectedMap = + ImmutableMap.of( + "nested", ImmutableMap.of("key1", "value1", "key2", "value2"), + "key_to_keep", + "v_keep"); + ObjectMapper mapper = new ObjectMapper(); + Map actualMap = mapper.readValue(requestBody, new TypeReference>() {}); + assertEquals(expectedMap, actualMap); + } + + @Test + public void testRequestWithHttpOptions_extraBody_overwriteList() throws Exception { + // Arrange + HttpApiClient client = + new HttpApiClient(Optional.of(API_KEY), Optional.empty(), Optional.empty()); + setMockClient(client); + String initialJson = "{\"list\": [1, 2]}"; + HttpOptions httpOptions = + HttpOptions.builder() + .extraBody(ImmutableMap.of("list", com.google.common.collect.ImmutableList.of(3, 4))) + .build(); + + // Act + client.request("POST", TEST_PATH, initialJson, Optional.of(httpOptions)); + + // Assert + ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(Request.class); + verify(mockHttpClient).newCall(requestCaptor.capture()); + Request capturedRequest = requestCaptor.getValue(); + + RequestBody body = capturedRequest.body(); + assertNotNull(body); + final Buffer buffer = new Buffer(); + body.writeTo(buffer); + String requestBody = buffer.readUtf8(); + + Map expectedMap = + ImmutableMap.of("list", com.google.common.collect.ImmutableList.of(3, 4)); + ObjectMapper mapper = new ObjectMapper(); + Map actualMap = mapper.readValue(requestBody, new TypeReference>() {}); + assertEquals(expectedMap, actualMap); + } + + @Test + public void testRequestWithHttpOptions_extraBody_overwriteWithDifferentType() throws Exception { + // Arrange + HttpApiClient client = + new HttpApiClient(Optional.of(API_KEY), Optional.empty(), Optional.empty()); + setMockClient(client); + String initialJson = "{\"key\": \"string_value\"}"; + HttpOptions httpOptions = HttpOptions.builder().extraBody(ImmutableMap.of("key", 123)).build(); + + // Act + client.request("POST", TEST_PATH, initialJson, Optional.of(httpOptions)); + + // Assert + ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(Request.class); + verify(mockHttpClient).newCall(requestCaptor.capture()); + Request capturedRequest = requestCaptor.getValue(); + + RequestBody body = capturedRequest.body(); + assertNotNull(body); + final Buffer buffer = new Buffer(); + body.writeTo(buffer); + String requestBody = buffer.readUtf8(); + + Map expectedMap = ImmutableMap.of("key", 123); + ObjectMapper mapper = new ObjectMapper(); + Map actualMap = mapper.readValue(requestBody, new TypeReference>() {}); + + assertEquals(expectedMap, actualMap); + } + + @Test + public void testRequestWithHttpOptions_extraBody_complexMerge() throws Exception { + // Arrange + HttpApiClient client = + new HttpApiClient(Optional.of(API_KEY), Optional.empty(), Optional.empty()); + setMockClient(client); + String initialJson = + "{\"a\": 1, \"b\": {\"c\": 2, \"d\": [\"x\", \"y\"]}, \"e\": \"original\"}"; + HttpOptions httpOptions = + HttpOptions.builder() + .extraBody( + ImmutableMap.of( + "b", + ImmutableMap.of( + "d", com.google.common.collect.ImmutableList.of("z"), "f", "new_f"), + "e", + "overwritten")) + .build(); + + // Act + client.request("POST", TEST_PATH, initialJson, Optional.of(httpOptions)); + + // Assert + ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(Request.class); + verify(mockHttpClient).newCall(requestCaptor.capture()); + Request capturedRequest = requestCaptor.getValue(); + + RequestBody body = capturedRequest.body(); + assertNotNull(body); + final Buffer buffer = new Buffer(); + body.writeTo(buffer); + String requestBody = buffer.readUtf8(); + + Map expectedMap = + ImmutableMap.of( + "a", + 1, + "b", + ImmutableMap.of( + "c", 2, "d", com.google.common.collect.ImmutableList.of("z"), "f", "new_f"), + "e", + "overwritten"); + ObjectMapper mapper = new ObjectMapper(); + Map actualMap = mapper.readValue(requestBody, new TypeReference>() {}); + assertEquals(expectedMap, actualMap); + } + + @Test + public void testRequestWithHttpOptions_extraBody_getNoBody() throws Exception { + // Arrange + HttpApiClient client = + new HttpApiClient(Optional.of(API_KEY), Optional.empty(), Optional.empty()); + setMockClient(client); + HttpOptions httpOptions = + HttpOptions.builder().extraBody(ImmutableMap.of("newKey", "newValue")).build(); + + // Act + client.request("GET", TEST_PATH, "", Optional.of(httpOptions)); + + // Assert + ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(Request.class); + verify(mockHttpClient).newCall(requestCaptor.capture()); + Request capturedRequest = requestCaptor.getValue(); + + assertNull(capturedRequest.body()); + } + @Test public void testRequestWithInvalidHttpMethod() throws Exception { // Arrange @@ -226,6 +452,95 @@ public void testRequestWithInvalidHttpMethod() throws Exception { () -> client.request("INVALID_METHOD", TEST_PATH, TEST_REQUEST_JSON, Optional.empty())); } + @Test + public void testAsyncRequest_Success() throws Exception { + // Arrange + HttpApiClient client = + new HttpApiClient( + Optional.empty(), + Optional.of(PROJECT), + Optional.of(LOCATION), + Optional.of(CREDENTIALS), + Optional.empty(), + Optional.empty()); + setMockClient(client); + + String responseJson = "{\"fake\":\"response\"}"; + Response mockResponse = + new Response.Builder() + .request(new Request.Builder().url("https://example.com").build()) + .protocol(Protocol.HTTP_1_1) + .code(200) + .message("OK") + .body(ResponseBody.create(responseJson, null)) + .build(); + + // Capture the Callback passed to enqueue + ArgumentCaptor callbackCaptor = ArgumentCaptor.forClass(Callback.class); + doNothing().when(mockCall).enqueue(callbackCaptor.capture()); + + // Act + CompletableFuture future = + client.asyncRequest("POST", TEST_PATH, TEST_REQUEST_JSON, Optional.empty()); + + // Assert (Request was built correctly) + ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(Request.class); + verify(mockHttpClient).newCall(requestCaptor.capture()); + Request capturedRequest = requestCaptor.getValue(); + assertEquals("POST", capturedRequest.method()); + assertTrue(capturedRequest.url().toString().endsWith(TEST_PATH)); + + // Act (Simulate the async response) + Callback callback = callbackCaptor.getValue(); + callback.onResponse(mockCall, mockResponse); + + // Assert (Future completed successfully) + assertFalse(future.isCompletedExceptionally()); + assertNotNull(future.get()); + assertEquals(responseJson, future.get().getBody().string()); + } + + @Test + public void testAsyncRequest_Failure() throws Exception { + // Arrange + HttpApiClient client = + new HttpApiClient(Optional.of(API_KEY), Optional.empty(), Optional.empty()); + setMockClient(client); + + IOException networkError = new IOException("Fake network error"); + + // Capture the Callback passed to enqueue + ArgumentCaptor callbackCaptor = ArgumentCaptor.forClass(Callback.class); + doNothing().when(mockCall).enqueue(callbackCaptor.capture()); + + // Act + CompletableFuture future = + client.asyncRequest("GET", TEST_PATH, "", Optional.empty()); + + // Assert (Request was built) + verify(mockHttpClient).newCall(any(Request.class)); + + // Act (Simulate the async failure) + Callback callback = callbackCaptor.getValue(); + callback.onFailure(mockCall, networkError); + + // Assert (Future completed exceptionally) + assertTrue(future.isCompletedExceptionally()); + + // Check that the exception was wrapped in GenAiIOException + Exception ex = + assertThrows( + ExecutionException.class, + () -> future.get(), + "Expected CompletableFuture.get() to throw ExecutionException"); + + Throwable cause = ex.getCause(); + assertNotNull(cause); + assertEquals(GenAiIOException.class, cause.getClass()); + assertEquals("Failed to execute HTTP request.", cause.getMessage()); + assertEquals(networkError, cause.getCause()); + } + @Test public void testInitHttpClientMldev() throws Exception { HttpOptions httpOptions = @@ -320,24 +635,6 @@ public void testInitHttpClientVertexWithApiKey() throws Exception { assertEquals(Optional.of("https://aiplatform.googleapis.com"), client.httpOptions.baseUrl()); } - @Test - public void testInitHttpClientVertexWithNoApiKeyAndNoProject_throwsException() throws Exception { - IllegalArgumentException exception = - assertThrows( - IllegalArgumentException.class, - () -> - new HttpApiClient( - Optional.empty(), - Optional.empty(), - Optional.of(LOCATION), - Optional.empty(), - Optional.empty(), - Optional.empty())); - assertEquals( - "For Vertex AI APIs, either project/location or API key must be set.", - exception.getMessage()); - } - @Test public void testInitHttpClientWithCustomCredentialsAndApiKey_throwsException() throws Exception { GoogleCredentials credentials = Mockito.mock(GoogleCredentials.class); @@ -513,20 +810,20 @@ public void testInitHttpClientVertexApiKeyCombo3(MockedStatic mockedS } @Test - public void testHttpClientVertexWithNoApiKeyAndNoLocation_throwsException() throws Exception { + public void testHttpClientVertexWithNoApiKeyProject_throwsException() throws Exception { IllegalArgumentException exception = assertThrows( IllegalArgumentException.class, () -> new HttpApiClient( Optional.empty(), - Optional.of(PROJECT), + Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty())); assertEquals( - "For Vertex AI APIs, either project/location or API key must be set.", + "For Vertex AI APIs, either project or API key must be set.", exception.getMessage()); } @@ -635,6 +932,50 @@ public void testHttpClientVertexNoTimeout() throws Exception { assertFalse(client.httpOptions.headers().get().containsKey("X-Server-Timeout")); } + @Test + public void testHttpClientMldevWithRetryOptions() throws Exception { + HttpRetryOptions retryOptions = + HttpRetryOptions.builder().attempts(3).httpStatusCodes(400, 404).build(); + HttpOptions httpOptions = HttpOptions.builder().retryOptions(retryOptions).build(); + HttpApiClient client = + new HttpApiClient(Optional.of(API_KEY), Optional.of(httpOptions), Optional.empty()); + + RetryInterceptor retryInterceptor = + (RetryInterceptor) client.httpClient().interceptors().get(0); + assertEquals(retryOptions, retryInterceptor.retryOptions()); + } + + @Test + public void testHttpClientMldevWithNoRetryOptions() throws Exception { + HttpApiClient client = + new HttpApiClient(Optional.of(API_KEY), Optional.empty(), Optional.empty()); + + // If no retry options are specified, An empty retry options should be used. + RetryInterceptor retryInterceptor = + (RetryInterceptor) client.httpClient().interceptors().get(0); + assertEquals(HttpRetryOptions.builder().build(), retryInterceptor.retryOptions()); + } + + @Test + public void testHttpClientVertexWithRequestLevelRetryOptions() throws Exception { + HttpRetryOptions retryOptions = + HttpRetryOptions.builder().attempts(3).httpStatusCodes(400, 404).build(); + HttpOptions requestHttpOptions = HttpOptions.builder().retryOptions(retryOptions).build(); + HttpApiClient client = + new HttpApiClient( + Optional.empty(), + Optional.of(PROJECT), + Optional.of(LOCATION), + Optional.of(CREDENTIALS), + Optional.empty(), + Optional.empty()); + + Request request = + client.buildRequest("POST", "path", "requestJson", Optional.of(requestHttpOptions)); + + assertEquals(retryOptions, request.tag(HttpRetryOptions.class)); + } + @Test public void testHttpClientMldevCustomClientOptions() throws Exception { ClientOptions clientOptions = @@ -747,44 +1088,6 @@ public void testHttpClientMLDevWithNoHttpOptions() throws Exception { assertFalse(client.httpOptions.headers().get().containsKey("X-Server-Timeout")); } - @Test - public void testProxySetup() throws Exception { - WireMockServer wireMockServer = null; - try { - wireMockServer = new WireMockServer(options().dynamicPort()); - wireMockServer.start(); - WireMock.configureFor("localhost", wireMockServer.port()); - String expectedText = "This is Proxy speaking, Hello, World!"; - Part part = Part.builder().text(expectedText).build(); - Content content = Content.fromParts(part); - Candidate candidate = Candidate.builder().content(content).build(); - GenerateContentResponse fakeResponse = - GenerateContentResponse.builder().candidates(candidate).build(); - stubFor( - post(urlMatching(".*")) - .willReturn( - aResponse() - .withStatus(200) - .withHeader("Content-Type", "application/json") - .withBody(fakeResponse.toJson()))); - - HttpOptions httpOptions = - HttpOptions.builder() - .baseUrl("http://localhost:" + wireMockServer.port()) - .apiVersion("v1beta") - .build(); - Client client = - Client.builder().apiKey(API_KEY).vertexAI(false).httpOptions(httpOptions).build(); - - GenerateContentResponse response = - client.models.generateContent("gemini-2.0-flash", "What is your name?", null); - - assertEquals(response.text(), expectedText); - } finally { - wireMockServer.stop(); - } - } - @Test public void testClientInitializationWithBaseUrlFromHttpOptions() throws Exception { HttpOptions httpOptions = @@ -889,4 +1192,151 @@ public void testVertexClientInitializationWithBaseUrlFromEnvironment( assertTrue(client.baseUrl().isPresent()); assertEquals(client.baseUrl().get(), "https://custom-base-url.googleapis.com/"); } + + @Test + public void testDefaultLocationToGlobalWhenOnlyProjectIsProvided( + MockedStatic mockedStaticApiClient) throws Exception { + mockedStaticApiClient + .when(ApiClient::defaultEnvironmentVariables) + .thenReturn(ImmutableMap.of("googleApiKey", "env-api-key")); + HttpApiClient client = + new HttpApiClient( + Optional.empty(), + Optional.of("fake-project-id"), + Optional.empty(), + Optional.of(CREDENTIALS), + Optional.empty(), + Optional.empty()); + + assertEquals("fake-project-id", client.project()); + assertEquals("global", client.location()); + assertNull(client.apiKey()); + assertTrue(client.vertexAI()); + } + + @Test + public void testDefaultLocationToGlobalWhenCredentialsProvidedWithProjectButNoLocation( + MockedStatic mockedStaticApiClient) throws Exception { + mockedStaticApiClient + .when(ApiClient::defaultEnvironmentVariables) + .thenReturn(ImmutableMap.of("googleApiKey", "env-api-key")); + HttpApiClient client = + new HttpApiClient( + Optional.empty(), + Optional.of("fake-project-id"), + Optional.empty(), + Optional.of(CREDENTIALS), + Optional.empty(), + Optional.empty()); + + assertEquals("fake-project-id", client.project()); + assertEquals("global", client.location()); + assertNull(client.apiKey()); + assertTrue(client.vertexAI()); + } + + @Test + public void testDefaultLocationToGlobalWhenExplicitProjectTakesPrecedenceOverEnvApiKey( + MockedStatic mockedStaticApiClient) throws Exception { + mockedStaticApiClient + .when(ApiClient::defaultEnvironmentVariables) + .thenReturn(ImmutableMap.of("googleApiKey", "env-api-key")); + HttpApiClient client = + new HttpApiClient( + Optional.empty(), + Optional.of("explicit-project-id"), + Optional.empty(), + Optional.of(CREDENTIALS), + Optional.empty(), + Optional.empty()); + + assertEquals("explicit-project-id", client.project()); + assertEquals("global", client.location()); + assertNull(client.apiKey()); + assertTrue(client.vertexAI()); + } + + @Test + public void testDefaultLocationToGlobalWhenEnvProjectTakesPrecedenceOverEnvApiKey( + MockedStatic mockedStaticApiClient) throws Exception { + mockedStaticApiClient + .when(ApiClient::defaultEnvironmentVariables) + .thenReturn( + ImmutableMap.of("googleApiKey", "env-api-key", "project", "env-project-id")); + HttpApiClient client = + new HttpApiClient( + Optional.empty(), + Optional.empty(), + Optional.empty(), + Optional.of(CREDENTIALS), + Optional.empty(), + Optional.empty()); + + assertEquals("env-project-id", client.project()); + assertEquals("global", client.location()); + assertNull(client.apiKey()); + assertTrue(client.vertexAI()); + } + + @Test + public void testNoDefaultLocationToGlobalWhenExplicitLocationIsSet( + MockedStatic mockedStaticApiClient) throws Exception { + mockedStaticApiClient + .when(ApiClient::defaultEnvironmentVariables) + .thenReturn(ImmutableMap.of()); + HttpApiClient client = + new HttpApiClient( + Optional.empty(), + Optional.of("fake-project-id"), + Optional.of("us-central1"), + Optional.of(CREDENTIALS), + Optional.empty(), + Optional.empty()); + + assertEquals("fake-project-id", client.project()); + assertEquals("us-central1", client.location()); + assertTrue(client.vertexAI()); + } + + @Test + public void testNoDefaultLocationToGlobalWhenEnvLocationIsSet( + MockedStatic mockedStaticApiClient) throws Exception { + mockedStaticApiClient + .when(ApiClient::defaultEnvironmentVariables) + .thenReturn( + ImmutableMap.of("project", "fake-project-id", "location", "us-west1")); + HttpApiClient client = + new HttpApiClient( + Optional.empty(), + Optional.empty(), + Optional.empty(), + Optional.of(CREDENTIALS), + Optional.empty(), + Optional.empty()); + + assertEquals("fake-project-id", client.project()); + assertEquals("us-west1", client.location()); + assertTrue(client.vertexAI()); + } + + @Test + public void testNoDefaultLocationWhenUsingApiKeyOnlyMode( + MockedStatic mockedStaticApiClient) throws Exception { + mockedStaticApiClient + .when(ApiClient::defaultEnvironmentVariables) + .thenReturn(ImmutableMap.of()); + HttpApiClient client = + new HttpApiClient( + Optional.of("vertexai-api-key"), + Optional.empty(), + Optional.empty(), + Optional.empty(), + Optional.empty(), + Optional.empty()); + + assertEquals("vertexai-api-key", client.apiKey()); + assertNull(client.project()); + assertNull(client.location()); + assertTrue(client.vertexAI()); + } } diff --git a/src/test/java/com/google/genai/LocalTokenizerLoaderTest.java b/src/test/java/com/google/genai/LocalTokenizerLoaderTest.java new file mode 100644 index 00000000000..b7a5f88b76f --- /dev/null +++ b/src/test/java/com/google/genai/LocalTokenizerLoaderTest.java @@ -0,0 +1,289 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.genai; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.google.genai.errors.GenAiIOException; +import com.google.genai.proto.SentencepieceModel.ModelProto; +import java.io.IOException; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.security.MessageDigest; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import okhttp3.Call; +import okhttp3.OkHttpClient; +import okhttp3.Protocol; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +public class LocalTokenizerLoaderTest { + + @TempDir Path tempDir; + + private String originalTmpDir; + private OkHttpClient mockHttpClient; + private Call mockCall; + private Map originalTokenizers; + + // Helper to modify final static fields + private static void setStatic(Field field, Object newValue) throws Exception { + field.setAccessible(true); + field.set(null, newValue); + } + + @BeforeEach + void setUp() throws Exception { + originalTmpDir = System.getProperty("java.io.tmpdir"); + System.setProperty("java.io.tmpdir", tempDir.toString()); + + // Mock HttpClient + mockHttpClient = mock(OkHttpClient.class); + mockCall = mock(Call.class); + when(mockHttpClient.newCall(any(Request.class))).thenReturn(mockCall); + + Field clientField = LocalTokenizerLoader.class.getDeclaredField("httpClient"); + setStatic(clientField, mockHttpClient); + + // Backup original tokenizers map + Field tokenizersField = LocalTokenizerLoader.class.getDeclaredField("TOKENIZERS"); + tokenizersField.setAccessible(true); + originalTokenizers = (Map) tokenizersField.get(null); + + // Clear caches + Field modelProtoCacheField = LocalTokenizerLoader.class.getDeclaredField("modelProtoCache"); + modelProtoCacheField.setAccessible(true); + ((Map) modelProtoCacheField.get(null)).clear(); + + Field processorCacheField = + LocalTokenizerLoader.class.getDeclaredField("localTokenizerProcessorCache"); + processorCacheField.setAccessible(true); + ((Map) processorCacheField.get(null)).clear(); + } + + @AfterEach + void tearDown() throws Exception { + System.setProperty("java.io.tmpdir", originalTmpDir); + // Restore original tokenizers map + Field tokenizersField = LocalTokenizerLoader.class.getDeclaredField("TOKENIZERS"); + setStatic(tokenizersField, originalTokenizers); + } + + @Test + void getTokenizerName_supportedModels() { + assertEquals("gemma2", LocalTokenizerLoader.getTokenizerName("gemini-1.5-pro")); + assertEquals("gemma3", LocalTokenizerLoader.getTokenizerName("gemini-2.5-pro")); + } + + @Test + void getTokenizerName_unsupportedModel_throwsException() { + IllegalArgumentException exception = + assertThrows( + IllegalArgumentException.class, + () -> LocalTokenizerLoader.getTokenizerName("unsupported-model")); + assertTrue(exception.getMessage().contains("is not supported")); + } + + @Test + void loadModelProto_unsupportedTokenizer_throwsException() { + IllegalArgumentException exception = + assertThrows( + IllegalArgumentException.class, + () -> LocalTokenizerLoader.loadModelProto("unsupported-tokenizer")); + assertTrue(exception.getMessage().contains("is not supported")); + } + + @Test + void loadModelProto_loadsAndCaches() throws Exception { + // 1. Prepare test data + String tokenizerName = "test-tokenizer"; + String modelUrl = "http://fake.url/model"; + ModelProto testProto = + ModelProto.newBuilder() + .addPieces( + ModelProto.SentencePiece.newBuilder() + .setPiece("") + .setType(ModelProto.SentencePiece.Type.CONTROL)) + .build(); + byte[] protoBytes = testProto.toByteArray(); + String protoHash = sha256(protoBytes); + + // 2. Inject test tokenizer config + Field tokenizersField = LocalTokenizerLoader.class.getDeclaredField("TOKENIZERS"); + tokenizersField.setAccessible(true); + @SuppressWarnings("unchecked") + Map tokenizers = (Map) tokenizersField.get(null); + Map modifiableTokenizers = new HashMap<>(tokenizers); + LocalTokenizerLoader.TokenizerConfig tokenizerConfig = + new LocalTokenizerLoader.TokenizerConfig(modelUrl, protoHash); + modifiableTokenizers.put(tokenizerName, tokenizerConfig); + setStatic(tokenizersField, Collections.unmodifiableMap(modifiableTokenizers)); + + // 3. Mock the network response + Response mockResponse = + new Response.Builder() + .request(new Request.Builder().url(modelUrl).build()) + .protocol(Protocol.HTTP_1_1) + .code(200) + .message("OK") + .body(ResponseBody.create(null, protoBytes)) + .build(); + when(mockCall.execute()).thenReturn(mockResponse); + + // 4. First call: should download and cache + ModelProto loadedProto1 = LocalTokenizerLoader.loadModelProto(tokenizerName); + assertEquals(testProto, loadedProto1); + verify(mockHttpClient, times(1)).newCall(any(Request.class)); + + // 5. Second call: should use in-memory cache + ModelProto loadedProto2 = LocalTokenizerLoader.loadModelProto(tokenizerName); + assertEquals(testProto, loadedProto2); + verify(mockHttpClient, times(1)).newCall(any(Request.class)); + + // 6. Third call after clearing memory cache: should use file cache + Field modelProtoCacheField = LocalTokenizerLoader.class.getDeclaredField("modelProtoCache"); + modelProtoCacheField.setAccessible(true); + ((Map) modelProtoCacheField.get(null)).clear(); + + ModelProto loadedProto3 = LocalTokenizerLoader.loadModelProto(tokenizerName); + assertEquals(testProto, loadedProto3); + verify(mockHttpClient, times(1)).newCall(any(Request.class)); + + // Verify file was created in temp dir + Path modelDir = Paths.get(tempDir.toString(), "vertexai_tokenizer_model"); + String filename = sha1(modelUrl); + Path modelPath = modelDir.resolve(filename); + assertTrue(Files.exists(modelPath)); + assertArrayEquals(protoBytes, Files.readAllBytes(modelPath)); + } + + @Test + void loadModelProto_downloadFails() throws Exception { + String tokenizerName = "test-tokenizer-fail"; + String modelUrl = "http://fake.url/model-fail"; + + // Inject test tokenizer config + Field tokenizersField = LocalTokenizerLoader.class.getDeclaredField("TOKENIZERS"); + tokenizersField.setAccessible(true); + @SuppressWarnings("unchecked") + Map tokenizers = (Map) tokenizersField.get(null); + Map modifiableTokenizers = new HashMap<>(tokenizers); + LocalTokenizerLoader.TokenizerConfig tokenizerConfig = + new LocalTokenizerLoader.TokenizerConfig(modelUrl, "dummy-hash"); + modifiableTokenizers.put(tokenizerName, tokenizerConfig); + setStatic(tokenizersField, Collections.unmodifiableMap(modifiableTokenizers)); + + // Mock failed network response + Response mockResponse = + new Response.Builder() + .request(new Request.Builder().url(modelUrl).build()) + .protocol(Protocol.HTTP_1_1) + .code(404) + .message("Not Found") + .body(ResponseBody.create(null, "")) + .build(); + when(mockCall.execute()).thenReturn(mockResponse); + + // Assert that an exception is thrown + GenAiIOException exception = + assertThrows( + GenAiIOException.class, () -> LocalTokenizerLoader.loadModelProto(tokenizerName)); + assertTrue(exception.getMessage().contains("Failed to download tokenizer model")); + } + + @Test + void loadModelProto_hashMismatch() throws Exception { + String tokenizerName = "test-tokenizer-hash-mismatch"; + String modelUrl = "http://fake.url/model-hash-mismatch"; + ModelProto testProto = ModelProto.newBuilder().build(); + byte[] protoBytes = testProto.toByteArray(); + String wrongHash = "wrong-hash"; + + // Inject test tokenizer config + Field tokenizersField = LocalTokenizerLoader.class.getDeclaredField("TOKENIZERS"); + tokenizersField.setAccessible(true); + @SuppressWarnings("unchecked") + Map tokenizers = (Map) tokenizersField.get(null); + Map modifiableTokenizers = new HashMap<>(tokenizers); + LocalTokenizerLoader.TokenizerConfig tokenizerConfig = + new LocalTokenizerLoader.TokenizerConfig(modelUrl, wrongHash); + modifiableTokenizers.put(tokenizerName, tokenizerConfig); + setStatic(tokenizersField, Collections.unmodifiableMap(modifiableTokenizers)); + + // Mock network response + Response mockResponse = + new Response.Builder() + .request(new Request.Builder().url(modelUrl).build()) + .protocol(Protocol.HTTP_1_1) + .code(200) + .message("OK") + .body(ResponseBody.create(null, protoBytes)) + .build(); + when(mockCall.execute()).thenReturn(mockResponse); + + // Assert that an exception is thrown + GenAiIOException exception = + assertThrows( + GenAiIOException.class, () -> LocalTokenizerLoader.loadModelProto(tokenizerName)); + assertTrue(exception.getMessage().contains("Downloaded model file is corrupted")); + } + + // Helper for hashing + private String sha256(byte[] data) throws Exception { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + byte[] hash = digest.digest(data); + return bytesToHex(hash); + } + + private String sha1(String input) throws Exception { + MessageDigest digest = MessageDigest.getInstance("SHA-1"); + byte[] hash = digest.digest(input.getBytes()); + return bytesToHex(hash); + } + + private String bytesToHex(byte[] hash) { + StringBuilder hexString = new StringBuilder(2 * hash.length); + for (byte b : hash) { + String hex = Integer.toHexString(0xff & b); + if (hex.length() == 1) { + hexString.append('0'); + } + hexString.append(hex); + } + return hexString.toString(); + } +} diff --git a/src/test/java/com/google/genai/LocalTokenizerProcessorIT.java b/src/test/java/com/google/genai/LocalTokenizerProcessorIT.java new file mode 100644 index 00000000000..767b0c4b862 --- /dev/null +++ b/src/test/java/com/google/genai/LocalTokenizerProcessorIT.java @@ -0,0 +1,160 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.genai; + +import static org.junit.jupiter.api.Assertions.*; + +import com.google.common.collect.ImmutableList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +public class LocalTokenizerProcessorIT { + + private LocalTokenizerProcessor processor; + + @BeforeAll + void setUp() throws Exception { + processor = LocalTokenizerLoader.getSentencePiece("gemma2"); + } + + @ParameterizedTest(name = "{index}") + @MethodSource("encodeIDsTestCases") + void testEncodeIDs(String inputText, List expectedTokens) throws Exception { + List actualPieces = processor.encode(inputText); + assertNotNull(actualPieces, "Encoded result should not be null."); + assertEquals( + expectedTokens, + actualPieces.stream().map(Token::id).collect(Collectors.toList()), + String.format("Encoding '%s' did not produce the expected token IDs", inputText)); + } + + static Stream encodeIDsTestCases() { + return Stream.of( + Arguments.of("Hello world", Arrays.asList(4521, 2134)), + Arguments.of("12345", Arrays.asList(235274, 235284, 235304, 235310, 235308)), + Arguments.of(" ", Arrays.asList(139)), + Arguments.of(" ", Arrays.asList(140)), + Arguments.of(" ", Arrays.asList(145)), + Arguments.of("ҔӌԐڎ", Arrays.asList(427, 365, 428, 357, 429, 361, 435, 359)), + Arguments.of(" ", Arrays.asList(235248, 4, 139, 235322, 8939, 235313)), + Arguments.of("
", Arrays.asList(169, 175, 183, 177)), + Arguments.of("one line\nand another line", Arrays.asList(785, 2017, 108, 639, 2550, 2017)), + Arguments.of( + "Language: English\r\n\r\nCredits: Produced by David Widger\r\n", + Arrays.asList( + 14357, 235292, 4645, 235316, 108, 235316, 108, 34711, 235292, 99662, 731, 6046, + 37303, 1197, 235316, 108)), + Arguments.of("Bienvenido a este proyecto", Arrays.asList(176831, 476, 4004, 25431)), + Arguments.of( + "अस्मिन् परियोजनायां स्वागतम्", + Arrays.asList( + 236088, 22740, 212361, 18029, 14480, 19900, 146166, 6751, 235563, 56545, 44071, + 235550, 26989)), + Arguments.of( + "if allow == true { return x;} else {return x+y;}", + Arrays.asList( + 648, 2765, 1159, 1382, 612, 2203, 1141, 22505, 1354, 612, 773, 1141, 235340, 235267, + 22505))); + } + + @ParameterizedTest(name = "{index} - input: {0}") + @MethodSource("encodeTextsTestCases") + void testEncodeTexts(String inputText, List expectedTokens) throws Exception { + List actualTokens = processor.encode(inputText); + + assertNotNull(actualTokens, "Encoded result should not be null."); + assertEquals( + expectedTokens, + actualTokens, + String.format("Encoding '%s' did not produce the expected tokens", inputText)); + } + + static Stream encodeTextsTestCases() { + return Stream.of( + Arguments.of( + "hi bye", + ImmutableList.of( + new Token("hi", 544), + new Token("▁", 235248), + new Token("", 176), + new Token("▁bye", 44788))), + Arguments.of( + "hiƻ 🤨there ⇲bob, สวัสดี", + ImmutableList.of( + new Token("hi", 544), + new Token("<0xC6>", 415), + new Token("<0xBB>", 404), + new Token("▁", 235248), + new Token("", 176), + new Token("🤨", 241847), + new Token("there", 11048), + new Token("▁", 235248), + new Token("⇲", 248372), + new Token("bob", 26242), + new Token(",", 235269), + new Token("▁ส", 12515), + new Token("วัส", 151622), + new Token("ดี", 28890)))); + } + + @ParameterizedTest(name = "IDs: {0} -> Expected: \"{1}\"") + @MethodSource("decodeIdsTestCases") + void testDecodeIds(List ids, String expectedText) { + String actualText = processor.decodeIds(ids); + assertEquals( + expectedText, + actualText, + String.format("Decoding IDs %s did not produce the expected text", ids)); + } + + static Stream decodeIdsTestCases() { + return Stream.of( + Arguments.of(Arrays.asList(17534, 2134), "hello world"), + Arguments.of( + Arrays.asList(427, 365, 428, 357, 29422, 1653, 427, 365, 428, 357), "Ҕӌnever againҔӌ"), + Arguments.of(Arrays.asList(785, 2017, 108, 639, 2550, 2017), "one line\nand another line"), + Arguments.of(Arrays.asList(1001, 1002, 1003, 1004), "buark}) res"), + Arguments.of( + Arrays.asList(111001, 111002, 111003, 111004), " Wichita EducaçãoVocabulary天堂"), + Arguments.of(Arrays.asList(139), " "), + Arguments.of(Arrays.asList(140), " "), + Arguments.of(Arrays.asList(145), " "), + Arguments.of(Arrays.asList(441, 401, 387), "ส"), + Arguments.of(Arrays.asList(411, 380), "£"), + + // control IDs + Arguments.of(Arrays.asList(2, 411, 380), "£"), + Arguments.of(Arrays.asList(1, 2, 411, 380), "£"), + Arguments.of(Arrays.asList(2, 411, 380, 0, 1, 2, 0), "£"), + + // unknown (id=3) + Arguments.of(Arrays.asList(3, 411, 380), " ⁇ £"), // " ⁇ " is U+0020 U+2047 + Arguments.of(Arrays.asList(3, 3, 1000, 3), " ⁇ ⁇ ew ⁇ "), + + // invalid bytes for UTF-8, produce "invalid unicode" (U+FFFD) + Arguments.of(Arrays.asList(349, 349, 349), "���"), + Arguments.of(Arrays.asList(800, 348, 500, 348), "sed�it�")); + } +} diff --git a/src/test/java/com/google/genai/LocalTokenizerProcessorTest.java b/src/test/java/com/google/genai/LocalTokenizerProcessorTest.java new file mode 100644 index 00000000000..e2fb91a7939 --- /dev/null +++ b/src/test/java/com/google/genai/LocalTokenizerProcessorTest.java @@ -0,0 +1,232 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.genai; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import com.google.common.collect.ImmutableList; +import com.google.genai.proto.SentencepieceModel.ModelProto; +import com.google.genai.proto.SentencepieceModel.NormalizerSpec; +import com.google.genai.proto.SentencepieceModel.TrainerSpec; +import com.google.genai.proto.SentencepieceModel.ModelProto.SentencePiece; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** Unit tests for {@link LocalTokenizerProcessor}. */ +public class LocalTokenizerProcessorTest { + + private LocalTokenizerProcessor processor; + + @BeforeEach + void setUp() { + // Create a mock ModelProto for testing purposes. + // The scores are set to prefer longer tokens. + ModelProto testProto = + ModelProto.newBuilder() + .setTrainerSpec( + TrainerSpec.newBuilder() + .setModelType(TrainerSpec.ModelType.BPE) + .setVocabSize(0) + .setUnkId(0) + .build()) + .setNormalizerSpec( + NormalizerSpec.newBuilder() + .setAddDummyPrefix(false) + .setRemoveExtraWhitespaces(false) + .build()) + // 0: + .addPieces( + SentencePiece.newBuilder() + .setPiece("") + .setType(SentencePiece.Type.UNKNOWN) + .setScore(0.0f)) + // 1: + .addPieces( + SentencePiece.newBuilder() + .setPiece("") + .setType(SentencePiece.Type.CONTROL) + .setScore(0.0f)) + // 2: + .addPieces( + SentencePiece.newBuilder() + .setPiece("") + .setType(SentencePiece.Type.CONTROL) + .setScore(0.0f)) + // 3: " " + .addPieces(SentencePiece.newBuilder().setPiece("▁").setScore(-3.0f)) + // 4: "h" + .addPieces(SentencePiece.newBuilder().setPiece("h").setScore(-20.0f)) + // 5: "e" + .addPieces(SentencePiece.newBuilder().setPiece("e").setScore(-21.0f)) + // 6: "l" + .addPieces(SentencePiece.newBuilder().setPiece("l").setScore(-22.0f)) + // 7: "o" + .addPieces(SentencePiece.newBuilder().setPiece("o").setScore(-23.0f)) + // 8: "w" + .addPieces(SentencePiece.newBuilder().setPiece("w").setScore(-24.0f)) + // 9: "r" + .addPieces(SentencePiece.newBuilder().setPiece("r").setScore(-25.0f)) + // 10: "d" + .addPieces(SentencePiece.newBuilder().setPiece("d").setScore(-26.0f)) + // Merged pieces with better scores + // 11: "he" + .addPieces(SentencePiece.newBuilder().setPiece("he").setScore(-10.0f)) + // 12: "lo" + .addPieces(SentencePiece.newBuilder().setPiece("lo").setScore(-10.0f)) + // 13: "llo" + .addPieces(SentencePiece.newBuilder().setPiece("llo").setScore(-11.0f)) + // 14: "world" + .addPieces(SentencePiece.newBuilder().setPiece("▁world").setScore(-5.0f)) + // 15: "hello" + .addPieces(SentencePiece.newBuilder().setPiece("hello").setScore(-4.0f)) + .addPieces(SentencePiece.newBuilder().setPiece("▁w").setScore(-12.0f)) + .addPieces(SentencePiece.newBuilder().setPiece("▁wo").setScore(-12.0f)) + .addPieces(SentencePiece.newBuilder().setPiece("▁wor").setScore(-12.0f)) + .addPieces(SentencePiece.newBuilder().setPiece("ld").setScore(-12.0f)) + .build(); + + processor = new LocalTokenizerProcessor(testProto); + } + + @Test + @DisplayName("Encode should correctly tokenize a simple string into whole words") + void encode_simpleString_returnsCorrectTokens() throws Exception { + String inputText = "hello world"; + List expectedTokens = ImmutableList.of(new Token("hello", 15), new Token("▁world", 14)); + + List actualTokens = processor.encode(inputText); + + assertNotNull(actualTokens); + assertEquals(expectedTokens, actualTokens); + } + + @Test + @DisplayName("Encode should correctly tokenize a string into subwords") + void encode_stringWithSubwords_returnsCorrectTokens() throws Exception { + // This test uses a different vocabulary where "hello" is not a single token. + ModelProto subwordProto = + ModelProto.newBuilder() + .setTrainerSpec( + TrainerSpec.newBuilder() + .setModelType(TrainerSpec.ModelType.BPE) + .setVocabSize(0) + .setUnkId(0) + .build()) + .setNormalizerSpec( + NormalizerSpec.newBuilder() + .setAddDummyPrefix(false) + .setRemoveExtraWhitespaces(false) + .build()) + .addPieces( + SentencePiece.newBuilder() + .setPiece("") + .setType(SentencePiece.Type.UNKNOWN) + .setScore(0.0f)) // 0 + .addPieces( + SentencePiece.newBuilder() + .setPiece("") + .setType(SentencePiece.Type.CONTROL) + .setScore(0.0f)) // 1 + .addPieces( + SentencePiece.newBuilder() + .setPiece("") + .setType(SentencePiece.Type.CONTROL) + .setScore(0.0f)) // 2 + .addPieces(SentencePiece.newBuilder().setPiece("h").setScore(-5.0f)) // 3 + .addPieces(SentencePiece.newBuilder().setPiece("e").setScore(-5.0f)) // 4 + .addPieces(SentencePiece.newBuilder().setPiece("l").setScore(-5.0f)) // 5 + .addPieces(SentencePiece.newBuilder().setPiece("o").setScore(-5.0f)) // 6 + .addPieces(SentencePiece.newBuilder().setPiece("he").setScore(-2.0f)) // 7 + .addPieces(SentencePiece.newBuilder().setPiece("lo").setScore(-2.0f)) // 8 + .addPieces(SentencePiece.newBuilder().setPiece("llo").setScore(-2.0f)) // 9 + .build(); + LocalTokenizerProcessor subwordProcessor = new LocalTokenizerProcessor(subwordProto); + String inputText = "hello"; + List expectedTokens = ImmutableList.of(new Token("he", 7), new Token("llo", 9)); + + List actualTokens = subwordProcessor.encode(inputText); + + assertNotNull(actualTokens); + assertEquals(expectedTokens, actualTokens); + } + + @Test + @DisplayName("Encode should handle unknown characters by returning the unknown token") + void encode_unknownCharacters_returnsUnknownToken() throws Exception { + String inputText = "z"; + // Assuming byte fallback is not enabled in the test proto, "z" is unknown. + // The piece is the unknown character itself, and the ID is for the token + // (ID 0). + List expectedTokens = ImmutableList.of(new Token("z", 0)); + + List actualTokens = processor.encode(inputText); + + assertNotNull(actualTokens); + assertEquals(expectedTokens, actualTokens); + } + + @Test + @DisplayName("Decode should correctly reconstruct a string from token IDs") + void decodeIds_simpleList_returnsCorrectString() { + List ids = Arrays.asList(15, 14); + String expectedText = "hello world"; + + String actualText = processor.decodeIds(ids); + + assertEquals(expectedText, actualText); + } + + @Test + @DisplayName("Decode should correctly reconstruct a string from subword token IDs") + void decodeIds_withSubwords_returnsCorrectString() { + List ids = Arrays.asList(11, 13); + String expectedText = "hello"; + + String actualText = processor.decodeIds(ids); + + assertEquals(expectedText, actualText); + } + + @Test + @DisplayName("Decode should ignore control characters") + void decodeIds_withControlCharacters_ignoresThem() { + // IDs 1 () and 2 () are control characters. + List ids = Arrays.asList(1, 15, 14, 2); + String expectedText = "hello world"; + + String actualText = processor.decodeIds(ids); + + assertEquals(expectedText, actualText); + } + + @Test + @DisplayName("Encode and decode should be consistent") + void encodeAndDecode_areConsistent() throws Exception { + String inputText = "hello world"; + + List tokens = processor.encode(inputText); + List ids = tokens.stream().map(Token::id).collect(Collectors.toList()); + String decodedText = processor.decodeIds(ids); + + assertEquals(inputText, decodedText); + } +} diff --git a/src/test/java/com/google/genai/LocalTokenizerTest.java b/src/test/java/com/google/genai/LocalTokenizerTest.java new file mode 100644 index 00000000000..2af9831ca97 --- /dev/null +++ b/src/test/java/com/google/genai/LocalTokenizerTest.java @@ -0,0 +1,208 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.genai; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.Mockito.when; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import com.google.genai.proto.SentencepieceModel.ModelProto; +import com.google.genai.proto.SentencepieceModel.ModelProto.SentencePiece; +import com.google.genai.types.Content; +import com.google.genai.types.CountTokensConfig; +import com.google.genai.types.CountTokensResult; +import com.google.genai.types.FunctionDeclaration; +import com.google.genai.types.GenerateContentConfig; +import com.google.genai.types.GenerationConfig; +import com.google.genai.types.Part; +import com.google.genai.types.Schema; +import com.google.genai.types.Tool; +import com.google.genai.types.ComputeTokensResult; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.List; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; + +public class LocalTokenizerTest { + + private static final String TEST_MODEL_NAME = "gemini-pro"; + + @Mock private LocalTokenizerProcessor mockedProcessor; + @Mock private ModelProto mockedProto; + + private LocalTokenizer tokenizer; + private AutoCloseable closeable; + + @BeforeEach + void setUp() { + closeable = MockitoAnnotations.openMocks(this); + tokenizer = new LocalTokenizer(mockedProto, mockedProcessor); + } + + @AfterEach + void tearDown() throws Exception { + closeable.close(); + } + + @Test + void constructor_unsupportedModel_throwsException() { + String unsupportedModel = "unsupported-model"; + try (MockedStatic mockedLoader = + Mockito.mockStatic(LocalTokenizerLoader.class)) { + mockedLoader + .when(() -> LocalTokenizerLoader.getTokenizerName(unsupportedModel)) + .thenThrow( + new IllegalArgumentException("Model " + unsupportedModel + " is not supported.")); + + IllegalArgumentException exception = + assertThrows(IllegalArgumentException.class, () -> new LocalTokenizer(unsupportedModel)); + assertTrue(exception.getMessage().contains("is not supported")); + } + } + + @Test + void countTokens_string() throws Exception { + String text = "hello world!"; + when(mockedProcessor.encode(text)) + .thenReturn(ImmutableList.of(new Token("a", 1), new Token("b", 2))); + + CountTokensResult response = tokenizer.countTokens(text, null); + + assertEquals(2, response.totalTokens().get()); + } + + @Test + void countTokens_content() throws Exception { + String text = "hello world!"; + Content content = Content.fromParts(Part.fromText(text)); + when(mockedProcessor.encode(text)) + .thenReturn(ImmutableList.of(new Token("a", 1), new Token("b", 2))); + + CountTokensResult response = tokenizer.countTokens(content, null); + assertEquals(2, response.totalTokens().get()); + } + + @Test + void countTokens_withConfig() throws Exception { + Content systemInstruction = Content.fromParts(Part.fromText("hello!")); + Tool tool = + Tool.builder() + .functionDeclarations( + FunctionDeclaration.builder() + .name("hello") + .description(" world") + .parameters( + Schema.builder() + .properties( + ImmutableMap.of( + "hello", Schema.builder().description("!").build())))) + .build(); + Schema responseSchema = Schema.builder().description("hello world").build(); + CountTokensConfig config = + CountTokensConfig.builder() + .systemInstruction(systemInstruction) + .tools(tool) + .generationConfig(GenerationConfig.builder().responseSchema(responseSchema).build()) + .build(); + List contents = ImmutableList.of(Content.fromParts(Part.fromText("hello"))); + + when(mockedProcessor.encode("hello")).thenReturn(ImmutableList.of(new Token("hello", 1))); + when(mockedProcessor.encode("hello!")) + .thenReturn(ImmutableList.of(new Token("hello", 1), new Token("!", 2))); + when(mockedProcessor.encode("hello world")) + .thenReturn(ImmutableList.of(new Token("hello world", 3))); + when(mockedProcessor.encode(" world")).thenReturn(ImmutableList.of(new Token(" world", 4))); + when(mockedProcessor.encode("!")).thenReturn(ImmutableList.of(new Token("!", 5))); + + CountTokensResult response = tokenizer.countTokens(contents, config); + + assertEquals(8, response.totalTokens().get()); + } + + @Test + void countTokens_withFunctionCalling() throws Exception { + Content content = + Content.fromParts( + Part.fromFunctionCall("hello", ImmutableMap.of("key", " world")), + Part.fromFunctionResponse("hello", ImmutableMap.of("key", "!"))); + + when(mockedProcessor.encode("hello")).thenReturn(ImmutableList.of(new Token("hello", 1))); + when(mockedProcessor.encode("key")) + .thenReturn(ImmutableList.of(new Token("k", 2), new Token("e", 3), new Token("y", 4))); + when(mockedProcessor.encode(" world")).thenReturn(ImmutableList.of(new Token(" world", 5))); + when(mockedProcessor.encode("!")).thenReturn(ImmutableList.of(new Token("!", 6))); + + CountTokensResult response = tokenizer.countTokens(ImmutableList.of(content), null); + + assertEquals(10, response.totalTokens().get()); + } + + @Test + void countTokens_unsupportedPart_throwsException() { + Content content = Content.fromParts(Part.fromBytes(new byte[0], "image/png")); + + IllegalArgumentException e = + assertThrows(IllegalArgumentException.class, () -> tokenizer.countTokens(content, null)); + assertEquals("LocalTokenizers do not support non-text content types.", e.getMessage()); + } + + @Test + void computeTokens_string() throws Exception { + String text = "hello world!"; + when(mockedProcessor.encode(text)) + .thenReturn(ImmutableList.of(new Token("hello world", 4), new Token("!", 3))); + when(mockedProto.getPieces(anyInt())) + .thenReturn(SentencePiece.newBuilder().setType(SentencePiece.Type.NORMAL).build()); + + ComputeTokensResult response = tokenizer.computeTokens(text); + + assertEquals(1, response.tokensInfo().get().size()); + assertEquals(2, response.tokensInfo().get().get(0).tokenIds().get().size()); + assertEquals(4L, response.tokensInfo().get().get(0).tokenIds().get().get(0)); + assertEquals(3L, response.tokensInfo().get().get(0).tokenIds().get().get(1)); + assertEquals( + "hello world", new String(response.tokensInfo().get().get(0).tokens().get().get(0))); + assertEquals("!", new String(response.tokensInfo().get().get(0).tokens().get().get(1))); + } + + @Test + void computeTokens_withBytePiece() throws Exception { + String text = "A"; + when(mockedProcessor.encode(text)).thenReturn(ImmutableList.of(new Token("<0x41>", 5))); + when(mockedProto.getPieces(5)) + .thenReturn(SentencePiece.newBuilder().setType(SentencePiece.Type.BYTE).build()); + + ComputeTokensResult response = tokenizer.computeTokens(text); + + assertEquals(1, response.tokensInfo().get().size()); + assertEquals(1, response.tokensInfo().get().get(0).tokenIds().get().size()); + assertEquals(5L, response.tokensInfo().get().get(0).tokenIds().get().get(0)); + byte[] expectedBytes = new byte[] {(byte) 0x41}; + assertTrue( + Arrays.equals(expectedBytes, response.tokensInfo().get().get(0).tokens().get().get(0))); + } +} diff --git a/src/test/java/com/google/genai/ModelsTest.java b/src/test/java/com/google/genai/ModelsTest.java index b544843d9f5..1e4243ddbbf 100644 --- a/src/test/java/com/google/genai/ModelsTest.java +++ b/src/test/java/com/google/genai/ModelsTest.java @@ -262,6 +262,7 @@ public void testEmbedContent_withText(boolean vertexAI) throws Exception { // Assert assertTrue(response.embeddings().isPresent()); assertEquals(1, response.embeddings().get().size()); + assertNotNull(response.sdkHttpResponse().get().headers().get()); } @ParameterizedTest @@ -289,6 +290,7 @@ public void testEmbedContent_withListOfTexts(boolean vertexAI) throws Exception // Assert assertTrue(response.embeddings().isPresent()); assertEquals(2, response.embeddings().get().size()); + assertNotNull(response.sdkHttpResponse().get().headers().get()); } @ParameterizedTest @@ -306,6 +308,7 @@ public void testCountTokens_withText(boolean vertexAI) throws Exception { // Assert assertTrue(response.totalTokens().isPresent()); + assertNotNull(response.sdkHttpResponse().get().headers().get()); } @ParameterizedTest @@ -327,6 +330,7 @@ public void testComputeTokens_withText(boolean vertexAI) throws Exception { // Assert assertTrue(response.tokensInfo().isPresent()); + assertNotNull(response.sdkHttpResponse().get().headers().get()); } @ParameterizedTest @@ -351,6 +355,7 @@ public void testListModels(boolean vertexAI) throws Exception { IndexOutOfBoundsException exception = assertThrows(IndexOutOfBoundsException.class, () -> pager.nextPage()); assertEquals("No more page in the pager.", exception.getMessage()); + assertNotNull(pager.sdkHttpResponse().get().headers().get()); } @ParameterizedTest @@ -395,6 +400,7 @@ public void testEditImage_withMaskReference(boolean vertexAI) throws Exception { .outputCompressionQuality(80) .baseSteps(32) .addWatermark(false) + .labels(ImmutableMap.of("imagen_label_key", "edit_image")) .build(); // Act @@ -408,6 +414,7 @@ public void testEditImage_withMaskReference(boolean vertexAI) throws Exception { // Assert assertTrue(response.generatedImages().get().get(0).image().isPresent()); + assertNotNull(response.sdkHttpResponse().get().headers().get()); } else { UnsupportedOperationException exception = assertThrows( @@ -452,6 +459,7 @@ public void testEditImage_withControlReference(boolean vertexAI) throws Exceptio // Assert assertTrue(response.generatedImages().get().get(0).image().isPresent()); + assertNotNull(response.sdkHttpResponse().get().headers().get()); } else { UnsupportedOperationException exception = assertThrows( @@ -497,6 +505,7 @@ public void testEditImage_withSubjectReference(boolean vertexAI) throws Exceptio // Assert assertTrue(response.generatedImages().get().get(0).image().isPresent()); + assertNotNull(response.sdkHttpResponse().get().headers().get()); } else { UnsupportedOperationException exception = assertThrows( @@ -545,6 +554,7 @@ public void testEditImage_withStyleTransfer(boolean vertexAI) throws Exception { // Assert assertTrue(response.generatedImages().get().get(0).image().isPresent()); + assertNotNull(response.sdkHttpResponse().get().headers().get()); } else { UnsupportedOperationException exception = assertThrows( diff --git a/src/test/java/com/google/genai/OperationsTest.java b/src/test/java/com/google/genai/OperationsTest.java index bdcb054a9cf..1b44b3266d6 100644 --- a/src/test/java/com/google/genai/OperationsTest.java +++ b/src/test/java/com/google/genai/OperationsTest.java @@ -43,8 +43,8 @@ public void testGetVideosOperation(boolean vertexAI) throws Exception { String operationName = vertexAI - ? "projects//locations//publishers/google/models/veo-2.0-generate-001/operations/ddb46542-07ed-4000-958d-655fbffb05a4" - : "models/veo-2.0-generate-001/operations/ren0ubieaocs"; + ? "projects//locations//publishers/google/models/veo-3.1-generate-preview/operations/6a55ba83-558a-4b29-9999-325b1eb218cf" + : "models/veo-3.1-generate-preview/operations/9jwcbmi5tkvw"; // Act GenerateVideosOperation generateVideosOperation = diff --git a/src/test/java/com/google/genai/RetryInterceptorTest.java b/src/test/java/com/google/genai/RetryInterceptorTest.java new file mode 100644 index 00000000000..65c980c2b5a --- /dev/null +++ b/src/test/java/com/google/genai/RetryInterceptorTest.java @@ -0,0 +1,291 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.genai; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.google.genai.types.HttpRetryOptions; +import java.io.IOException; +import java.util.Random; +import okhttp3.Interceptor; +import okhttp3.MediaType; +import okhttp3.Protocol; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +class RetryInterceptorTest { + + @Mock Interceptor.Chain chain; + @Mock Random random; + + private Request baseRequest; + private HttpRetryOptions retryOptions; + private Response successResponse; + private Response retryableErrorResponse; + private Response nonRetryableErrorResponse; + private IOException ioException; + + private AutoCloseable openMocks; + + @BeforeEach + void setUp() { + openMocks = MockitoAnnotations.openMocks(this); + // A base request that our mock chain will return + baseRequest = new Request.Builder().url("http://localhost").build(); + lenient().when(chain.request()).thenReturn(baseRequest); + + // Default retry options + retryOptions = + HttpRetryOptions.builder() + .attempts(3) + .httpStatusCodes(503) + // Set to small values to make the test faster + .initialDelay(0.1) + .maxDelay(0.5) + .expBase(3.0) + .jitter(0.5) + .build(); + + // A successful 200 OK response + successResponse = createMockResponse(200); + + // A 503 error, which is in the default retry list + retryableErrorResponse = createMockResponse(503); + + // A 404 error, which is NOT in the default retry list + nonRetryableErrorResponse = createMockResponse(404); + + // An IOException + ioException = new IOException("Network failed"); + } + + @AfterEach + void tearDown() throws Exception { + openMocks.close(); + } + + /** Helper to create mock OkHttp Responses. */ + private Response createMockResponse(int code) { + return new Response.Builder() + .request(baseRequest) + .code(code) + .protocol(Protocol.HTTP_1_1) + .message("Mock response") + .body(ResponseBody.create("", MediaType.get("application/json"))) + .build(); + } + + @Test + void testIntercept_SuccessfulOnFirstTry() throws Exception { + RetryInterceptor interceptorSpy = spy(new RetryInterceptor(retryOptions)); + when(chain.proceed(baseRequest)).thenReturn(successResponse); + + Response response = interceptorSpy.intercept(chain); + + verify(chain, times(1)).proceed(baseRequest); + assertEquals(200, response.code()); + } + + @Test + void testIntercept_NonRetryableError_NoRetry() throws Exception { + RetryInterceptor interceptorSpy = spy(new RetryInterceptor(retryOptions)); + when(chain.proceed(baseRequest)).thenReturn(nonRetryableErrorResponse); + + Response response = interceptorSpy.intercept(chain); + + verify(chain, times(1)).proceed(baseRequest); + assertEquals(404, response.code()); + } + + @Test + void testIntercept_RetryableError_ThenSuccess() throws Exception { + RetryInterceptor interceptorSpy = spy(new RetryInterceptor(retryOptions)); + when(chain.proceed(baseRequest)).thenReturn(retryableErrorResponse).thenReturn(successResponse); + + Response response = interceptorSpy.intercept(chain); + + verify(chain, times(2)).proceed(baseRequest); + assertEquals(200, response.code()); + } + + @Test + void testIntercept_RetryableError_ExhaustsAttempts() throws Exception { + RetryInterceptor interceptorSpy = spy(new RetryInterceptor(retryOptions)); + when(chain.proceed(baseRequest)) + .thenReturn(retryableErrorResponse) + .thenReturn(retryableErrorResponse) + .thenReturn(retryableErrorResponse) + .thenReturn(successResponse); + + Response response = interceptorSpy.intercept(chain); + + verify(chain, times(3)).proceed(baseRequest); + assertEquals(503, response.code()); + } + + @Test + void testIntercept_NonRetryableErrorWithCustomCodeList_thenSuccess() throws Exception { + HttpRetryOptions customRetryOptions = + HttpRetryOptions.builder().attempts(3).httpStatusCodes(400, 404).build(); + RetryInterceptor interceptorSpy = spy(new RetryInterceptor(customRetryOptions)); + when(chain.proceed(baseRequest)) + .thenReturn(nonRetryableErrorResponse) + .thenReturn(successResponse); + + Response response = interceptorSpy.intercept(chain); + + verify(chain, times(2)).proceed(baseRequest); + assertEquals(200, response.code()); + } + + @Test + void testIntercept_defaultAttempts_retriesFiveTimes() throws Exception { + HttpRetryOptions defaultRetryOptions = HttpRetryOptions.builder().initialDelay(0.0).build(); + RetryInterceptor interceptorSpy = spy(new RetryInterceptor(defaultRetryOptions)); + when(chain.proceed(baseRequest)).thenReturn(retryableErrorResponse); + + Response response = interceptorSpy.intercept(chain); + + verify(chain, times(5)).proceed(baseRequest); + assertEquals(503, response.code()); + } + + @Test + void testIntercept_defaultHttpStatusCodes_retriesWithDefaultCodes() throws Exception { + HttpRetryOptions defaultRetryOptions = + HttpRetryOptions.builder().attempts(7).initialDelay(0.0).build(); + RetryInterceptor interceptorSpy = spy(new RetryInterceptor(defaultRetryOptions)); + when(chain.proceed(baseRequest)) + .thenReturn(createMockResponse(408)) + .thenReturn(createMockResponse(429)) + .thenReturn(createMockResponse(500)) + .thenReturn(createMockResponse(502)) + .thenReturn(createMockResponse(503)) + .thenReturn(createMockResponse(504)) + .thenReturn(successResponse); + + Response response = interceptorSpy.intercept(chain); + + verify(chain, times(7)).proceed(baseRequest); + assertEquals(200, response.code()); + } + + @Test + void testIntercept_IOException_ThenSuccess() throws Exception { + RetryInterceptor interceptorSpy = spy(new RetryInterceptor(retryOptions)); + when(chain.proceed(baseRequest)).thenThrow(ioException).thenReturn(successResponse); + + Response response = interceptorSpy.intercept(chain); + + verify(chain, times(2)).proceed(baseRequest); + assertEquals(200, response.code()); + } + + @Test + void testIntercept_IOException_ExhaustsAttempts() throws Exception { + RetryInterceptor interceptorSpy = spy(new RetryInterceptor(retryOptions)); + when(chain.proceed(baseRequest)) + .thenThrow(ioException) + .thenThrow(ioException) + .thenThrow(ioException) + .thenReturn(successResponse); + + assertThrows(IOException.class, () -> interceptorSpy.intercept(chain)); + verify(chain, times(3)).proceed(baseRequest); + } + + @Test + void testIntercept_PerRequestOptions_OverridesClientLevelOptions() throws Exception { + HttpRetryOptions perRequestOptions = HttpRetryOptions.builder().attempts(2).build(); + Request customRequest = + baseRequest.newBuilder().tag(HttpRetryOptions.class, perRequestOptions).build(); + when(chain.request()).thenReturn(customRequest); + when(chain.proceed(customRequest)).thenReturn(retryableErrorResponse); + + RetryInterceptor interceptorSpy = spy(new RetryInterceptor(retryOptions)); + + Response response = interceptorSpy.intercept(chain); + + verify(chain, times(2)).proceed(customRequest); + assertEquals(503, response.code()); + } + + @Test + void testCalculateDelay_FirstAttempt() { + RetryInterceptor interceptor = new RetryInterceptor(retryOptions, random); + when(random.nextDouble()).thenReturn(0.5); + + long delayMs = interceptor.calculateDelay(retryOptions, 1); + + assertEquals(100L, delayMs); // 0.1 + } + + @Test + void testCalculateDelay_SecondAttempt() { + RetryInterceptor interceptor = new RetryInterceptor(retryOptions, random); + when(random.nextDouble()).thenReturn(1.0); + + long delayMs = interceptor.calculateDelay(retryOptions, 2); + + assertEquals(450L, delayMs); // 0.1 * (3^1) * (1.0 + 0.5 * (1.0)) = 0.45 + } + + @Test + void testCalculateDelay_ThirdAttempt_ReachMaxDelay() { + RetryInterceptor interceptor = new RetryInterceptor(retryOptions, random); + when(random.nextDouble()).thenReturn(0.5); + + long delayMs = interceptor.calculateDelay(retryOptions, 3); + + assertEquals(500L, delayMs); // 0.1 * (3^2) = 0.9 > 0.5, so max delay is reached + } + + @Test + void testCalculateDelay_DefaultValues() { + RetryInterceptor interceptor = new RetryInterceptor(HttpRetryOptions.builder().build(), random); + when(random.nextDouble()).thenReturn(1.0); + + long delayMs = interceptor.calculateDelay(HttpRetryOptions.builder().build(), 2); + + // Default values: initialDelay = 1.0, maxDelay = 60.0, expBase = 2.0, jitter = 1.0 + // Delay = 1.0 * (2^1) * (1.0 + 1.0 * (1.0 * 2.0 - 1.0)) = 4.0 + assertEquals(4000L, delayMs); + } + + @Test + void testCalculateDelay_DefaultValues_MaxDelay() { + RetryInterceptor interceptor = new RetryInterceptor(HttpRetryOptions.builder().build(), random); + when(random.nextDouble()).thenReturn(1.0); + + long delayMs = interceptor.calculateDelay(HttpRetryOptions.builder().build(), 10); + + // Default maxDelay is 60.0 + assertEquals(60000L, delayMs); + } +} diff --git a/src/test/java/com/google/genai/TableTest.java b/src/test/java/com/google/genai/TableTest.java index 43b38552a74..8d74a1cbe6e 100644 --- a/src/test/java/com/google/genai/TableTest.java +++ b/src/test/java/com/google/genai/TableTest.java @@ -56,8 +56,15 @@ private static Collection createTableTests(String path, boolean ver // Gets module name and method name. String testMethod = testTableFile.testMethod().get(); String[] segments = testMethod.split("\\."); - if (segments.length != 2) { - throw new RuntimeException("Invalid test method: " + testMethod); + if (segments.length == 1) { + String msg = " => Test skipped: multistep test " + testMethod + " not supported in Java"; + List dynamicTests = new ArrayList<>(); + for (TestTableItem testTableItem : testTableFile.testTable().get()) { + String testName = + String.format("%s.%s.%s", testMethod, testTableItem.name().get(), suffix); + dynamicTests.add(DynamicTest.dynamicTest(testName + msg, () -> {})); + } + return dynamicTests; } String originalModuleName = segments[0]; String moduleName = Common.snakeToCamel(originalModuleName); @@ -91,6 +98,10 @@ private static Collection createTableTests(String path, boolean ver && candidate.getName().equals("privateEmbedContent")) { candidate.setAccessible(true); methods.add(candidate); + } else if (methodName.equals("generateVideos") + && candidate.getName().equals("privateGenerateVideos")) { + candidate.setAccessible(true); + methods.add(candidate); } } if (methods.isEmpty()) { @@ -155,6 +166,13 @@ private static Collection createTestCases( Map fromParameters = (Map) normalizeKeys((Map) testTableItem.parameters().get()); ReplaySanitizer.sanitizeMapByPath( fromParameters, "image.imageBytes", new ReplayBase64Sanitizer(), false); + ReplaySanitizer.sanitizeMapByPath( + fromParameters, "source.image.imageBytes", new ReplayBase64Sanitizer(), false); + ReplaySanitizer.sanitizeMapByPath( + fromParameters, + "source.scribbleImage.image.imageBytes", + new ReplayBase64Sanitizer(), + false); // TODO(b/403368643): Support interface param types in Java replay tests. // ReplaySanitizer.sanitizeMapByPath( // fromParameters, @@ -288,6 +306,10 @@ private static String getReplayFilePath(String testName) { Collection createTests() throws IOException { String replaysPath = System.getenv("GOOGLE_GENAI_REPLAYS_DIRECTORY"); String testsReplaysPath = replaysPath + "/tests"; + String testsSubDir = System.getenv("GOOGLE_GENAI_TESTS_SUBDIR"); + if (testsSubDir != null) { + testsReplaysPath += "/" + testsSubDir; + } Collection dynamicTests = new ArrayList<>(); Files.walk(Paths.get(testsReplaysPath)) .filter(Files::isRegularFile) diff --git a/src/test/java/com/google/genai/TuningsTest.java b/src/test/java/com/google/genai/TuningsTest.java index d0ed0b86ff9..7141cdf33e9 100644 --- a/src/test/java/com/google/genai/TuningsTest.java +++ b/src/test/java/com/google/genai/TuningsTest.java @@ -21,6 +21,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import com.google.genai.types.CreateTuningJobConfig; import com.google.genai.types.JobState; import com.google.genai.types.ListTuningJobsConfig; import com.google.genai.types.TuningDataset; @@ -98,7 +99,8 @@ public void testTuneUntilSuccess(boolean vertexAI) { .gcsUri( "gs://cloud-samples-data/ai-platform/generative_ai/gemini-2_0/text/sft_train_data.jsonl") .build(); - TuningJob job = client.tunings.tune("gemini-2.0-flash-001", tuningDataset, null); + CreateTuningJobConfig tuningConfig = CreateTuningJobConfig.builder().epochCount(1).build(); + TuningJob job = client.tunings.tune("gemini-2.0-flash-001", tuningDataset, tuningConfig); // Act TuningJob currentJob = job; @@ -116,4 +118,69 @@ public void testTuneUntilSuccess(boolean vertexAI) { assertNotNull(currentJob); assertTrue(currentJob.state().get().knownEnum() == JobState.Known.JOB_STATE_SUCCEEDED); } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + public void testContinuousTuning(boolean vertexAI) { + if (!vertexAI) { // MLDev test removed, tune not supported anymore + return; + } + + // Arrange + String suffix = vertexAI ? "vertex" : "mldev"; + Client client = + TestUtils.createClient( + vertexAI, "tests/tunings/end_to_end/test_continuous_tuning." + suffix + ".json"); + + TuningDataset tuningDataset = + TuningDataset.builder() + .gcsUri( + "gs://cloud-samples-data/ai-platform/generative_ai/gemini-2_0/text/sft_train_data.jsonl") + .build(); + CreateTuningJobConfig tuningConfig = CreateTuningJobConfig.builder().epochCount(1).build(); + TuningJob job = client.tunings.tune("gemini-2.5-flash", tuningDataset, tuningConfig); + + // Act + TuningJob currentJob = job; + JobState.Known state = job.state().get().knownEnum(); + + // Needed to go through the running + pending tuning job states. + while (state != JobState.Known.JOB_STATE_SUCCEEDED + && state != JobState.Known.JOB_STATE_FAILED + && state != JobState.Known.JOB_STATE_CANCELLED) { + currentJob = client.tunings.get(currentJob.name().get(), null); + state = currentJob.state().get().knownEnum(); + } + + // Assert + assertNotNull(currentJob); + assertTrue(currentJob.state().get().knownEnum() == JobState.Known.JOB_STATE_SUCCEEDED); + + // Arrange + CreateTuningJobConfig continuousTuningConfig = + CreateTuningJobConfig.builder() + .tunedModelDisplayName("continuous tuning job") + .epochCount(1) + .build(); + TuningJob continuousJob = + client.tunings.tune( + currentJob.tunedModel().get().model().get(), tuningDataset, continuousTuningConfig); + + // Act + TuningJob currentContinuousJob = continuousJob; + JobState.Known continuousState = continuousJob.state().get().knownEnum(); + + // Needed to go through the running + pending tuning job states. + while (continuousState != JobState.Known.JOB_STATE_SUCCEEDED + && continuousState != JobState.Known.JOB_STATE_FAILED + && continuousState != JobState.Known.JOB_STATE_CANCELLED) { + currentContinuousJob = client.tunings.get(currentContinuousJob.name().get(), null); + continuousState = currentContinuousJob.state().get().knownEnum(); + } + + // Assert + assertNotNull(currentContinuousJob); + assertTrue( + currentContinuousJob.state().get().knownEnum() == JobState.Known.JOB_STATE_SUCCEEDED); + } } diff --git a/src/test/java/com/google/genai/types/FunctionResponsePartTest.java b/src/test/java/com/google/genai/types/FunctionResponsePartTest.java new file mode 100644 index 00000000000..4108f8b895a --- /dev/null +++ b/src/test/java/com/google/genai/types/FunctionResponsePartTest.java @@ -0,0 +1,42 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.genai.types; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +public class FunctionResponsePartTest { + + @Test + public void testFunctionResponsePartFromUri() { + FunctionResponsePart part = FunctionResponsePart.fromUri("test-uri", "test-mime-type"); + + assertEquals("test-uri", part.fileData().get().fileUri().get()); + assertEquals("test-mime-type", part.fileData().get().mimeType().get()); + } + + @Test + public void testPartFromBytes() { + byte[] bytes = new byte[] {1, 2, 3}; + FunctionResponsePart part = + FunctionResponsePart.fromBytes(bytes, "test-mime-type"); + + assertEquals(bytes, part.inlineData().get().data().get()); + assertEquals("test-mime-type", part.inlineData().get().mimeType().get()); + } +} diff --git a/src/test/java/com/google/genai/types/PartTest.java b/src/test/java/com/google/genai/types/PartTest.java index b78e648a156..fe592a25fcb 100644 --- a/src/test/java/com/google/genai/types/PartTest.java +++ b/src/test/java/com/google/genai/types/PartTest.java @@ -95,4 +95,25 @@ public void testPartFromFunctionResponse() { assertFalse(part.inlineData().isPresent()); assertFalse(part.videoMetadata().isPresent()); } + + @Test + public void testPartFromFunctionResponseWithFunctionResponseParts() { + FunctionResponsePart functionResponsePart = + FunctionResponsePart.fromBytes(new byte[] {1, 2, 3}, "image/png"); + FunctionResponsePart[] functionResponseParts = + new FunctionResponsePart[] {functionResponsePart}; + Part part = + Part.fromFunctionResponse( + "test-function-name", ImmutableMap.of("test-key", "test-value"), functionResponseParts); + + assertEquals("test-function-name", part.functionResponse().get().name().get()); + assertEquals("test-value", part.functionResponse().get().response().get().get("test-key")); + assertEquals(functionResponsePart, part.functionResponse().get().parts().get().get(0)); + + assertFalse(part.text().isPresent()); + assertFalse(part.fileData().isPresent()); + assertFalse(part.functionCall().isPresent()); + assertFalse(part.inlineData().isPresent()); + assertFalse(part.videoMetadata().isPresent()); + } } diff --git a/versions.txt b/versions.txt index 91058d0cec9..18ba7a0e1d0 100644 --- a/versions.txt +++ b/versions.txt @@ -1,4 +1,4 @@ # Format: # module:released-version:current-version -google-genai:1.10.0:1.11.0-SNAPSHOT +google-genai:1.25.0:1.26.0-SNAPSHOT